$(function(){
	
	/*
	 * 
	 *   LOCATION CHANGE
	 * 
	 */
	
	if ( $('#location').length != 0 ) {
		
		
		(function(){
			
			// VARS
			
			var locationBtn = $('#location .btn');
			
			//
			
			locationBtn.click(
					
					function (e) {
						
						e.stopPropagation();
						e.preventDefault();
						
						$(this).parent('#location').toggleClass('collapsed');
						return false;
					}
					
			);
			
		})();
		
	}
	
	$(document).ready(function () {
  		$('#location li a').click(function(){
  			 if($(this).attr("href") == "#") {
	  			 $.post('/region/setregion/', {region : $(this).attr('region_id')}, function(response) {
	             	if(response.success && response.redirect) {
	             		location = response.redirect;
	             	}
	             	if(response.success)
	             		location.reload();
	             	
	        	}, 'json');
	  			 return false;
  			 }
  		});
	});
	
	/*
	 * 
	 *   ACCOUNT
	 * 
	 */
	
	if ( $('#account').length != 0 ) {
		
		
		(function(){
			
			// VARS
			
			var loginBtn = $('#account .login'),
				logoutBtn = $('#account .logout'),
				user = $('#account .user'),
				submit = $('#account .submit'),
				windowLogin = $('#account .window'),
				closeWindow = $('#account .window .close'),
				account = $('#account');
			
			//
			
			loginBtn.click(
					
					function (e) {
						
						e.stopPropagation();
						e.preventDefault();
						
						windowLogin.toggleClass('hidden');
						
						
					}
					
			);
			
			submit.click(
					
				function (e) {
						
					e.stopPropagation();
					e.preventDefault();
						
				    $.post('/user/login/', {is_auth: 1, user_login: $("#login").val(), user_password: $("#password").val()}, function(data) {
				    	$('.e', account).remove();
				    	if (data.user) {
				    		_gaq.push(['_trackPageview', '/virtual/auth']); 
				    		yaCounter731958.reachGoal('virtual/auth');
				    		switch (region_idx) {
				    			case 3:  yaCounter748903.reachGoal('virtual/auth');break;
				    			case 10: yaCounter748919.reachGoal('virtual/auth');break;
				    			case 6:  yaCounter918223.reachGoal('virtual/auth');break;
				    			case 11: yaCounter918215.reachGoal('virtual/auth');break;
				    			case 14: yaCounter1402997.reachGoal('virtual/auth');break;
				    			case 16: yaCounter4485682.reachGoal('virtual/auth');break;
				    			case 4:  yaCounter1278991.reachGoal('virtual/auth');break;
				    			case 7:  yaCounter918217.reachGoal('virtual/auth');break;
				    			case 8:  yaCounter918221.reachGoal('virtual/auth');break;
				    			case 9:  yaCounter1278989.reachGoal('virtual/auth');break;
				    			case 17: yaCounter1278987.reachGoal('virtual/auth');break;
				    			case 12: yaCounter1278983.reachGoal('virtual/auth');break;
				    			case 13: yaCounter1278985.reachGoal('virtual/auth');break;
				    			case 1:  yaCounter11349188.reachGoal('virtual/auth');break;
				    			case 2:  yaCounter11350345.reachGoal('virtual/auth');break;
				    			case 5:  yaCounter11350372.reachGoal('virtual/auth');break;
				    		}
				    		account.html(data.user);
				        } else {
					        $.map(data.errors, function(i){
					          $('<div class="e"/>').text(i.error).prependTo($('#account'));
					          $('.e').fadeIn('slow', function(){
					        	  var self = this;
					        	  function fadeBack() {
					        		  $(self).fadeOut('slow')
					        	  }
					        	  setTimeout(fadeBack, 1000) });
					        });
					      }
					}, 'json');
				}
		
			);
			
			closeWindow.click(
					
					function (e) {
						
						e.stopPropagation();
						e.preventDefault();
						
						windowLogin.toggleClass('hidden');
						
					}
			
			);
			/*
			logoutBtn.click(
					
					function (e) {
						
						e.stopPropagation();
						e.preventDefault();
						
						user.toggleClass('hidden');
						loginBtn.toggleClass('hidden');
						
					}
			
			);
			*/
			$('#login, #password')
					.click(function(){
				if($(this).val() == $(this).attr("def")) $(this).val('');
			})
					.blur(function(){
				if($(this).val() == '') $(this).val($(this).attr("def"));
			});
			
		})();
		
	}
	
	/*
	 * 
	 *   BASKET
	 * 
	 */
	
	setBasketButton();
	
	
	/*
	 * 
	 *   SLIDER
	 * 
	 */
	
	if ($('#slider').length != 0) {
		
		
		(function(){
			
			
			// VARS
			
			var slider = $('#slider'),
				container = slider.find('.container'),
				containerItem = slider.find('.container li'),
				step = parseInt(slider.find('.container li').width()),
				prevBtn = slider.find('.nav .prev'),
				currentBtn = slider.find('.nav .current'),
				nextBtn = slider.find('.nav .next'),
				prevSpans = slider.find('.nav .prev span'),
				currentSpans = slider.find('.nav .current span'),
				nextSpans = slider.find('.nav .next span'),
				currentStep = 1,
				maxStep = 0,
				prevArrow = slider.find('.prev-arrow'),
				nextArrow = slider.find('.next-arrow');

			// INIT

			(

				function() {
					
					container.append(containerItem.first().clone());
					container.prepend(containerItem.last().clone());
					maxStep = parseInt(slider.find('.container li').length);
					container.css({'left':-step,'width':maxStep*parseInt(containerItem.css('width'))});
					setHeaders();
				}

			)();
			
			// 	METHODS
			
			function prev() {

				if (currentStep>1) {
					
					currentStep -= 1;
					container.animate({'left':-(step*currentStep)}, 300);
					setHeaders();

				} else if(currentStep==1) {

					currentStep -= 1;
					container.animate({'left':-(step*currentStep)}, 300, function() {
						
						currentStep = maxStep-2;
						container.css({'left':-(step*(currentStep))});
						setHeaders();

					});

				}
				
			};
			
			function next() {

				if (currentStep<maxStep-2) {
					
					currentStep += 1;
					container.animate({'left':-(step*currentStep)}, 300);
					setHeaders();

				} else if(currentStep==maxStep-2) {
					
					currentStep += 1;
					container.animate({'left':-(step*currentStep)}, 300, function() {
						
						currentStep = 1;
						container.css({'left':-(step*(currentStep))});
						setHeaders();

					});

				}
				
			};
			
			function setHeaders() {

				prevSpans.each(

					function() {

						var index = currentStep - 2;

						if (index===-1) {
							
							index = maxStep-3;

						}

						if ($(this).index() == index) {
							
							$(this).removeClass('hidden');

						} else {
							
							$(this).addClass('hidden');

						}

					}

				);

				currentSpans.each(

					function() {

						var index = currentStep - 1;

						if ($(this).index() == index) {
							
							$(this).removeClass('hidden');

						} else {
							
							$(this).addClass('hidden');

						}

					}

				);

				nextSpans.each(

					function() {

						var index = currentStep;

						if (index===maxStep-2) {
							
							index = 0;

						}
						
						if ($(this).index() == index) {
							
							$(this).removeClass('hidden');

						} else {
							
							$(this).addClass('hidden');

						}

					}

				);

			}

			// HANDLERS

			prevBtn.click(
					
				function(e) {
					
					e.stopPropagation();
					e.preventDefault();
					
					//
					
					prev();
					
				}
					
			);

			prevBtn.hover(

				function() {
					
					prevArrow.css({'background-position':'0 -50px'});

				},

				function() {
					
					prevArrow.css({'background-position':'0 0'});

				}

			);
			
			nextBtn.click(
					
					function(e) {
						
						e.stopPropagation();
						e.preventDefault();
						
						//

						next();
						
					}
					
			);

			nextBtn.hover(

				function() {
					
					nextArrow.css({'background-position':'0 -50px'});

				},

				function() {
					
					nextArrow.css({'background-position':'0 0'});

				}

			);
				
			
		})();
		
	}
	
	/*
	 * 
	 *   ORDER FORM
	 * 
	 */
	
	if ($('.order-form').length != 0) {
			
		(function(){
			
			// VARS
			
			var btnDelivery = $('.btn-delivery'),
				btnSelfDelivery = $('.btn-self-delivery'),
				deliveryCont = $('.delivery-type .delivery'),
				selfDeliveryCont = $('.delivery-type .self-delivery');
			
			//
			
			btnDelivery.click(
					
				function (e) {
					
					e.stopPropagation();
					e.preventDefault();
					
					//
					
					if ( !btnDelivery.hasClass('active') ) {
						
						btnDelivery.addClass('active');
						
					}
					
					if ( btnSelfDelivery.hasClass('active') ) {
						
						btnSelfDelivery.removeClass('active');
						
					}
					
					//
					
					if ( deliveryCont.hasClass('hidden') ) {
						
						deliveryCont.removeClass('hidden');
						
					}
					
					if ( !selfDeliveryCont.hasClass('hidden') ) {
						
						selfDeliveryCont.addClass('hidden');
						
					}
					
				}
			
			);
			
			btnSelfDelivery.click(
					
					function (e) {
						
						e.stopPropagation();
						e.preventDefault();
						
						//
						
						if ( !btnSelfDelivery.hasClass('active') ) {
							
							btnSelfDelivery.addClass('active');
							
						}
						
						if ( btnDelivery.hasClass('active') ) {
							
							btnDelivery.removeClass('active');
							
						}
						
						//
						
						if ( selfDeliveryCont.hasClass('hidden') ) {
							
							selfDeliveryCont.removeClass('hidden');
							
						}
						
						if ( !deliveryCont.hasClass('hidden') ) {
							
							deliveryCont.addClass('hidden');
							
						}
						
						
					}
					
			);
			
		})();

	}

	if ($('.basket-form').length != 0) {
		
		(function(){
			
			// VARS
			
			var btnPhysical = $('.btn-physical'),
				btnJuridical = $('.btn-juridical'),
				physicalCont = $('.user-type .physical'),
				juridicalCont = $('.user-type .juridical');
			
			//
			
			btnPhysical.click(
					
				function (e) {
					
					e.stopPropagation();
					e.preventDefault();
					
					//
					
					if ( !btnPhysical.hasClass('active') ) {
						
						btnPhysical.addClass('active');
						
					}
					
					if ( btnJuridical.hasClass('active') ) {
						
						btnJuridical.removeClass('active');
						
					}
					
					//
					
					if ( physicalCont.hasClass('hidden') ) {
						
						physicalCont.removeClass('hidden');
						
					}
					
					if ( !juridicalCont.hasClass('hidden') ) {
						
						juridicalCont.addClass('hidden');
						
					}
					
				}
			
			);
			
			btnJuridical.click(
					
					function (e) {
						
						e.stopPropagation();
						e.preventDefault();
						
						//
						
						if ( !btnJuridical.hasClass('active') ) {
							
							btnJuridical.addClass('active');
							
						}
						
						if ( btnPhysical.hasClass('active') ) {
							
							btnPhysical.removeClass('active');
							
						}
						
						//
						
						if ( juridicalCont.hasClass('hidden') ) {
							
							juridicalCont.removeClass('hidden');
							
						}
						
						if ( !physicalCont.hasClass('hidden') ) {
							
							physicalCont.addClass('hidden');
							
						}
						
						
					}
					
			);
			
		})();

	}
	
	
	
	/*
	 * 
	 *   GOODS ALL LIST
	 * 
	 */
	
	if ($('#goods-all-list').length != 0) {

		(function(){
			
			// VARS
			
			var goodsBtn = $('#main-nav .btn'),
				goodsList = $('#goods-all-list');
			
			//
			
			goodsBtn.click(
			
					function (e) {
						
						e.stopPropagation();
						e.preventDefault();
						
						//
						
						goodsList.toggleClass('hidden');
						goodsBtn.toggleClass('collapsed');
						
					}
			
			);
			
		})();
		
	}
	
	
	/*
	 * 
	 *   BRANDS
	 * 
	 */
	
	
	if ($('#brands').lenght != 0) {
		
		(function(){
			
			// VARS
			
			var brands = $('#brands'),
				brandsContainer = brands.find('.container'),
				brandsInner = brands.find('.inner'),
				brandsLinks = brands.find('.list a'),
				brandsList = brands.find('.list'),
				brandsBubble = brands.find('#brands-bubble'),
				brandsLi = brands.find('.list>li'),
				brandsImg = brands.find('img'),
				brandsImgMaxWidth = 0,
				isBubbleLeft = false,
				isBrandsInnerLeft = false,
				prevBtn = brands.find('.prev'),
				nextBtn = brands.find('.next'),
				stepSize = 0;
			
			// INIT

			(

				function () {
					
					brandsImg.each(

						function () {

							if (brandsImgMaxWidth<$(this).width()) {
								
								brandsImgMaxWidth = $(this).width();
							}

						}
					);

					brandsLi.each(

						function () {
							
							$(this).width(brandsImgMaxWidth);

						}

					);

					var itemsPerContainer = Math.floor(brandsContainer.width()/brandsImgMaxWidth)-1,
						itemRightPadding = Math.ceil((brandsContainer.width()-(itemsPerContainer*brandsImgMaxWidth))/itemsPerContainer);


					brandsLi.each(

						function () {
							
							var thisLi = $(this);

							$(this).css({'padding-right':itemRightPadding});
							$(this).find('a').css({'margin-top':Math.ceil(($(this).height()-$(this).find('a').height())/2)});

							$(this).find('img').each(

								function () {

									if ($(this).hasClass('over')) {
										
										$(this).css({'left':Math.ceil((thisLi.width()-$(this).width())/2)});

									} else {
										
										$(this).css({'margin-left':Math.ceil((thisLi.width()-$(this).width())/2)});

									}

								}

							);

						}

					);

					stepSize = brandsImgMaxWidth+itemRightPadding;
					brandsList.css({'margin-left':0,'width':(brandsLi.length*(brandsImgMaxWidth+itemRightPadding))})
				}

			)();

			// HANDLERS

			prevBtn.click(

				function (e) {
					
					e.stopPropagation();
					e.preventDefault();

					//

					if ( parseInt(brandsList.css('margin-left')) !== 0 ) {
						
						brandsList.animate({'margin-left':parseInt(brandsList.css('margin-left'))+stepSize},200);

					}

				}

			);

			nextBtn.click(

				function (e) {
					
					e.stopPropagation();
					e.preventDefault();

					//

					if ( (brandsList.width()-brandsContainer.width()-stepSize) > Math.abs(parseInt(brandsList.css('margin-left'))) ) {
						
						brandsList.animate({'margin-left':parseInt(brandsList.css('margin-left'))-stepSize},200);
						
					}
					
				}

			);

			brandsInner.mouseleave(

				function () {

					brandsBubble.addClass('hidden');

				}

			);
			
			brandsLinks.hover(
					
				function() {
					
					var itemOffset = $(this).position();
					
					$(this).find('img.over').css({'visibility':'visible'});
					$(this).find('img.normal').css({'visibility':'hidden'});
					
					brandsBubble.html($('div.content_bubble', $(this).parent()).html());
					
					if (brandsBubble.hasClass('hidden')) {
						
						brandsBubble.removeClass('hidden');
						
					}
					
					brandsBubble.css({'left':itemOffset.left});
					
				},
				
				function() {
					
					$(this).find('img.over').css({'visibility':'hidden'});
					$(this).find('img.normal').css({'visibility':'visible'});
					
				}
			
			
			);
			
		})();
		
	}
	

	
	
	
	/*
	 * 
	 *   HIGHLIGHTS
	 * 
	 */
	
	if ($('#highlights').lenght != 0) {
		
		(function(){
			
			// VARS
			
			var navLinks = $('#highlights .nav a, #item .bottom .nav a'),
				sections = $('#highlights .container > div, #item .bottom .container > div');
			
			//
			
			navLinks.click(
			
					function (e) {
						
						e.stopPropagation();
						e.preventDefault();
						
						var currentLink = $(this).attr('rel').toString();
						
						navLinks.each(
						
								function (e) {
									
									if ( $(this).hasClass(currentLink) ) {
										
										if ( !$(this).hasClass('current') ) {
											
											$(this).addClass('current');
											
										} 
										
									} else {
										
										if ( $(this).hasClass('current') ) {
											
											$(this).removeClass('current');
											
										}
										
									}
									
								}
						
						);
						
						sections.each(
								
								function () {
									
									if ( $(this).hasClass(currentLink) ) {
										
										if ( $(this).hasClass('hidden') ) {
											
											$(this).removeClass('hidden');
											
										}
										
									} else {
										
										if ( !$(this).hasClass('hidden') ) {
											
											$(this).addClass('hidden');
											
										}
										
									}
									
								}
						
						);
						
					}
			
			);
			
		})();
		
	}
	
	
	/*
	 * 
	 *   CATALOGUE
	 * 
	 */
	
	
	if ( $('.cat-sub').length != 0 ) {
		
		(function(){
			
			// VARS
			
			var catSub = $('.cat-sub'),
				catSubMore = $('.cat-sub .more'),
				overflowDefHeight = catSub.find('.overflow').height();
			
			// INIT
			
			$('body').prepend('<div id="page-overlay"></div>');
			
			//
			
			catSub.hover(
					
				function () {
					
					$(this).find('.inner').toggleClass('over');
					
				},
				
				function () {
					
					$(this).find('.inner').toggleClass('over');
					
				}
			
			);
			
			//
			
			catSubMore.click(
					
				function (e) {
					
					e.stopPropagation();
					e.preventDefault();
					var overflowDeffHeight = $(this).prev().attr("height") ? $(this).prev().attr("height") : overflowDefHeight;
					//
					var catSub = $(this).parents('.cat-sub'),
						catSubDefHeight = catSub.height(),
						catSubInner = catSub.find('.inner'),
						thisP = catSub.find('p'),
						pHeight = thisP.height(),
						overFlow = catSub.find('.overflow'),
						overflowHeight = overFlow.height(),
						diffHeight = (pHeight + 5) - overflowHeight,
						moreBtn = catSub.find('.more');

					if (!$(this).parents('.cat-sub').hasClass('active')) {
							
						catSub.addClass('active');
						
						if (diffHeight > 0) {
							
							catSubInner.animate({'height':catSub.height() + diffHeight}, 200);
							overFlow.animate({'height':overFlow.height() + diffHeight}, 200);
							moreBtn.css({'background-position':'left -15px'});
							moreBtn.text('СКРЫТЬ');
						}
						
						$('#page-overlay').css({'display':'block','opacity':'0.5','height':$(document).height(),'width':$(document).width()});

						$('#page-overlay').bind('click', function () {
							
							$(this).unbind('click');
							$(this).css({'display':'none'});
							
							catSub.each(
							
								function () {
									
									if ($(this).hasClass('active')) {
										
										moreBtn.css({'background-position':'left 5px'});
										moreBtn.text('ЕЩЕ...');
										catSubInner.height(catSubDefHeight);
										overFlow.height(overflowHeight);
										$(this).removeClass('active');

									}
									
								}
							
							);
							
						});

					} else {

						$('#page-overlay').unbind('click');
						$('#page-overlay').css({'display':'none'});

						catSub.each(
							
								function () {

									moreBtn.css({'background-position':'left 5px'});
									moreBtn.addClass('more');
									moreBtn.text('ЕЩЕ...');
									catSubInner.height(catSubDefHeight);
									overFlow.height(overflowDeffHeight);
									$(this).removeClass('active');
									
								}
							
							);

					}
					
				}
			
			);
			
			
		})();
		
	};

	/*
	 *
	 *   FOOTER LINKS
	 *
	 */

	 if ($('#footer .ql').length != 0) {
	 	
	 	(

	 		function() {
	 			
	 			// VARS

	 			var ql = $('#footer .ql'),
	 				qlContainer = ql.find('.container'),
	 				qlMore = ql.find('.more'),
	 				qlCont = ql.find('.content');

	 			// INIT

	 			(

	 				function() {
	 					


	 				}

		 		)();

	 			// HANDLERS

	 			qlMore.click(

	 				function(e) {

	 					e.stopPropagation();
	 					e.preventDefault();

	 					//
	 					
	 					if(qlContainer.height()<qlCont.height()) {
	 						
		 					qlContainer.animate({'height':qlCont.height()}, 100, function(){
		 						
		 						qlMore.addClass('hidden');

		 					});

	 					}


	 				}

	 			);

	 		}

		 )();

	 };
	 
	 
	 
	 

	 /*
	  *
	  *  CHECKBOXES
	  *
	  */

	  if ($('img.checkbox').length != 0) {
	  	
	  	(function(){
	  		
	  		// VARS

	  		var imgCheckBox = $('img.checkbox');

	  		// HANDLERS

	  		imgCheckBox.click(function(){

	  			/*var inputCheckBox = $(this).siblings('input');
	  			
	  			$(this).toggleClass('checked');

	  			if (inputCheckBox.attr('checked') == 'checked') {
	  				
	  				inputCheckBox.attr('checked', false);

	  			} else {
	  				
	  				inputCheckBox.attr('checked', true);	  				

	  			}*/
	  			
	  			var inputCheckBox = $(this).siblings('input').first();
	  			
	  			if (inputCheckBox.prop('checked')) {
	  				$(this).removeClass('checked');
	  				inputCheckBox.prop('checked', true);
	  			} else {
	  					
	  				$(this).addClass('checked');
	  				inputCheckBox.prop('checked', false);
	  			}

	  		});

	  	})();

	  };


	  /*
	  *
	  *  PAYMENT RADIOBUTTONS
	  *
	  */

	  if ($('.payment').length != 0) {
	  	
	  	(function(){

	  		// VARS

	  		var imgRadioBTNs = $('.payment img.radiobutton');
	  			inpuRadioBTNs = $('.payment input');

	  		// HANDLERS

	  		imgRadioBTNs.click(function(){
	  			
	  			imgRadioBTNs.removeClass('checked');

	  			$(this).addClass('checked');

	  			inpuRadioBTNs.each(function() {
	  				
	  				if ($(this).siblings('.radiobutton').hasClass('checked')) {
	  					$(this).prop('checked', true);
	  					//$(this).attr('checked', true)

	  				} else {
	  					$(this).prop('checked', false);
	  					//$(this).attr('checked', false)

	  				}

	  			});

	  		});

	  	})();

	  };
	 
	 	 /*
	  *
	  *  ITEM POPUPS
	  *
	  */


	  if ($('.characteristics').length != 0) {
	  	
	  	(function(){
	  		
	  		// VARS

	  		var c = $('.characteristics'),
	  			cLink = c.find('a'),
	  			cPopup = c.find('.popup'),
	  			cClose = c.find('.close');

	  		// HANDLERS

	  		cLink.click(

	  			function (e) {

	  				e.stopPropagation();
 					e.preventDefault();

 					//

 					cPopup.each(

 						function () {
 							
 							if(!$(this).hasClass('hidden')) {
 								
 								$(this).addClass('hidden');

 							}

 						}

 					);

 					//
	  				
	  				$(this).siblings('.pp').find('.popup').toggleClass('hidden');

	  			}

	  		);

	  		cClose.click(

	  			function (e) {
	  				
	  				e.stopPropagation();
 					e.preventDefault();

 					//

 					if(!$(this).hasClass('hidden')) {
 						
 						$(this).parents('.popup').addClass('hidden');	

 					}
 					
	  			}

	  		);


	  	})();

	  };

	/*
	 *
	 *  FEEDBACK
	 *
	 */

	 if ($('#feedback').length != 0) {
	 	
	 	(function(){
	 		
	 		// VARS

	 		var fb = $('#feedback'),
	 			close = fb.find('.close');

	 		// HANDLERS

	 		close.click(

	 			function(){
	 				
	 				fb.toggleClass('hidden');

	 			}

	 		);

	 	})();

	 };

	 /*
	  *
	  *  GALLERY POPUP
	  *
	  */

	  if ($('#gallery-popup').length!=0) {
		  
		function _checkExternalClick(event) {
			if ($('#gallery-popup').hasClass('hidden')) {
				return;
			}
			var target = $(event.target);
			if (!target.parents().andSelf().hasClass('gallery-popup')) {
				$('#gallery-popup').addClass('hidden');
			}
		}



		$(function() {
			$(document).mousedown(_checkExternalClick)
		});
	  	
	  	(function(){
	  		
	  		// VARS

	  		var invokeBtn = $('.gallery .magnify'),
	  			gal = $('#gallery-popup'),
	  			close = gal.find('.close'),
	  			imgCont = gal.find('.img'),
	  			imgContW = imgCont.width(),
	  			imgContH = imgCont.height(),
	  			imgs = gal.find('.img img'),
	  			prev = gal.find('.prev'),
	  			next = gal.find('.next'),
	  			thumbs = gal.find('.thumbs li'),
	  			thumbsLink = gal.find('.thumbs li a');

	  		// FUNCTIONS

	  		var nextImg = function () {

	  			
	  			if (gal.find('.img img.visible').next().length!=0) {
	  				
	  				gal.find('.img img.visible').removeClass('visible').next().addClass('visible');

	  			} else {
	  				
	  				gal.find('.img img.visible').removeClass('visible');
	  				gal.find('.img img:first').addClass('visible');

	  			}

	  			thumbs.each(function(){

	  				if ($(this).index() == gal.find('.img img.visible').index()) {
	  					
	  					$(this).find('a').addClass('current');

	  				} else {
	  					
	  					$(this).find('a').removeClass('current');
	  				}

	  			});

	  		};

	  		var prevImg = function () {
	  			
	  			if (gal.find('.img img.visible').prev().length!=0) {
	  				
	  				gal.find('.img img.visible').removeClass('visible').prev().addClass('visible');

	  			} else {
	  				
	  				gal.find('.img img.visible').removeClass('visible');
	  				gal.find('.img img:last').addClass('visible');

	  			}

	  			thumbs.each(function(){

	  				if ($(this).index() == gal.find('.img img.visible').index()) {
	  					
	  					$(this).find('a').addClass('current');

	  				} else {
	  					
	  					$(this).find('a').removeClass('current');
	  				}

	  			});


	  		};

	  		// HANDLERS

	  		invokeBtn.click(function(e){
	  			
	  			e.stopPropagation();
				e.preventDefault();

				//

				gal.removeClass('hidden');

				//

				(function(){
	  			
		  			imgs.each(function(){
		  				
		  				var top = (imgContH/2)-($(this).height()/2),
		  					left = (imgContW/2)-($(this).width()/2);

		  				$(this).css({'top':top,'left':left});

		  			});

		  		})();

	  		});

	  		close.click(function(e){

	  			e.stopPropagation();
				e.preventDefault();

				//
	  			
	  			gal.addClass('hidden');

	  		});

	  		imgCont.click(nextImg);

	  		next.click(function(e){
	  			
	  			e.stopPropagation();
				e.preventDefault();

				//

				nextImg();

	  		});

	  		prev.click(function(e){
	  			
	  			e.stopPropagation();
				e.preventDefault();

				//

				prevImg();

	  		});

	  		thumbsLink.click(function(e){

	  			var thisI = $(this).parent().index();

	  			//
	  			
	  			e.stopPropagation();
				e.preventDefault();

				//

				thumbs.each(function(){
	  				
	  				$(this).find('a').removeClass('current');

	  			});

	  			$(this).addClass('current');


	  			//

	  			imgs.each(function(){
	  				
	  				if ($(this).index()==thisI) {
	  					
	  					$(this).addClass('visible');

	  				} else {
	  					
	  					$(this).removeClass('visible');

	  				}

	  			});



	  		});	

	  	})();

	  };
	  
	  
	  /*
	   	*
	   	*  COMPARE
	   	*
	   	*/

	   	if ($('#compare').length!=0) {
	   		
	   		(function(){
	   			
	   			// VARS

	   			var c = $('#compare'),
	   				container = c.find('.container'),
	   				params = c.find('.params'),
	   				mask = c.find('.mask'),
	   				items = c.find('.container > li'),
	   				paramsColumn = c.find('.params ul'),
	   				itemsColumns = c.find('ul.item'),
	   				nextBtn = c.find('.next-arrow'),
	   				prevBtn = c.find('.prev-arrow'),
	   				step = items.width(),
	   				posStart = 0,
	   				itemVisAtOnce = 3,
	   				posEnd = -((items.length*items.width())-(itemVisAtOnce*items.width())),
	   				maxHeights = [],
	   				deleteSingle = c.find('.item .delete'),
	   				deleteAll = c.find('.column-head .delete');

	   			// INIT

	   			(function(){
	   				
	   				calcHeights();

	   			})();

	   			// 	METHODS

	   			function calcHeights(){
	   				

	   				var itemsNow = c.find('.container > li');

	   				paramsColumn.find('li').each(

	   					function(i){

	   						if(!$(this).hasClass('column-head')){
	   						
	   							maxHeights[i-1] = $(this).outerHeight();

	   						}

	   					}

	   				);

	   				itemsColumns.each(

	   					function(){
	   						
	   						$(this).find('li').each(

	   							function(i){
	   								

	   								if(!$(this).hasClass('item-head')) {
	   									
	   									if ($(this).outerHeight() > maxHeights[i-1]) {
	   										
	   										maxHeights[i-1] = $(this).outerHeight();

	   									}

	   								}

	   							}

	   						);

	   					}

	   				);

	   				paramsColumn.find('li').each(

	   					function(i){

	   						if(!$(this).hasClass('column-head')){
	   						
	   							$(this).height(maxHeights[i-1]-20);

	   						}

	   					}

	   				);

	   				itemsColumns.each(

	   					function(){
	   						
	   						$(this).find('li').each(

	   							function(i){

	   								if(!$(this).hasClass('item-head')) {
	   									
	   									//if ($(this).outerHeight() < maxHeights[i-1]) {
	   										
	   										$(this).height(maxHeights[i-1]-20);

	   									//}

	   								}

	   							}

	   						);

	   					}

	   				);

	   				// ETC

	   				container.width(itemsNow.length*itemsNow.width());
	   				posEnd = -((itemsNow.length*itemsNow.width())-(3*itemsNow.width()))

	   				if(parseInt(container.css('margin-left'))<0){

						container.animate({'margin-left':posEnd}, 300);

					}

					if(itemsNow.length>itemVisAtOnce) {
						
						nextBtn.removeClass('hidden');
						prevBtn.removeClass('hidden');

					} else {
						
						nextBtn.addClass('hidden');
						prevBtn.addClass('hidden');

					}

	   				mask.height(params.height());

	   				c.find('ul.item').removeClass('light-gray').filter(":even").addClass('light-gray');

	   			}

	   			var nextItem = function(){

	   				var marginLeft = parseInt(container.css('margin-left'));

	   				if(marginLeft>posEnd){

						container.animate({'margin-left':marginLeft-step}, 300);

					}

	   			}

	   			var prevItem = function(){

	   				var marginLeft = parseInt(container.css('margin-left'));

	   				if(marginLeft<posStart){
	   				
	   					container.animate({'margin-left':marginLeft+step}, 300);

	   				}

	   			}

	   			// HANDLERS

	   			nextBtn.click(nextItem);

	   			prevBtn.click(prevItem);

	   			deleteSingle.click(

	   				function(e){
	   					
	   					e.preventDefault();
	   					e.stopPropagation();

	   					//

	   					$(this).parents('.item').parent().remove();
	   					
	   					$.post($(this).attr('href'));

	   					calcHeights();
	   				}

	   			);

	   			
	   			deleteAll.click(

		   				function(e){
		   					
		   					e.preventDefault();
		   					e.stopPropagation();

		   					//

		   					$('#compare, #content .compare-nav a.selected').remove();
								
							$.post($(this).attr('href'));

		   					calcHeights();
		   				}

		   			);
	   			/*
	   			deleteAll.click(

	   				function(e){
	   					
	   					e.preventDefault();
	   					e.stopPropagation();

	   					//

	   					$('.container > li').remove();

	   					calcHeights();
	   				}

	   			);
	   			*/

	   		})();

	   	};
	  
	  
	 /*  */
	$("#tip_main, #tip_main2").each(function() {
		var $cnt = $(this);
		
		var maxHeight = 100;
		$cnt.find('.tip_main').each(function() {
			maxHeight = Math.max(maxHeight, $(this).height());
		});
		$cnt.find(".tips_mask").height(maxHeight);
		var tips_count = parseInt($cnt.find(".tips_mask_absolute .tip_main").length);
		var tips_step = parseInt($cnt.find(".tips_mask_absolute .tip_main").css('width'));
		$cnt.find(".tips_mask_absolute").css({'width':tips_count*tips_step});
		
		if ($cnt.find('.tip_main').length > 1) {
			$cnt.find(".next").click(function() {
				$cnt.find(".tips_mask_absolute").animate({'left':-(tips_step)}, 300, function() {
					$cnt.find('.tips_mask_absolute .tip_main:last').after(
							$cnt.find('.tips_mask_absolute .tip_main:first')
					);
					$cnt.find(".tips_mask_absolute").css({'left':0});
				});
				return false;
			});
			$cnt.find(".prev").click(function(){
				$cnt.find('.tips_mask_absolute .tip_main:first').before(
					$cnt.find('.tips_mask_absolute .tip_main:last')
				);
				$cnt.find(".tips_mask_absolute").css({'left':-(tips_step)});
				$cnt.find(".tips_mask_absolute").animate({'left':0}, 300);
				return false;
			});
		}
	});
	 
	 $('.c_input_text')
	 			.focus(function() {
		    		if ($(this).val() == $(this).attr('_value')) $(this).val('');
				}).blur(function() {
					if ($(this).val() == '') $(this).val($(this).attr('_value'));
				});
	 
	 
	$('#call_manager').click(function(){
		return getForm(1);
	});
	
	/* Services */
	
	$('.services_more a').click(function(){
		$('.services_extra_list').show();
		$('.services_more').hide();
		$('.services_less').show();
		return false;
	});
	
	$('.services_less a').click(function(){
		$('.services_extra_list').hide();
		$('.services_less').hide();
		$('.services_more').show();
		return false;
	});
	
	$('#services_form .btn').click(function() {
		var obj = this;
        var options = {
        		service_id: $('#services_form input[name="service"]:checked').val(),
        		cat_id:	$('#services_form').attr("cat")
        };
        $.post('/basket/ajaxServiceAdd/', options, function(responseText) {
        	//обновляем корзину
            $('#basket').html(responseText.basket_info_html);
            $('#service_list').html(responseText.service_list);
            if( $('.services_less').is(':visible') ) {
            	$('.services_extra_list').show();
            }
        }, 'json');
        return false;
     });
	
});

function getForm(form_id) {
	$.post('/form/getForm/', {form_id: form_id}, function(data) {
		if(data.head && data.body && data.image) {
			$('#feedback .form_content').html(data.head+data.body);
			if($('#feedback .image_button').length) {
				$('#feedback .image_button').attr("src", data.image);
			} else {
				$('<img src="'+data.image+'" class="image_button"/>').insertAfter('#feedback .form_content');
				$('#feedback .image_button').click(function(){ 
					var t = $(this).parent();
					$.post('/form/submitForm/', t.serializeArray(), function(data) {
						$('.e', t).remove();
						if (data.done) {
							_gaq.push(['_trackPageview', '/virtual/callback']); 
				    		yaCounter731958.reachGoal('virtual/callback');
				    		switch (region_idx) {
				    			case 3:  yaCounter748903.reachGoal('virtual/callback');break;
				    			case 10: yaCounter748919.reachGoal('virtual/callback');break;
				    			case 6:  yaCounter918223.reachGoal('virtual/callback');break;
				    			case 11: yaCounter918215.reachGoal('virtual/callback');break;
				    			case 14: yaCounter1402997.reachGoal('virtual/callback');break;
				    			case 16: yaCounter4485682.reachGoal('virtual/callback');break;
				    			case 4:  yaCounter1278991.reachGoal('virtual/callback');break;
				    			case 7:  yaCounter918217.reachGoal('virtual/callback');break;
				    			case 8:  yaCounter918221.reachGoal('virtual/callback');break;
				    			case 9:  yaCounter1278989.reachGoal('virtual/callback');break;
				    			case 17: yaCounter1278987.reachGoal('virtual/callback');break;
				    			case 12: yaCounter1278983.reachGoal('virtual/callback');break;
				    			case 13: yaCounter1278985.reachGoal('virtual/callback');break;
				    			case 1:  yaCounter11349188.reachGoal('virtual/callback');break;
				    			case 2:  yaCounter11350345.reachGoal('virtual/callback');break;
				    			case 5:  yaCounter11350372.reachGoal('virtual/callback');break;
				    		}
							
							$('#feedback .image_button').remove();
							$('.form_content').html('<div class="success_message">Ваше сообщение отправлено</div>');
							setTimeout(function(){$('#feedback .close').click();}, 2500);
					    } else {
					    	$.map(data.errors, function(i){
					    		$('<div class="e"/>').text(i.error).insertBefore($('*[name="form_element[' + i.id + ']"]', t));
					        });
					    }
					}, 'json');
				});
			}
			$('#feedback').removeClass('hidden');
			$.scrollTo($('#feedback'), 800);
		}
	}, 'json');
	return false;
}

function setBasketButton(){
		
		// VARS
		
		var basket = $('#basket'),
			itemsHeight = $('#basket .items').height(),
			startHeight = 0,
			endHeight = itemsHeight,
			basketBtn = basket.find('.btn');
		
		//
		
		basketBtn.click(
		
				function (e) {
					
					e.stopPropagation();
					e.preventDefault();
					
					//
					
					if ( $(this).hasClass('collapsed') ) {
						
						$(this).removeClass('collapsed');
						basket.animate({'top':endHeight}, 300);
						
					} else {
						
						$(this).addClass('collapsed');
						basket.animate({'top':startHeight}, 300);
						
					}
					
				}
		
		);
		
};

function get_more_comments(obj, t_id, e_id) {
	var p_c = $(obj).attr("more");
	$.post('/reviews/getMoreComments/', {type: t_id, ext_id: e_id, pointer: p_c}, function(data) {
		if(data.html) {
			var last_comment = $('.comment-wrap:last', $(obj).parent());
			last_comment.removeClass("last");
			last_comment.after(data.html);
			if(data.more_comments) {
				$(obj).attr('more', data.more_comments);
			} else {
				$(obj).remove();
			}
		}
	}, 'json');
}
	
function submit_comment(obj, t_id, e_id) {
	var parentDiv = $(obj).parent();
	var name = $('.c_input_name', parentDiv).val();
	if(name == $('.c_input_name', parentDiv).attr("_value")) name = '';
	var email = $('.c_input_email', parentDiv).val();
	if(email == $('.c_input_email', parentDiv).attr("_value")) email = '';
	var text = $('.c_input_textarea', parentDiv).val();
	
	$.post('/reviews/ajaxAddComments/', {type: t_id, ext_id: e_id, name: name, email: email, text: text}, function(data) {
		$('.e, .message', parentDiv).remove();
		
		if(data.html) {
			$(obj).after(data.html);
			if($('.comment-wrap', parentDiv).length > 1) {
				$('.comment-wrap:first', parentDiv).removeClass("last");
			}
			var mc = $('.more_comments', parentDiv);
			if(mc.length) {
				var mc_pointer = parseInt(mc.attr('more'))+1;
				mc.attr('more', mc_pointer);
			}
		}
		if(data.errors) {
			$.map(data.errors, function(i){
				$('<div class="e"/>').text(i).insertBefore($(obj));
		    });
		}
		if(data.success) {
			$('<div class="message"/>').text(data.success).insertBefore($(obj));
		}
		
		$('.c_input_name', parentDiv).val($('.c_input_name', parentDiv).attr("_value"));
		$('.c_input_email', parentDiv).val($('.c_input_email', parentDiv).attr("_value"));
		$('.c_input_textarea', parentDiv).val('');
		
	}, 'json');
	
}
