var HOST_CORE = 'https://cc.gid.turtella.ru';
var HOST_STATIC = 'https://st.gid.turtella.ru';
var SUBDOMAIN = 'gid';
try {
// document.domain = 'turtella.ru';
} catch (e){}
var bPop = {opacity: 0.6, speed: 10, zIndex: 100};
if (typeof String.prototype.startsWith != 'function') {
String.prototype.startsWith = function (str){
return this.slice(0, str.length) == str;
};
}
if (typeof String.prototype.endsWith != 'function') {
String.prototype.endsWith = function (str){
return this.slice(-str.length) == str;
};
}
function isValidUrl(url){
return url.match(/^https?:\/\/[a-z0-9-\.]+\.[a-z]{2,4}\/?([^\s<>\#%"\,\{\}\\|\\\^\[\]`]+)?$/);
}
var ajx = {
request: function(params) {
jQuery.ajax({
data: params.data,
error: function(data, status, request) {
if (params.error!=undefined) {
params.error(data, status, request);
} else {
ajx.defaultError(data, status, request);
}
},
success: function(data, status, request) {
if (data.length>=4 && data.substring(0,4)=='err:') {
ajx.displayErrorMessage(data.substring(4));
} else {
params.success(data, status, request);
}
},
type: 'POST',
url: params.url
});
},
defaultError: function(data, status, request) {
},
displayErrorMessage: function(msg) {
},
requestS: function(params) {
var data = $.ajax({
data: params.data,
type: "POST",
async: false,
url: params.url
}).responseText;
return data;
}
};
var divClick = function(e) {
var a = $(this).find('a');
if (a.length>0) {
if (e.ctrlKey) {
window.open(a.attr('href'), a.attr('href')+Math.random());
} else {
if (a.attr('target')!=undefined) {
window.open(a.attr('href'), a.attr('href')+Math.random());
} else {
window.location=a.attr('href');
}
}
}
e.preventDefault();
};
function preload(arrayOfImages) {
$(arrayOfImages).each(function(){
$('')[0].src = this;
});
}
function openWindow(url, target) {
if (target=='' || target==undefined) {
window.location=url;
} else {
window.open(url, target);
}
}
$(document).ready(function() {
dd.init(); // dropdowns
if (typeof init !='undefined') init();
$('#searchField').focus(function() {
if ($(this).val()=='Поиск по сайту...') $(this).val('');
}).focusout(function() {
if ($(this).val()=='') $(this).val('Поиск по сайту...');
});
$('#searchBtn').click(function() {
$('#searchForm').submit();
});
$('#searchForm').submit(function() {
if ($('#searchField').val()=='' || $('#searchField').val()=='Поиск по сайту...') {
return false;
} else {
return true;
}
});
$('#eventCount').click(function() {window.location='/profile/events/';});
$('#headerUser').hover(function() {
$('.userMenu').show();
}, function() {
$('.userMenu').hide();
});
$('#headerUser table, .divClick').click(divClick);
$('.userMenuItem').hover(function() {
$(this).addClass('userMenuItemSel');
}, function() {
$(this).removeClass('userMenuItemSel');
}).click(divClick);
$('#headerBot td .countries').hover(function() {
$('#countryList').show();
}, function() {
$('#countryList').hide();
});
$('#headerBot td .resorts').hover(function() {
$('#resortList').show();
}, function() {
$('#resortList').hide();
});
$('#headerBot td.menu').click(divClick);
$('#contentsTop .tab').click(contents.click);
$("#loginPopBtn").click(function() {
ptv.loginFormErrMsg('');
$('#loginPop').bPopup(bPop);
});
$("#passwordPopBtn").click(function() {
$('#loginPop').bPopup().close();
ptv.sendChgPasswdLnkErr('');
$('#passEmail').val('');
$('#passwordPop').bPopup(bPop);
});
$('#sendPasswdBtn').click(ptv.sendChgPasswdLnk);
$('#loginBtn').click(ptv.login);
$('div.user').click(divClick);
$('div.clickDiv').click(divClick);
$('.meta .rate .rateYes').hover(function() {
$(this).addClass('rateYesSel');
}, function() {
$(this).removeClass('rateYesSel');
});
$('.meta .rate .rateNo').hover(function() {
$(this).addClass('rateNoSel');
}, function() {
$(this).removeClass('rateNoSel');
});
$('.meta .rate .rateYes').click(rate.click);
$('.meta .rate .rateNo').click(rate.click);
$('#msgPopBtn').click(msg.hide);
$('.weatherMapTabs .tab a').click(function() {
$('.weatherMapTabs .tab').removeClass('sel');
$(this).closest('div').addClass('sel');
wm.switchMap();
});
$('#mSelection td').hover(function() {
if (!$(this).hasClass('sel')) {
$(this).addClass('over');
}
}, function() {
$(this).removeClass('over');
}).click( function() {
$('#mSelection td').removeClass('sel').removeClass('over');
$(this).addClass('sel');
wm.switchMap();
});
$('.chartYears a').click(function() {
$(this).closest('table').find('a').removeClass('sel');
$(this).addClass('sel');
eval($(this).attr('js'));
});
$('#socialButtons .vk').click(function(){ptv.loginVk($(this).attr('t'));});
$('#socialButtons .ok').click(function(){ptv.loginOk($(this).attr('t'));});
$('#socialButtons .mm').click(function(){ptv.loginMM($(this).attr('t'));});
$('#socialButtons .fb').click(function(){ptv.loginFB($(this).attr('t'));});
preload([HOST_CORE+'/i/yes-sel.png',HOST_CORE+'/i/no-sel.png']);
$('#mainBanner').click(function(){window.location='/post/';});
if (typeof lastStep !='undefined') lastStep();
$('#sendEmailLnk').click(ptv.sendEmail);
$('#sendEmailBtn').click(ptv.sendEmailSubmit);
// $('.trPop').click(tourRequest.tourRequestPop);
$('.trPop').click(tourRequest.travelata);
// tripster
rsz.tripster();
$(window).resize(function() {
rsz.tripster();
});
$('.tr_close').click(function() {
tourRequest.bPopEl.close();
});
$(window).scroll(function(){
var el = $('#fixedAd');
if (el.length) {
var objectTop = $('#scrollLimit').position().top;
var windowScrollTop = $(window).scrollTop();
if (windowScrollTop > objectTop) {
if (!el.hasClass('rightAd')) el.addClass('rightAd');
} else {
if (el.hasClass('rightAd')) el.removeClass('rightAd');
}
}
});
setTimeout(showHExtra, 200);
// setTimeout(showVExtra, 500);
});
showHExtra = function() {
if ($('.topAdv').length) {
var height = $('.topAdv').height();
if (height==0) {
var url = "https://turtella.ru/alt/h/gid/gid-h/?callback=?"
$.getJSON(url, function(json){
$('.topAdv').html(json.content);
});
}
}
};
showVExtra = function() {
if ($('#extraV').length) {
if ($('.exOriginal').length) return;
var ch = $('#center').height();
var rh = $('#rPanel').height();
var height = 0;
if (ch>0 && rh>0) {
height = ch - rh;
}
if (height>200) {
var url = "https://turtella.ru/alt/v/gid/gid-v/"+height+"/"+$('#extraV').attr('location')+"/?exTripster=1&callback=?"
$.getJSON(url, function(json){
$('#extraV').html(json.content);
});
}
}
};
var reg = new Object();
reg.init = function() {
$('#regBtn').click(ptv.registration);
};
reg.sendPasswordPop = function() {
ptv.sendChgPasswdLnkErr('');
$('#passEmail').val('');
$('#passwordPop').bPopup(bPop);
};
var changePassword = new Object();
changePassword.init = function() {
$('#chgPwdFormBtn').click(ptv.validateChgPwdForm);
};
var profile = new Object();
profile.init = function() {
$('#profilePhotoBtn').click(ptv.changeProfilePhoto);
$('#profileAvatarBtn').click(ptv.changeProfileAvatar);
$('#tmpProfileImgUploadBtn').click(ptv.tmpProfileImgUploadSubmit);
$('#tmpProfileJCropBtn').click(ptv.cropProfileImg);
$('#tmpProfileJCropBtnCancel').click(ptv.cropProfileImgCancel);
$('#userInfoUpdateBtn').click(ptv.userInfoUpdate);
$('#userContactsUpdateBtn').click(ptv.userContactsUpdate);
$('#userPasswordUpdateBtn').click(ptv.userPasswordUpdate);
};
var ta = new Object();
ta.init=function($ta) {
$('.editor .bPanel .btn').hover(function() {
$(this).addClass('btnSel');
}, function() {
$(this).removeClass('btnSel');
});
$('#downloadImgBtn').click(ta.downloadImg);
$('#downloadVideoBtn').click(ta.downloadVideo);
$('#addLinkBtn').click(ta.addLink);
$ta.on('keyup focusout', ta.onChangeFn);
$ta.on('keyup', function(e) {
var code = e.keyCode ? e.keyCode : e.which;
if(code == 13) {
var txt = $ta[0].value;
var lineEnd = $ta.getLineStartPosition();
var lineStart = 0;
if (lineEnd>0) {
if (lineEnd>1 && txt.substr(lineEnd-2, 2)=='\r\n') {
lineEnd -= 2;
} else if (txt.substr(lineEnd-1, 1)=='\r' || txt.substr(lineEnd-1, 1)=='\n') {
lineEnd -= 1;
}
}
if (lineEnd>0) {
lineStart=lineEnd;
var char = txt.substr(lineStart-1, 1);
while (char!='\r' && char!='\n' && lineStart>0) {
lineStart -= 1;
char = lineStart>0?txt.substr(lineStart-1, 1):'';
}
}
var line = txt.substring(lineStart, lineEnd);
var regexp = /^([ \t]*\*[ \t]{0,3})/;
var match = regexp.exec(line);
if (match!=null) {
if (line.length==match[0].length) { // empty line
$ta.deleteText(lineStart, lineStart+match[0].length+1);
$ta.setSelection(lineStart,lineStart);
} else {
$ta.replaceSelectedText('* ');
};
};
// $('#test').html(txt.substr(lineStart,lineEnd-lineStart));
};
});
$ta.on("keydown", function(e) {
var code = e.keyCode ? e.keyCode : e.which;
if(code == 8) { // remove *{space} on backspace
var txt = $ta[0].value;
var lineStart = $ta.getLineStartPosition();
var p1=txt.indexOf('\n',lineStart);
var p2=txt.indexOf('\r',lineStart);
var lineEnd = p1>=0?p1:lineStart;
lineEnd = (p2>=0&&p2/g,'>');
val=val.replace(/\r/g,'\n');
val=val.replace(/(youtube:[^\s]+)/g,'\n$1\n');
val=val.replace(/(\[QUOTE\]|\[\/QUOTE\])/g,'\n$1\n');
var lines = val.split('\n');
for (var i=0;i to prev line
lines[i-1]=lines[i-1]+'\n';
ulOpened=false;
}
if (line==''||line=='[H]'||line=='[/H]'||line=='[QUOTE]'||line=='[/QUOTE]') {
} else if (line.startsWith('[H]')&&line.endsWith('[/H]')) {
// new
} else if (line.startsWith('youtube')) {
} else if (line.startsWith('* ') || line=='*') {
lines[i]=(!ulOpened?'
\n':'')+'
'+$.trim(line.substring(1))+'
';
ulOpened=true;
} else {
lines[i]='
'+line+'
';
}
}
val = lines.join('\n');
if (ulOpened) val+='
';
val = val.replace(/\[B\](.*?)\[\/B\]/g,'$1');
val = val.replace(/\[U\](.*?)\[\/U\]/g,'$1');
val = val.replace(/\[I\](.*?)\[\/I\]/g,'$1');
val = val.replace(/\[H\](.*?)\[\/H\]/g,'
$1
');
val = val.replace(/\[H3\](.*?)\[\/H3\]/g,'
$1
');
val = val.replace(/\[QUOTE\]\n
([\s\S]*?)<\/p>\n\[\/QUOTE\]/g,'
\n
$1
\n
');
val = val.replace(/\[QUOTE\]([\s\S]*?)\[\/QUOTE\]/g,'
$1
');
val = val.replace(/https?:\/\/(st\.)?gid\.turtella.ru(\/img\/[0-9]{1,3}\/[0-9a-z]{4}\.jpg)/g,'');
val = val.replace(/\[A\s*URL=(.*?)](.*?)\[\/A\]/g,'$2');
// new
val = val.replace(/youtube:([a-zA-Z0-9-_]{5,}):([^\s]+)/g,'');
$('#preview').html(val);
}, 10);
};
ta.isValidSelection=function(str) {
return (str.indexOf('\n')<0 && str.indexOf('\r')<0);
};
ta.imgUploadDone = function(result) {
$('#imgUpload').bPopup().close();
if (result=='') {
msg.showErr('Ошибка', 'Изображение не может быть загружено.');
} else {
var $ta = $("#ta");
$ta.replaceSelectedText(' '+result+' ',"collapseToEnd");
ta.onChangeFn();
}
};
ta.downloadImg = function() {
var url = $('#imgUrl').val();
if (url!='') {
ajx.request({
data: {url: url},
success: function(data, status, request) {
ta.imgUploadDone(data);
},
url: '/ajax/downloadImg/'
});
}
};
ta.addLink = function() {
var url = $('#linkUrl').val();
if (isValidUrl(url)) {
var $ta = $("#ta");
$ta.surroundSelectedText("[A URL="+url+"]", "[/A]");
$('#userLink').bPopup().close();
ta.onChangeFn();
} else {
$('#userLinkErr').show();
}
};
ta.downloadVideo = function() {
var url = $('#videoUrl').val();
if (url!='') {
ajx.request({
data: {url: url},
success: function(data, status, request) {
$('#videoUpload').bPopup().close();
if (data.startsWith('VALID:')) {
var idUrl = data.substring(6);
var pos = idUrl.indexOf(':');
if (pos>0) {
var videoId = idUrl.substring(0,pos);
var videoImg = idUrl.substring(pos+1);
var $ta = $("#ta");
$ta.replaceSelectedText(' youtube:'+videoId+':'+videoImg+' ',"collapseToEnd");
ta.onChangeFn();
}
} else {
var err = 'Ошибка обработки видео';
if (data=='BAD_URL') {
err = 'Неверный адрес видео';
} else if (data=='CANT_FIND') {
err = 'Указанное Вами видео не найдено';
} else if (data=='NOT_EMBEDDABLE') {
err = 'Данное видео не может быть встроено на сторонних сайтах';
}
msg.showErr('Ошибка', err);
}
},
url: '/ajax/downloadVideo/'
});
}
};
var exR = new Object();
exR.init = function() {
var $ta = $("#ta");
if ($ta.length!=0) {
ta.init($ta);
};
dd.onChange('countrySel', function(el, val) {
// uncheck checkbox
$('#resortChk').attr('checked',false);
// clear resorts dropdown
dd.clear('resortSel');
if (val>0) {
// rebuild step 2 selection
ajx.request({
data: {countryId: val},
success: function(data, status, request) {
var arr = JSON.parse(data);
dd.addElements('resortSel', arr);
},
url: '/ajax/getCountryResortsExt/'
});
}
});
dd.onChange('resortSel', function(el, val) {
if (val>0) {
if ($('#resortChk').attr('checked')=='checked') {
// uncheck checkbox
$('#resortChk').attr('checked',false);
}
}
});
$('#exRSubmit').click(exR.submit);
$('.mButtons .btn').hover(function() {
var color = $(this).attr('color');
if (color==undefined) color='';
$(this).addClass('btnOver'+color);
}, function() {
var color = $(this).attr('color');
if (color==undefined) color='';
$(this).removeClass('btnOver'+color);
}).click(function() {
var c = $(this).closest('.mButtons');
var sameBtn = $(this).attr('val')==c.attr('val');
// remove selection
var val = c.attr('val');
var selected = c.find('div[val='+val+']');
var color = selected.attr('color');
if (color==undefined) color='';
selected.removeClass('btnSel'+color);
c.attr('val',0);
if (!sameBtn) {
// select new btn
var color = $(this).attr('color');
if (color==undefined) color='';
$(this).addClass('btnSel'+color);
c.attr('val',$(this).attr('val'));
};
});
};
exR.saveInProgress=0;
exR.submit = function() {
if (exR.saveInProgress==0) {
exR.saveInProgress = 1;
var id = $('#postId').val();
var c = dd.get('countrySel');
var r = dd.get('resortSel');
var reviewName = $('#reviewName').val();
var post = $('#ta').val();
var impression = $('#impression').attr('val');
var userName = $('#userName').val();
// validate
var err = [];
if (c==0) {
err.push('Выберите страну');
}
if (r==0) {
err.push('Выберите курорт');
}
if (reviewName=='') {
err.push('Укажите заголовок вашего отзыва');
} else if (reviewName.length<5) {
err.push('Заголовок отзыва слишком короткий');
}
if (post=='') {
err.push('Введите текст Вашего отзыва');
} else if (post.length<200) {
err.push('Текст отзыва слишком короткий');
}
if (userName=='') {
err.push('Укажите Ваше имя');
} else if (userName.length<3) {
err.push('Ваше имя слишком короткое');
}
if (impression==0) {
err.push('Укажите Вашу рекомендацию');
}
if (err.length>0) {
var errList = '
';
$.each(err, function(id,val) {
errList+='
- '+val+'
';
});
errList+="
";
msg.showErr('Исправте следующие ошибки:',errList);
exR.saveInProgress = 0;
} else {
// save
ajx.request({
data: {id: id, r: r, title: reviewName, p: post, userName: userName, impression: impression},
success: function(data, status, request) {
if (data.startsWith('OK:')) {
var url = data.substring(3);
window.location=url;
} else {
msg.showErr('Ошибка','Невозможно сохранить Ваш отзыв.');
}
exR.saveInProgress = 0;
},
error: function(data, status, request) {
exR.saveInProgress = 0;
},
url: '/ajax/saveExReview/'
});
}
}
};
var p = new Object();
p.step2Disabled = false;
p.step3Disabled = false;
p.init = function() {
var $ta = $("#ta");
if ($ta.length!=0) {
ta.init($ta);
};
$('#updateRatio').click(p.updateRatio);
dd.onChange('countrySel', function(el, val) {
// uncheck checkbox
$('#resortChk').attr('checked',false);
// clear resorts dropdown
dd.clear('resortSel');
if (val>0) {
// rebuild step 2 selection
ajx.request({
data: {countryId: val},
success: function(data, status, request) {
var arr = JSON.parse(data);
dd.addElements('resortSel', arr);
},
url: '/ajax/getCountryResortsExt/'
});
}
p.clearQ();
});
dd.onChange('resortSel', function(el, val) {
if (val>0) {
if ($('#resortChk').attr('checked')=='checked') {
// uncheck checkbox
$('#resortChk').attr('checked',false);
}
}
p.clearQ();
p.updateRatio();
});
$('#resortChk').change(p.countryChkChanged);
$('#postTab1').click(function(){p.activateTab('A');});
$('#postTab2').click(function(){p.activateTab('T');});
$('#postTab3').click(function(){p.activateTab('R');});
$('#postTab4').click(function(){p.activateTab('P');});
$('#postTabPr1').click(function(){p.activatePrTab('tour');});
$('#postTabPr2').click(function(){p.activatePrTab('self');});
$('#qSelectPopBtn').click(p.selectQPop);
$('#qSelectPopBtn2').click(p.selectQPop);
$('#pSubmit').click(p.submit);
$('#postSavedPopBtn').click(function(){$('#postSavedPop').bPopup().close();});
$('.mButtons .btn').hover(function() {
var color = $(this).attr('color');
if (color==undefined) color='';
$(this).addClass('btnOver'+color);
}, function() {
var color = $(this).attr('color');
if (color==undefined) color='';
$(this).removeClass('btnOver'+color);
}).click(function() {
var c = $(this).closest('.mButtons');
var sameBtn = $(this).attr('val')==c.attr('val');
// remove selection
var val = c.attr('val');
var selected = c.find('div[val='+val+']');
var color = selected.attr('color');
if (color==undefined) color='';
selected.removeClass('btnSel'+color);
c.attr('val',0);
if (!sameBtn) {
// select new btn
var color = $(this).attr('color');
if (color==undefined) color='';
$(this).addClass('btnSel'+color);
c.attr('val',$(this).attr('val'));
};
});
};
p.activeTab='A';
p.activePrTab='tour';
p.countryChkChanged = function() {
var val = $('#resortChk').attr('checked')=='checked';
if (val) {
// $('#resortSel').val(0);
dd.setInitial('resortSel');
}
// clear q selection
p.clearQ();
p.updateRatio();
};
p.selectQPop = function(){
var c = dd.get('countrySel');
if ($('#resortChk').attr('checked')=='checked') {
// country
if (c==0) {
msg.showErr('Ошибка', 'Сперва укажите страну и/или город для которых Вы хотите написать сообщение.');
} else {
p.loadAndShowQList('/ajax/questions/'+c+'/');
}
} else {
// resort
var r = dd.get('resortSel');
if (r==0) {
msg.showErr('Ошибка', 'Сперва укажите страну и/или город для которых Вы хотите написать сообщение.');
} else {
p.loadAndShowQList('/ajax/questions/'+c+'/'+r+'/');
}
}
};
p.loadAndShowQList = function(url) {
ajx.request({
success: function(data, status, request) {
$('#qSelectionPop .container').html(data);
p.pop=$('#qSelectionPop').bPopup(bPop);
$('.qItem').hover(function() {
$(this).addClass('qItemSel');
}, function() {
$(this).removeClass('qItemSel');
});
},
url: url
});
};
p.qClick = function() {
var id = $(this).attr('id');
p.selectQ(id);
};
p.clearQ = function() {
$('#questionId').val(0);
$('#qSelection').hide();
$('#q0').show();
};
p.selectQ = function(qId, qName, qDesc) {
$('#questionId').val(qId);
$('#qName').html(qName);
$('#qDesc').html(qDesc);
$('#qSelection').show();
$('#q0').hide();
if(p.pop!=undefined) p.pop.close();
p.updateRatio();
};
p.activateTab = function(type) {
if (p.activeTab==type) return;
$('#postType').val(type);
if (p.activeTab!='') p.deactivateTab(p.activeTab);
if (type=='A') {
$('#postTab1').addClass('sel');
$('.postTab1').show();
$('#editorPanel').show();
$('.botTab3').hide();
p.activeTab='A';
} else if (type=='T') {
$('#postTab2').addClass('sel');
$('.postTab2').show();
$('#editorPanel').show();
$('.botTab3').hide();
p.activeTab='T';
} else if (type=='R') {
$('#postTab3').addClass('sel');
$('.postTab3').show();
$('#editorPanel').show();
$('.botTab3').show();
p.activeTab='R';
} else if (type=='P') {
$('#postTab4').addClass('sel');
$('.postTab4').show();
$('#editorPanel').hide();
$('.botTab3').hide();
p.activeTab='P';
}
p.updateRatio();
};
p.deactivateTab = function(type) {
if (type=='A') {
$('#postTab1').removeClass('sel');
$('.postTab1').hide();
} else if (type=='T') {
$('#postTab2').removeClass('sel');
$('.postTab2').hide();
} else if (type=='R') {
$('#postTab3').removeClass('sel');
$('.postTab3').hide();
} else if (type=='P') {
$('#postTab4').removeClass('sel');
$('.postTab4').hide();
}
};
p.activatePrTab = function(type) {
if (p.activePrTab==type) return;
$('#priceType').val(type);
if (p.activePrTab!='') p.deactivatePrTab(p.activePrTab);
if (type=='tour') {
$('#postTabPr1').addClass('sel');
$('#priceTypeTour').show();
$('#priceTypeTourTitle').show();
p.activePrTab='tour';
} else if (type=='self') {
$('#postTabPr2').addClass('sel');
$('#priceTypeSelf').show();
$('#priceTypeSelfTitle').show();
p.activePrTab='self';
}
p.updateRatio();
};
p.deactivatePrTab = function(type) {
if (type=='tour') {
$('#postTabPr1').removeClass('sel');
$('#priceTypeTour').hide();
$('#priceTypeTourTitle').hide();
} else if (type=='self') {
$('#postTabPr2').removeClass('sel');
$('#priceTypeSelf').hide();
$('#priceTypeSelfTitle').hide();
}
};
p.saveInProgress=0;
p.submit = function() {
if (p.activeTab=='P') {
pr.submit();
} else {
if (p.saveInProgress==0) {
p.saveInProgress = 1;
var id = $('#postId').val();
var c = dd.get('countrySel');
var r = dd.get('resortSel');
var isCQ = $('#resortChk').attr('checked')=='checked';
var qId = $('#questionId').val();
var tipName = $('#tipName').val();
var reviewName = $('#reviewName').val();
var post = $('#ta').val();
var title = '';
var impression = $('#impression').attr('val');
var month = dd.get('monthSel1');
var year = dd.get('yearSel1');
// validate
var err = [];
if (c==0) {
err.push('Выберите страну');
}
if (!isCQ && r==0) {
err.push('Выберите курорт');
}
if (p.activeTab=='A' && qId==0) {
err.push('Выберите вопрос, на который Вы хотите ответить');
}
if (p.activeTab=='T') {
if (tipName=='') {
err.push('Укажите заголовок Вашего совета');
} else if (tipName.length<5) {
err.push('Заголовок сообщения слишком короткий');
}
title = tipName;
}
if (p.activeTab=='R') {
if (reviewName=='') {
err.push('Укажите заголовок вашего отзыва');
} else if (reviewName.length<5) {
err.push('Заголовок сообщения слишком короткий');
}
title = reviewName;
if (month==0 || year==0) {
err.push('Укажите время вашего отдыха');
}
if (impression==0) {
err.push('Укажите ваше общее впечатление от отдыха');
}
}
if (post=='') {
err.push('Введите текст Вашего сообщения');
} else if (post.length<200) {
err.push('Текст сообщения слишком короткий');
}
if (err.length>0) {
var errList = '
';
$.each(err, function(id,val) {
errList+='
- '+val+'
';
});
errList+="
";
msg.showErr('Исправте следующие ошибки:',errList);
p.saveInProgress = 0;
} else {
// save
ajx.request({
data: {id: id, c: c, r: r, month: month, year: year, impression: impression, type: p.activeTab, q: qId, title: title, p: post},
success: function(data, status, request) {
if (data.startsWith('OK:')) {
var o = JSON.parse(data.substring(3));
p.savedPostURL = o.url;
if (o.pointsRequired>0) {
var params = {
onClose: function() {window.location=p.savedPostURL;}
};
for (var attrName in bPop) {params[attrName]=bPop[attrName];}
$('#postSavedPop').bPopup(params);
} else {
window.location=p.savedPostURL;
}
} else {
msg.showErr('Ошибка','Невозможно сохранить Ваше сообщение.');
}
p.saveInProgress = 0;
},
error: function(data, status, request) {
p.saveInProgress = 0;
},
url: '/ajax/savePost/'
});
}
}
}
};
p.updateRatio = function() {
if (p.author && $('#postId').val()==0) {
// var c = $('#countrySel').val();
var c = dd.get('countrySel');
// var r = $('#resortSel').val();
var r = dd.get('resortSel');
var isCQ = $('#resortChk').attr('checked')=='checked';
var qId = $('#questionId').val();
if (c>0 && (r>0 || isCQ) && (p.activeTab=='T' || p.activeTab=='R' || (p.activeTab=='A' && qId!=0))) {
$('#ratio').text('Обновление...');
ajx.request({
data: {c: c, r: r, type: p.activeTab, q: qId},
success: function(data, status, request) {
$('#ratio').text('$'+data);
},
error: function(data, status, request) {
$('#ratio').text('Ошибка!');
},
url: '/ajax/getRatio/'
});
};
}
};
p.initNotifications = function() {
var modalBPop = bPop;
modalBPop.modalClose = false;
modalBPop.escClose = false;
$('#notificationConfirmBtn').click(function() {
$('#notifications').bPopup().close();
ajx.request({
data: {nId: $('#lastNotificationId').val()},
success: function(data, status, request) {
},
error: function(data, status, request) {
},
url: '/ajax/markNotifications/'
});
});
$('#notifications').bPopup(modalBPop);
};
var pr = new Object();
pr.submit = function() {
if (p.saveInProgress==0) {
p.saveInProgress = 1;
var id = $('#postId').val();
var c = dd.get('countrySel');
var r = dd.get('resortSel');
var isCQ = $('#resortChk').attr('checked')=='checked';
var month = dd.get('monthSel2');
var year = dd.get('yearSel2');
p.activePrTab; // tour || self
var prTour = $('#prTour').val().trim();
var prExcursions = $('#prExcursions').val().trim();
var prFood = $('#prFood').val().trim();
var prGoods = $('#prGoods').val().trim();
var prServices = $('#prServices').val().trim();
var combinedTxt = prTour+prExcursions+prFood+prGoods+prServices;
var total = $('#total').val().trim();
var currency = dd.get('currSel');
// validate
var err = [];
if (c==0) {
err.push('Выберите страну');
}
if (!isCQ && r==0) {
err.push('Выберите курорт');
}
if (month==0 || year==0) {
err.push('Укажите время вашего отдыха (год и месяц)');
}
if (combinedTxt=='') {
err.push('Заполните хотя бы один текстовый раздел о ценах на отдыхе');
} else if (combinedTxt.length<500) {
err.push('Ваше сообщение слишком короткое. Минимальная допустимая длина - 500 символов');
}
if (total!='' && total*1!=total) {
err.push('Укажите числовое значение в разделе \'Общее количество денег, затраченное на отдых\'');
}
if (total*1>0 && currency=='') {
err.push('Укажите валюту в разделе \'Общее количество денег, затраченное на отдых\'');
}
if (err.length>0) {
var errList = '
';
$.each(err, function(id,val) {
errList+='
- '+val+'
';
});
errList+="
";
msg.showErr('Исправте следующие ошибки:',errList);
p.saveInProgress = 0;
} else {
// save
ajx.request({
data: {id: id, c: c, r: r, month: month, year: year, type: p.activePrTab, prTour: prTour, prExcursions: prExcursions, prFood: prFood, prGoods: prGoods, prServices: prServices, total: total, currency: currency},
success: function(data, status, request) {
if (data.startsWith('OK:')) {
var o = JSON.parse(data.substring(3));
p.savedPostURL = o.url;
if (o.pointsRequired>0) {
var params = {
onClose: function() {window.location=p.savedPostURL;}
};
for (var attrName in bPop) {params[attrName]=bPop[attrName];}
$('#postSavedPop').bPopup(params);
} else {
window.location=p.savedPostURL;
}
} else {
msg.showErr('Ошибка','Невозможно сохранить Ваше сообщение.');
}
p.saveInProgress = 0;
},
error: function(data, status, request) {
p.saveInProgress = 0;
},
url: '/ajax/savePrices/'
});
}
}
};
var ptv = new Object();
ptv.openSocialWindow=function(url, width, height) {
var h = 600;
var w = 800;
if (width!=undefined) w=width;
if (height!=undefined) h=height;
window.open(url,'social','height='+h+',width='+w+',location=0,menubar=0,resizable=0,scrollbars=1,status=0,toolbar=0,top='+Math.round(($(window).height()-h)/2)+',left='+Math.round(($(window).width()-w)/2));
};
ptv.loginVk = function(action) {
ptv.openSocialWindow('http://'+SUBDOMAIN+'.turtella.ru/social/vk/'+action+'/');
};
ptv.loginOk = function(action) {
ptv.openSocialWindow('http://'+SUBDOMAIN+'.turtella.ru/social/ok/'+action+'/');
};
ptv.loginFB = function(action) {
ptv.openSocialWindow('http://'+SUBDOMAIN+'.turtella.ru/social/fb/'+action+'/', 1000, 710);
};
ptv.loginMM = function(action) {
ptv.openSocialWindow('http://'+SUBDOMAIN+'.turtella.ru/social/mm/'+action+'/');
};
ptv.sendChgPasswdLnkErr = function(msg) {
var el = $('#sendPasswdErr');
if (msg=='') {
el.hide();
el.find('td').html('');
} else {
el.find('td').html(msg);
el.show();
}
};
ptv.sendChgPasswdLnk = function() {
ptv.sendChgPasswdLnkErr('');
var email = $('#passEmail').val();
ajx.request({
data: {email: email},
success: function(data, status, request) {
if (data=='true') {
$('#passwordPop').bPopup().close();
msg.showInfo('Сообщение отправлено','На Ваш адрес отправленоо сообщение с инструкциями по восстановлению пароля.');
} else {
ptv.sendChgPasswdLnkErr('Пользователь c таким адресом не найден.');
}
},
url: '/ajax/sendChangePasswordLnk/'
});
};
ptv.chgPwdFormErrMsg = function(msg) {
var el = $('#errMsg');
if (msg=='') {
el.hide();
} else {
el.find('td').html(msg);
el.show();
}
};
ptv.validateChgPwdForm = function() {
ptv.chgPwdFormErrMsg('');
var p1=$('#p1').val();
var p2=$('#p2').val();
if (p1=='' || p2=='') {
ptv.chgPwdFormErrMsg('Введите новый пароль дважды.');
} else if (p1!=p2) {
ptv.chgPwdFormErrMsg('Несоответствие значений пароля.');
} else if (p1.length<5) {
ptv.chgPwdFormErrMsg('Длинна пароля должна составлять 5-16 символов.');
} else {
$('#chgPwdForm').submit();
}
};
ptv.loginFormErrMsg = function(msg) {
var el = $('#loginErr');
if (msg=='') {
el.hide();
} else {
el.find('td').html(msg);
el.show();
}
};
ptv.login = function() {
ptv.loginFormErrMsg('');
var email = $('#logEmail').val();
var pwd = $('#logPwd').val();
if (email=='' || pwd=='') {
ptv.loginFormErrMsg('Введите Ваш e-mail и пароль');
} else {
ajx.request({
data: {email: email, password: pwd},
success: function(data, status, request) {
if (data=='true') {
window.location=window.location; // reload page
} else {
ptv.loginFormErrMsg('Ошибка авторизации. Проверьте правильность введенных данных.');
}
},
url: '/ajax/login/'
});
}
};
ptv.removeNewSocialLnk = function(network) {
ajx.request({
data: {network: network},
success: function(data, status, request) {
$('#socialLinks').html(data);
},
url: '/ajax/removeNewUserSocialLink/'
});
};
ptv.removeUserSocialLnk = function(network) {
ajx.request({
data: {network: network},
success: function(data, status, request) {
$('#socialLinks').html(data);
},
url: '/ajax/removeUserSocialLink/'
});
};
ptv.socialActionDone = function(action, result) {
if (action=='auth') { // success, notFound, notAuthorized
if (result=='success') {
window.location=window.location;
}
} else if (action=='newLnk') { // notAuthorized, success
if (result=='success') {
ajx.request({
success: function(data, status, request) {
$('#socialLinks').html(data);
},
url: '/ajax/getNewUserSocialLinks/'
});
};
} else if (action=='userLnk') { // notAuthorized, success
if (result=='success') {
ajx.request({
success: function(data, status, request) {
$('#socialLinks').html(data);
},
url: '/ajax/getUserSocialLinks/'
});
};
}
};
ptv.hideRegErrors = function() {
$('#emailErr').hide().find('td').html('');
$('#userNameErr').hide().find('td').html('');
$('#passwordErr').hide().find('td').html('');
$('#uniqueEmailErr').hide();
};
ptv.displayRegErrors = function(err) {
if (err!=undefined) {
if (err.email!=undefined) {
if (err.email=='busy') {
$('#uniqueEmailErr').show();
} else {
$('#emailErr').find('td').html(err.email);
$('#emailErr').show();
}
}
if (err.userName!=undefined) {
$('#userNameErr').find('td').html(err.userName);
$('#userNameErr').show();
}
if (err.password!=undefined) {
$('#passwordErr').find('td').html(err.password);
$('#passwordErr').show();
}
}
};
ptv.socialLinksCount = 0;
ptv.registration = function() {
if (grecaptcha.getResponse()=='') return;
ptv.hideRegErrors();
var email = $('#email').val();
var userName = $('#userName').val();
var password1 = $('#password1').val();
var password2 = $('#password2').val();
var err = {};
var validForm = true;
// validate email
if (email=='') {
err.email = 'Укажите свой электронный адрес';
validForm = false;
} else if (email.length>64) {
err.email = 'Слишком длинное значение';
validForm = false;
} else if (!ptv.isValidEmail(email)) {
err.email = 'Неверный формат почтового адреса';
validForm = false;
};
// validate user name
if (userName=='') {
err.userName = 'Укажите имя пользователя';
validForm = false;
} else if (userName.length>30) {
err.userName = 'Слишком длинное значение';
validForm = false;
} else if (userName.length<3) {
err.userName = 'Слишком короткое значение (минимум 3 символа)';
validForm = false;
};
// validate password
if (ptv.socialLinksCount==0 && password1.length==0 && password2.length==0) {
err.password = 'Укажите хоть один способ авторизации (пароль или социальную сеть)';
validForm = false;
} else if ((password1.length>0 || password2.length>0) && password1!=password2 ) {
err.password = 'Несоответствие паролей';
validForm = false;
} else if (password1.length>0 && password1==password2 && password1.length<5 ) {
err.password = 'Слишком короткий пароль (минимум 5 символов)';
validForm = false;
} else if (password1.length>0 && password1==password2 && password1.length>16 ) {
err.password = 'Слишком длинный пароль';
validForm = false;
}
// is user name and email unique?
ajx.request({
data: {userName: userName, email: email},
success: function(data, status, request) {
if (data.startsWith('OK:')) {
var o = JSON.parse(data.substring(3));
if (err.userName==undefined) {
if (o.userName=='busy') {
err.userName = 'Данное имя пользователя уже занято';
validForm = false;
}
}
if (err.email==undefined) {
if (o.email=='busy') {
err.email = 'busy';
validForm = false;
}
}
// submit request or display error message
if (validForm) {
$('#regForm').submit();
} else {
ptv.displayRegErrors(err);
// grecaptcha.reset();
}
}
},
url: '/ajax/checkUserNameAndEmail/'
});
};
ptv.isValidEmail = function(email) {
if (email==undefined) return false;
return email.match(/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,5}/)!=null;
};
ptv.sendActivationCode = function() {
ajx.request({
success: function(data, status, request) {
if (data=='OK') {
msg.showInfo('Действие выполнено','Код активации был повторно отправлен на Ваш e-mail адрес.');
}
},
url: '/ajax/sendActivationEmail/'
});
};
ptv.tmpProfileImgUploadSubmit = function() {
$('#tmpProfileImgErr').hide().find('td').html('');
$('#tmpProfileImgForm').submit();
};
ptv.profileTmpImgType='';
ptv.changeProfilePhoto = function() {
ptv.profileTmpImgType='photo';
$('#uploadImg').val('');
$('#tmpProfileImgForm').attr('action','/uploadProfileTmpImg/photo/');
$('#tmpProfileImgUpload').bPopup(bPop);
};
ptv.changeProfileAvatar = function() {
ptv.profileTmpImgType='avatar';
$('#uploadImg').val('');
$('#tmpProfileImgForm').attr('action','/uploadProfileTmpImg/avatar/');
$('#tmpProfileImgUpload').bPopup(bPop);
};
ptv.profileTmpImgUploadDone = function(type,url,x,y) {
if (x==0 || y==0) {
$('#tmpProfileImgErr').show().find('td').html('Ошибка обработки изображения');
} else {
var dX = Math.round(x/20);
var dY = Math.round(y/20);
var params = {setSelect: [dX,dY,x-dX,y-dY]};
if (type=='avatar') {
var side = Math.round(0.9*(x>y?y:x));
var xStart = Math.round((x-side)/2);
var yStart = Math.round((y-side)/2);
params = {setSelect: [xStart,yStart,xStart+side,yStart+side], aspectRatio: 1};
}
params.onSelect=function(sel){ptv.jcropSelection=sel;};
params.onChange =function(sel){ptv.jcropSelection=sel;};
ptv.cropImgUrl = url;
$('#profileCropImgPanel').html('');
$('#profileCropImg').Jcrop(params);
$('#tmpProfileImgUpload').bPopup().close();
$('#tmpProfileJCropErr').hide().find('td').html('');
$('#tmpProfileImgJCrop').bPopup(bPop);
}
};
ptv.cropProfileImgCancel = function() {
$('#tmpProfileImgJCrop').bPopup().close();
};
ptv.cropProfileImg = function() {
$('#tmpProfileJCropErr').hide().find('td').html('');
if ((ptv.profileTmpImgType=='avatar' && (ptv.jcropSelection.w<48 || ptv.jcropSelection.h<48)) ||
(ptv.profileTmpImgType=='photo' && (ptv.jcropSelection.w<300 || ptv.jcropSelection.h<200))) {
$('#tmpProfileJCropErr').show().find('td').html('Выделенная область изображения слишком мала');
} else {
ajx.request({
data: {x: ptv.jcropSelection.x, y: ptv.jcropSelection.y, w: ptv.jcropSelection.w, h: ptv.jcropSelection.h, type: ptv.profileTmpImgType, url: ptv.cropImgUrl},
success: function(data, status, request) {
if (data.startsWith('OK:')) {
var src = data.substr(3);
if (ptv.profileTmpImgType=='avatar') {
$('#usrAvatarImg').attr('src', src);
} else if (ptv.profileTmpImgType=='photo') {
$('#usrPhotoImgTmp').hide();
$('#usrPhotoImg').show().attr('src',src);
}
$('#tmpProfileImgJCrop').bPopup().close();
} else {
$('#tmpProfileJCropErr').show().find('td').html('Ошибка обработки изображения');
}
},
url: '/ajax/cropProfileImg/'
});
}
};
ptv.userInfoUpdateErr = function(msg) {
if (msg=='' || msg==undefined) {
$('#userNameErr').hide().find('td').html('');
} else {
$('#userNameErr').show().find('td').html(msg);
}
};
ptv.userInfoUpdate = function() {
ptv.userInfoUpdateErr();
var userName = $('#userNameFormField').val();
if (userName.length<3) {
ptv.userInfoUpdateErr('Имя пользователя слишком короткое (минимум 3 символа)');
} else if (userName.length>30) {
ptv.userInfoUpdateErr('Имя пользователя слишком длинное');
} else {
ajx.request({
data: {userName: userName, location: $('#location').val()},
success: function(data, status, request) {
if (data=='fail') {
ptv.userInfoUpdateErr('Данное имя пользователя уже занято');
} else {
msg.showInfo('Действие выполнено','Основные данные пользователя были обновлены');
}
},
url: '/ajax/updateUserInfo/'
});
}
};
ptv.userContactsUpdate = function() {
ajx.request({
data: {emailOption: dd.get('emailOption'), skype: $('#skype').val(), icq: $('#icq').val(), phone: $('#phone').val()},
success: function(data, status, request) {
if (data=='success') {
msg.showInfo('Действие выполнено','Контактные данные пользователя были обновлены');
}
},
url: '/ajax/updateUserContacts/'
});
};
ptv.userPasswordUpdateErr = function(msg) {
if (msg=='' || msg==undefined) {
$('#userPasswordErr').hide().find('td').html('');
} else {
$('#userPasswordErr').show().find('td').html(msg);
}
};
ptv.userPasswordUpdate = function() {
ptv.userPasswordUpdateErr();
var p1 = $('#password1').val();
var p2 = $('#password2').val();
if (p1=='') {
ptv.userPasswordUpdateErr('Введите новый пароль');
} else if (p1!=p2) {
ptv.userPasswordUpdateErr('Несоответствие значений');
} else if (p1.length<5) {
ptv.userPasswordUpdateErr('Значение пароля слишком короткое (минимум 5 символов)');
} else if (p1.length>16) {
ptv.userPasswordUpdateErr('Значение пароля слишком длинное');
} else {
ajx.request({
data: {password: $('#password1').val()},
success: function(data, status, request) {
if (data=='success') {
msg.showInfo('Действие выполнено','Пароль обновлен. Следующий раз для входа на сайт используйте новый пароль.');
}
},
url: '/ajax/updateUserPassword/'
});
}
};
ptv.validateHashCode = function() {
var hash = window.location.hash;
if (hash.length>0) {
hash = hash.substring(1);
if (hash=='sectionResortList') {
$("#contentResortTab").trigger('click');
}
}
};
ptv.sendEmail = function() {
$('#sendEmailFrom').val('');
$('#sendEmailBody').val('');
$('#sendEmailMsg').hide();
$('#sendEmailPop').bPopup(bPop);
};
ptv.sendEmailSubmit = function() {
$('#sendEmailMsg').hide();
var from = $('#sendEmailFrom').val();
var body = $('#sendEmailBody').val();
var publicUserId = $('#sendEmailPop').attr('publicId');
if (!ptv.isValidEmail(from) || body.length==0) {
$('#sendEmailMsg').show();
} else {
ajx.request({
data: {publicId: publicUserId, from: from, body: body},
success: function(data, status, request) {
$('#sendEmailPop').bPopup().close();
msg.showInfo('Готово','Ваше сообщение было отправлено');
},
url: '/ajax/sendEmail/'
});
}
};
var c = new Object();
c.init = function() {
var $ta = $("#ta");
if ($ta.length!=0) {
ta.init($ta);
};
$('#cSubmit').click(c.submit);
$('#parentMsg a').click(c.clearParentComment);
$('textarea.simpleEditor').focus(function(){$(this).addClass('simpleEditorFocus');});
$('#msgPopBtnNo').on('click',c.deleteHide);
$('#msgPopBtnYes').on('click',c.deleteConfirm);
c.init2();
};
c.init2 = function() {
$('#commentsBody .reply').on('click',c.setParentComment);
$('#commentsBody .delete').on('click',c.deleteComment);
$('.media').on('click',c.showMedia);
$('.comment').hover(
function() {$(this).addClass('commentSel');},
function() {$(this).removeClass('commentSel');}
);
vote.init();
};
c.showMedia = function() {
var el = $(this);
var type = el.attr('type');
if (type=='v') {
var v = el.attr('v');
$('#mediaPanel').html('');
} else if (type=='i') {
var src = el.attr('src');
$('#mediaPanel').html('');
}
$('#mediaPop').bPopup(bPop).delay(200);
};
c.setParentComment = function() {
var el = $(this);
var userName = el.attr('un');
var date = el.attr('d');
var parentId = el.attr('p');
$('#parentId').val(parentId);
$('#parentMsg').show().find('span').html('Ответ на сообщение пользователя '+userName+' от '+date);
$('html, body').animate({
scrollTop: $("#addComment").offset().top
}, 20);
$('#ta').focus();
};
c.deleteComment = function() {
var el = $(this);
c.delteCommentPublicId = el.attr('p');
$('#deleteConfirmPop').bPopup(bPop);
};
c.deleteHide = function() {
$('#deleteConfirmPop').bPopup().close();
};
c.deleteConfirm = function() {
$('#deleteConfirmPop').bPopup().close();
ajx.request({
data: {publicId: c.delteCommentPublicId},
success: function(data, status, request) {
if (data=='OK') {
$('.comment[p='+c.delteCommentPublicId+']').hide();
msg.showInfo('Выполнено','Ваш комментарий был удален.');
} else {
msg.showErr('Ошибка','Комментарий не может быть удален.');
}
},
url: '/ajax/deleteComment/'
});
};
c.clearParentComment = function() {
$('#parentId').val(0);
$('#parentMsg').hide().find('span').html('');
};
c.saveInProgress = 0;
c.submit = function() {
if (c.saveInProgress==0) {
c.saveInProgress = 1;
var type = $('#type').val();
var objectId = $('#objectId').val();
var parent = $('#parentId').val();
var comment = $('#ta').val();
// validate
var err = '';
if (comment=='') {
err='Введите текст Вашего комментария.';
} else if (comment.length<5) {
err='Текст комментария слишком короткий (минимум 5 символов).';
}
if (err!='') {
msg.showErr('Ошибка',err);
c.saveInProgress = 0;
} else {
// save
ajx.request({
data: {type: type, objectId: objectId, parent: parent, c: comment},
success: function(data, status, request) {
if (data.startsWith('OK:')) {
var o = JSON.parse(data.substring(3));
if (o.user>0) {
$('#ta').val('');
$('#postComments').html(o.html);
$('html, body').animate({
scrollTop: $('#'+o.cPublicId).offset().top
}, 20);
if (o.pointsRequired>0) {
msg.showInfo('Комментарий добавлен','Ваш комментарий отправлен на модерацию. До окончания проверки он не будет доступен другим пользователям.');
$('#ta').val('');
}
c.init2();
} else {
msg.showInfo('Комментарий добавлен','Ваш комментарий отправлен на модерацию. До окончания проверки он не будет доступен другим пользователям.');
$('#ta').val('');
}
} else {
msg.showErr('Ошибка','Комментарий не сохранен.');
}
c.saveInProgress = 0;
},
error: function(data, status, request) {
c.saveInProgress = 0;
},
url: '/ajax/saveComment/'
});
}
}
};
var ev = new Object();
ev.init = function() {
$('.markLnk').click(ev.setMarkEvent);
$('#markAll').click(ev.setMarkAllEvents);
$('a.reason').click(function() {
msg.showInfo('Пояснение',$(this).attr('title'));
});
$('input.postEditBtn').click(function() {
window.location=$(this).attr('lnk');
});
$('input.newPost').click(function() {
window.location='/post/';
});
};
ev.setMarkEvent = function() {
var publicId = $(this).attr('c');
ajx.request({
data: {publicId: publicId},
success: function(data, status, request) {
if (data.startsWith('OK:')) {
var events = 1*data.substring(3);
if (events>0) {
if (events>99) {
events = 99;
}
$('#eventCount').html(events);
} else {
$('#eventCount').hide();
}
$('#e'+publicId).removeClass('newEvent');
}
},
url: '/ajax/markEvent/'
});
};
ev.setMarkAllEvents = function() {
ajx.request({
success: function(data, status, request) {
if (data=='OK') {
$('div.newEvent').removeClass('newEvent');
$('#eventCount').hide();
}
},
url: '/ajax/markAllEvents/'
});
};
var tasks = new Object();
tasks.init = function(doNotAsk) {
$('.getTaskBtn').click(tasks.getAction);
$('#confirmYes').click(function() {
$('#confirmPop').bPopup().close();
tasks.getTask();
});
$('#confirmNo').click(function() {
$('#confirmPop').bPopup().close();
});
};
tasks.getAction = function() {
tasks.taskId = $(this).attr('taskId').substring(0,1);
$('#confirmPop').bPopup(bPop);
};
tasks.getTask = function() {
ajx.request({
data: {taskId: tasks.taskId},
success: function(data, status, request) {
if (data.startsWith('OK:')) {
var tr = $('tr[taskId='+data.substring(3)+']');
tr.addClass('green');
tr.find('td.action').html('в работе');
} else if (data.startsWith('LIMIT')) {
msg.showErr('Ошибка', 'Вы не можете брать более 3 заданий одновременно', 400);
}
},
url: '/ajax/getTask/'
});
};
var sb = new Object();
sb.init = function(doNotAsk) {
sb.doNotAsk = doNotAsk;
$('.unsubscribeLnk').click(sb.unsubscribe);
$('#confirmYes').click(function() {
$('#confirmPop').bPopup().close();
if($('#confirmDoNotAsk').attr('checked')=='checked') {
sb.doNotAsk=1;
}
sb.unsubscribeSend();
});
$('#confirmNo').click(function() {
$('#confirmPop').bPopup().close();
});
};
sb.unsubscribe = function() {
sb.type = $(this).attr('objId').substring(0,1);
sb.publicId = $(this).attr('objId').substring(1);
if (sb.doNotAsk>0) {
sb.unsubscribeSend();
} else {
$('#confirmPop').bPopup(bPop);
}
};
sb.unsubscribeSend = function() {
ajx.request({
data: {publicId: sb.publicId, type: sb.type, doNotAsk: sb.doNotAsk},
success: function(data, status, request) {
if (data.startsWith('OK:')) {
data = data.substring(3);
$('#'+data).hide();
}
},
url: '/ajax/unsubscribe/'
});
};
var pay = new Object();
pay.init = function() {
$('#paymentRequest').click(pay.requestPayment);
};
pay.requestPayment = function() {
ajx.request({
data: {currency: $('#currency').val()},
success: function(data, status, request) {
if (data=='OK') {
window.location=window.location;
}
},
url: '/ajax/requestPayment/'
});
};
var contents = new Object();
contents.click = function() {
var div = $(this);
var id = div.attr('id');
$('#contentsTop .tab').removeClass('sel');
$(this).addClass('sel');
if (div.attr('first')=='yes') {
$('#contentsBottom').addClass('firstTab');
} else {
$('#contentsBottom').removeClass('firstTab');
}
$('#contentsBottom').find('div').hide();
if (id=='contentMainTab') $('#contentMainPanel').show();
if (id=='contentResortTab') $('#contentResortsPanel').show();
if (id=='contentRestTab') $('#contentRestPanel').show();
if (id=='contentPrepareTab') $('#contentPreparePanel').show();
};
var rate = new Object();
rate.click = function() {
var el = $(this);
var v = el.attr('v');
var rateEl = el.closest('.rate');
var postId = rateEl.attr('id').substring(1);
var type = rateEl.attr('id').substring(0,1);
ajx.request({
data: {publicId: postId, type: type, vote: v},
success: function(data, status, request) {
if (data.startsWith('OK:')) {
var id = data.substring(3);
$('#'+type+id).html('Спасибо, Ваш голос учтен!');
}
},
url: '/ajax/pVote/'
});
};
$(document).mouseup(function (e) {
if (dd.opened!='') {
var container = dd.opened;
if (!container.is(e.target) && container.has(e.target).length === 0) {
dd.close();
}
}
});
var dd = new Object();
dd.onChangeMap = new Object();
dd.initValMap = new Object();
dd.initTextMap = new Object();
dd.opened = '';
dd.init = function() {
$('.dd').click(dd.click);
$('.dd .panel div').click(dd.select).hover(function() {
$(this).addClass('sel');
}, function() {
$(this).removeClass('sel');
});;
$('.dd').each(function(index,el) {
var e = $(el);
var id = e.attr('id');
var text = e.find('.selection').html();
var val = e.find('.selection').attr('val');
dd.initValMap[id]=val;
dd.initTextMap[id]=text;
});
};
dd.clear = function(ddId) {
$('#'+ddId).find('.panel div').remove();
dd.setInitial(ddId);
};
dd.setInitial = function(ddId) {
$('#'+ddId).find('.selection').html(dd.initTextMap[ddId]).attr('val',dd.initValMap[ddId]);
};
dd.click = function() {
var el = $(this);
if ((dd.opened == '' || dd.opened.attr('id')!=el.attr('id')) && el.find('.panel div').length>0) {
dd.opened = el;
dd.open();
} else if (dd.opened != '' && dd.opened.attr('id')==el.attr('id')) {
dd.close();
}
};
dd.close = function() {
if (dd.opened!='') {
dd.opened.find('.panel').hide();
}
dd.opened='';
};
dd.open = function() {
dd.opened.find('.panel').show();
};
dd.select = function() {
var el = $(this);
var ddEl = el.closest('.dd');
var oldVal = ddEl.find('.selection').attr('val');
var newVal = el.attr('id');
if (oldVal!=newVal) {
ddEl.find('div.selection').text(el.text()).attr('val', newVal);
var ddId = ddEl.attr('id');
var f = dd.onChangeMap[ddId];
if (f!=undefined) {
f(ddEl, newVal);
}
}
};
dd.set = function(ddId, val) {
if (val!='') {
var dEl = $('#'+ddId);
var selEl = dEl.find('.selection');
var selectedEl = dEl.find('#'+val);
if (selectedEl.length>0) {
selEl.text(selectedEl.text()).attr('val',selectedEl.attr('id'));
}
}
};
dd.get = function(ddId) {
return $('#'+ddId).find('.selection').attr('val');
};
dd.onChange = function(ddId, f) {
dd.onChangeMap[ddId]=f;
};
dd.addElements = function(ddId, arr) {
var panel = $('#'+ddId+' .panel');
jQuery.each(arr, function() {
panel.append($('').attr('id',this.id).text(this.n));
});
$('#'+ddId+' .panel div').click(dd.select).hover(function() {
$(this).addClass('sel');
}, function() {
$(this).removeClass('sel');
});
};
var msg = new Object();
msg.showErr = function(title, txt, w) {
msg.show('err',title,txt,w);
};
msg.showInfo = function(title, txt, w) {
msg.show('info',title,txt,w);
};
msg.show = function(type, title, txt, w) {
if (type=='err') {
$('#msgPopTitle').attr('class','popTitleErr mb10');
} else {
$('#msgPopTitle').attr('class','popTitleInfo mb10');
}
if (w!=undefined && w>0) {
$('#msgPopPanel').width(w);
}
$('#msgPopTitle').html(title);
$('#msgPopTxt').html(txt);
$('#msgPop').bPopup(bPop);
};
msg.hide = function(title, txt, width, height) {
$('#msgPop').bPopup().close();
};
var vote = new Object();
vote.votes = {};
vote.init = function() {
$('.comment').hover(
function() {
var el = $(this).find('.vote');
var id = el.attr('id');
var plus = el.find('.plus');
var minus = el.find('.minus');
if (minus.hasClass('minusDark')) {
vote.votes[id]=-1;
} else if (plus.hasClass('plusDark')) {
vote.votes[id]=1;
}
minus.addClass('minusRed');
plus.addClass('plusGreen');
},
function() {
var el = $(this).find('.vote');
var id = el.attr('id');
var plus = el.find('.plus');
var minus = el.find('.minus');
var v = 0;
if (id in vote.votes) {
v = vote.votes[id];
};
minus.attr('class','minus');
plus.attr('class','plus');
if (v>0) {
plus.addClass('plusDark');
} else if (v<0) {
minus.addClass('minusDark');
}
}
);
$('.vote .minus').click(function(){vote.vote($(this).closest('.vote').attr('id'), -1);});
$('.vote .plus').click(function(){vote.vote($(this).closest('.vote').attr('id'), 1);});
preload([HOST_CORE+'/i/minus-red.png',HOST_CORE+'/i/plus-green.png',HOST_CORE+'/i/minus-dark.png',HOST_CORE+'/i/plus-dark.png']);
};
vote.vote = function(id, v) {
var publicCommentId = id.substring(1);
ajx.request({
data: {publicId: publicCommentId, vote: v},
success: function(data, status, request) {
if (data.startsWith('OK:')) {
var str = data.substring(3);
var pos = str.indexOf(':');
var id = str.substring(0,pos);
var points = str.substring(pos+1);
var el = $('#v'+id);
points = points*1;
var pointsClass='';
if (points>0) {
pointsClass='pointsGreen';
} else if (points<0) {
pointsClass='pointsRed';
}
if (points>=0) points = '+'+points;
el.find('.points').removeClass('pointsRed').removeClass('pointsGreen').addClass(pointsClass).html(points);
vote.votes['v'+id]=v;
if (v>0 && !el.find('.plus').hasClass('plusGreen')) {
el.find('.plus').addClass('plusDark');
} else if (v<0 && !el.find('.minus').hasClass('minusRed')) {
el.find('.minus').addClass('minusDark');
}
}
},
url: '/ajax/cVote/'
});
};
var wm = new Object();
wm.switchMap = function() {
var type = $('div.weatherMapTabs div.sel').attr('type');
var mId = $('#mSelection td.sel').attr('m');
var mType = '';
var mMonth = '';
if (type=='weather') {
if (mId==0) {
mType = 'weather';
mMonth = '';
} else {
mType = 'avg';
mMonth = 'm'+mId;
}
} else { // sst
if (mId==0) {
mType = 'sst';
mMonth = '';
} else {
mType = 'sst';
mMonth = 'm'+mId;
}
}
//document.getElementById('weatherMapPanel').contentWindow.map.switchMapType(mType, mMonth);
document.getElementById('weatherMapPanel').contentWindow.postMessage({action:'change',type:mType,subtype:mMonth}, '*');
// alert('type='+type+', m='+mId);
};
var r = new Object();
r.txtLen = 0;
r.init = function() {
dd.onChange('countrySel', function(el, val) {
// clear resorts dropdown
dd.clear('resortSel');
if (val>0) {
// rebuild step 2 selection
ajx.request({
data: {countryId: val},
success: function(data, status, request) {
var arr = JSON.parse(data);
dd.addElements('resortSel', arr);
},
url: '/ajax/getCountryResortsExt/'
});
}
});
$('.mButtons .btn').hover(function() {
var color = $(this).attr('color');
if (color==undefined) color='';
$(this).addClass('btnOver'+color);
}, function() {
var color = $(this).attr('color');
if (color==undefined) color='';
$(this).removeClass('btnOver'+color);
}).click(function() {
var c = $(this).closest('.mButtons');
var sameBtn = $(this).attr('val')==c.attr('val');
// remove selection
var val = c.attr('val');
var selected = c.find('div[val='+val+']');
var color = selected.attr('color');
if (color==undefined) color='';
selected.removeClass('btnSel'+color);
c.attr('val',0);
if (!sameBtn) {
// select new btn
var color = $(this).attr('color');
if (color==undefined) color='';
$(this).addClass('btnSel'+color);
c.attr('val',$(this).attr('val'));
};
r.redrawDependantBlocks();
});
$('#btnPanel div').hover(function() {
$(this).addClass('over');
}, function() {
$(this).removeClass('over');
}).click(function() {
var selected = $(this).attr('val')==1;
if (selected) {
$(this).removeClass('sel').attr('val',0);
} else {
$(this).addClass('sel').attr('val',1);
}
r.redrawDependantBlocks();
});
$('#reportForm textarea').keyup(function() {
r.recalculateTxtLen();
});
$('#rSubmit').click(r.submit);
$('#reportSavedPopBtn').click(function(){$('#reportSavedPop').bPopup().close();});
};
r.redrawDependantBlocks = function() {
if ($('#isBestMonth').attr('val')==2) {
$('#step15').show();
} else {
$('#step15').hide();
};
if ($('#bestMonth').attr('val')==0) {
$('#bestMonthTxtContainter').hide();
} else {
$('#bestMonthTxtContainter').show();
};
if ($('#restTypeChildren').attr('val')==0) {
$('#restTypeChildrenTxtContainer').hide();
} else {
$('#restTypeChildrenTxtContainer').show();
};
if ($('#restTypeFamily').attr('val')==0) {
$('#restTypeFamilyTxtContainer').hide();
} else {
$('#restTypeFamilyTxtContainer').show();
};
if ($('#restTypeYouth').attr('val')==0) {
$('#restTypeYouthTxtContainer').hide();
} else {
$('#restTypeYouthTxtContainer').show();
};
if ($('#restTypeElderly').attr('val')==0) {
$('#restTypeElderlyTxtContainer').hide();
} else {
$('#restTypeElderlyTxtContainer').show();
};
if ($('#restTypeSingle').attr('val')==0) {
$('#restTypeSingleTxtContainer').hide();
} else {
$('#restTypeSingleTxtContainer').show();
};
r.recalculateTxtLen();
};
r.recalculateTxtLen = function() {
r.txtLen = 0;
$('#reportForm textarea:visible').each(function() {
r.txtLen += $.trim($(this).val()).length;
});
$('#txtLen').html(r.txtLen);
};
r.setValue = function(control, value) {
$('#'+control+' div[val='+value+']').trigger('click');
};
r.enableControl = function(control) {
$('#'+control).trigger('click');
};
r.saveInProgress=0;
r.submit = function() {
if (r.saveInProgress==0) {
r.saveInProgress = 1;
// clear hidden textarea field
$('#reportForm textarea:hidden').each(function() {
$(this).val('');
});
// gather all data
var rpt = {};
rpt.reportId = $('#reportId').val();
rpt.resortId = dd.get('resortSel');
rpt.guest = $.trim($('#guest').val());
// put all textareas to rpt obj
$('#reportForm textarea').each(function() {
var elementId = $(this).attr('id');
var elementVal = $.trim($(this).val());
rpt[elementId]=elementVal;
});
// put all buttons to rpt obj
$('div.mButtons').each(function() {
var elementId = $(this).attr('id');
var elementVal = $(this).attr('val');
rpt[elementId]=elementVal;
});
// put all buttons from panel to rpt obj
$('#btnPanel div').each(function() {
var elementId = $(this).attr('id');
var elementVal = $(this).attr('val');
rpt[elementId]=elementVal;
});
r.recalculateTxtLen();
rpt.txtLen = r.txtLen;
// validate
var err = [];
if (rpt.resortId==0) {
err.push('Укажите страну и курорт где вы отдыхали');
}
if (rpt.year==0 || rpt.month==0) {
err.push('Укажите время отдыха');
}
if (rpt.isBestMonth==2 && rpt.month>0 && rpt.month==rpt.bestMonth) {
err.push('Месяцы, выбранные в разделах 1.3 и 1.5, не должны совпадать.');
}
if (rpt.txtLen<250) {
err.push('Общий размер сообщения слишком короткий. Минимальный размер - 250 символов.');
} else {
if (rpt.impressionMonthTxt.length>0 && rpt.impressionMonthTxt.length<50) {
err.push('Ваше сообщение в разделе 1.3 слишком короткое. Минимальный размер - 50 символов.');
}
if (rpt.bestMonthTxt.length>0 && rpt.bestMonthTxt.length<50) {
err.push('Ваше сообщение в разделе 1.5 слишком короткое. Минимальный размер - 50 символов.');
}
if (
(rpt.restTypeChildrenTxt.length>0 && rpt.restTypeChildrenTxt.length<50) ||
(rpt.restTypeYouthTxt.length>0 && rpt.restTypeYouthTxt.length<50) ||
(rpt.restTypeFamilyTxt.length>0 && rpt.restTypeFamilyTxt.length<50) ||
(rpt.restTypeElderlyTxt.length>0 && rpt.restTypeElderlyTxt.length<50) ||
(rpt.restTypeSingleTxt.length>0 && rpt.restTypeSingleTxt.length<50)
) {
err.push('Ваше сообщение в разделе 2.1 слишком короткое. Минимальный размер - 50 символов.');
}
if (rpt.thingsTxt.length>0 && rpt.thingsTxt.length<50) {
err.push('Ваше сообщение в разделе 2.2 слишком короткое. Минимальный размер - 50 символов.');
}
if (rpt.placeTxt.length>0 && rpt.placeTxt.length<50) {
err.push('Ваше сообщение в разделе 2.3 слишком короткое. Минимальный размер - 50 символов.');
}
if (rpt.activityTxt.length>0 && rpt.activityTxt.length<50) {
err.push('Ваше сообщение в разделе 2.4 слишком короткое. Минимальный размер - 50 символов.');
}
if (rpt.excursionsTxt.length>0) {
if (rpt.excursionsTxt.length<50) {
err.push('Ваше сообщение в разделе 3.1 слишком короткое. Минимальный размер - 50 символов.');
} else if (rpt.excursionsRating==0) {
err.push('Пожалуйста, оцените качество экскурсионных программ в разделе 3.1');
}
}
if (rpt.beachesTxt.length>0) {
if (rpt.beachesTxt.length<50) {
err.push('Ваше сообщение в разделе 3.2 слишком короткое. Минимальный размер - 50 символов.');
} else if (rpt.beachesRating==0) {
err.push('Пожалуйста, оцените качество пляжей в разделе 3.2');
}
}
if (rpt.shoppingTxt1.length>0 || rpt.shoppingTxt2.length>0 ) {
if ((rpt.shoppingTxt1.length>0 && rpt.shoppingTxt1.length<50) || (rpt.shoppingTxt2.length>0 && rpt.shoppingTxt2.length<50)) {
err.push('Ваше сообщение в разделе 3.3 слишком короткое. Минимальный размер - 50 символов.');
} else if (rpt.shoppingRating==0) {
err.push('Пожалуйста, оцените качество шоппинга в разделе 3.3');
}
}
if (rpt.foodTxt1.length>0 || rpt.foodTxt2.length>0 || rpt.foodTxt3.length>0) {
if ((rpt.foodTxt1.length>0 && rpt.foodTxt1.length<50) || (rpt.foodTxt2.length>0 && rpt.foodTxt2.length<50) || (rpt.foodTxt3.length>0 && rpt.foodTxt3.length<50)) {
err.push('Ваше сообщение в разделе 3.4 слишком короткое. Минимальный размер - 50 символов.');
} else if (rpt.foodRating==0) {
err.push('Пожалуйста, оцените качество питания в разделе 3.4');
}
}
if (rpt.amenitiesTxt.length>0) {
if (rpt.amenitiesTxt.length<50) {
err.push('Ваше сообщение в разделе 3.5 слишком короткое. Минимальный размер - 50 символов.');
} else if (rpt.amenitiesRating==0) {
err.push('Пожалуйста, оцените качество развлечений в разделе 3.5');
}
}
if (rpt.positiveTxt.length>0 && rpt.positiveTxt.length<50) {
err.push('Ваше сообщение в разделе 4.1 слишком короткое. Минимальный размер - 50 символов.');
}
if (rpt.negativeTxt.length>0 && rpt.negativeTxt.length<50) {
err.push('Ваше сообщение в разделе 4.2 слишком короткое. Минимальный размер - 50 символов.');
}
if (rpt.alternativeTxt.length>0 && rpt.alternativeTxt.length<50) {
err.push('Ваше сообщение в разделе 4.3 слишком короткое. Минимальный размер - 50 символов.');
}
}
if ($('#guest').val()==1) {
rpt.userName=$('#userName').val();
if (rpt.userName.length==0) {
err.push('Пожалуйста, укажите ваше имя в разделе 5.1');
} else if (rpt.userName.length<3) {
err.push('Указанное имя в разделе 5.1 слишком короткое. Минимальная длина - 3 символа.');
}
}
if (err.length>0) {
var errList = '
';
$.each(err, function(id,val) {
errList+='
- '+val+'
';
});
errList+="
";
msg.showErr('Исправте следующие ошибки:',errList);
r.saveInProgress = 0;
} else {
// save
ajx.request({
data: rpt,
success: function(data, status, request) {
if (data.startsWith('OK:')) {
var o = JSON.parse(data.substring(3));
r.savedPostURL = o.url;
if (o.pointsRequired>0) {
var params = {
onClose: function() {
window.location=r.savedPostURL;
}
};
for (var attrName in bPop) {params[attrName]=bPop[attrName];}
$('#reportSavedPop').bPopup(params);
} else {
window.location=r.savedPostURL;
}
} else {
msg.showErr('Ошибка','Невозможно сохранить Ваше сообщение.');
}
r.saveInProgress = 0;
},
error: function(data, status, request) {
r.saveInProgress = 0;
},
url: '/ajax/saveReport/'
});
}
}
};
var rsz = new Object();
rsz.tripster = function() {
if ( $( "#exTable" ).length ) {
var exTableWidth = $('#exTable').width();
var blockWidth = parseInt((exTableWidth-100)/3);
$('.exDiv').width(blockWidth);
}
};
var tourRequest = Object();
tourRequest.pop = '';
tourRequest.travelata=function() {
var win = window.open('https://ad.admitad.com/g/0fa8722e8da4c172f10aa89c09321b/?subid=gidb', 'ot');
win.focus();
}
tourRequest.tourRequestPop=function() {
tourRequest.pop = $('#tourRequestPop').bPopup({
content:'iframe',
zIndex: 50,
contentContainer:'#tourRequestPopPanel',
loadUrl:'/iframe/getTourRequestForm'
});
};
tourRequest.close=function() {
tourRequest.pop.close();
}
tourRequest.bPopEl='';
tourRequest.showUserErrors = function(err) {
var ul = $('#tourRequestErr ul').empty();
jQuery.each(err, function(key, val) {
ul.append('