var Notifier={ask:function(message)
{return confirm(message);},showError:function(message,el)
{var msg=(message==''||message==undefined)?view.translate('Произошла ошибка. Попробуйте еще.'):message;if(el!=undefined&&$(el).length>0){this.notify({'type':'error','msg':view.translate(msg),'el':el})}
else{alert(msg);}},showMessage:function(message,el)
{if(el!=undefined&&$(el).length>0){this.notify({'type':'ok','msg':message,'el':el})}
else{alert(message);}},notify:function(params)
{var tmpl=this.getTemplate();$('.'+$(tmpl).attr('class')).fadeOut();$(tmpl).addClass(params.type).html(params.msg);$(params.el).prepend($(tmpl));$(tmpl).fadeIn();var topCoord=$(params.el).position().top;var scrollTop=$(params.el).scrollTop();if(scrollTop>0){$('body,html').animate({scrollTop:topCoord},200);}
setTimeout(function(){$(tmpl).fadeOut();$(tmpl).remove();},3000);},getTemplate:function()
{return $('<div class="notifier"/>');},showIndicator:function(blockId,isWindow)
{var btn=this.getIndicatorBtn(blockId,isWindow);btn.addClass('loader');btn.prepend('<div class="btn_lock"></div>');},hideIndicator:function(blockId,isWindow)
{var btn=this.getIndicatorBtn(blockId,isWindow);btn.removeClass('loader').addClass('active');btn.children('.btn_lock').remove();},getIndicatorBtn:function(blockId,isWindow)
{var $isWindow=isWindow||false;if($isWindow==false){if($('#'+blockId+' button.blue').length==0){return $('#'+blockId+' .buttons.order-btn');}else{return $('#'+blockId+' button.blue');}}else{return $('#'+blockId+' footer button.blue');}},getLoader:function(el)
{return'<div id="ajax-loader"></div>';},showNotice:function(el,txt)
{if($(el).length>0){var notice='<div id="user-notice" style="display:none;">'+txt+'</div>';$(el).append(notice);var appended=$(el).find('#user-notice');$(appended).fadeIn();setTimeout(function(){$(appended).fadeOut();$(appended).remove();},2500);}}}
var Popup={loadEvents:function()
{var _self=this;$(".window .close, .window .close-link a, .window .cancel").live('click',function(){_self.closeDialog();return false;});},getParams:function(){return{'showCloseButton':false,'enableEscapeButton':true,'margin':0,'padding':2,'centerOnScroll':true}}(),showDialog:function(data,params){var _self=this;var windParams=params||_self.getParams;$.fancybox(data,windParams);},closeDialog:function(){$.fancybox.close();},progressBar:function(action)
{if(action=='show'){$.fancybox.showActivity();}
else{$.fancybox.hideActivity();}},center:function()
{$.fancybox.center();}}
Visitor={init:function()
{$('#footer').append($('<div id="temp-block"/>'));this.loadEvents();this._initValidate();this.decorateContent();Tooltip.init();Popup.loadEvents();this.ymapSetMap();this.gmapSetMap();},loadEvents:function()
{var _self=this;$('.mailerForm .send').live('click',function(){$('.mailerForm form').submit();});$('#topcontacts .feedback-btn').live('click',function(){return Feedback.init('feedback');});$('#up-link').live('click',function(event){return _self.scrollTop(event);});$('#up-link').live('mouseover',function(){$(this).stop(true,true).animate({opacity:1},200);});$('#up-link').live('mouseout',function(){$(this).stop(true,true).animate({opacity:0.4},200);});$(window).scroll(function(){_self.showUpLink(this);});$('#services .order-btn').live('click',function(){return _self.makeOrder(this);});document.onkeydown=function(event){_self.keyEvents(event);}
this.placeSlogan();$('.fancy-img').fancybox();$('.video-intext').click(function(){_self.getVideo(this);});$('.video-item > div > a:not(.video-link), .video-link').fancybox({'centerOnScroll':true});$("#contactsmain-left .ymap, #contactsmain .ymap").live('click',function(){_self.ymapFindAddress(this,_self.ymapShowAddress);return false;});$("#contactsmain-left .gmap, #contactsmain .gmap").live('click',function(){_self.gmapFindAddress(this);return false;});$("#bugreport-edit-window footer .save").live('click',function(){$('#bugreport-edit-window form').submit();return false;});$("#header .tell_mistake a").click(function(){_self.getFormReportBug();return false;});$('#important-news .close-news').live('click',function(){return _self.markPostRead();})
$('#important-news .popup').live('click',function(){return _self.getUrgentMessage();});$('#blog-posts-lnk').live('click',function(){return _self.setPostCounterNull();});},getFormReportBug:function(){var _self=this;var $url="/reportbugform";Popup.progressBar('show');$.post($url,function(data){Popup.progressBar('hide');try{if(data.success==true){Popup.showDialog(data.form);_self.validateReportBug($('#bugreport-form'));}
else{throw new Error('');}}
catch(e){Notifier.showError(e.message);}},"json");},validateReportBug:function(el){var _self=this;$.validator.addMethod('filesize',function(value,element,param){return this.optional(element)||(element.files[0].size<=param);});$.validator.addMethod('fileext',function(value,element){return this.optional(element)||/(.png|.jpg|.jpeg|.gif)$/i.test(value);});el.validate({submitHandler:function(form){var browser=jQuery.browser;var out=new Array();var j=0;for(i in browser){out[j]=new Array();out[j]['key']=i;out[j]['value']=browser[i];j++;}
$('#bugreport-edit-window form #browser').val('Browser: '+out[0]['key']+' Version: '+out[1]['value']);$('#bugreport-edit-window form #platform').val(navigator.platform);Notifier.showIndicator(_self.id);$(form).ajaxSubmit({dataType:'json',iframe:true,type:'post',success:function(result,b,c){Notifier.hideIndicator(_self.id);if(result.success){$.fancybox({content:'<div style="color: #357b13">'+view.translate('Сообщение отправлено')+'<div>'});}
else{$.fancybox({content:'<div style="color: #C10001">'+view.translate('Произошла ошибка')+'<div>'});}}});},focusInvalid:false,focusCleanup:true,rules:{name:{required:true,maxlength:60,minlength:2},email:{required:true,email:true},error_url:{required:true,url:true},error:{required:true,maxlength:200,minlength:10},description:{required:true,maxlength:600,minlength:10},image:{fileext:true,filesize:1048576}},messages:{name:{required:view.translate('Обязательное поле'),maxlength:view.translate("Максимальная длина")+' 60 '+view.translate("символов"),minlength:view.translate("Минимальная длина")+' 2 '+view.translate("символа")},email:{email:view.translate("Неверный формат почты"),required:view.translate("Пожалуйста, укажите email адрес для обратной связи")},error_url:{required:view.translate('Обязательное поле'),url:view.translate('Введен некорректный URL ошибки')},error:{required:view.translate("Пожалуйста, введите наименование ошибки"),maxlength:view.translate("Максимальная длина")+' 200 '+view.translate("символов"),minlength:view.translate("Минимальная длина")+' 10 '+view.translate("символов")},description:{required:view.translate("Пожалуйста, введите описание ошибки"),maxlength:view.translate("Максимальная длина")+' 600 '+view.translate("символов"),minlength:view.translate("Минимальная длина")+' 20 '+view.translate("символов")},image:{filesize:view.translate("Максимальный размер файла 1MB"),fileext:view.translate("Файл может быть картинкой с раширением .png, .jpg, .jpeg, .gif")}}});},getVideo:function(el){var _self=this;var type=$(el).prop('class').replace('video-intext ','');var desc=$(el).prop('alt');var code=$(el).prop('id');var name=$(el).prop('title');var content=_self.VideoConfig[type].content.replace(/\#/g,code);content='<div id="video-content">'+'<div class="item-content">'+'<header>'+'<h1>'+name+'</h1>'+
content+'</header>'+'<div class="video-desc">'+desc+'</div>'+'</div>'+'</div>';$.fancybox({content:content});},VideoConfig:{'youtube':{image:'http://img.youtube.com/vi/?/default.jpg',regexp:/(?:(?:youtube\.com\/watch\?(?:[\w\d]+\=[\w\d]+\&)*v\=)|(?:youtu\.be\/)|(?:youtube\.com\/user\/[\w\d]+(?:\?(?:[\w\d]+\=[\w\d]+[\&]?)+)?#p\/(?:[\w]\/){0,4}[\d]+\/))([_a-zA-Z0-9-]+)/i,content:'<iframe width="700" height="390" src="http://www.youtube.com/embed/#?rel=0" frameborder="0" allowfullscreen></iframe>'},'youtu':{image:'http://img.youtube.com/vi/?/default.jpg',regexp:/(?:(?:youtube\.com\/watch\?(?:[\w\d]+\=[\w\d]+\&)*v\=)|(?:youtu\.be\/)|(?:youtube\.com\/user\/[\w\d]+(?:\?(?:[\w\d]+\=[\w\d]+[\&]?)+)?#p\/(?:[\w]\/){0,4}[\d]+\/))([_a-zA-Z0-9-]+)/i,content:'<iframe width="700" height="390" src="http://www.youtube.com/embed/#?rel=0" frameborder="0" allowfullscreen></iframe>'},'rutube':{image:'http://tub.rutube.ru/thumbs-wide/?-2.jpg',regexp:/(?:(?:rutube\.ru\/tracks\/[0-9]+\.html\?v\=)|(?:video\.rutube\.ru\/))([_a-zA-Z0-9]+)/i,content:'<OBJECT width="700" height="390"><PARAM name="movie" value="http://video.rutube.ru/#"></PARAM><PARAM name="wmode" value="window"></PARAM><PARAM name="allowFullScreen" value="true"></PARAM><EMBED src="http://video.rutube.ru/#" type="application/x-shockwave-flash" wmode="window" width="700" height="390" allowFullScreen="true" ></EMBED></OBJECT>'},'vimeo':{image:'',regexp:/vimeo\.com\/([0-9]+)/i,content:'<iframe src="http://player.vimeo.com/video/#?title=0&amp;byline=0&amp;portrait=0" width="700" height="390" frameborder="0" webkitAllowFullScreen mozallowfullscreen allowFullScreen></iframe>'}},showUpLink:function(el)
{if($(el).scrollTop()>400){$('#up-link').fadeIn();}else{$('#up-link').fadeOut(200);}},scrollTop:function(event)
{$('body,html').animate({scrollTop:0},200);event.preventDefault();return false;},placeSlogan:function(){var height=$('#header-wrapper').height();if($('#slogan').children('#slogan-edit').length==0){$('#slogan-show').height(height);}},keyEvents:function(e){e=e||window.event;if(e.keyCode==27){$form=$(".on-edit:not(.static)");if($form.length>0){Site.toggleBlock();}}},decorateContent:function()
{$('#content .user-inner li').prepend('<i class="circles"></i>');},makeOrder:function(el)
{$forOrder=$(el).parents('.content-block').attr('id').replace('-show','');var $item=$(el).parents('.item-content');var $sid='';if($item.length>0){var $sid=$($item).attr('id').replace('item','')||'';}
return Feedback.init($forOrder,{'sid':$sid,'order':true});},_initValidate:function(){$.validator.setDefaults({showErrors:function(errorMap,errorList){if(errorList.length<1){$('ul.errors').remove();return;}
$.each(errorList,function(index,error){$(error.element).removeClass('valid').addClass('error');$(error.element).next('ul.errors').remove();$(error.element).after($('<ul/>').addClass('errors').append($('<li/>').text(error.message)));});}});},preloadBannerImages:function(images)
{if(typeof document.body=="undefined")return;try{$('#banner-carousel').html(Notifier.getLoader());var div=document.createElement("div");var s=div.style;s.position="absolute";s.top=s.left=0;s.visibility="hidden";document.body.appendChild(div);div.innerHTML="<img src=\""+images.join("\" /><img src=\"")+"\" />";var lastImg=div.lastChild;lastImg.onload=function(){BannerShow();document.body.removeChild(document.body.lastChild);};}
catch(e){}},ymaploaded:function(e){var src=$(e).attr('src');if(src==undefined||src=='about:blank')return;$("#ymap-container #ajax-loader").remove();},ymapFindAddress:function(el){var address=$(el).prevAll('.address-value').html();var host=$(el).data('host');var _this=this;var url="http://"+host+"/ymaps/addr/"+address+"/w/600/h/450/popup";$.fancybox('<div id="ymap-container"><div id="ajax-loader"></div><iframe id="ymap-frame" width="600" height="450" marginheight="0" marginwidth="0" frameborder="0" src=""></iframe></div>',{'opacity':1});$("#ymap-frame").attr("src",url);$("#ymap-frame").load(function(){Visitor.ymaploaded(this)});},ymapSetMap:function(){var maps=$("#main-contacts .address ul iframe[id^=ymap-]");if(maps.length){maps.each(function(){if($(this).attr('src')!=undefined)return true;var host=$(this).data('host');var address=$(this).prevAll('span.address-value').html();$(this).attr('src',"http://"+host+"/ymaps/addr/"+address+"/w/550/h/300/embedded");});}
return false;},gmapSetMap:function(){var maps=$("#main-contacts .address ul iframe[id^=gmap-]");if(maps.length){maps.each(function(){if($(this).attr('src')!=undefined)return true;var host=$(this).data('host');var address=$(this).prevAll('span.address-value').html();$(this).attr('src',"http://"+host+"/gmaps/addr/"+address+"/w/550/h/300/embedded");});}},gmaploaded:function(e){var src=$(e).attr('src');if(src==undefined||src=='about:blank')return;$("#gmap-container #ajax-loader").remove();},gmapFindAddress:function(el){var address=$(el).prevAll('.address-value').html();var host=$(el).data('host');var _this=this;var url="http://"+host+"/gmaps/addr/"+address+"/w/600/h/450/popup";$.fancybox('<div id="gmap-container"><div id="ajax-loader"></div><iframe id="gmap-frame" width="600" height="450" marginheight="0" marginwidth="0" frameborder="0" src=""></iframe></div>',{'opacity':1});$("#gmap-frame").attr("src",url);$("#gmap-frame").load(function(){Visitor.gmaploaded(this);});},markPostRead:function(){var url='/markpostread/';var params={'pid':$('#important-news').data('mid'),'type':'urgent'}
var success=function(result){$('#important-news').animate({opacity:0},300,function(){$('#important-news').animate({height:0},100,function(){$('#important-news').remove();});});}
Site.query(url,success,null,params);return false;},getUrgentMessage:function(){var url='/geturgentcontent/';var params={'pid':$('#important-news').data('mid')}
var success=function(result){Popup.showDialog(result.content);}
Site.query(url,success,null,params);return false;},setPostCounterNull:function()
{var counter=$('#blog-counter');if(counter.length>0){var url='/markpostread/';var params={type:'all'}
var success=function(result){counter.hide();}
Site.query(url,success,null,params);}}}
var d=document;var offsetfromcursorY=15
var ie=d.all&&!window.opera;var ns6=d.getElementById&&!d.all;var tipobj='';var op='';Tooltip={init:function(){var _self=this;$('.forexplain').live('mouseover',function(){_self.tooltip(this);});$('.forexplain').live('mouseout',function(){_self.hide_info(this);});},tooltip:function(el){tipobj=d.getElementById('for-explain');tipobj.innerHTML=$(el).data('faq');op=0.1;tipobj.style.opacity=op;tipobj.style.visibility="visible";el.onmousemove=this.positiontip;this.appear();},hide_info:function(el){d.getElementById('for-explain').style.visibility='hidden';el.onmousemove='';},ietruebody:function(){return(d.compatMode&&d.compatMode!="BackCompat")?d.documentElement:d.body},positiontip:function(e){var curX=(ns6)?e.pageX:event.clientX+Tooltip.ietruebody().scrollLeft;var curY=(ns6)?e.pageY:event.clientY+Tooltip.ietruebody().scrollTop;var winwidth=ie?Tooltip.ietruebody().clientWidth:window.innerWidth-20
var winheight=ie?Tooltip.ietruebody().clientHeight:window.innerHeight-20
var rightedge=ie?winwidth-event.clientX:winwidth-e.clientX;var bottomedge=ie?winheight-event.clientY-offsetfromcursorY:winheight-e.clientY-offsetfromcursorY;if(rightedge<tipobj.offsetWidth)tipobj.style.left=curX-tipobj.offsetWidth+"px";else tipobj.style.left=curX+"px";if(bottomedge<tipobj.offsetHeight)tipobj.style.top=curY-tipobj.offsetHeight-offsetfromcursorY+"px"
else tipobj.style.top=curY+offsetfromcursorY+"px";},appear:function(){if(op<1){op+=0.1;tipobj.style.opacity=op;tipobj.style.filter='alpha(opacity='+op*100+')';t=setTimeout('Tooltip.appear()',30);}}}
Feedback={init:function($type,$params)
{this.type=$type;this.params=$params||{}
this.loadEvents();this.showFeedback();this.id=($type=='feedback')?'feedback-edit-window':'services-edit-window';return false;},loadEvents:function()
{var _self=this;},showFeedback:function()
{var _self=this;if(this.params.order){var $url="/"+this.type+"/load/makeorder";this.params.type=this.type;$urlParams=this.params;}
else{var $url="/mailer/getform";var $urlParams={'type':this.type}}
$.fancybox.showActivity();$.post($url,$urlParams,function(data){try{if($(data).closest('section.window').length>0){$(_self.windowId).addClass(_self.type);Popup.showDialog(data);_self.submitFeedback($('#'+_self.type+'-order-form'));}
else{throw new Error(view.translate('Ошибка при загрузке формы'));}}
catch(e){Notifier.showError(e);}});return false;},submitFeedback:function(el)
{var _self=this;el.validate({submitHandler:function(form){Notifier.showIndicator(_self.id);$(form).ajaxSubmit({dataType:'json',success:function(result,b,c){try{if(result!=undefined&&result.success==true){Notifier.showMessage(view.translate(view.translate('Письмо успешно отправлено!')),'#'+_self.id+' #windowContent');Popup.closeDialog();}
else{Notifier.hideIndicator(_self.id);Notifier.showError(view.translate(view.translate('Ошибка при отправке письма!')),'#'+_self.id+' #windowContent');}}
catch(e){Notifier.showError(e);}}});},focusInvalid:false,focusCleanup:false,rules:_self.feedbackRules(),messages:_self.feedbackErrors()});return true;},feedbackRules:function()
{var $rules={content:{required:true,maxlength:1000},fio:{required:true,maxlength:100},email:{required:true,maxlength:50,email:true},phone:{required:true,maxlength:40}}
switch(this.type){case'services-order':$rules.serviceName={required:true}
break;}
return $rules;},feedbackErrors:function()
{var $messages={content:{maxlength:view.translate('Введено больше символов'),required:view.translate('Обязательное поле')},fio:{maxlength:view.translate('Введено больше символов'),required:view.translate('Обязательное поле')},email:{maxlength:view.translate('Введено больше символов'),required:view.translate('Обязательное поле'),email:view.translate('Неверный формат почты')},phone:{maxlength:view.translate(view.translate('Введено больше символов')),required:view.translate(view.translate('Обязательное поле'))}}
switch(this.type){case'services-order':$messages.serviceName={required:view.translate('Выберите услугу')}
break;}
return $messages;}}
function showThumb(data){if(data[0]){var id_img=".vimeo-"+data[0].id;$(id_img).each(function(){$(this).attr('src',data[0].thumbnail_medium);});}}
function vimeoLoadingThumb(id){var url="http://vimeo.com/api/v2/video/"+id+".json?callback=showThumb";var id_img=".vimeo-"+id;$(id_img).each(function(){$(this).before('<script type="text/javascript" src="'+url+'"></script>');});}
$(document).ready(function(){Visitor.init();Tooltip.init();});

view={translate:function(txt){var lang=$('#top-body').data('lang');if(lang!='ru'&&txt!=undefined&&txt!=''&&window.Translate!=undefined){return Translate[txt]||txt;}else{return txt;}}}

var Cart=function(){this.blockId='products';this.blockLeft='products-cart-left';this.orderBtn=$('#products .order-btn');this.orderForm='#product-order-form';this.pushUrl="/"+this.blockId+"/load/pushtocart";this.updateUrl="/"+this.blockId+"/load/updatecart";this.loadEvents();}
$.extend(Cart.prototype,{loadEvents:function(){var _self=this;this.orderBtn.live('click',function(){return _self.addToCart(this,false);});$('#'+this.blockId+' .product-item .cart-btn').live('click',function(){return _self.addToCart(this,true);});$('.cart-item .delete').live('click',function(){return _self.update(this,'delete');});$('#view-cart .delete-item').live('click',function(){return _self.update(this,'delete',true);});$('#'+this.blockLeft+' .num-items').live('change',function(){return _self.update(this);});$('#view-cart tr:not(.deleted-item) .num-items').live('change',function(){return _self.update(this,'update',true);});$('#view-cart .restore-item').live('click',function(){return _self.restoreItem(this);});$('#user-info .order-btn').live('click',function(){$('#product-order-form').submit();});_self.submitOrderForm();},addToCart:function(btn,isSimle){var item=(isSimle==true)?$(btn).parents('.product-item'):$(btn).parents('.item-content');if(item.length>0){var itemId=$(item).attr('id').replace('item','')||0;var shownotice=(isSimle)?undefined:btn;this.push({'itemId':itemId,'num':1,'getcart':1,'button':shownotice});}
return false;},push:function(params){var _self=this;if(params!=undefined){$.post(_self.pushUrl,{'cid':params.itemId,'num':params.num,'getcart':params.getcart||0},function(result){try{if(result!=undefined&&result.success==true){if(result.cart!=undefined){if($('#'+_self.blockLeft).length>0){$('#'+_self.blockLeft).html($(result.cart).html());}else{$(result.cart).insertBefore('#main-menu');}}
if(params.action=='restore'){_self.markItem(params.itemId,true);}
if(params.button!=undefined){Notifier.showNotice(params.button,view.translate('Товар добавлен'));}}else{var msg=(result.msg!=undefined)?result.msg:'Произошла ошибка, попробуйте  позже';throw new Error(msg);}}
catch(e){Notifier.showError(e.message,$('#'+_self.blockId+'-show'));}},'json');}
return false;},update:function(btn,act,isCartInner){var _self=this;var action=act||'update';var isInner=isCartInner||false;var itemId=(isInner)?$(btn).parents('tr').eq(0).attr('id').replace('item',''):$(btn).parents('.cart-item').eq(0).data('cid');if(itemId!=undefined){var params={'cid':itemId,'act':action}
if(action=='update'){var numItems=parseInt($(btn).val());if(isNaN(numItems)){return false;}
if(numItems==0){params.act='delete';}else{$.extend(params,{'num':numItems});}}
$.post(_self.updateUrl,params,function(result){try{if(result!=undefined&&result.success==true){switch(action){case'update':if(numItems==0){if(isInner){_self.markItem(params.cid);}else{_self.removeItem(params.cid);}}
break;case'delete':if(isInner){_self.markItem(params.cid);}else{_self.removeItem(params.cid);}
break;}}else{throw new Error(view.translate('Произошла ошибка, попробуйте  позже'));}}
catch(e){Notifier.showError(e.message,$('#'+_self.blockLeft+'-show'));}},'json');}
return false;},removeItem:function(itemId)
{$('#cid'+itemId).remove();if($('#'+this.blockLeft+' .cart-item').length==0){$('#'+this.blockLeft).remove();}},markItem:function(itemID,isRestore){if(itemID!=undefined){var restore=isRestore||false;if(restore){var btnClass='delete-item';var itemClass='';}else{var btnClass='restore-item';var itemClass='deleted-item';}
$('#item'+itemID+' .cart-manage span').attr('class',btnClass);$('#item'+itemID).attr('class',itemClass);}
return false;},restoreItem:function(btn)
{var item=$(btn).parents('tr.deleted-item').eq(0);if(item.length>0){var itemID=item.attr('id').replace('item','');var num=parseInt($('#item'+itemID+' .num-items').val());if(num==0){var num=1;$('#item'+itemID+' .num-items').val(1);}
this.push({'itemId':itemID,'num':num,'action':'restore'});}
return false;},submitOrderForm:function(){var _self=this;$(this.orderForm).validate({submitHandler:function(form){Notifier.showIndicator('user-info',false);$(form).ajaxSubmit({dataType:'json',success:function(result,b,c){Notifier.hideIndicator('user-info',false);try{if(result!=undefined&&result.success==true){var notice=$('#view-cart-show .notice.success');$('#user-info').remove();$('#view-cart-show').html(notice);$('#view-cart-show').find('.notice.success').fadeIn(200);}
else{Notifier.showError(view.translate('Ошибка при отправке заказа!'),_self.orderForm);}}
catch(e){Notifier.showError(e);}}});},focusInvalid:false,focusCleanup:false,rules:{comment:{maxlength:1000},fio:{required:true,maxlength:50},email:{required:true,maxlength:40,email:true},phone:{required:true,maxlength:40}},messages:{comment:{maxlength:view.translate('Введено больше символов')},fio:{maxlength:view.translate('Введено больше символов'),required:view.translate('Обязательное поле')},email:{maxlength:view.translate('Введено больше символов'),required:view.translate('Обязательное поле'),email:view.translate('Неверный формат почты')},phone:{maxlength:view.translate('Введено больше символов'),required:view.translate('Обязательное поле')}}});}});$('document').ready(function(){var cart=new Cart();});

var Comments=function(){this.init();}
Comments.prototype={init:function(){this.type=$('#comment_wrap').attr('class');this.object=$('#comment_wrap .comment').attr('id');this.page=2;this.loadEvents();},loadEvents:function()
{var _self=this;$('#comment_wrap .addcomment').click(function(){_self.loadForm($(this));return false;});$('#comment_wrap .removecomment').click(function(){_self.removeComment($(this));return false;});$('#comment_wrap .editcomment').click(function(){_self.editComment($(this));return false;});if($('#comment_wrap').length!=0&&$('#comment_wrap .not_scroll').length==0){_self.infiniteScroll();}},infiniteScroll:function(){var _self=this;$('.end_comments').endlessScroll({fireOnce:false,fireDelay:10,loader:"<img id='loader' src='/img/lazyload.gif'>",url:"/comment/load/getcomments/",toElement:true,params:{type:_self.type,object:_self.object,page:_self.page},success:function(data,options){if(data.success){options.params.page++;if(!data.next_page){options.disable=true;$('#comment_wrap .is_scroll').replaceWith('<h2 class="not_scroll">Комментарии</h2>');}
else{$('#comment_wrap .is_scroll .per_page').html(data.count);}
return data.output;}
return false;},insertAfter:"#all-comments div.comment_wrap:last",callback:function(){_self.reloadEvents();}});},reloadEvents:function(){var _self=this;$('#comment_wrap .removecomment').unbind('click');$('#comment_wrap .editcomment').unbind('click');$('#comment_wrap .removecomment').click(function(){_self.removeComment($(this));return false;});$('#comment_wrap .editcomment').click(function(){_self.editComment($(this));return false;});},editComment:function(link){var _self=this;$('#form_wrap #comment_form').hide();$('.comment_wrap #comment_form').remove();$('.comment_wrap .item').show();var comment=link.attr('id').replace('edit-','');var cmnt=$('.comment_wrap #item-'+comment)
cmnt.hide();var container=cmnt.parent();var loader=Notifier.getLoader();container.append(loader);$.post('/comment/load/geteditform',{comment:comment},function(data){if(data.success){container.find('#ajax-loader').remove();form=container.append(data.form);$('#all-comments .cancel').click(function(){$('.comment_wrap .item').show();$('#all-comments #comment_form').remove();});_self.validateForm($('#all-comments #comment_form'));}else{container.find('#ajax-loader').remove();cmnt.show();Notifier.showError(view.translate('Произошла ошибка'));}},'json');},loadForm:function(link)
{var _self=this;var loader=Notifier.getLoader();$('#form_wrap').html(loader);$('.comment_wrap #comment_form').remove();$('.comment_wrap .item').show();$.post('/comment/load/getform',{type:_self.type,object:_self.object},function(data){if(data.success){$('.comment_wrap #comment_form').remove();$('#form_wrap').html(data.form);var form=$('#comment_form');$('#comment_form #reload').click(function(){_self.reloadCaptcha();});link.unbind('click');link.click(function()
{$('.comment_wrap #comment_form').remove();$('.comment_wrap .item').show();if($('#comment_form').is(':hidden')){_self.reloadCaptcha();form.show();}
else
form.hide();});_self.validateForm(form);}
else
{$('#form_wrap').html('');Notifier.showError(view.translate('Произошла ошибка'));}},'json');},validateForm:function(form)
{var _self=this;$(form).validate({highlight:function(element,errorClass){$(element).addClass(errorClass);},unhighlight:function(element,errorClass){$(element).removeClass(errorClass).next('.errors');},showErrors:function(errorMap,errorList){$('#comment_form .errors').remove();$('#comment_form .error').removeClass('error');for(var i=0;i<errorList.length;i++){err=errorList[i];el=$(err.element);messageBlock=$('<ul class="errors">');messageBlock.append($('<li>').text(err.message));if(el.hasClass('cleditor')){messageBlock.insertAfter(el.parents('.cleditorMain').find('iframe'));}else{messageBlock.insertAfter(el);}
this.settings.highlight.call(this,err.element,'error');}},submitHandler:function(form){$(form).ajaxSubmit({dataType:'json',success:function(result,b,c)
{Notifier.hideIndicator('comment_wrap',false);$('#comment_form').hide();if(result.success)
{if(result.isNew)
{$('#all-comments').prepend(result.comment);$('#form_wrap #name').val('');$('#form_wrap #comment').val('');$('#form_wrap #captcha-input').val('');if($('#comment_wrap .no-comments').length!=0)
{$('#comment_wrap .no-comments').replaceWith('<h2 class="not_scroll">Комментарии</h2>');$('#comment_wrap .bold_sep').html('<hr/>');}
else if($('#comment_wrap .is_scroll').length!=0){var oPer_page=$('#comment_wrap .is_scroll .per_page');var oTotal=$('#comment_wrap .is_scroll .total');var count=parseInt(oPer_page.text())+1;var total=parseInt(oTotal.text())+1;oTotal.html(total);oPer_page.html(count);}}
else
{$('#all-comments #item-'+result.item).parent().replaceWith(result.comment);}
_self.reloadEvents();}
else{if(result.captchaFaild){_self.reloadCaptcha();$('#form_wrap #ajax-loader').remove();$('#form_wrap #captcha-input').val('').addClass('error');$('#form_wrap #captcha-element').append('<ul class="errors"><li>Неверно введены символы, указанные на картинке.</li></ul>')
$('#form_wrap #comment_form').show();}
else{$('.comment_wrap .item').show();Notifier.showError(view.translate('Произошла ошибка'));}}},beforeSubmit:function(arr,jqForm)
{Notifier.showIndicator('comment_wrap',false);}});return false;},focusInvalid:false,focusCleanup:true,rules:{name:{required:true,maxlength:40},comment:{required:true,maxlength:1024},"captcha[input]":{required:true,minlength:6,maxlength:6}},messages:{name:{required:view.translate('Обязательное поле.'),maxlength:view.translate('Максимальная длина')+' 40 '+view.translate('символов')},comment:{required:view.translate('Обязательное поле.'),maxlength:view.translate('Максимальная длина')+' 1024 '+view.translate('символов')},"captcha[input]":{required:view.translate('Обязательное поле.'),maxlength:view.translate('Введено не')+' 6 '+view.translate('символов'),minlength:view.translate('Введено не')+' 6 '+view.translate('символов')}}});},reloadCaptcha:function(){$.post('/comment/load/captcha',function(data){if(data.success)
{$('#comment_form #captcha-element img').attr('src',data.image);$('#comment_form #captcha-id').val(data.captcha);}
else{Notifier.showError(view.translate('Произошла ошибка'));}},'json');},removeComment:function(link){$('#form_wrap #comment_form').hide();$('.comment_wrap #comment_form').remove();$('.comment_wrap .item').show();var cmnt_id=link.attr('id').replace('delete-','');var cmnt=$('.comment_wrap #item-'+cmnt_id);var cmnt_parent=cmnt.parent();cmnt.hide();cmnt_parent.append(Notifier.getLoader());if(confirm(view.translate('Вы уверены, что хотите удалить?'))){$.post('/comment/remove',{comment:cmnt_id},function(data){if(data.success){cmnt_parent.remove();if($('#comment_wrap .is_scroll').length!=0){var oPer_page=$('#comment_wrap .is_scroll .per_page');var oTotal=$('#comment_wrap .is_scroll .total');var count=parseInt(oPer_page.text())-1;var total=parseInt(oTotal.text())-1;oTotal.html(total);oPer_page.html(count);}else if($('#comment_wrap .not_scroll').length!=0){if($('#all-comments .comment_wrap').length==0){$('#comment_wrap .bold_sep').html('');$('#comment_wrap .not_scroll').replaceWith('<h2 class="no-comments">Нет комментариев</h2>');}}}
else{cmnt.show();cmnt_parent.find('#ajax-loader').remove();Notifier.showError(view.translate('Произошла ошибка'));}},'json');}else{cmnt.show();cmnt_parent.find('#ajax-loader').remove();}}}
$('document').ready(function()
{if($('#comment_wrap').length!=0){Comments=new Comments();}});

