$(document).ready(function(){
    
	
	
	
	$("body").append('<div id="alertboxList"></div>');
    $.opt = {};
    $.opt = {
        cHeight: $.opt.cHeight = ($.browser.mozilla || $.browser.safari ? $(window).height() : document.documentElement.clientHeight),
        sTop: $(document).scrollTop(),
        wLoc: window.location.href.replace(window.location.hash,""),
        wHash: window.location.hash
    };
    
    $("#forgot").click(function(){
        var emailObj = $('form#authform input[name="email"]'), email = emailObj.attr("value");
        var par = emailObj.parent().parent();
        if(email.length == 0) {
            alert('Не забудьте ввести свой e-mail адрес.');            
            par.css("color","red");
            emailObj.focus();
            return false;
        }
        if(email.length < 6) {
            alert('Неправильно введен e-mail адрес.\nПожалуйста введите свой e-mail адрес, который был указан при регистрации.');
            par.css("color","red");
            emailObj.focus();
            return false;
        }
        jQuery.ajax({
            type: "GET",
            url: "/ajax_profile.php?forget=true&email=" + email,
            timeout: 10000,
            encoding: "cp1251",
            error: function(){ alert('We got an error during try to submit your request'); },
            success: function(r){
                alert(r);
                if(r.substr(0,2) == 'На') {
                    par.css("color","green");
                } else {
                    par.css("color","red");
                }
            }
        });   
    });
    
    $("#alogin").click(showLoginScreen);
    $("#alogin2").click(showLoginScreen);
   /* 
    $(".r1 img").each(function() { 
        var src = $(this).attr('src'), parenT = $(this).parent();
        if(src != '/i/nofoto.gif') {
            var img = new Image();
            $(this).parent().append('<div style="background: url(\'/i/ajax-loader.gif\') no-repeat center center; display: block; width: 140px; height: 50px;"></div>');
            $(this).remove();            
            $(img).load(function(){
                $(this).hide();
                parenT.find("div").remove();
                parenT.append(this);
                $(this).fadeIn();
            }).attr('src',src);            
        }
    });*/
    
    // Отображаем или скрываем вендоров
    $("div.sbutton").css("cursor","pointer").click(function (e) {
        var hV = $("#hiddenVendors"), hVa = hV.length;
        if($("#hiddenVendors_cont").length) {
            if(!hVa) {
                $("body").append("<div id=\"hiddenVendors\" style=\"display: none;\">" + $("#hiddenVendors_cont").html() +"</div>");
                var fromTop = (parseInt(($("#hiddenVendors").height() / 2)) * -1) + parseInt($(window).scrollTop()) + "px";
                var fromLeft = $("#hiddenVendors").width() / 2 + "px";
                $("#hiddenVendors")
                  .css("position","absolute")
                  .css("top","50%")
                  .css("min-height","310px")
                  .css("left","40%")
                  .css("margin-top",fromTop)
                  .css("margin-left","-" + fromLeft)
                  .css("padding","20px")
                  .css("z-index","900000")
                  .css("background-color","white")
                  .css("border","4px solid #E0E0E0")
                  .show();
                  $("div.sbutton_close").unbind("click");
                  $("div.sbutton_close").click(function() { 
                    $("div.sbutton a").html("<img src=\"/i/svdn.gif\"> Все бренды"); $("#hiddenVendors").remove(); return false; 
                  });  
            } else {
                $("#hiddenVendors").remove();
            }            
        } else {
            if($("ul.hd").is(":hidden")) {        
                $("ul.hd").show();
                $("div.sbutton a").html("<img src=\"/i/svup.gif\"> Все бренды");
                return false;    
            } else {        
                $("ul.hd").hide();
                $("div.sbutton a").html("<img src=\"/i/svdn.gif\"> Все бренды");
                return false;
            }
        }   
    });
    
    // Отправляем форму Options (сортировка, TovarsPerPage)
    $("select#tpp").change(function(){
        $(this).parents('form').submit();
    });
    $("select#sort").change(function(){
        $(this).parents('form').submit();
    });
	$("select#nalichie").change(function(){
        $(this).parents('form').submit();
    });
 
    // Открываем ссылки начинающиеся с '/news/cat_img/' в отдельном окне.
    $("a[@href^='/news/cat_img/']").click(function(){        
        var name = $(this).attr('href').substr(14);
        var wName = $(this).attr('title');                
        nAma = wName.split(','); 
        wName = nAma[0];
        geometry = nAma[1].split('x');
        var width = parseInt(geometry[0]) + parseInt(30);
        var height = parseInt(geometry[1]) + parseInt(65);
        
        var left = parseInt((screen.availWidth/2) - (width/2));
        var top = parseInt((screen.availHeight/2) - (height/2));
        var options = "menubar=yes,location=yes,resizable=yes,scrollbars=yes,status=no,width=" + width + ",height=" + height + ",top=" + top + ",left=" + left;
        
        myWindow = window.open('/news/preview/' + name, wName, options);
        myWindow.focus();               
        return false;
    });
    $(window).resize(function(){$.opt.cHeight = ($.browser.mozilla || $.browser.safari ? $(window).height() : document.documentElement.clientHeight);});
    $(window).scroll(function(){$.opt.sTop = $(document).scrollTop();});    
    imagePreview();
    checkCommentsInput();
    showVotes();
	showRegions();
	showMoscow();
    
	var bindBehaviors = function() {
	
    // Sending comments by ajax.
    $("#sendComment :input").keyup(checkCommentsInput);
    $('#sendComment').submit(function(){
        var inputs = [];
		nameok=false;
		typeok=false;
        $(':input',this).each(function(){
            if (this.name=='tov_id') {nameok=true;}
			if (this.name=='comment_type') {typeok=true;}
			inputs.push(this.name + '=' + $(this).attr("value").replace(/&/g,'::amp::'));
        });

		if (nameok==false) {inputs.push('tov_id=' + $('#tov_id').attr("value").replace(/&/g,'::amp::'));}
		if (typeok==false) {inputs.push('comment_type=' + $('#comment_type').attr("value").replace(/&/g,'::amp::'));}

		jQuery.ajax({
			data: inputs.join('&'),
			type: "POST",
			url: '/addComment.php',
			timeout: 10000,
			encoding: "cp1251",
			error: function(e) {
				alert('We got an error during try to submit comment: '+inputs);
			},
			success: function(r) {
				var data = [];
					data = r.split("\n");
				var result = data[0];
					data.shift();
					data = data[0];
				if(result == 202) {
					var comment_parent_id = $('#comment_parent_id').val();
					if (comment_parent_id>0)
					{
						$("#li_"+comment_parent_id+"").append('<ul class="comment_ul"><li class="comment_li">'+data+'</li></ul>');
						$('.comment_reply_block').html('');
						$('.comment_reply_block').hide();
						$('#reply_0').show();
						new_text = '<div id="reply_to_0" class="addcomment"><form id="sendComment" method="post"><div class="forms_name">Ваш отзыв:</div><div class="forms_inputs"><div><textarea id="comment_text" name="text"></textarea></div><div align="right" style="margin-top: 5px;"><input type="submit" id="submit" value="Отправить"></div></form><div class="clear"></div></div>';
						$('#reply_0').html(new_text);
						bindBehaviors();
					}
					else
					{
						$("#comments_list").prepend(data);
					}
					$("#sendComment textarea").val("");
					$("#sendComment #submit").attr("disabled","disabled");
					showAlert('Комментарий был добавлен!');
					var inc = $("#comm .tov_count").html().replace("(","").replace(")","");                                                
						inc = parseInt(inc) + 1;
					$("#comm .tov_count").html("("+inc+")");
				}
				else { alert("We\'re so sorry, but some error catched during try to post your comment"+inputs); }
			}
		});        
        return false;
    });
	
	}
	bindBehaviors();

    $("#addBasketBtn").click(function(){
        addToCart($(this).attr("rel"));
    });
	$(".toOrder").click(function(){
        addToPartnerOrder($(this).attr("rel"));
    });
	$("#addOrderBtn").click(function(){
        addToCart($(this).attr("rel"));
    });
	$("#addRemindBtn").click(function(){
        addToRemindList($(this).attr("rel"));
    });
	$("#addRemindMeBtn").click(function(){
        addToRemindList($(this).attr("rel"));
    });
	$("#addWishListBtn").click(function(){
        addToWishList($(this).attr("rel"));
    });
	$("#removeWishListBtn").click(function(){
        RemoveFromWishList($(this).attr("rel"));
    });
    $(".toCart").mousedown(function(){
        addToCart($(this).attr("rel"));
        $(this).css("color","#E67300");
        $(this).onselectstart = function() { return false; }
        $(this).onmousedown = function() { return false; }
        return false;
    }).mouseup(function(){
        $(this).css("color","#000");
        $(this).onselectstart = function() { return false; };
        $(this).onmousedown = function() { return false; };
        return false;
    });
    // Button switching between Descriptions and Comments
    var dop = $(".inner .main .dop"),
        op = $(".inner .main .d"),
        comm = $(".inner .main .comments"),
		wish = $(".inner .main .wish_list"),
		addit = $("#addit_list"),
		alter = $("#alter_list");
		sharel = $("#share_list");
		spec_tov = $("#spec_tov_list");
		new_tov = $("#new_tov_list");
		hit_tov = $("#hit_tov_list");
		view_tov = $("#view_tov_list");
    
	function removeSwitchButtons()
	{
		dop.hide(); op.hide(); comm.hide(); wish.hide(); addit.hide(); alter.hide(); sharel.hide();
        $("#desc").removeClass("sel"); $("#comm").removeClass("sel"); $("#wish").removeClass("sel"); $("#addit").removeClass("sel"); $("#alter").removeClass("sel");$("#share").removeClass("sel");
	}
    
    $("#desc").click(function(){
            removeSwitchButtons();
			dop.show(); op.show();
			$("#desc").addClass("sel");
            $("#desc img").attr("src","/i/svdn.gif");
            $("#comm img").attr("src","/i/svup.gif");
			$("#wish img").attr("src","/i/svup.gif");
            window.location.href = $.opt.wLoc + "#description";
    });
    $("#comm").click(function(){
            removeSwitchButtons();
			comm.show();
			$("#comm").addClass("sel");
            $("#desc img").attr("src","/i/svup.gif");
            $("#comm img").attr("src","/i/svdn.gif");
			$("#wish img").attr("src","/i/svup.gif");
            window.location.href = $.opt.wLoc + "#comments";
    });
	$("#wish").click(function(){
            removeSwitchButtons();
			wish.show();
			$("#wish").addClass("sel");
            $("#desc img").attr("src","/i/svup.gif");
            $("#comm img").attr("src","/i/svup.gif");
			$("#wish img").attr("src","/i/svdn.gif");
            window.location.href = $.opt.wLoc + "#wish_list";
    });

	$("#addit").click(function(){
            removeSwitchButtons();
			addit.show();
			$("#addit").addClass("sel");
            window.location.href = $.opt.wLoc + "#additlist";
    });

	$("#alter").click(function(){
            removeSwitchButtons();
			alter.show();
			$("#alter").addClass("sel");
            window.location.href = $.opt.wLoc + "#alterlist";
    });

	$("#share").click(function(){
            removeSwitchButtons();
			sharel.show();
			$("#share").addClass("sel");
            window.location.href = $.opt.wLoc + "#sharelist";
    });

	$("#hit_tov").click(function(){
			$("#view_tov").removeClass("sel");
			$("#spec_tov").removeClass("sel");
            $("#new_tov").removeClass("sel");
			new_tov.hide();
			spec_tov.hide();
			view_tov.hide();
			hit_tov.show();
			$("#hit_tov").addClass("sel");
            window.location.href = $.opt.wLoc + "#hittov";
    });
	
	$("#view_tov").click(function(){
			$("#hit_tov").removeClass("sel");
			$("#spec_tov").removeClass("sel");
            $("#new_tov").removeClass("sel");
			new_tov.hide();
			spec_tov.hide();
			hit_tov.hide();
			view_tov.show();
			$("#view_tov").addClass("sel");
            window.location.href = $.opt.wLoc + "#viewtov";
    });

	$("#spec_tov").click(function(){
			$("#hit_tov").removeClass("sel");
            $("#new_tov").removeClass("sel");
			$("#view_tov").removeClass("sel");
			new_tov.hide();
			hit_tov.hide();
			view_tov.hide();
			spec_tov.show();
			$("#spec_tov").addClass("sel");
            window.location.href = $.opt.wLoc + "#spectov";
    });

	$("#new_tov").click(function(){
			$("#spec_tov").removeClass("sel");
            $("#hit_tov").removeClass("sel");
			$("#view_tov").removeClass("sel");
			hit_tov.hide();
			spec_tov.hide();
			view_tov.hide();
			new_tov.show();
			$("#new_tov").addClass("sel");
            window.location.href = $.opt.wLoc + "#newtov";
    });
    // ^^ end of BSBDC
    
    // switching by URI
    switch($.opt.wHash) {
        case '#comments':
            dop.hide(); op.hide(); comm.show();
            $("#comm").addClass("sel"); $("#desc").removeClass("sel");
            $("#desc img").attr("src","/i/svup.gif");
            $("#comm img").attr("src","/i/svdn.gif");
            break;
        case '#description':
            dop.show(); op.show(); comm.hide();
            $("#desc").addClass("sel"); $("#comm").removeClass("sel");
            $("#desc img").attr("src","/i/svdn.gif");
            $("#comm img").attr("src","/i/svup.gif");            
            break;
		case '#wish_list':
			dop.hide(); op.hide(); comm.hide(); wish.show();
            $("#comm").removeClass("sel"); $("#desc").removeClass("sel"); $("#wish").addClass("sel");
            $("#desc img").attr("src","/i/svup.gif");
            $("#comm img").attr("src","/i/svup.gif");
			$("#wish img").attr("src","/i/svdn.gif");          
			break;
		case '#additlist':
			removeSwitchButtons();
			addit.show();
			$("#addit").addClass("sel");
			break;
		case '#alterlist':
			removeSwitchButtons();
			alter.show();
			$("#alter").addClass("sel");       
			break;
		case '#sharelist':
			removeSwitchButtons();
			sharel.show();
			$("#share").addClass("sel");       
			break;
        default:
            //window.location.href = $.opt.wLoc;
    }               
    // ^^ end of SBU
    
    $("#vStar1").hover(function(){onhoverStars(1);},function(){onoutStars(1);}).click(function(){vfStar(1);});
    $("#vStar2").hover(function(){onhoverStars(2);},function(){onoutStars(2);}).click(function(){vfStar(2);});
    $("#vStar3").hover(function(){onhoverStars(3);},function(){onoutStars(3);}).click(function(){vfStar(3);});
    $("#vStar4").hover(function(){onhoverStars(4);},function(){onoutStars(4);}).click(function(){vfStar(4);});
    $("#vStar5").hover(function(){onhoverStars(5);},function(){onoutStars(5);}).click(function(){vfStar(5);});
    $(".delete_button").hover(function(){
        $(this).css("background-position","32 0");
        $(this).css("cursor","Pointer");
        return false;
    },function(){
        $(this).css("background-position","0 0");
        return false;
    }).mousedown(function(){
        $(this).css("background-position","16 0");
        cartDelete($(this),$(this).attr("rel"));
    }).mouseup(function(){
        $(this).css("background-position","32 0");
        return false;
    });
    $("#addBasketBtn").hover(function()
		{$(this).css("background-position","0 40")},function(){$(this).css("background-position","0 0")}).mousedown(function(e){
        document.getElementById("price").onselectstart = function() { return false; }
        document.getElementById("price").onmousedown = function() { return false; }
        $(this).css("background-position","0 20");
        animatePlus(e);
    }).mouseup(function(){
        document.getElementById("price").onselectstart = "";
        document.getElementById("price").onmousedown = "";
        $(this).css("background-position","0 40");
    });
	$("#addRemindBtn").hover(function()
		{$(this).css("background-position","0 40")},function(){$(this).css("background-position","0 0")}).mousedown(function(e){
        document.getElementById("price").onselectstart = function() { return false; }
        document.getElementById("price").onmousedown = function() { return false; }
        $(this).css("background-position","0 20");
        animatePlus(e);
    }).mouseup(function(){
        document.getElementById("price").onselectstart = "";
        document.getElementById("price").onmousedown = "";
        $(this).css("background-position","0 40");
    });

	$("#addOrderBtn").hover(function()
		{$(this).css("background-position","0 40")},function(){$(this).css("background-position","0 0")}).mousedown(function(e){
        document.getElementById("price").onselectstart = function() { return false; }
        document.getElementById("price").onmousedown = function() { return false; }
        $(this).css("background-position","0 20");
        animatePlus(e);
    }).mouseup(function(){
        document.getElementById("price").onselectstart = "";
        document.getElementById("price").onmousedown = "";
        $(this).css("background-position","0 40");
    });

	$("#addRemindBtn").hover(function(){$(this).css("background-position","0 40")},function(){$(this).css("background-position","0 0")})
	$("#addWishListBtn").hover(function(){$(this).css("background-position","0 40")},function(){$(this).css("background-position","0 0")})
	$("#removeWishListBtn").hover(function(){$(this).css("background-position","0 40")},function(){$(this).css("background-position","0 0")})
	$(".voting .auth .vote_minus").hover(function(){$(this).css("background-position","left 39")},function(){$(this).css("background-position","left 52")})
	$(".voting .auth .vote_plus").hover(function(){$(this).css("background-position","right 39")},function(){$(this).css("background-position","right 52")})
	
	$(".voting .auth .vote_plus").click(function(){
		comment_n = $(this).attr("rel");
		$("#vote_"+comment_n).removeClass("voting");
		$("#vote_"+comment_n).addClass("voted");
		$("#vote_"+comment_n+" .vote_buttons").empty();
		$("#vote_"+comment_n+" .vote_buttons").append('<span rel="'+comment_n+'" class="vote_minus vote-for-comment" title="Плохой комментарий"></span><span rel="'+comment_n+'" class="voted_plus vote-for-comment" title="Хороший комментарий"></span>');
		changeVoteMark(comment_n,1);
    });

	$(".voting .auth .vote_minus").click(function(){
		comment_n = $(this).attr("rel");
		$("#vote_"+comment_n).removeClass("voting");
		$("#vote_"+comment_n).addClass("voted");
		$("#vote_"+comment_n+" .vote_buttons").empty();
		$("#vote_"+comment_n+" .vote_buttons").append('<span rel="'+comment_n+'" class="voted_minus vote-for-comment" title="Плохой комментарий"></span><span rel="'+comment_n+'" class="vote_plus vote-for-comment" title="Хороший комментарий"></span>');
		changeVoteMark(comment_n,-1);
    });

	function changeVoteMark(comment_n,vote_val)
	{
		old_val = $("#vote_"+comment_n+" .vote_mark .vote_num").html();
		new_val = old_val*1+vote_val;
		
		jQuery.ajax({
        data: { comment_id: comment_n,vote_value: vote_val},
        type: "POST",
        url: "/addCommentVote.php",
        timeout: 10000,
        encoding: "cp1251",
        error: function(){ alert('We got an error during try to submit your vote choice'); },
        success: function(r){
				if (new_val>0)
				{
					$("#vote_"+comment_n+" .vote_mark span").removeClass("vote_red");
					$("#vote_"+comment_n+" .vote_mark span").addClass("vote_green");
					$("#vote_"+comment_n+" .vote_mark .vote_symbol").html('+');
				}
				else if (new_val==0)
				{
					$("#vote_"+comment_n+" .vote_mark span").removeClass("vote_red");
					$("#vote_"+comment_n+" .vote_mark span").removeClass("vote_green");
					$("#vote_"+comment_n+" .vote_mark .vote_symbol").html('');
				}
				else
				{
					$("#vote_"+comment_n+" .vote_mark span").addClass("vote_red");
					$("#vote_"+comment_n+" .vote_mark span").removeClass("vote_green");
					$("#vote_"+comment_n+" .vote_mark .vote_symbol").html('');
				}
				$("#vote_"+comment_n+" .vote_mark .vote_num").html(new_val);
				showAlert('Оценка была поставлена!');
			}
		});
	}

    $(".carttovar .count input").keyup(function(){
        cartUpdateTov($(this).attr("name"),$(this).attr("value"));
        $(".cart_bottom .nal").html(number_format(checkCartSum(),0,","," ") + " руб.");
    });
    $("#cashout").click(function(){
        $(".reginfo").toggle();
        //$(this).attr("disabled","disabled");
    });
    
    var mHeight = 0;
    $("#advices .column").each(function(){
        //alert($(this).height());
        if($(this).height() > mHeight) { mHeight = $(this).height(); }
    });
    $("#advices .column").each(function(){
        $(this).height(mHeight + "px");
    });
    
    
    // ########   FORMS
    // ######## 
    $("#ihave").click(function(){
        if($(this).attr("checked")) {
            $(".discountcard").show();
			$(".cardholder").show();
			$(".cardnumber").show();
        } else {
            $(".discountcard").hide();
            $("input[name=discountcard_fio]").attr("value","");
            $("input[name=discountcard_number]").attr("value","");
			$(".cardholder").hide();
			$(".cardnumber").hide();
        }
    });

	$('.comment_reply').click(function(){
		var rel = this.rel;
		$('.comment_reply_block').html('');
		$('.comment_reply_block').hide();
		$('#reply_'+rel).show();
		new_text = '<ul class="comment_ul"><li class="comment_li"><div id="reply_to_'+rel+'" class="addcomment"><form id="sendComment" method="post"><div class="forms_name">Ваш отзыв:</div><div class="forms_inputs"><div><textarea id="comment_text" name="text"></textarea></div><div align="right" style="margin-top: 5px;"><a href="#reply_to_0"  class="comment_cancel" onclick="cancelReply();">отменить</a><input type="hidden" id="comment_parent_id" name="comment_parent_id" value="'+rel+'" /><input type="submit" id="submit" value="Отправить" disabled="disabled"></div></div></form></li></ul>';
		$('#reply_'+rel).html(new_text);
		$('#comment_text').focus();
		bindBehaviors();
	});

	$("#ireg").click(function(){
        if($(this).attr("checked")) {
            $(".passwd_block").show();
        } else {
            $(".passwd_block").hide();
            $("input[name=passwd]").attr("value","");
        }
    });
	
    $("input[name=person]").click(function(){
        if($("#person").attr("checked")) {
            $("#props_div").show();
        } else {
            $("#props_div").hide();
        }
    });
	
	


    $("#town").change(function(){
        if($(this).attr("value") == "Москва") {
			if ($("input[name=delivery_type]").value!="Самовывоз")
			{
				$("#select_metro").show();
			}
			$('input[name="delivery_type"]').attr('checked', false);
			$('#delivery_type_2').attr('checked', true);
			$('#delivery_type_3').attr('disabled', true);
			$('#delivery_type_2').attr('disabled', false);
			$('#delivery_type_1').attr('disabled', false);
        } else {
            $("#select_metro").hide();
			$('input[name="delivery_type"]').attr('checked', false);
			$('#delivery_type_3').attr('checked', true);
			$('#delivery_type_3').attr('disabled', false);
			$('#delivery_type_2').attr('disabled', true);
			$('#delivery_type_1').attr('disabled', true);
        }
		check_form_error();
    });

	$("input[name=delivery_type]").click(function(){
		delivery_value = this.value;
		if (delivery_value=="Самовывоз")
		{
			$("#select_metro").hide();
			$("#address").html("Самовывоз из магазина м. Таганская");
		}
		else
		{
			if ($("#town").attr("value")=="Москва") { $("#select_metro").show();}
			$("#address").html("");
		}
    });
	
	if($("#town").attr("value") == "Москва") {
        $("#select_metro").show();
    } else {
        $("#select_metro").hide();
    }
	
	
    if($("#ihave").attr("checked")) {
        $(".discountcard").show();
    }
    if($("#person").attr("checked")) {
        $("#props_div").show();
    }
    
    
    
    $("#lastorder .image").click(function(){
        $(window).attr("location",$(this).find("span a").attr("href"));
    });
    
    // ##################
    // ##################

});
//this.cartUpdateTov = function(tovid,num) {
//    $.post("/ajax_cart.php?update",{ tov_id: tovid, number: num });
//};
/*
this.cartDelete = function(e,tovid) {
    jQuery.ajax({
        data: { tov_id: tovid },
        type: "POST",
        url: "/ajax_cart.php?del",
        timeout: 10000,
        error: function(){},
        success: function(r){
            if(r == 0) {
                e.parent().parent().fadeOut("slow",function(){
                    $(this).remove();
                    $(".cart_bottom .nal").html(number_format(checkCartSum(),0,","," ") + " руб.");
                });
            } else {
                alert("Возникли некоторые трудности.");
            }
        }
    });
};
*/
this.number_format = function ( number, decimals, dec_point, thousands_sep ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +     bugfix by: Michael White (http://crestidg.com)
    // +     bugfix by: Benjamin Lupton
    // +     bugfix by: Allan Jensen (http://www.winternet.no)
    // +    revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +     bugfix by: Howard Yeend
    // *     example 1: number_format(1234.5678, 2, '.', '');
    // *     returns 1: 1234.57     
 
    var n = number, c = isNaN(decimals = Math.abs(decimals)) ? 2 : decimals;
    var d = dec_point == undefined ? "." : dec_point;
    var t = thousands_sep == undefined ? "," : thousands_sep, s = n < 0 ? "-" : "";
    var i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "", j = (j = i.length) > 3 ? j % 3 : 0;
    
    return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
}
this.checkCartSum = function() {
    var summ = 0;
    $(".cartcont .carttovar").each(function(i){
        summ += $(this).find("input").attr("value") * $(this).find(".price").html().replace(" руб.","").replace(/ /g,"");
    });
    return summ;
};
this.animatePlus = function(e) {
    return false;
    $("body").append("<p style=\"display: none\" id=\"plusik\">+1</p>");
    $("#plusik")
        .css("position","absolute")
        .css("top",e.pageY + "px")
        .css("left",e.pageX + "px")
        .fadeIn("slow");
        //.animate({ opacity: 1 }, { queue:false, duration:3000 });
};
this.onhoverStars = function(num) { for(var i = 1; i <= num; i++) $("#vStar"+i).css("background-position","14 14"); return false; };
this.onoutStars = function(num) { for(var i = 1; i <= num; i++) $("#vStar"+i).css("background-position","0 0"); return false; };
this.vfStar = function(num) {

    voteErrors = new Array();
    voteErrors[105] = "Для того, чтобы иметь возможность голосовать,\nВам необходимо зарегистрироваться на сайте,\nесли Вы этого не сделали раньше и авторизироваться.";
    voteErrors[106] = 'Вы уже отдали свой голос за этот товар';
    voteErrors[107] = 'Внутренняя ошибка БД';

    // ajax here.
    jQuery.ajax({
        data: "vote="+num,
        type: "POST",
        url: "/addVote.php",
        timeout: 10000,
        encoding: "cp1251",
        error: function(){ alert('We got an error during try to submit your vote choice'); },
        success: function(r){
            var data = [];
                data = r.split("\n"); 
            if(voteErrors[r]) { alert(voteErrors[r]); return false; }
            if(data[0] == 0) {
                displayMark(data[1],data[2],num);
				showAlert('Оценка была поставлена!');
                return false;
            }
            alert(r);
        }
    });     
};
this.displayMark = function(mark,people,own) {
    var stars = '';
    for(var i = 1; i <= 5; i++) { 
        if(i <= Math.round(mark)) stars += '<img src="/i/star.gif">';
        else stars += '<img src="/i/star_.gif">'; 
    }
    $(".rating").append("\n<div class=\"o\" id=\"displayNums\">Средняя оценка: <strong title=\"Голосовало: "+people+" чел.\">"+stars+"</strong><em>("+mark+")</em></div>");
    //$("#displayNums").find("strong").html(stars);
    //$("#displayNums").find("em").html("("+mark+")");
    $("#displayStars").html("<font size=\"1\" style=\"color:#ACACAC\">Ваша оценка данному товару: <strong>"+own+"</strong> бал.</font>");
    //$("#displayNums").find("strong").attr("title","Голосовало: "+people+" чел.");
    
};
// превьюшки
this.imagePreview = function(){
    xOffset = 10;
    yOffset = 30;
    botMarg = 35;
    if($.browser.msie) botMarg = 17; // for MSIE browsers, bottom margin = 17pixels.
    $(".r1 img[@src!='/i/nofoto.gif']").hover(function(e){
        this.t = this.title;
        this.title = "";    
        var medium = this.src.slice(this.src.lastIndexOf('/') + 1);
        var c = (this.t != "") ? "<br/>" + this.t : "";
        var elTop = $.opt.cHeight + ($.opt.sTop) - botMarg;
        $("body").append("<p id=\"preview\"></p>");  
        
        var img = new Image();
        $(img).load(function(){
            $(this).css("display","none");
            $("#preview img").remove();                              
            $("#preview").css("background","white").append(this);
            $("#preview img").fadeIn();
        }).attr('src','/news/preview/' + medium).css('display','none');
        var top = ((e.pageY - xOffset) > elTop - $("#preview").height() ? elTop - $("#preview").height() : e.pageY - xOffset);
        $("#preview")
            .css("top",top + "px" )
            .css("left",(e.pageX + yOffset) + "px")
            .css("background","white url('/i/ajax-loader.gif') no-repeat center center")
            .css("min-width","50px")
            .css("min-height","50px")
            .css("z-index","99999")
            .fadeIn("fast");        
    },
    function(){
        this.title = this.t;    
        $("#preview").remove();
    });    
    $(".r1 img").mousemove(function(e){
        var elTop = $.opt.cHeight + ($.opt.sTop) - botMarg;
        var top = ((e.pageY - xOffset) > elTop - $("#preview").height() ? elTop - $("#preview").height() : e.pageY - xOffset);
        $("#preview")
            .css("top",top + "px")
            .css("left",(e.pageX + yOffset) + "px");
    }); 
    
};
this.showVotes = function() {
    xOffset = 2;
    yOffset = 5;
    botMarg = 35;
    if($.browser.msie) botMarg = 17;
    $(".tovstars").hover(function(e){
        var elTop = $.opt.cHeight + ($.opt.sTop) - botMarg;
        var texthere = '';
        var data = [];
            data = $(this).attr("rel").split(":");
        var commentsnum = '';
        if(data[2] > 0) {commentsnum = "<img src=\"/i/comments.gif\" align=\"absmiddle\"> <span style=\"font-size: 10px;\">Отзывов:</span> "+data[2]}
        else { commentsnum = ''; }
        texthere = "<img src=\"/i/bigstar2.gif\" align=\"absmiddle\"> <span style=\"font-size: 10px;\">Оценка:</span> <strong>"+data[0]+"</strong><br/><img src=\"/i/people.gif\" align=\"absmiddle\"> <span style=\"font-size: 10px;\">Голосов:</span> "+data[1]+"<br/>"+commentsnum;
        
        $("body").append("<p id=\"tt_votes\">"+texthere+"</p>");
        var top = top = ((e.pageY - xOffset) > elTop - $("#tt_votes").height() ? elTop - $("#tt_votes").height() : e.pageY - xOffset);
        $("#tt_votes")
            .css("top",top + "px")
            .css("left",(e.pageX + yOffset) + "px")
            .fadeIn("fast");
    },
    function(){
        $("#tt_votes").remove();
    });
};

this.showRegions = function() {
    xOffset = 2;
    yOffset = 8;
    botMarg = 35;
    if($.browser.msie) botMarg = 17;
    $(".templink").hover(function(e){
        var elTop = $.opt.cHeight + ($.opt.sTop) - botMarg;
        var texthere = '';
        
        texthere = "<span style=\"font-size: 11px;\"><a href=\"/shops/barnaul/\">Барнаул</a><br/><a href=\"/shops/vladimir/\">Владимир</a><br/><a href=\"/shops/volgograd/\">Волгоград</a><br/><a href=\"http://www.muztorg.ua/shops/donetsk\">Донецк</a><br/><a href=\"/shops/ekat/\">Екатеринбург</a><br/><a href=\"/shops/izh/\">Ижевск</a><br/><a href=\"/shops/irk/\">Иркутск</a><br/><a href=\"/shops/kazan/\">Казань</a><br/><a href=\"/shops/kaluga/\">Калуга</a><br/><a href=\"/shops/kemerovo/\">Кемерово</a><br/><a href=\"http://www.muztorg.ua/shops/kiev\">Киев</a><br/><a href=\"/shops/krasn/\">Красноярск</a><br/><a href=\"/shops/novgorod/\">Нижний Новгород</a><br/><a href=\"/shops/tagil/\">Нижний Тагил</a><br/><a href=\"/shops/novosib/\">Новосибирск</a><br/><a href=\"/shops/omsk/\">Омск</a><br/><a href=\"/shops/orel/\">Орел</a><br/><a href=\"/shops/perm/\">Пермь</a><br/><a href=\"/shops/rnd/\">Ростов-на-Дону</a><br/><a href=\"/shops/samara/\">Самара</a><br/><a href=\"/shops/spb/\">Санкт-Петербург</a><br/><a href=\"/shops/saratov/\">Саратов</a><br/><a href=\"/shops/smol/\">Смоленск</a><br/><a href=\"/shops/tol/\">Тольятти</a><br/></span>";
        
        $("body").append("<p id=\"tt_region\" onMouseOver=\"show_citys();\">"+texthere+"</p>");
        var top = top = ((e.pageY - xOffset) > elTop - $("#tt_region").height() ? elTop - $("#tt_region").height() : e.pageY - xOffset);
        $("#tt_region")
            .css("top",top -4 + "px")
            .css("left",(e.pageX + yOffset) + "px")
            .fadeIn("fast");
    },
    function(){
        
    });
	

};

this.showMoscow = function() {
    xOffset = 2;
    yOffset = 8;
    botMarg = 35;
    if($.browser.msie) botMarg = 17;
    $(".msklink").hover(function(e){
        var elTop = $.opt.cHeight + ($.opt.sTop) - botMarg;
        var texthere = '';
        
        texthere = "<span style=\"font-size: 11px;\"><a href=\"/shops/taganka/\">Музторг (м.Таганская)</a><br/><a href=\"/shops/savel/\">Музторг (м.Савеловская)</a><br/><a href=\"http://www.muztorg-yamaha.ru/\" target=\"_blank\">МузТорг-YAMAHA (м.Савеловская)</a><br/><a href=\"/shops/discount/\">МУЗТОРГ-ДИСКОНТ (м.Новогиреево)</a></span>";
        
        $("body").append("<p id=\"tt_region1\" onMouseOver=\"show_citys1();\">"+texthere+"</p>");
        var top = top = ((e.pageY - xOffset) > elTop - $("#tt_region1").height() ? elTop - $("#tt_region1").height() : e.pageY - xOffset);
        $("#tt_region1")
            .css("top",top -10 + "px")
            .css("left",(e.pageX + yOffset) + "px")
            .fadeIn("fast");
    },
    function(){
        
    });
	
	$("#content").hover(function(e){
        $("#tt_region1").remove();
		$("#tt_region").remove();
    },
    function(){
        
    });
	
	$(".search").hover(function(e){
        $("#tt_region").remove();
		$("#tt_region1").remove();
    },
    function(){
        
    });
	
	$(".templink").hover(function(e){
		$("#tt_region1").remove();
    },
    function(){
        
    });
	
	$(".msklink").hover(function(e){
		$("#tt_region").remove();
    },
    function(){
        
    });
	
	$("#lite_menu").hover(function(e){
        $("#tt_region").remove();
		$("#tt_region1").remove();
    },
    function(){
        
    });
	

};

this.checkCommentsInput = function() {    
        $(":input","#sendComment").each(function(){            
            if(this.name == 'text') {
                if(this.value.replace(/(^\s+)|(\s+$)/g, "").length > 0) $("#sendComment #submit").removeAttr("disabled");
                else $("#sendComment #submit").attr("disabled","disabled");
            }
        });
};

this.showLoginScreen = function() {    
    if($("#loginscreen").css("display") == undefined || $("#loginscreen").is(":hidden")) {
        $("body").append("<div id=\"closebg\"></div>");
        $("body").append("<div id=\"loginscreen\" style=\"display: none;\">" +
            "<form id=\"loginform\" method=\"post\" style=\"position: relative; z-index: 99999999\">"+
            "<span style=\"position: relative; top: 20px; left: 45px; font-family: Tahoma, Arial; font-size: 170%; color: #000\"><img src=\"/i/login48.gif\" align=\"absmiddle\"> Вход</span>"+
            "<table style=\"position: relative; top: 28px; left: 11px; z-index: 99999999999999\" class=\"logintable\"><tr><td align=\"right\" style=\"font-family: Tahoma, Arial; font-size: .95em;\">E-mail:</td><td><input type=\"text\" name=\"email\"></td></tr>"+
            "<tr><td align=\"right\" style=\"font-family: Tahoma, Arial; font-size: .95em;\">Пароль:</td><td><input type=\"password\" name=\"passwd\"> <img src=\"/i/forgot.gif\" id=\"forgot_btn\" width=\"16\" height=\"16\" align=\"absmiddle\" title=\"Восстановить пароль немедленно!\"></td></tr>"+
            "<tr><td>&nbsp;</td><td style=\"padding-top: 6px; font-family: Tahoma, Arial; font-size: .9em;\"><input type=\"checkbox\" name=\"rememberme\" id=\"rm\"> <label for=\"rm\">Не забывать меня</a></td></tr>"+
            "<tr><td>&nbsp;</td><td style=\"padding-top: .8em; \"><input type=\"submit\" value=\"Войти\"></td></tr></table></form></div>");        
        $("#loginform").append("<input type=\"hidden\" name=\"trytologin\" value=\"1\">");
        $("#loginform").append("<div style=\"position:absolute;top:3px;right:3px;z-index:999\" id=\"closels\" onclick=\"document.getElementById('loginscreen').style.display='none';document.getElementById('closebg').style.display='none';return false;\"><a href=\"#\"><img src=\"/i/login_close.gif\" border=\"0\" title=\"Закрыть\" vspace=\"2\" hspace=\"2\"></a></div>");
        
        $("#loginform #forgot_btn").css("opacity","0.3").css("cursor","pointer").hover(function(){
            $(this).css("opacity","1");
        },function(){
            $(this).css("opacity","0.3");
        }).click(function(){
            var email = $('form#loginform input[name="email"]').attr("value");
            if(email.length == 0) {
                alert('Не забудьте ввести свой e-mail адрес.');
                return false;
            }
            if(email.length < 6) {
                alert('Неправильно введен e-mail адрес.\nПожалуйста введите свой e-mail адрес, который был указан при регистрации.');
                return false;
            }
            jQuery.ajax({
                type: "GET",
                url: "/ajax_profile.php?forget=true&email=" + email,
                timeout: 10000,
                encoding: "cp1251",
                error: function(){ alert('We got an error during try to submit your request'); },
                success: function(r){ alert(r); }
            });   
        });
        
        $("#closebg").css("position","absolute").
            css("display","none").
            css("opacity",0.7).            
            css("z-index","10").
            css("width","100%").
            css("height",$("body").height()).
            css("top","0").
            css("left","0").
            css("background-color","#000").            
            show();   
            
        $("#loginscreen").
            css("position","absolute").
            css("top","50%").
            css("width","310px").
            css("margin-top","-100px").
            css("height","211px").
            css("left","50%").
            css("margin-left","-150px").
            css("z-index","15").
            show();
        $("#loginscreen input:first").focus();
    } else {
        $("#loginscreen").hide();
    }    
    $(document).keydown(function(e){if(e.which == 27) { $("#loginscreen").hide(); $("#closebg").hide(); }});    
    return false;
};

function doRegistrationByWishList()
{
	$("#wishlistscreen").hide(); $("#closebg").hide();showLoginScreen();
}

this.showPartnerOrderListScreen = function(t)
{
	if($("#wishlistscreen").css("display") == undefined || $("#wishlistscreen").is(":hidden")) {
        $("body").append("<div id=\"closebg\"></div>");
		$("body").append("<div id=\"wishlistscreen\" style=\"display: block;\"></div>");
		$('#wishlistscreen').empty();
		$("#wishlistscreen").append("<div style=\"margin: 20px; z-index: 99999999999999;\"><div style=\"font-size: 20pt; margin-bottom: 10px;\">Заказ товара</div>"+
			"Вы можете оставить нам свои контактные данные и мы привезём Вам "+t+"<br /><br />"+
			"<table width=\"100%\" class=\"remindTable\"><tr><td colspan=\"2\">Вас зовут:"+
			"<input id=\"remindListName\" type=\"text\" style=\"height: 30px; width: 100%; font-size: 18px;\">"+
			"</td><tr><td width=\"50%\" class=\"remindListpad\">"+
			"Email:"+
			"<input id=\"remindListEmail\" type=\"text\" style=\"height: 30px; width: 100%; font-size: 18px;\">"+
			"</td><td>"+
			"Телефон:"+
			"<input id=\"remindListPhone\" type=\"text\" style=\"height: 30px; width: 100%; font-size: 18px;\">"+
			"</td></tr></table>"+
			"<div align=\"right\"><input type=\"button\" value=\"Оставить заказ\" style=\"margin-top: 2px;\" onclick=\"sendToPartnerOrderList('"+t+"')\" /></div>"+
			"</div>");
        $("#wishlistscreen").append("<div style=\"position:absolute;top:3px;right:3px;z-index:999\" id=\"closewls\"><a href=\"#\"><img src=\"/i/login_close.gif\" border=\"0\" title=\"Закрыть\" vspace=\"2\" hspace=\"2\" onclick=\"document.getElementById('wishlistscreen').style.display='none';document.getElementById('closebg').style.display='none';return false;\"></a></div>");

        $("#closebg").css("position","absolute").
            css("display","none").
            css("opacity",0.7).            
            css("z-index","10").
            css("width","100%").
            css("height",$("body").height()).
            css("top","0").
            css("left","0").
            css("background-color","#000").            
            show();   
            
        $("#wishlistscreen").
            css("position","fixed").
            css("top","50%").
            css("width","450px").
            css("margin-top","-125px").
            css("height","250px").
            css("left","50%").
            css("margin-left","-225px").
            css("z-index","15").
            show();
    } else {
        $("#wishlistscreen").hide();
    }    
    $(document).keydown(function(e){if(e.which == 27) { $("#wishlistscreen").hide(); $("#closebg").hide(); }});    
    return false;		
};

this.showRemindListScreen = function(t)
{
	if($("#wishlistscreen").css("display") == undefined || $("#wishlistscreen").is(":hidden")) {
        $("body").append("<div id=\"closebg\"></div>");
		$("body").append("<div id=\"wishlistscreen\" style=\"display: block;\"></div>");
		$('#wishlistscreen').empty();
		$("#wishlistscreen").append("<div style=\"margin: 20px; z-index: 99999999999999;\"><div style=\"font-size: 20pt; margin-bottom: 10px;\">Напоминание</div>"+
			"Вы можете оставить нам свои контактные данные и мы уведомим Вас когда товар появится в нашем магазине:<br /><br />"+
			"<table width=\"100%\" class=\"remindTable\"><tr><td colspan=\"2\">Вас зовут:"+
			"<input id=\"remindListName\" type=\"text\" style=\"height: 30px; width: 100%; font-size: 18px;\">"+
			"</td><tr><td width=\"50%\" class=\"remindListpad\">"+
			"Email:"+
			"<input id=\"remindListEmail\" type=\"text\" style=\"height: 30px; width: 100%; font-size: 18px;\">"+
			"</td><td>"+
			"Телефон:"+
			"<input id=\"remindListPhone\" type=\"text\" style=\"height: 30px; width: 100%; font-size: 18px;\">"+
			"</td></tr></table>"+
			"<div align=\"right\"><input type=\"button\" value=\"Оставить заявку\" style=\"margin-top: 2px;\" onclick=\"sendToNotifyList('"+t+"')\" /></div>"+
			"</div>");
        $("#wishlistscreen").append("<div style=\"position:absolute;top:3px;right:3px;z-index:999\" id=\"closewls\"><a href=\"#\"><img src=\"/i/login_close.gif\" border=\"0\" title=\"Закрыть\" vspace=\"2\" hspace=\"2\" onclick=\"document.getElementById('wishlistscreen').style.display='none';document.getElementById('closebg').style.display='none';return false;\"></a></div>");

        $("#closebg").css("position","absolute").
            css("display","none").
            css("opacity",0.7).            
            css("z-index","10").
            css("width","100%").
            css("height",$("body").height()).
            css("top","0").
            css("left","0").
            css("background-color","#000").            
            show();   
            
        $("#wishlistscreen").
            css("position","fixed").
            css("top","50%").
            css("width","450px").
            css("margin-top","-125px").
            css("height","250px").
            css("left","50%").
            css("margin-left","-225px").
            css("z-index","15").
            show();
    } else {
        $("#wishlistscreen").hide();
    }    
    $(document).keydown(function(e){if(e.which == 27) { $("#wishlistscreen").hide(); $("#closebg").hide(); }});    
    return false;		
};

this.showWishListScreen = function(r,t,type) {    
    if($("#wishlistscreen").css("display") == undefined || $("#wishlistscreen").is(":hidden")) {
        $("body").append("<div id=\"closebg\"></div>");
        if ((type==0)&&(r>0))
        {
			$("body").append("<div id=\"wishlistscreen\" style=\"display: block;\"></div>");
			$('#wishlistscreen').empty();
			$("#wishlistscreen").append("<div style=\"margin: 20px; z-index: 99999999999999;\"><div style=\"font-size: 20pt; margin-bottom: 10px;\">Вишлист</div>"+
				"Напишите, пожалуйста, комментарий к желанию:"+
				"<textarea id=\"wishListComment\" style=\"width: 100%; height: 120px;\"></textarea>"+
				"<div align=\"right\"><input type=\"button\" value=\"Сохранить\" style=\"margin-top: 2px;\" onclick=\"sendToWishList('"+t+"')\" /></div></div>");
		}
		else if ((type==1)&&(r>0))
		{
			$("body").append("<div id=\"wishlistscreen\" style=\"display: block;\"></div>");
			$('#wishlistscreen').empty();
			$("#wishlistscreen").append("<div style=\"margin: 20px; z-index: 99999999999999;\"><div style=\"font-size: 20pt; margin-bottom: 10px;\">Вишлист</div>"+
				"Вы действительно собираетесь удалить товар из вишлиста?"+
				"<textarea id=\"wishListComment\" style=\"width: 100%; height: 120px; visibility: hidden;\"></textarea>"+
				"<div align=\"right\"><input type=\"button\" value=\"Удалить\" style=\"margin-top: 2px;\" onclick=\"deleteFromWishList('"+t+"')\" /></div>"+
				"</div>");
		}
		else if (r==0)
		{
			$("body").append("<div id=\"wishlistscreen\" style=\"display: block;\"></div>");
			$('#wishlistscreen').empty();
			$("#wishlistscreen").append("<div style=\"margin: 20px; z-index: 99999999999999;\"><div style=\"font-size: 20pt; margin-bottom: 10px;\">Вишлист</div>"+
				"Для чего нужен список желаний?<br /><br />"+
				"<strong>Чтобы не забыть, что вы хотите купить.<br />"+
				"Чтобы ваши друзья знали, что подарить вам.<br />"+
				"Чтобы вы знали, что хотят ваши друзья.</strong><br /><br />Подробнее о вишлистах на МузТорге можно прочитать <a href=\"/service/wishlist/\">здесь</a>.<br /><br />"+
				"Мы предупредим вас, когда ваше желание станет доступней!<br /><br />"+
				"Для того, чтобы пополнить свой список в вишлисте &mdash; <a href=\"#login\" onclick=\"doRegistrationByWishList();\">авторизуйтесь</a>, либо <a href=\"/registration/\">зарегистрируйтесь</a>.</div>");
			/*
			$("body").append("<div id=\"wishlistscreen\" style=\"display: block;\">"+
			"<div style=\"margin: 20px;\"<div style=\"font-size: 20pt; margin-bottom: 10px;\">Вишлист</div>"+
				"Для чего нужен список желаний?<br /><br /><br />"+
				"<strong>Чтобы не забыть, что вы хотите купить.<br />"+
				"Чтобы ваши друзья знали, что подарить вам.<br />"+
				"Чтобы вы знали, что хотят ваши друзья.</strong><br /><br />"+
				"Мы предупредим вас, когда ваше желание станет доступней!<br /><br /><br />"+
				"Для того, чтобы пополнить свой список в вишлисте &mdash; <a href=\"#login\" onclick=\"doRegistrationByWishList();\">авторизуйтесь</a>, либо <a href=\"/registration/\">зарегистрируйтесь</a>.</div>"+
			"</div>");
			*/
		}
        $("#wishlistscreen").append("<div style=\"position:absolute;top:3px;right:3px;z-index:999\" id=\"closewls\"><a href=\"#\"><img src=\"/i/login_close.gif\" border=\"0\" title=\"Закрыть\" vspace=\"2\" hspace=\"2\" onclick=\"document.getElementById('wishlistscreen').style.display='none';document.getElementById('closebg').style.display='none';return false;\"></a></div>");

        $("#closebg").css("position","absolute").
            css("display","none").
            css("opacity",0.7).            
            css("z-index","10").
            css("width","100%").
            css("height",$("body").height()).
            css("top","0").
            css("left","0").
            css("background-color","#000").            
            show();   
            
        $("#wishlistscreen").
            css("position","fixed").
            css("top","50%").
            css("width","450px").
            css("margin-top","-125px").
            css("height","250px").
            css("left","50%").
            css("margin-left","-225px").
            css("z-index","15").
            show();
    } else {
        $("#wishlistscreen").hide();
    }    
    $(document).keydown(function(e){if(e.which == 27) { $("#wishlistscreen").hide(); $("#closebg").hide(); }});    
    return false;
};

this.addToCart = function(tovid) {

    jQuery.ajax({
        data: { tov_id: tovid },
        type: "POST",
        url: "/ajax_cart.php?add",
        timeout: 5000,
        error: function(e) {
            alert(e);
        },
        success: function(r) {
            var data = [];
                data = r.split(":");
            if($("#cartDiv").length <= 0) {
                //$("#con_left").prepend("<div class=\"leftcolumn\" id=\"cartDiv\">Ваша корзина<br/>В корзине <strong id=\"pos\">"+data[0]+"</strong> позиция<br/>на сумму <strong id=\"summ\">"+data[1]+"</strong> руб.</div>");
                $("#con_left").prepend("<div class=\"leftcolumn\" id=\"cartDiv\"><div class=\"yC\"><a href=\"/cart/\"><u>Ваша корзина</u></a></div><div class=\"St\">В корзине <strong id=\"pos\">"+data[0]+"</strong> позиция<br/>на сумму <strong id=\"summ\">"+data[1]+"</strong> руб.</div></div>");
            } else {
                $("#cartDiv #pos").text(data[0]);   
                $("#cartDiv #summ").text(data[1]);
            }
			showAlert('Товар #'+tovid+' добавлен в корзину!');
        }
    });
};

this.addToRemindList = function(tovid) {
	showRemindListScreen(tovid);
};

this.addToPartnerOrder = function(tovname) {
	showPartnerOrderListScreen(tovname);
};

this.addToWishList = function(tovid) {
	var user_n = $('#user_n').val();
	showWishListScreen(user_n,tovid,0);
};

this.RemoveFromWishList = function(tovid) {
	var user_n = $('#user_n').val();
	showWishListScreen(user_n,tovid,1);
};

function sendToWishList(tovid)
{
	comment = $('#wishListComment').val();
	jQuery.ajax({
        data: { tov_id: tovid,comment_text: comment },
        type: "POST",
        url: "/ajax_wish_list.php?add",
        timeout: 5000,
        error: function(e) {
            alert(e);
        },
        success: function(r) {
			$("#wishlistscreen").hide(); $("#closebg").hide();
			$("#addWishListBtn").hide();
			$("#removeWishListBtn").show();
			showAlert('Товар добавлен в вишлист!');
        }
    });
}

function deleteFromWishList(tovid)
{
	jQuery.ajax({
        data: { tov_id: tovid },
        type: "POST",
        url: "/ajax_wish_list.php?delete",
        timeout: 5000,
        error: function(e) {
            alert(e);
        },
        success: function(r) {
			$("#wishlistscreen").hide(); $("#closebg").hide();
			$("#removeWishListBtn").hide();
			$("#addWishListBtn").show();
			showAlert('Товар удалён из вишлиста!');
        }
    });
}

function sendToNotifyList(tovid)
{
	var n_email = $('#remindListEmail').val();
	var n_name = $('#remindListName').val();
	var n_phone = $('#remindListPhone').val();
	jQuery.ajax({
        data: { tov_id: tovid, email: n_email,fio: n_name,phone: n_phone },
        type: "POST",
        url: "/ajax_notify_list.php",
        timeout: 5000,
        error: function(e) {
            alert(e);
        },
        success: function(r) {
			$("#wishlistscreen").hide(); $("#closebg").hide();
			//$("#removeWishListBtn").hide();
			//$("#addWishListBtn").show();
			showAlert('Напоминание было активировано!');
        }
    });
}

function sendToPartnerOrderList(tovid)
{
	var n_email = $('#remindListEmail').val();
	var n_name = $('#remindListName').val();
	var n_phone = $('#remindListPhone').val();
	jQuery.ajax({
        data: { tov_id: tovid, email: n_email,fio: n_name,phone: n_phone },
        type: "POST",
        url: "/ajax_order_list.php",
        timeout: 5000,
        error: function(e) {
            alert(e);
        },
        success: function(r) {
			$("#wishlistscreen").hide(); $("#closebg").hide();
			//$("#removeWishListBtn").hide();
			//$("#addWishListBtn").show();
			showAlert('Товар был заказан!');
        }
    });
}

function showAlert(text)
{
	$("#alertboxList").append('<div class="alertbox">'+text+'</div>');
	$("alertbox").css({ opacity: 0 }); // works in all browsers
	$('.alertbox').show();
	$(".alertbox").animate({
		opacity: 1
		}, 2000, function() {
		$(".alertbox").animate({
			opacity: 0
			}, 1000, function() {
			$('#alertboxList').empty();
		});
	});
	}

function number_format( number, decimals, dec_point, thousands_sep ) {	// Format a number with grouped thousands
	// 
	// +   original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
	// +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
	// +	 bugfix by: Michael White (http://crestidg.com)

	var i, j, kw, kd, km;

	// input sanitation & defaults
	if( isNaN(decimals = Math.abs(decimals)) ){
		decimals = 2;
	}
	if( dec_point == undefined ){
		dec_point = ",";
	}
	if( thousands_sep == undefined ){
		thousands_sep = ".";
	}

	i = parseInt(number = (+number || 0).toFixed(decimals)) + "";

	if( (j = i.length) > 3 ){
		j = j % 3;
	} else{
		j = 0;
	}

	km = (j ? i.substr(0, j) + thousands_sep : "");
	kw = i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + thousands_sep);
	//kd = (decimals ? dec_point + Math.abs(number - i).toFixed(decimals).slice(2) : "");
	kd = (decimals ? dec_point + Math.abs(number - i).toFixed(decimals).replace(/-/, 0).slice(2) : "");


	return km + kw + kd;
}

function recalc_sum()
{
	var total_num = $("#total_tovs").val();
	var total_sum = 0;
	for (i=1;i<=total_num;i++)
	{
		var count = $('#count_'+i).val();
		var price = $('#price_'+i).val();
		var summ = price*count;
		total_sum=total_sum+summ;
	}
	
	if (total_sum>=1000)
	{
		$('#error_price').hide();
		$('#order_button').removeAttr("disabled");

	}
	else
	{
		$('#error_price').show();
		$('#order_button').attr("disabled","disabled");
	}

	total_sum = number_format(total_sum,0,","," ");
	total_sum = 'Итоговая стоимость '+total_sum+' руб.';
	$('#total_nal').text(total_sum);
}

function change_sum(position_n)
{
	var count = $('#count_'+position_n).val();
	if (count<0)
	{
		count = 0;
		$('#count_'+position_n).val(count);
	}
	
	var price = $('#price_'+position_n).val();
	var summ = price*count;
	summ = number_format(summ,0,","," ");
	summ = summ+' руб.';
	$('#display_summ_'+position_n).text(summ);
	recalc_sum();
}

function check_label(label)
{
	var inp_value = $("input[name='"+label+"']").val();
	if (inp_value=='') inp_value = $("input[name='"+label+"']").value;

	if (inp_value)
	{
		
		$('#'+label+'_label').removeClass('redy');
		return 0;
	}
	else
	{
		$('#'+label+'_label').addClass('redy');
		return 1;
	}
}

function check_address()
{
	var inp_value = $("#address").val();
	if (inp_value)
	{
		$('#address_label').removeClass('redy');
		return 0;
	}
	else
	{
		$('#address_label').addClass('redy');
		return 1;
	}
}

function check_town()
{
	var inp_value = $("#town option:selected").val();
	if ((inp_value)&&(inp_value!='-'))
	{
		$('#town_label').removeClass('redy');
		return 0;
	}
	else
	{
		$('#town_label').addClass('redy');
		return 1;
	}
}

function check_form_error()
{
	var err=0;
	err += check_label('f');
	err += check_label('im');
	err += check_label('o');
	err += check_label('phones');
	err += check_label('email');
	err += check_label('delivery_type');
	err += check_town();
	err += check_address();
	return err;
}

function submitOrder()
{
	var total_errors = check_form_error();
	if (total_errors>0)
	{
		alert("Вы не заполнили обязательные поля. Каждый заказ должен включать в себя:\n\n— Фамилию;\n— Имя;\n— Отчество;\n— Мобильные телефон;\n— Email;\n— Город или область доставки;\n— Метод доставки;\n— Адрес доставки.\n\nПожалуйста, проверьте ещё раз заполнение необходимых полей и нажмите на кнопку отправить заказ. Если у Вас не получается отправить нам заказ — оформите Ваш заказ по телефону.\n\nИзвините за неудобства.");
	}
	else
	{
		$('#frmOrder').submit();
	}
}

function add_alternate(tov_id,depend_id)
{
	var tovrelationid = $('#tov_relation_id').val();
	if (tovrelationid)
	{
		$.post('/ajax_add_alternate.php', {tov_id: tov_id,tov_relation_id:tovrelationid,tovar_relation_depend_id:depend_id}, function(data) {
		  $('#additional_list').html(data);
		  $('#tov_relation_id').val('');
		  showAlert('Аксессуар был добавлен!');
		});
	}
}


function cancelReply()
{
	var rel = 0;
	$('.comment_reply_block').html('');
	$('.comment_reply_block').hide();
	$('#reply_'+rel).show();
	new_text = '<div id="reply_to_0" class="addcomment"><form id="sendComment" method="post"><div class="forms_name">Ваш отзыв:</div><div class="forms_inputs"><div><textarea id="comment_text" name="text"></textarea></div><div align="right" style="margin-top: 5px;"><input type="submit" id="submit" value="Отправить"></div></form><div class="clear"></div></div>';
	$('#reply_'+rel).html(new_text);
	bindBehaviors();
}