$(document).ready(function(){
    
    $.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();
    //onTime(5000, imagePreview());
    // Sending comments by ajax.
    $("#sendComment :input").keyup(checkCommentsInput);
    $('#sendComment').submit(function(){
        var inputs = [];
        $(':input',this).each(function(){
            inputs.push(this.name + '=' + $(this).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');
            },
            success: function(r) {
                var data = [];
                    data = r.split("\n");
                var result = data[0];
                    data.shift();
                    data = data[0];
                if(result == 202) {
                    $("#commentsdiv").prepend(data);
                    $("#sendComment textarea").val("");
                    $("#sendComment #submit").attr("disabled","disabled");
                    var inc = $("#comm").find("em").html().replace("(","").replace(")","");                                                
                        inc = parseInt(inc) + 1;
                    $("#comm").find("em").html("("+inc+")");
                }
                else { alert("We\'re so sorry, but some error catched during try to post your comment"); }
            }
        });        
        return false;
    });

    $("#addBasketBtn").click(function(){
        addToCart($(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");
    
    
    $("#desc").click(function(){
            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");
            window.location.href = $.opt.wLoc + "#description";
    });
    $("#comm").click(function(){
            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");
            window.location.href = $.opt.wLoc + "#comments";
    });
    // ^^ 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;
        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");
    });
    $(".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();
        } else {
            $(".discountcard").hide();
            $("input[name=discountcard_fio]").attr("value","");
            $("input[name=discountcard_number]").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") == "Москва") {
            $("#select_metro").show();
        } else {
            $("#select_metro").hide();
        }
    });
	
	if($("#town").attr("value") == 66) {
        $("#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);
                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 () {
//alert(this);
    xOffset = 10;
    yOffset = 30;
    botMarg = 35;
    if($.browser.msie) botMarg = 17; // for MSIE browsers, bottom margin = 17pixels.
    $(".r1 img[@src!='/IMG/nofoto.gif']").hover(function(e){
		
        this.t = this.title;
		//alert(this.id);
		this.title = ""; 		
        //var medium = this.src.slice(this.src.lastIndexOf('/') + 1);
		var medium = this.id; //this.src.substr(0,this.src.lastIndexOf('/')) + '/' + this.id;
		//alert (medium);
        var c = (this.t != "") ? "<br/>" + this.t : "";
        var elTop = $.opt.cHeight + ($.opt.sTop) - botMarg;
        $("body").append("<p id=\"preview\"></p>");  
        //alert(medium);
        var img = new Image();
		//alert(img);
        $(img).load(function(){		
		//alert("ok");
            $(this).css("display","none");
            $("#preview img").remove();                              
            $("#preview").css("background","white").append(this);
            $("#preview img").fadeIn();	
		//alert("buy");			
        }).attr('src', medium).css('display','none');
		//}).attr('src','/IMG/comb5.jpg').css('display','none');
		//alert($("#preview").attr('background'));
        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('./IMG/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",e.pageY - 200 + "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 - 200 + "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/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;
};

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]);   
            }
        }
    });
};

