/**/
jQuery.fn.countdown = function (date, options) {
		options = jQuery.extend({
			lang: {
				years:   ['год', 'года', 'лет'],
				months:  ['месяц', 'месяца', 'месяцев'],
				days:    ['день', 'дня', 'дней'],
				hours:   ['час', 'часа', 'часов'],
				minutes: ['минута', 'минуты', 'минут'],
				seconds: ['секунда', 'секунды', 'секунд'],
				plurar:  function(n) {
					return (n % 10 == 1 && n % 100 != 11 ? 0 : n % 10 >= 2 && n % 10 <= 4 && (n % 100 < 10 || n % 100 >= 20) ? 1 : 2);
				}
			}, 
			prefix: "", 
			suffix: "",
			finish: "Всё"			
		}, options);
 
		var timeDifference = function(begin, end) {
		    if (end < begin) {
			    return false;
		    }
		    var diff = {
		    	seconds: [end.getSeconds() - begin.getSeconds(), 60],
		    	minutes: [end.getMinutes() - begin.getMinutes(), 60],
		    	hours: [end.getHours() - begin.getHours(), 24],
		    	days: [end.getDate()  - begin.getDate(), new Date(begin.getYear(), begin.getMonth() + 1, 0).getDate() - 1],
		    	months: [end.getMonth() - begin.getMonth(), 12],
		    	years: [end.getYear()  - begin.getYear(), 0]
		    };
		    var result = new Array();
		    var flag = false;
		    for (i in diff) {
		    	if (flag) {
		    		diff[i][0]--;
		    		flag = false;
		    	}    	
		    	if (diff[i][0] < 0) {
		    		flag = true;
		    		diff[i][0] += diff[i][1];
		    	}
		    	if (!diff[i][0]) continue;
			    result.push('<b>'+diff[i][0] + '</b> ' + options.lang[i][options.lang.plurar(diff[i][0])]);
		    }
		    return result.reverse().join(' ');
		};
		var elem = $(this);
		var timeUpdate = function () {
		    var s = timeDifference(new Date(), date);
		    if (s.length) {
		    	elem.html(options.prefix + " " +s + " "+options.suffix);
		    } else {
		        clearInterval(timer);
		        elem.html(options.finish);
		    }		
		};
		timeUpdate();
		var timer = setInterval(timeUpdate, 1000);		
};


jQuery.fn.countdown2 = function (date, options) {
	options = jQuery.extend({
		lang: {
			years:   [' год ', ' года ', ' лет '],
			months:  [' месяц ', ' месяца ', ' месяцев '],
			days:    [' день ', ' дня ', ' дней '],
			hours:   [':', ':', ':'],
			minutes: [':', ':', ':'],
			seconds: ['', '', ''],
			plurar:  function(n) {
				return (n % 10 == 1 && n % 100 != 11 ? 0 : n % 10 >= 2 && n % 10 <= 4 && (n % 100 < 10 || n % 100 >= 20) ? 1 : 2);
			}
		}, 
		prefix: "", 
		suffix: "",
		finish: '<p class="close">Аукцион <strong>закрыт</strong></p>'			
	}, options);

	var timeDifference = function(begin, end) {
	    if (end < begin) {
		    return false;
	    }
	    var diff = {
	    	seconds: [end.getSeconds() - begin.getSeconds(), 60],
	    	minutes: [end.getMinutes() - begin.getMinutes(), 60],
	    	hours: [end.getHours() - begin.getHours(), 24],
	    	days: [end.getDate()  - begin.getDate(), new Date(begin.getYear(), begin.getMonth() + 1, 0).getDate() - 1],
	    	months: [end.getMonth() - begin.getMonth(), 12],
	    	years: [end.getYear()  - begin.getYear(), 0]
	    };
	    var result = new Array();
	    var flag = false;
	    for (i in diff) {
	    	if (flag) {
	    		diff[i][0]--;
	    		flag = false;
	    	}    	
	    	if (diff[i][0] < 0) {
	    		flag = true;
	    		diff[i][0] += diff[i][1];
	    	}
	    	if (!diff[i][0] && i != 'seconds' && i != 'minutes' && i != 'hours')
	    	{
	    		continue;
	    	}
	    	if (i == 'seconds' || i == 'minutes')
	    	{
	    		diff[i][0] = diff[i][0] > 9 ? diff[i][0] : '0' + diff[i][0];	
	    	}
		    result.push(diff[i][0] + '' + options.lang[i][options.lang.plurar(diff[i][0])]);
	    }
	    return result.reverse().join('');
	};
	var elem = $(this);
	var timeUpdate = function () {
	    var s = timeDifference(new Date(), date);
	    if (s.length) {
	    	elem.html(s);
	    } else {
	        clearInterval(timer);
	        elem.html(options.finish);
	    }		
	};
	timeUpdate();
	var timer = setInterval(timeUpdate, 1000);		
};


var deliveryPrice = new Array();
$(document).ready(function () {
	var pageNum=2;
	
	
	if (!(/msie/.test(navigator.userAgent.toLowerCase()))) {
		$(".pager-container.no-js").css("display", "none");
		$(".pager-container.js").css("display", "block");
	}
	
	
	
	
	$(".check-pay .steps, #protuct-list.about-product .controls").css("display", "block");
	$(".check-pay .carusel").each(function () {
		$(this).children(".item").css({
			"float": "left",
			"width": $(this).children(".item:first-child").width()
		});
		$(this).css({
			"width": $(this).children(".item").length*$(this).children(".item:first-child").width()
		});
	});
	
	
	
	


	$(".others-city").click(function () {
		$(".select-window").css({
			"display":"block",
			"top":$(this).offset().top,
			"left":$(this).offset().left-3
		});
		return false;
	});
	$(".select-window .close").click(function () {
		$(".select-window").css("display", "none");
	});
	$(document).keyup(function(event){
		if (event.keyCode == 27) {
			$(".select-window").css("display", "none");
		}
	});
	
	$("header .search .textbox").focus(function () {
		if ($(this).val() == "Поиск…")
			$(this).val("");
		
		$(this).parent().parent().animate({"width":"150%"}, 500);
	});
	$("header .search .textbox").focusout(function () {
		if ($(this).val().length == 0)
			$(this).val("Поиск…");
		if ($("#keyboardInputMaster").length) return true;
		$(this).parent().parent().animate({"width":"80%"}, 500);
	});
	
	$(".search em strong, .check-pay form em strong").click(function () {
		$(this).parent().parent().find(".textbox").val($(this).text());
	});
	$(".specials-blocks form em strong").click(function () {
		$(this).parent().prev().val($(this).text());
	});
	
	
	$(".offline").live('click',function () {
		if ($(this).children("em").css("display") != "block") {
			$(".offline em").css("display", "none");
			$(this).children("em").css("display", "block");
		} else {
			$(".offline em").css("display", "none");
		}
		return false;		
	});
	
	$(".have").live('click', function () {
		if ($(this).css("z-index") != "999") {
			$(".have").css("z-index", "0");
			$(".have .more").css("display", "none");
			$(this).css("z-index", "999");
			$(this).children(".more").css("display", "block");
			
		} else {
			$(".have").css("z-index", "0");
			$(".have .more").css("display", "none");
		}
		return false;
	});
	$(".item-list .shop").live('click', function () {
		if ($(this).children(".hidden-block").css("display") == "block") {
			$(this).children(".hidden-block").fadeOut(300);
		} else {
			$(".item-list .shop .hidden-block").css("display", "none");
			$(this).children(".hidden-block").fadeIn(300);
		}
	});
	
	
	
	
	
	$(".specials-blocks form .textbox").focus(function () {
		if ($(this).val() == "Номер счета…")
			$(this).val("");
	});
	$(".specials-blocks form .textbox").focusout(function () {
		if ($(this).val().length == 0)
			$(this).val("Номер счета…");
	});
	
	
	
	$(".product, .order").live('submit', function () {
		var self = this;
		var data = $(this).serialize();
		$.post('?ajax=1&block=basket',data,function(data,status){
			if( status=='success'){
				$(".basket").html($(data).html()).removeClass("basket-empty");
				if ($(self).attr("class") == "product") 
				{
					$(self).find(".border").addClass("done").html("Добавлено в корзину<br /><a href='/general/basket/1/'>Оформить заказ</a>");
					
				} else 
				{
					$(self).find(".border input").blur();
					if (! $(self).find(".done").html())
					{
						$(self).find(".submit-box").append("<div class='done'>Добавлено в корзину<br /><a href='/general/basket/1/'>Оформить заказ</a></div>");
					}
				}
			}
		});
		return false;
	});
	$(".view-more input").click(function () {
		var self = this;
		var searchVar='';
		$(self).css("display", "none");
		$(self).parent().css("background", "url(/images/front-end/ajax-loader.gif) 50% 50% no-repeat");
		if (location.href.split("?")[1] != 'undefined') searchVar = location.href.split("?")[1]+"&";
		
		$.post('?'+searchVar+'ajax=1&block=content&page='+pageNum,function(data,status){
			if( status=='success'){
				$(self).css("display", "block");
				$(self).parent().attr("style", "");
				$("body").append("<div class='temp' style='display:none'></div>");
				$(".item-list").append($(".temp").append($(data)).find(".product"));
				$(".temp").remove();
				pageNum++;
				if (pageNum <= lastPage){
					return pageNum;
					
				} else {
					$(self).parent().css("display", "none");
				}
			}
		});
	});
	
	
	/***********************************************
	*
	* Карточка товара
	*
	***********************************************/
	if (ca=location.hash.toString().split('-')[0].substr(1))
	{	
		$(".about-product .controls span").removeClass("active");
		$(".about-product .item-tab").css("display", "none");
		$(".about-product .controls span#_"+ca).addClass("active");
		$(".about-product .item-tab:eq("+$(".about-product .controls span#_"+ca).index()+")").css("display", "block");
		
		$("a[name="+location.hash.toString().substr(1)+"]").parents().css("display", "block");
		if ($("a[name="+location.hash.toString().substr(1)+"]").length) {
			var scrollTopElem = $("a[name="+location.hash.toString().substr(1)+"]").offset().top;
			if (/chrome/.test(navigator.userAgent.toLowerCase())) {
				var element = 'body';
			} else {
				var element = 'html';
			}
			$(element).animate({scrollTop : scrollTopElem},500);
		}
		
	}
	else
	{
		$(".about-product .controls span:first").addClass("active");
		$(".about-product .item-tab").css("display", "none");
		$(".about-product .item-tab:first").css("display", "block");
	}
	
   
	if ($(".about-product .item-tab").length <2 ) {
		$(".about-product .item-tab i.active").css("left", "42px");
	}
	
	
	
	
	
	$(".about-product .controls span").click(function () {
		if ($(this).attr("class") == "active")
			return true;
		var self = this;
		$(".about-product .controls span").removeClass("active");
		location.assign('#'+$(this).attr('id').substr(1));
		$(this).addClass("active");
		
		$(".about-product .item-tab").slideUp(300, function () {
			
		});
		setTimeout(function () {$(".about-product .item-tab:eq("+$(self).index()+")").slideDown(300);}, 300);
		return false;
	});
	
	
	$(".pics .other-pics span").click(function () {
		$(".pics .other-pics span").removeClass("active");
		$(this).addClass("active");
		$(".pics .current-pic img").attr("src", $(this).attr("title"));
		return false;
	});
	
	$(".hide-form").live("click", function () {
		$(this).removeClass("hide-form").addClass("show-form").children("em").text("Написать отзыв");
		$("#protuct-list.about-product h2, #protuct-list.about-product form").css("display", "none");
	});
	$(".show-form").live("click", function () {
		$(this).removeClass("show-form").addClass("hide-form").children("em").text("Скрыть форму");
		$("#protuct-list.about-product h2, #protuct-list.about-product form").css("display", "block");
	});
	
	
	$(".comment .complaint").click(function () {
		var commentId = $(this).attr("href");
		var overlay = '<div class="complaint-overlay"></div><form method="post" class="complaint-form"><input type="hidden" name="module" value="catalogue"><input type="hidden" name="object" value="message"><input type="hidden" name="handler" value="complaint"><input type="hidden" name="message[messageId]" value="'+commentId+'"  /><abbr class="close" title="Закрыть">Закрыть</abbr><div class="title">Пожаловаться на комментарий</div><div  class="field">На что жалуетесь?<textarea name="message[complaint]"></textarea></div><input type="submit" class="submit" value="Отправить жалобу" /><input type="reset" class="reset" value="отменить" /></form>';
		$("body").append(overlay);
		return false;
	});
	$(".complaint-overlay, .complaint-form .reset, .complaint-form .close").live("click", function () {
		$(".complaint-overlay, .complaint-form").remove();
	});
	$(".complaint-form").live("submit", function () {
		var self  = $(this);
		var data = $(this).serialize();
		$.ajax({
 		    type: "POST",
			url: "?ajax=1&block=content",
			data: data,
			context: document.body,
			success: function(){
				self.html("<div class='done'>Сообщение отправлено</div>");
				setTimeout(function () {
					$(".complaint-overlay, .complaint-form").remove();
				}, 1000);
			}
		});
		return false;
	});
	
	
	/**************************************
	*
	* Кликер появления новых комментов
	*
	***************************************/
	
	$(".comment .after-text .answers").click(function () {
		var hiddenComments = $(this).parent().parent().parent().children(".comment-overlay");
		if (hiddenComments.css("display") == "block") {
			hiddenComments.css("display", "none");
		} else {
			hiddenComments.css("display", "block");
		}
	});	
	
	
	
	
	
	/**************************************
	*
	* Рейтинг
	*
	***************************************/
	if ($('input.star').length) {
		$('input.star').rating();
	}
	
	/**************************************
	*
	* Форма пользователя
	*
	***************************************/
	
	if ($(".open-form").length) {
		$(".open-form").fancybox({
			'overlayShow'	: true,
			'transitionIn'	: 'elastic',
			'transitionOut'	: 'elastic'
		});
		
	}
	if ($(".fbox").length) {
	$(".fbox").fancybox({
		'overlayShow'	: true,
		'transitionIn'	: 'elastic',
		'transitionOut'	: 'elastic'
	});
	}
	/**************************************
	*
	* Показ/скрытие комментов в бойне моделей
	*
	***************************************/
	
	if ($(".view-comments").length) {
		if (location.href.split("#")[1] == "show-comment") {
			$(".view-comments a").html("Скрыть комментарии<br>к битве");
			$("#disqus_thread").slideDown(300);
		}
	
	
		$(".view-comments a").click(function () {
			if($("#disqus_thread").css("display") == "none") {
				$(this).html("Скрыть комментарии<br>к битве");
				$("#disqus_thread").slideDown(300);
			} else {
				$(this).html("Показать комментарии<br>к битве");
				$("#disqus_thread").slideUp(300);
			}
		});
		
	
	}
	
	/**************************************
	*
	* Показывание баннеров
	*
	***************************************/
	
	$(".hot-deals .clicker span").click(function () {
		if ($(this).attr("class") == "active") return true;
		var indexItem = $(this).index(".hot-deals .clicker span");
		$(this).parent().children("span").removeClass("active");
		$(this).addClass("active");
		$(".hot-deals .itemActive").fadeOut(350, function () { 
			if (navigator.appName.indexOf("Microsoft") != -1) {
				jsfstart($(".hot-deals  .item:eq("+indexItem+") object").attr("id"));
			} else {
				jsfstart($(".hot-deals .item:eq("+indexItem+") embed").attr("name"));
			}
		}).removeClass("itemActive");
		$(".hot-deals .item:eq("+indexItem+")").fadeIn(350).addClass("itemActive");
	});
	
	/**************************************
	*
	* Блок авторизации
	*
	***************************************/
	$("header .enter .pseudolink").click(function () {
		$(".login-form").slideDown(300);
		return false;
	});
	$(".login-form .close").click(function () {
		$(".login-form").slideUp(300);
	});
	/*$(".login-form").live("submit", function () {
		var data = $(this).serialize();
		var temp = 0;
		$.post('?',data,function(data,status){
			if( status=='success'){
				$("header .enter").html($(data).find("header .enter").html());
				$(".login-form").css("display", "block");
			}
		});
		if ($(".login-form .field .error").length) {
			temp = 1;
		}
		if (temp == 1) {
			return false;
		} else {
			return true;
		}
	});
	*/
	$(".new-comment").submit(function () {
		if ($(this).find("input[name='message[name]']").val() == "Ваше имя") {
			$(this).find("input[name='message[name]']").val("");
		}
		if ($(this).find("input[name='message[email]']").val() == "e-mail") {
			$(this).find("input[name='message[email]']").val("");
		}
	});
	
	if ($('.new-comment').length){
		for (i=0; i<$('.new-comment').length; i++){
			var elID = $('.new-comment:eq('+i+')').attr("id");
			$("#"+elID).validate({
				rules: {
						'message[name]': {'required': true},
						'message[email]': {'required': true},
						'message[text]': {'required': true}
					},
				messages: {
						'message[name]': "",
						'message[email]': "",
						'message[text]': ""
					},
				errorElement: 'em'
			});
		}
	}
	
	$(".hot-deals .clicker span").click(function () {
		if ($(this).attr("class") == "active") return true;
		var indexItem = $(this).index(".hot-deals .clicker span");
		$(this).parent().children("span").removeClass("active");
		$(this).addClass("active");
		$(".hot-deals .itemActive").fadeOut(350, function () { 
			if (navigator.appName.indexOf("Microsoft") != -1) {
				jsfstart($(".hot-deals  .item:eq("+indexItem+") object").attr("id"));
			} else {
				jsfstart($(".hot-deals .item:eq("+indexItem+") embed").attr("name"));
			}
		}).removeClass("itemActive");
		$(".hot-deals .item:eq("+indexItem+")").fadeIn(350).addClass("itemActive");
	});
	
	
		$('.feedback, #form-error-in-description').validate({
			rules: {
				'name': {'required': true},
				'data[name]': {'required': true},
				'data[fname]': {'required': true},
				'email': {'required': true, email: true},
				'data[email]': {'required': true, email: true},
				'orgname': {'required': true},
				'telphone': {'required': true},
				'orgaddress': {'required': true},
				'city': {'required': true},
				'data[cityName]': {'required': true},
				'address': {'required': true},
				'phone': {'required': true},
				'square': {'required': true},
				'data[password]': {'required': true},
				'data[repeatpassword]': {'required': true},
				'data[capcha]': {'required': true},
				'data[phone]': {'required': true}
			},
			messages: {
				'name': "Введите ваше имя",
				'data[name]': "Введите ваше имя",
				'data[fname]': "Введите вашу фамилию",
				'data[cityName]': "Введите город",
				'email': "Введите ваш E-mail",
				'data[email]': "Введите электронную почту",
				'orgname': "Введите название организации",
				'telphone': "Введите номер телефона",
				'orgaddress': "Введите адрес организации",
				'city': "Введите город",
				'address': "Введите адрес помещения",
				'phone': "Введите номер телефона",
				'square': "Введите площадь помещения",
				'data[password]': "Не менее 6-х любых символов",
				'data[repeatpassword]': "Повторите пароль",
				'data[capcha]': "Введите код с картинки",
				'data[phone]': "Введите номер мобильного телефона"
			},
			errorElement: 'em'
		});
	$("#form-to-mush, #form-error-in-description").live('submit', function () {
		var self = this;
		$(self).css("height", $(self).height());
		var data = $(this).serialize();
		$(self).html("<h2>Ваше сообщение отправляется</h2>");
		$.post('?',data,function(data,status){
			
			if( status=='success'){
				$(self).html("<h2>Ваше сообщение отправлено</h2>");
				setTimeout(function () {$("#fancybox-wrap, #fancybox-overlay").css("display", "none")}, 1000);
			}
		});
		return false;
	});
	
	
	
	if ($("#form-to-mush").length) {
		$("#form-to-mush").validate({
			rules: {
				'data[name]'    : {'required': true},
				'data[phone]'   : {'required': true},
				'data[price]'   : {'required': true}
			},
			messages: {
				'data[name]'    : "Введите ваше имя",	
				'data[phone]'   : "Введите ваш телефон",
				'data[price]'   : "Введите цену"
			},
			errorElement: 'em'
		});
	}

	if ($('#form-report').length)
	{
		$('#form-report').validate({
			rules: {
				'data[name]'    : 'required',
				'data[email]'   : {required: true, email: true},
				'data[cityName]': 'required',
				'data[rating]'  : {required:  function(element) {element.value=''; return true;}},
				'data[report]'  : 'required',
				'data[advantages]': 'required',
				'data[limitations]': 'required'
			},
			messages: {
				'data[name]'    : "Введите ваше имя",
				'data[email]'   :   "Введите ваш E-mail",
				'data[cityName]': "Введите город",
				'data[rating]': "Введите оценку",
				'data[report]': "Введите отзыв",
				'data[advantages]': "Введите достоинства",
				'data[limitations]': "Введите недостатки"
			},
			errorElement: 'em'
		});
	}
	
	if ($("#form-error-in-description").length) {
		$("#form-error-in-description").validate({
			rules: {
				'data[descrErrorInfo]': {'required': true}
			},
			messages: {
				'data[descrErrorInfo]': "Введите описание ошибки"	
			},
			errorElement: 'em'
		});
	}
	
	
});

function thisMovie(movieName) {
	
	if (navigator.appName.indexOf("Microsoft") != -1) {
	
		return window[movieName];
	} else {
		return document[movieName];
	}
}
function jsfstart(value) {
	if (typeof thisMovie(value).jsfstart == 'function') 
	{
		thisMovie(value).jsfstart();
	}
}
function jsfstop(value) {
	if ($("#"+value).parent().css("display") == "none") return false;
	var indexItem = $(".hot-deals .itemActive").index()+1;
	
	if (indexItem+1 > $(".hot-deals .item").length) {
		indexItem = 0;
	}
	$(".hot-deals .itemActive").fadeOut(350, function () { 
		if (navigator.appName.indexOf("Microsoft") != -1) {
			jsfstart($(".hot-deals  .item:eq("+indexItem+") object").attr("id"));
		} else {
			jsfstart($(".hot-deals .item:eq("+indexItem+") embed").attr("name"));
		}
	}).removeClass("itemActive");
	$(".hot-deals .item:eq("+indexItem+")").fadeIn(350).addClass("itemActive");
		
	$(".hot-deals .clicker span").removeClass("active");
	$(".hot-deals .clicker span:eq("+indexItem+")").addClass("active");
}	
	
	
		
	
	
$(window).load(function () {
	if ($(".hot-deals .clicker").length) {
		if (navigator.appName.indexOf("Microsoft") != -1) {
			jsfstart($(".hot-deals .item:eq(0) object").attr("id"));
		} else {
			jsfstart($(".hot-deals .item:eq(0) embed").attr("name"));
		}
	}
});

function showElement(elem) {
		if ($("#"+elem).css("display") == "block") {
			$("#"+elem).css("display", "none");
		} else {
			$("#"+elem).css("display", "block");
		}
	};


	

