/*
 * Мигание фонового изображения
 */

var m = document.uniqueID&& document.compatMode&& !window.XMLHttpRequest&& document.execCommand;
try{if (!!m){m("BackgroundImageCache", false, true)}} catch(oh){};

/*
 * image preload
 */
(function($) {
  var cache = [];
  // Arguments are image paths relative to the current page.
  $.preLoadImages = function() {
    var args_len = arguments.length;
    for (var i = args_len; i--;) {
      var cacheImage = document.createElement('img');
      cacheImage.src = arguments[i];
      cache.push(cacheImage);
    }
  }
}  
)(jQuery)
/*
$(function() {
	spruceGlow();
	timerNewYear();
});
*/
$.preLoadImages('/img/buy-small-btnH.png', '/img/purchase-big-btnH.png', '/img/recalculate-btnH.png', '/img/reg-btn-white-bgH.png', '/img/search-btnH.png', '/img/send-btnH.png', '/img/subscribe-btnH.png', '/img/buy-btn-hover.png', '/img/search-btn.png', '/img/enter-btnH.png', '/img/buy-btn-hover.png', '/img/enter-btn-white-bgH.png')


/*
 * Простой шаблонизатор
 */
String.prototype.supplant = function(o) {
    return this.replace(/{([^{}]*)}/g,
        function(a, b) {
            var r = o[b];
            return typeof r === 'string' || typeof r === 'number' ? r : a;
        }
    );
};



/*
 * placeholder
 */

var placeholder = {
	init: function() {
				//if ($.browser.safari) {
				// $('label.placeholder').hide();
				//} else {
					placeholder.o = $('input.hasPlaceholder')
						.filter('input[value^=]').prev().hide().end().end()
						.prev().addClass('placeholder_on')
						.next('input').bind('blur focus change mouseover', placeholder.event);
				//}
			},
	event: function(/* Event */ e) {
		var $etype = e.type, $this = $(this);
		if ($etype == 'blur') {
			if ($this.val() == '') {
				$this.prev().show();
			}
		} else if ( ($etype == 'focus') || ( ($etype == 'mouseover' || $etype == 'change') && $this.val() != '') ) {
			$this.prev().hide();
		}
	}
}

/*
 * Переключение основной фотографии товара в каталоге
 */
$.fn.thumbsSwitch = function(getOptions) {
    var options = $.extend({
	    
    }, getOptions);
    
    var event = function(e) {
    	var A = $(e.target).closest('a');
    	if (!A.hasClass('current')) {
    		A.addClass('current').siblings().removeClass('current');
    		var src = A.attr('href'),
    			image = new Image();
    		$(image)
				.load(function() {
					$('img', imageContainer).attr('src', src)
				})
				.error(function() {
					//error
				})
				.attr('src', src);
    	}
    	
    	return false;
    }
    
    var imageContainer = this.prev();
    return this
    		.bind('click.thumbSwitch', event);
};

/*
 * Главный банер
 */
$.fn.banner = function(options) {
	    var options = $.extend({
	    	 lineWeight: 20,
			 lineCount: 10,
			 slideWidth: 100,
			 slideHeight: 100,
			 speed:3000,
			 init:function() {}
	    }, options);

		var $this = $(this),
    		slidesContainer = $('#slides',$this),
    		slides = $('a', slidesContainer),
    		slidesCount = slides.length,
    		slideHeight = options.slideHeight,
    		slideWidth = options.slideWidth,
    		lineWeight = options.lineWeight,
			lineCount = options.lineCount;
		//	currentSlide = $('a.c', slidesContainer);

		var preBanner = $('#prebanner');

		if (preBanner.length) {

			setTimeout(function() {
				preBanner.fadeOut('slow');
				options.init($this);
			}, 6000)
		} else {
			options.init($this);
		}


		
   
		 /**
		 * Едем вправо
		 * @param {Number} next порядковый номер следующего слайда
		 * @param {Function} callback Колбек
		 */
   		function slideRight(currentSlide, next, callback){
				setNext(next);
				var lines = [currentSlide];
				for (var i = lineCount - 1; i >= 0; i -= 1) {
					var opacity = (1 / (lineCount+1) * (i+1)).toFixed(2), 
						marginLeft = [-(lineCount - i) * lineWeight, 'px'].join(''), 
						bgPosition = [-(i + 1) * lineWeight, 'px 0'].join('');
					lines.push(currentSlide.clone()
									.appendTo(slidesContainer)
									.css({
										width: lineWeight,
										opacity: opacity,
										marginLeft: marginLeft,
										backgroundPosition: bgPosition
									})
									.addClass('clone')
								);
				}
				animobj = $('a.c', slidesContainer)
				var z = 0, pN = 0;
				$({x: 0}).animate({
					x: slideWidth + lineWeight * lineCount
				}, {
					duration: options.speed,
					step: function(n){
						//n = Math.floor(n);
						if (pN != n) {
							for (var i = lines.length - 1; i >= 0; i -= 1) {
								lines[i].css({left: n,backgroundPosition: -n + lineWeight * i + 'px 0'
								});
							}
							pN = n;
						}
					},
					complete: function(){
						clear();
						if (!!callback) callback();
					}
				});
			}
   
   			/**
   			 * Едим влево
   			 * @param {Number} next порядковый номер следующего слайда
   			 * @param {Function} callback 
   			 */
   			function slideLeft(currentSlide, next, callback){
				setNext(next);
				var lines = [];
				for (var i = lineCount - 1; i >= 0; i -= 1) {
					var opacity = ((1 / (lineCount + 1)) * (i + 1)).toFixed(2), 
						bgPosition = [-slideWidth + (lineCount - i - 1) * lineWeight, 'px 0'].join('');
					lines.push(
						currentSlide.clone().appendTo(slidesContainer)
						.css({
							width: lineWeight,
							opacity: opacity,
							backgroundPosition: bgPosition
						})
						.addClass('clone')
					)
				}
				
				var z = 0, pN = 0;
				$({x: slideWidth}).animate({x: -lineCount * lineWeight}, {
					duration: options.speed,
					step: function(n){
						//n = Math.floor(n);
						//if (pN != n) {
							
							if ( n >= 0 ) currentSlide.css({width: n})
							else currentSlide.css({width: 0})
							
							for (var i = lines.length - 1; i >= 0; i -= 1) {
								lines[i][0].style.left = (n + lineWeight * i) + 'px';
								lines[i][0].style.backgroundPosition = -(n + lineWeight * i) + 'px 0';
								
								/*
								lines[i].css({
									marginLeft: [n + lineWeight * i, 'px'].join(''),
									backgroundPosition: [-n - lineWeight * i, 'px 0'].join('')
								})
								*/
							}
							//pN = n;
						//}
					},
					complete: function(){
						clear();
						if (!!callback) callback();
					}
				});
			}
   			/*
   			 * Всё зачистим после анимации
   			 */
   			function clear() {
					slidesContainer
						.find('a.clone')
							.remove()
						.end()
						.find('a.c')
							.removeClass('c')
							.css({left:0, backgroundPosition:'0 0', margin:0, width:options.slideWidth})
						.end()
						.find('a.n')[0].className = 'c';
						
						//console.log($('a.c'))
			}
   			
			/**
			 * Готовим следующий слайд
			 * @param {Number} n порядковый номер следующего слайда
			 */
			function setNext(n) {
				$('a', slidesContainer)[n].className = 'n';
			}
			
	
			//slideRight(slidesContainer);
	    	/**
	    	 * Распределяет анимацию: в зависимости от индекса нового слайда, анимирует влево, либо вправо
	    	 * @param {Number} newIndex Порядковый номер нового слайда
	    	 * @param {Function} callback Функция обратного вызова (вызывается после завершения анимации)
	    	 */
			function slide(newIndex, callback) {
				var currentSlide = $('a.c', slidesContainer), 
					currentSlideIndex = slides.index(currentSlide);
				if (newIndex > currentSlideIndex) {
					slideRight(currentSlide, newIndex, callback);
				} else if (newIndex < currentSlideIndex) {
					slideLeft(currentSlide, newIndex, callback);
				}
			}

	    	return {
				object: $this,
				slide: slide,
				slideLeft: slideLeft
			}
	};
	
/*
 * Показать основную фотографию товара
 * (взято со старого сайта)
 */	
(function($) {
	var settings;
	var process = 0;
	var imgBlockVisible = 0;
	var imageLoad = 0;
	var imagesA = [];
	var indexA;
	var direction;

	$.fn.dlb = function(callerSettings) {
			settings = $.extend({
				html: "<div id=\"dlb-overlay\"></div>",
				htmlImg: "<div id=\"dlb-img\"><a href=\"#\" id=\"dlb-prev\" title=\"Предыдущая\"><span>Предыдущаяspan></a><a href=\"#\" id=\"dlb-next\" title=\"Следующая\"><span>Следующая</span></a><span id=\"dlb-close\" title=\"Закрыть\">Закрыть</span></div>",
				opacity: .65,
				speed: 700
			}, callerSettings || {});
			return this.each(function(i) {
				if (i===0) {init();}
				imagesA[i]=$(this);
				$(this).unbind("click").click(function(e) {
					if (e.target.tagName != 'A') {
						indexA = i;
						start($(this));
					}
					return false;
				});
			});
		}
	
		function init() {
			body = $("body");
			body.append(settings.html, settings.htmlImg);
			overlay = $("#dlb-overlay");
			overlay.add($("#dlb-close")).click(function() {finish();});
			$("#dlb-prev").click(function() {prev(); return false;});
			$("#dlb-next").click(function() {next(); return false;});
			imgBlock = $("#dlb-img");
			s3 = settings.speed/3;
			$(document).keydown(function(e) {
				if (e.which==27) {finish();}
				if (e.ctrlKey) {
					switch (e.keyCode) {
						case 0x25: {
							prev();
						} break;
						case 0x27: {
							next();
						} break;
					}
				}
			});
		}
		function start(obj) {
			if (process==1) {return false;}
			process = 1;
	
			if (indexA != imagesA.length-1) {direction = 1;}
			else {direction =- 1;}
	
			var href = obj.attr("href");
			dlbImage = $("<img src=\"" + href + "\" />");
			dlbImage.prependTo(imgBlock).load(function() {
				imageLoad = 1;
				if (imgBlockVisible !== 0) {imageResize();}
			});
			firstLast();
	
			body.css({overflow:"hidden", position:'relative', height:'100%'});
			
			overlay
				.css({display:"block", opacity:0})
				.animate({opacity:settings.opacity}, s3)
				.animate({width:"100%", left:"-=48%"}, s3)
				.animate({height:document.documentElement.clientHeight+'px', top:"-=49.5%"}, s3, function() {
					process=0;
					imgBlock.fadeIn(function() {
						imgBlockVisible = 1;
						if (imageLoad !== 0) {imageResize();}
					});
				});
		}
		function prev() {
			if (indexA > 0) {
				indexA--;
				newImage();
			}
			direction = -1;
		}
		function next() {
			if (indexA < imagesA.length-1) {
				indexA++;
				newImage();
			}
			direction = 1;
		}
		function newImage() {
			var href = imagesA[indexA].attr("href");
			dlbImage.clone().prependTo(imgBlock).css("visibility", "visible").fadeOut(function() {$(this).remove();});
			imgBlock.attr("class", "");
			dlbImage.attr({src: href, style: ""});
			firstLast();
		}
		function firstLast() {
			if (indexA >= imagesA.length-1) {imgBlock.addClass("img-last");}
			if (indexA <= 0) {imgBlock.addClass("img-first");}
		}
		function preloading(preloadImg) {
			var pImg = new Image();
			pImg.src = imagesA[preloadImg].attr("href");
		}
		function finish() {
			if (process == 1 || !imgBlockVisible) {return false;}
			process = 1;
			imgBlock.hide().removeClass("loaded");
			overlay.animate({height:"1%", top:"49.5%"}, s3).
			animate({width:"-=96%", left:"48%"}, s3).
			animate({opacity:0}, s3, function() {
				this.style.display = "none";
				dlbImage.remove();
				body.css({overflow:"visible"});
				process = 0;
			});
		}
		function imageResize() {
			if ((indexA >= 0 && indexA < imagesA.length - 1 && direction == 1) || (indexA>0 && indexA <= imagesA.length - 1 && direction == -1)) {
				var preloadImg = indexA+direction;
				preloading(preloadImg);
			}
			var imageWidth = dlbImage.width();
			var imageHeight = dlbImage.height();
			var overlayWidth = $(window).width() - 50;
			var overlayHeight = $(window).height() - 50;
	
			if (imageWidth > overlayWidth) {
	
				imageWidth = overlayWidth;
				dlbImage.width(imageWidth);					
				while(dlbImage.height() > overlayHeight) {
					imageWidth--;
					dlbImage.width(imageWidth);
				}
				imageHeight = dlbImage.height();
			}
			if (imageHeight > overlayHeight) {
				imageHeight = overlayHeight;
				dlbImage.height(imageHeight);						
				while(dlbImage.width() > overlayWidth) {
					imageHeight--;
					dlbImage.height(imageHeight);
				}
				imageWidth = dlbImage.width();
			}
			imageWidth += 20;
			imageHeight += 14;
			imgBlock.css({
				width:imageWidth, 
				marginLeft:-imageWidth/2, 
				height:imageHeight, 
				marginTop:-imageHeight/2
			})
			.addClass("loaded");
			dlbImage.hide().fadeIn();
		}
})(jQuery)


/*
 * Карточка товара (переключение основного изображения)
 */
$.fn.mainThumbsSwitch = function() {
    var mainImage = this.prev();
    
    this.click(
    	function(/* Event */e){
    		var $li = $(e.target).closest('li'),
    			li = $li[0];
    		if (!li || li.className == 'current') return false;
    		
    		var newLink = 
		   		$li
	    			.addClass('current').siblings().removeClass('current').end()
	    			.find('a').attr('href').split('#');
    			
	    	if ($.browser.msie)
    			mainImage
    				.attr('href', newLink[0])
    				.find('img').attr('src', newLink[1]);
    		else 
	    		mainImage
	    			.attr('href', newLink[0])
	    			.find('img').animate({opacity:0}, 'slow', function(){$(this).remove()}).end()
	    			.prepend('<img src="'+newLink[1]+'"/>');
    		    		
    		return false;
    	}
    );
}

/*
 * form validation
 */ 

$.fn.validate = function() {
	return this.each(function() {
		var _this = this, $this = $(_this);

		$this.submit(function(/*Event*/e) {
			
			var inputs = $('input.required[value=], select.required[value=]', $this)
				.parent().siblings().andSelf().removeClass('error').end().end().end();
			$('span.btn-error-message', $this).remove();
				
			if (inputs[0]) {
				inputs.parent().addClass('error');
				
				if ($.browser.msie) 
					$(this).after('<span class="btn-error-message">Обязательные поля не заполнены.</span>');
				else 
					$(this).after('<span class="btn-error-message">Обязательные поля не заполнены.</span>').next().fadeOut(5000);
				
				return false;
			}
			$('<input type="hidden" name="dlab_check" value="111" />').prependTo($this);
		});

	
	});
};


/*
 * Отправить другу
 */
 /*	var popupFriendTimer;
	function closePopupFriend() {
		popupFriendTimer = clearTimeout(popupFriendTimer);
		$('#popup-frame').hide();
		$(document).unbind('keyup.sendFriend');
	}


	$('a.send-to-friend').live('click', function() {
		var pf = $('#popup-frame').show(),
			pbody = $('#popup-body', pf);
		
		if ($.browser.msie && $.browser.version == '6.0') body.css({height:'100%'});
			
		pbody
			.css({marginTop:-(pbody.height()/2) + 'px'})
			.find('p.server-message').hide().end()
			.find('input#friends-name, input#friends-email').val('')
			

			
		$(document).bind('keyup.sendFriend', function(e) {
			if (e.which === 27) closePopupFriend();
		});
		return false;
	});
	
	$('#popup-frame .close-popup').live('click',closePopupFriend);
*/

/*
 * validate form
 */
    
$.fn.validateFriendForm = function() {
	var emailRegexp = /^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i;
	var form = $(this),
		badInputs,
		inputs = $('input, textarea', form),
		serverMessage = $('p.server-message', form);
		
	var submit = form.find('.submit').click(function() {
		$('[name=nospam]', form).val(1);
		inputs.removeClass('error');
		badInputs = inputs.filter('input.required[value=], textarea.required[value=]');
		inputs.filter('input.check-email').each(function() {
			var _this = this;

			if (_this.value != '' && !emailRegexp.test(_this.value)) {
				badInputs = badInputs.add(_this);
			}
		});

		if (badInputs[0]) {
			badInputs.addClass('error').next().show();
		} else {
			serverMessage.show().html()
			//submit.attr('disabled', 'true');
			
			$.post(form[0].action, form.serialize(), function(response) {
				if (response.error) { // Если ошибка
					serverMessage.show().html(response.error);

					if (response.errorInputs) {
						for (i in response.errorInputs) {
							$('#'+response.errorInputs[i]).addClass('error')
						}
					}
					 
				} else { // Если всё нормально
					serverMessage.show().html(response.message);
					popupFriendTimer = setTimeout(function() {
						popup.close();
					}, 2000);
				}
			}, 'json');
		}
	
		return false;
	});
}




/**
 * Восстановление пароля
 */

$.fn.popup = function() {
	var popupFrame = $('<div id="popup-frame"><div id="popup-shadow" class="close-popup"></div><div id="popup-body"><div id="popup-content"></div><div class="close-button close-popup">Закрыть</div><div class="tl"></div><div class="tr"></div><div class="bl"></div><div class="br"></div></div></div>')
						.appendTo('body');
	
	var pbody = $('#popup-body');
	var popupContent = $('#popup-content', pbody);
	
	$('.close-popup', popupFrame).live('click', function() {
		close();
	});
	
	
	$(document).bind('keydown', function(e) {
		if (e.which === 27) close();
	})
	
	function close() {
		popupFrame.hide();
		popupContent.html('');
	}
	
	this.bind('click', function(e) {
		var anchor = $(e.target).closest('a');
		if (!anchor.length) return false;
		
		$.get(anchor[0].href, function(response) {
			popupContent.html(response);
			popupFrame.show();
			if ($.browser.msie && $.browser.version == '6.0') body.css({height:'100%'});
			pbody.css({marginTop:-(pbody.height()/2) + 'px'})
		})
		
		return false;
	})
	
	return {
		close: close
	}
}


/**
 * Отправка формы восстановления пароля
 */
$('form.password-recovery-form input[type=image]').live('click', checkRecoveryForm);
var recoveryCloseTimer;
function checkRecoveryForm() {
	var form = $(this).parents('form'),
		label = $('label', form).removeClass('error');
	
	recoveryCloseTimer = clearTimeout(recoveryCloseTimer);	
		
	$.post(form.attr('action'), form.serialize(), function(response) {
		if (response.message) {
			$('input, label', form).hide();
			form.find('fieldset').append('<span class="recovery-message">' + response.message + '</span>');
			recoveryCloseTimer = setTimeout(function() {
				popup.close();
			},'3000')
		}
	}, 'json')
	
	return false;
}


var popup;
/*
 * Dom ready
 */
$(function() {
	placeholder.init();
	$('div.thumbs').thumbsSwitch();
	$(".dlb").dlb(); 
	$('form.form').validate();
	$('form#purchase').submit(function(){
		var checkboxes = $('input[name=paying]', $(this));
		if (checkboxes.length && checkboxes.filter(':checked').length != 1){
			alert('Не указан способ оплаты');
			return false;
		}
	});
	$('ul.extra-image').mainThumbsSwitch();
	$('#send-to-friend').validateFriendForm();
	popup = $('a.popup').popup();

	/*
	* Основное меню
	*/
	if (!$.browser.msie) {
	  $('#m > li').hover(

		  function() {
		  	$(this)
		  		.find('div').stop().css({opacity:0, display:'block'})
		  			.animate({opacity:1},300)
		  },
		  function() {
		  	$(this)
		  		.find('div').stop().animate({opacity:0},300, function() {
		  			$(this).css({opacity:0, display:'none'})
		  		});
		  }
	  );
  }
  
  
  // Главный баннер - инициализация
  var banner = $('#banner').banner({
	  	slideWidth: 543, // ширина
		slideHeight: 219, // высота
		lineCount: 3, // количество полос
		lineWeight: 16, // ширина полосы
		speed: 1200, // скорость
		init:function(obj) {
			var ol = $('ol.pager', obj);
			var timeout = $('#slides').attr('data-timeout');
			var pagerEvent = function(e) {
				var $this = $(this), et = $(e.target);
				if (!et.hasClass('active')) {
					slTimer = clearTimeout(slTimer);
					et.addClass('active').siblings().removeClass('active');
					var index  = $('li', $this).index($(e.target));
					$('#banner-next,#banner-prev').add(ol).unbind('click');
					banner.slide(index, function() {
						ol.bind('click', pagerEvent);
						$('#banner-next,#banner-prev').bind('click', nextPrevEvent);
						slTimer = setTimeout(function() {
							$(nextBTN).trigger('click');
						}, timeout);
					});
				}
			}
			
			var nextPrevEvent = function() {
				var newIndex;
				slTimer = clearTimeout(slTimer);
				$('#banner-next,#banner-prev').add(ol).unbind('click');
				if (this.id.split('banner-')[1] === 'next') {
					newIndex = $('li', ol).index($('li.active', ol).next());
					if (newIndex === -1) newIndex = 0;
				} else {
					newIndex = $('li', ol).index($('li.active', ol).prev());
					if (newIndex === -1) newIndex = $('li', ol).length-1;
				}
				
				$('li:eq('+ newIndex +')', ol).addClass('active').siblings().removeClass('active')
				
				$('#banner-next,#banner-prev').unbind('click');
				banner.slide(newIndex, function() {
					$('ol.pager', obj).bind('click', pagerEvent);
					var nextBTN = $('#banner-next,#banner-prev').bind('click', nextPrevEvent)[0];
					slTimer = setTimeout(function() {
						$(nextBTN).trigger('click');
					}, timeout);
				});
			}
			
			
			$('ol.pager', obj).bind('click', pagerEvent);
			var nextBTN = $('#banner-next,#banner-prev').bind('click', nextPrevEvent)[0];
			
			slTimer = setTimeout(function() {
				$(nextBTN).trigger('click');
			}, timeout);
		}
		
	  });
	  
	 // Форма оформления зазака
	  if ($('form#purchase')[0]) {
		 var formPurchase = {
		  	obj: $('form#purchase'),
		  	$price: $('#price', this.obj),
		  	$deliveryPrice:$('#deliv-price', this.obj),
		  	$totalPrice:$('#total-price', this.obj),
		  	$dprice:$('#dprice', this.obj),
		  	oldPrice: parseInt($('#price').text()),
		  	oldTotalPrice: parseInt($('#total-price').text())
		  }
		  var purTable = $('#basket tbody');
		  	  tableRowTemplate = '<tr class="cert-row"><td></td><td></td><td>{id} (<a class="delete" href="/certificat.php?do=delete&id={id}">???????</a>)</td><td></td><td></td><td></td><td></td><td>-{discount}</td><td></td></tr>',
		  	  inputNumber = $('#cert-number',  formPurchase.obj)
		  	  	.bind('keydown', function(e) { 
		  	  		if (e.which === 13) return false;
		  	  	}),
		  	  messageBox = inputNumber.next();
		 
		 
		  	  
		  	  
		  	 function sendCert(e) {
		  	
			  	$.post(
			  		this.href, 
			  		{"certification":inputNumber[0].value}, 
			  		function(response) {
				  		if (response.error == undefined) {
					  		$('>tr.cert-row', purTable).remove();
				  			
				  			var discount = 0;
				  			for (var i = response.certificates.length, tableRows = '', discount = 0; i--;)  {
				  				discount  +=  response.certificates[i].discount;
				  				tableRows += tableRowTemplate.supplant(response.certificates[i]);
				  			}
							
							//console.log(purTable.append());
							if (tableRows) {
								$(tableRows)
									.find('a.delete').bind('click', sendCert).end()
									.appendTo(purTable);
							}							
							
				  			inputNumber.val('');
							
							messageBox.text(response.message);
							var nPrice = formPurchase.oldPrice - discount;
							if (nPrice < 0) nPrice = 0;
							
							formPurchase.$price.text(nPrice + ' руб.').css('fontWeight', 'bold')
							formPurchase.$totalPrice.text(nPrice + (parseInt(formPurchase.$deliveryPrice.text()) || 0) + ' руб.').css('fontWeight', 'bold')
							
							if (nPrice < 2000) {
								$('.cup2000').hide();
							} else {
								$('.cup2000').show();
							}
							
							
						} else {
							messageBox.text(response.error)
						}
			  		},
			  		'json'
			  	);
			  	
		  	
		  	return false;
		  };	  
		$('#cert-submit', formPurchase.obj).bind('click',sendCert);
		
		function checkDelivery() {
			var citydata = $('#city').val().split("|");
			var minPrice = citydata.length > 1 ? parseInt(citydata[1]) : -1;
			var cityPrice = citydata.length > 1 ? parseInt(citydata[2]) : 0;
			var cityGroup = citydata.length > 1 ? parseInt(citydata[3]) : 0;

			var payCash = $('input[name="paying"]:eq(0)', formPurchase.obj);
			var payBank = $('input[name="paying"]:eq(1)', formPurchase.obj);
			var deliveryCur = $('input[name="delivery"]:eq(0)' , formPurchase.obj);
			var deliveryPost = $('input[name="delivery"]:eq(1)', formPurchase.obj);
			var deliverySelf = $('input[name="delivery"]:eq(2)', formPurchase.obj);
			var zipcodeField = $('input[name="zipcode"]');

			if (cityGroup != 1) {
				deliverySelf.attr('checked', false).attr('disabled', 'disabled').parent().parent().slideUp('fast');
			} else {
				deliverySelf.attr('disabled', '').parent().parent().slideDown('fast');
			}

			var canBank = !deliverySelf.attr('checked');
			var canCash = !canBank || minPrice != -1;
			if (!canCash) {
				payCash.attr('disabled', 'disabled').parent().parent().slideUp('fast');
				payBank.attr('checked','checked');
				if (deliveryCur.attr('checked')) {
					deliveryPost.attr('checked','checked');
				}
				deliveryCur.attr('disabled', 'disabled').parent().parent().slideUp('fast');
				zipcodeField.addClass('required');
			} else {
				payCash.attr('disabled', '').parent().parent().slideDown('fast');
				deliveryCur.attr('disabled', '').parent().parent().slideDown('fast');
				zipcodeField.removeClass('required');
			}

			if (!canBank) {
				payBank.attr('disabled', 'disabled').parent().parent().slideUp('fast');
				payCash.attr('checked','checked');
			} else {
				payBank.attr('disabled', '').parent().parent().slideDown('fast');
			}

			if (payCash.attr('checked')) {
				deliveryPost.attr('disabled', 'disabled').parent().parent().slideUp('fast');
				if (deliveryPost.attr('checked')) {
					deliveryCur.attr('checked','checked');
				}
			} else {
				deliveryPost.attr('disabled', '').parent().parent().slideDown('fast');
			}

			var price = parseInt(formPurchase.$price.text());
			var dprice = cityPrice;
			if (deliverySelf.attr('checked')) {
				dprice = 100;
			} else if (minPrice == -1 || payBank.attr('checked')) {
				dprice = parseInt($('input[name=default_dprice]').val());
			} else if (minPrice > 0 && price >= minPrice) {
				dprice = 0;
			}
			
			if ($('.free_delivery').length) {
				dprice = 0;
			}
			
			formPurchase.$deliveryPrice.text(dprice < 0 ? 'обсуждается отдельно' : (dprice + ' руб.'));
			formPurchase.$totalPrice.text((price + (dprice < 0 ? 0 : dprice)) + ' руб.');
			return true;
		}

		//Изменения цены доставки в зависимости от города
		$('select#city').change(function () {
			checkDelivery();
			var pay_options = $('input[name="paying"]:not([disabled])');
			if (pay_options.length > 1)
			{
				pay_options.attr('checked', false);
			}
		}).change();
		//Раскрытие (Подробнее...)
		$('a.smore', formPurchase.obj).toggle(
			function () {
				$(this).text('Скрыть текст').prev('div').slideDown(300);
				return false;
			},
			function () {
				$(this).text('Подробнее...').prev('div').slideUp(300);
				return false;
			}
		);
		$('div.hide', formPurchase.obj).hide();
		
		
		$('input[name="paying"]', formPurchase.obj).click(checkDelivery);
		$('input[name="delivery"]', formPurchase.obj).click(checkDelivery);
		checkDelivery();
	}
	
	

	
/*
 * Input type="image"
 */

if (!($.browser.msie && $.browser.version === '6.0'))  {
	$('input[type=image]').hover(
		function(/*Event*/e) {
			var _this = this;
			_this.src = _this.src.slice(0,-4)+'H.png';
		},
		function(/*Event*/e) {
			var _this = this;
			_this.src = _this.src.slice(0,-5)+'.png';
		}
	).hover();
}

	//disable context menu
 $(document).bind("contextmenu",function(e){
        return false;
    });

    /**
     * Балун для кнопки купить
     */
    
  
  	var baloon = function() {
  		var baloonBlock = $('#baloon');
  		
  		if (!baloonBlock[0])
  			baloonBlock = $('<div id="baloon">\u0422\u043e\u0432\u0430\u0440 \u0434\u043e\u0431\u0430\u0432\u043b\u0435\u043d \u0432 \u043a\u043e\u0440\u0437\u0438\u043d\u0443</div>').appendTo('body');
  		
  		baloonBlock
  			.click(function() {
  				$(this).hide();
  			});
  		var show = function(x,y) {
  			if ($.browser.msie) {  				
		  		baloonBlock.css({left:x, top:y}).show();
		  		
		  		baloonBlock.timer = clearTimeout(baloonBlock.timer);
		  		baloonBlock.timer = setTimeout(function() {
		  			baloonBlock.hide();
		  		}, 3000);
  			} else {
  				baloonBlock
		  			.stop().css({left:x, top:y, opacity:1}).show()
		  			.animate({opacity:0}, 3000, function() {
		  				baloonBlock.hide();
		  			});
  			}
  		}
  		
  		return {
  			show:show
  		}
	}();
    
    
    /**
     * Купить товар
     */
    $('a.buy-btn').click(function(/*Event*/e) {
    	$.get(this.href, function(data) {
    		baloon.show(e.pageX, e.pageY);
    		$('#top-basket').html(data);
    	});
    	
    	return false;
    });
    
    $('a.print-page').click(function() {
	    window.print();
	    return false;
    })

  
    
    
    
    
    
// /dom ready
 }); 
 
 
 
try {
	var snh = /^#snh(\w+)$/.exec(window.location.hash);
	if (snh) {
		setcookie('snh', snh[1], 365);
		setcookie('snh_first', snh[1]);
		snh_id = snh[1];
	}
} catch(e) {}

function setcookie(name, value, days)
{
	var expires = "";
	if (days) {
		var date = new Date();
		date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
		expires = "; expires=" + date.toGMTString();
	}
	document.cookie = name + "=" + value + expires + "; path=/";
}

function timerNewYear(){
	var timeleft = timeEnd - (new Date()).getTime();
		if((timeleft == 0)||(timeleft <0)){
			setTime (0, 0, 0, 0, 0, 0, 0, 0);
			$("div#newTime").hide();
			$("div#timer").hide();
			return;
		}

		var days = Math.floor(timeleft / (1000 * 60 * 60 * 24));

		var hours = Math.floor(timeleft /(1000*60*60)) -  days * 24;
		var minutes = Math.floor(timeleft/(1000 * 60)) - hours * 60 - days * 24 * 60;
		var seconds =  Math.floor(timeleft/1000) - days * 24 * 60 * 60 -hours* 60 * 60 - minutes * 60;

		var d1 = Math.floor(days/10);
		var d2 = days - d1*10;
		var h1 = Math.floor(hours/10);
		var h2 = hours - h1*10;
		var m1 = Math.floor(minutes/10);
		var m2 = minutes - m1*10;
		var s1 = Math.floor(seconds/10);
		var s2 = days - d1*10;
//		setTime(d1, d2, h1, h2, m1, m2, s1, s2);

	function point(){
		var timeleft = timeEnd - (new Date()).getTime();
		if(timeleft <= 0){
//			setTime (0, 0, 0, 0, 0, 0, 0, 0);
			$("div#newTime").hide();
			$("div#timer").hide();
			return;
		}

		var days = Math.floor(timeleft / (1000 * 60 * 60 * 24));
		var hours = Math.floor(timeleft /(1000*60*60)) -  days * 24;
		var minutes = Math.floor(timeleft/(1000 * 60)) - hours * 60 - days * 24 * 60;
		var seconds =  Math.floor(timeleft/1000) - days * 24 * 60 * 60 -hours* 60 * 60 - minutes * 60;

		var d1 = Math.floor(days/10);
		var d2 = days - d1*10;
		var h1 = Math.floor(hours/10);
		var h2 = hours - h1*10;
		var m1 = Math.floor(minutes/10);
		var m2 = minutes - m1*10;
		var s1 = Math.floor(seconds/10);
		var s2 = seconds - s1*10;
//		setTime(d1, d2, h1, h2, m1, m2, s1, s2);
	}

//	 setInterval(newYear, 100);
}


/*

originally found here: http://net.tutsplus.com/tutorials/html-css-techniques/learn-how-to-create-a-retro-animated-flip-down-clock/

simple jQuery Port made by team Odeon. http://od-eon.com

*/
    var current = {
		"d1": -1,
		"d2": -1,
        "h1": -1,
		"h2": -1,
        "m1": -1,
        "m2": -1,
        "s1": -1,
        "s2": -1
    }

    var paths = {
        "singles": '/img/banners/Single',
        "doubles": '/img/banners/Double'
    }





//	function flip(upperId, lowerId, changeNumber, pathUpper, pathLower){
//        var lowerBackId = lowerId+"Back";
//		if (!$(lowerBackId).length) return;
//        $(lowerId)
//            .attr('src', $(lowerBackId).attr('src'))
//            .height("16px")
//            .css({"visibility": "visible", 'display': 'inline-block' });
//
//        $(lowerBackId).attr('src', pathLower + parseInt(changeNumber) + ".png");
//
//        $(upperId)
//            .attr('src', pathUpper + parseInt(changeNumber) + ".png")
//            .height('0px')
//            .css({"visibility": "visible", 'display': 'inline-block'});
//
//        $(lowerId).animate({'height': 0}, { 'duration': 200, defaultEasing: 'easeinoutsine', 'complete': function(){
//            $(upperId).animate({'height': 16}, { 'duration': 200, defaultEasing: 'easeinoutsine', 'complete': function(){
//                $(upperId + "Back").attr('src', $(upperId).attr('src') );
//                $(upperId).add(lowerId).css({"visibility": "hidden",
//                                             "display": 'inline-block' }).height('0');
//            } } )
//        } })
//    }

   	function flip(upperId, lowerId, changeNumber, pathUpper, pathLower){
        if (!$(upperId).length || changeNumber == -1) return;
        var upperBackId = upperId+"Back";
        $(upperId)
            .attr('src', $(upperBackId).attr('src'))
            .height("16px")
            .css({"visibility": "visible", 'display': 'inline-block' });

        $(upperBackId).attr('src', pathUpper + parseInt(changeNumber) + ".png");

        $(lowerId)
            .attr('src', pathLower + parseInt(changeNumber) + ".png")
            .height('0px')
            .css({"visibility": "visible", 'display': 'inline-block'});

        $(upperId).animate({'height': 0}, { 'duration': 200, defaultEasing: 'easeinoutsine', 'complete': function(){
            $(lowerId).animate({'height': 16}, { 'duration': 200, defaultEasing: 'easeinoutsine', 'complete': function(){
                $(lowerId + "Back").attr('src', $(lowerId).attr('src') );
                $(lowerId).add(upperId).css({"visibility": "hidden",
                                             "display": 'inline-block' }).height('0');
            } } )
        } })
    }




    var point;
    function tick(){
	var timeleft = timeEnd - (new Date()).getTime(),
			days = Math.floor(timeleft / (1000 * 60 * 60 * 24)),
			h = Math.floor(timeleft /(1000*60*60)) -  days * 24,
			minutes = Math.floor(timeleft/(1000 * 60)) - h * 60 - days * 24 * 60,
			seconds =  Math.floor(timeleft/1000) - days * 24 * 60 * 60 -h* 60 * 60 - minutes * 60;

		if (timeleft <=0) {
			clearInterval(point);
			$("#bannerNewYear").addClass('expired');
			if (imageHide){
				$("div#banner_image").hide();
			}
		}

		var d1 = Math.floor(days/10),
			d2 = days - d1*10,
			h1 = Math.floor(h/10),
			h2 = h - h1*10,
			m1 = Math.floor(minutes/10),
			m2 = minutes - m1*10,
			s1 = Math.floor(seconds/10),
			s2 = seconds - s1*10,

// 			var now = new Date(),
//            h = now.getHours(),
//            m1 = now.getMinutes() / 10,
//            m2 = now.getMinutes() % 10,
//            s1 = now.getSeconds() / 10,
//            s2 = now.getSeconds() % 10,
//            pathSingle = paths.singles,
		    pathDouble = paths.doubles;



		if( d2 != current.d2){
            flip('#daysUpRight', '#daysDownRight', d2,pathDouble + '/Up/Right/', pathDouble + '/Down/Right/');
            current.d2 = d2;
		}

		if( d1 != current.d1){
			flip('#daysUpLeft', '#daysDownLeft', d1,pathDouble + '/Up/Left/', pathDouble + '/Down/Left/');
            current.d1 = d1;
        }

        if( h2 != current.h2){
            flip('#hoursUpRight', '#hoursDownRight', h2,pathDouble + '/Up/Right/', pathDouble + '/Down/Right/');
            current.h2 = h2;
		}

		if ( h1 != current.h1){
			flip('#hoursUpLeft', '#hoursDownLeft', h1,pathDouble + '/Up/Left/', pathDouble + '/Down/Left/');
            current.h1 = h1;
        }

        if( m2 != current.m2){
            flip('#minutesUpRight', '#minutesDownRight', m2, pathDouble + '/Up/Right/', pathDouble + '/Down/Right/');
            current.m2 = m2;
		}

		if(m1 != current.m1){
            flip('#minutesUpLeft', '#minutesDownLeft', m1, pathDouble + '/Up/Left/', pathDouble + '/Down/Left/');
            current.m1 = m1;
        }

         if (s2 != current.s2){
            flip('#secondsUpRight', '#secondsDownRight', s2, pathDouble + '/Up/Right/', pathDouble + '/Down/Right/');
            current.s2 = s2;
		 }

		if (s1  != current.s1) {
            flip('#secondsUpLeft', '#secondsDownLeft', s1, pathDouble + '/Up/Left/', pathDouble + '/Down/Left/');
            current.s1 = s1;
        }

    }
//

    function retroClock(){
		if (typeof timeEnd == "undefined") return;
		if ((new Date()).getTime() < timeEnd) {
			$("#bannerNewYear").removeClass('expired');
		}
        tick();
		point = setInterval(tick, 1000);
    }


    $(function(){
        retroClock();
    })

