$(document).ready(function(){
    
    var srok=7;
    var dom="";
    var pat="/";
    
    //инициализация
	$('div#trash_dialog').dialog({
		autoOpen: false,
		width: 900,
        height: window.screen.availHeight-200,
		modal: true,
        buttons: {
			'Оформить заказ': function() {
				if($.cookie("user") && $.cookie("user_mix") && $.cookie("user")!="" && $.cookie("user_mix")!="") {
                    $("#form_dialog").dialog("open");
                    $("div#flag").html(0);
                }
                else {
                    $("#reglog_dialog").dialog("open");
                    $("div#flag").html(1);
                }
			}
		}

	});
	
    //открытие
    if(!$.cookie("product_count") || $.cookie("product_count")=="0")
        $.cookie("product_order",null,{expires:0, path: "/", domain: ""});
	$('.oformit').live("click",function(){
	    if(!$.cookie("product_count") || $.cookie("product_count")=="0") {
	       alert('Корзина пуста');
           return false;
	    }
		$('div#trash_dialog').dialog('open');
        $("div#dialog_load").show();
        before_send();
        return false;
	});
    
    //при загрузке
    function before_send () {
        var cook=$.cookie("product_items");
        $.ajax({
			 url: $("div#site_name").html()+"include/ajax/trash_ajax.php",
			 data: "id="+cook,
			 type: "GET",
			 success: function(answ) {
                    $("div#dialog_load").hide();
				    $('div#trash_dialog div#dialog_inner').empty().html(answ);
			 }
        }); 
    }
    
    function setCookie (name, value, expires, path, domain, secure) {
      document.cookie = name + "=" + escape(value) +
        ((expires) ? "; expires=" + expires : "") +
        ((path) ? "; path=" + path : "") +
        ((domain) ? "; domain=" + domain : "") +
        ((secure) ? "; secure" : "");
    }

    
    
    //удаление элемента
    $("button.del").live("click", function(){
        if(confirm("Удалить?")) {
                                   
            $.cookie("product_count",parseInt($.cookie("product_count"))-1,{expires:window.srok, path: window.pat, domain: window.dom});
            var price=parseInt($(this).parent().prev().prev().prev().children("span").html());
            $.cookie("product_price",parseInt($.cookie("product_price"))-price,{expires:window.srok, path: window.pat, domain: window.dom});
            
            var mas=$.cookie("product_items").split(";");
            for(i=0; i<mas.length; i++)
                if(mas[i]==parseInt($(this).attr("id")))
                    mas.splice(i,1);
                    
            $.cookie("product_items",mas.join(";"),{expires:window.srok, path: window.pat, domain: window.dom});
            
            $(this).parent().parent("tr").slideUp().remove();
            
            if($.cookie("product_count")) {
                var count=parseInt($.cookie("product_count"));
                setTrash(count);
            }
            
            if($(".stoim").length!=0) {
                var sum=0;
                $(".stoim").each(function(){
                    sum+=parseInt($(this).html());
                });
                $(".itogo").html(sum);
            }
            else {
                $('div#trash_dialog').dialog("close");
                $.cookie("product_price",null);
                $.cookie("product_count",null);
                $.cookie("product_items",null);
                unsetTrash();
            }
            
            var tmp=$("a.buy[id="+$(this).attr("id")+"]");
			tmp.html('КУПИТЬ');
			//tmp.next("span").html(tmp.attr("price")+" руб."); 
        }
            
    });
    
    //пересчет
    function pereschet(obj) {
        var cena=$(obj).parent().prev().children("span#cena");
        var stoim=$(obj).parent().next().children("span.stoim");
        if($(obj).val()) 
            stoim.html(parseInt(cena.html())*parseInt($(obj).val()));
        var sum=0;
        $(".stoim").each(function(){
            sum+=parseInt($(this).html());
        });
        $(".itogo").html(sum);
        $.cookie("product_price",sum,{expires:srok, path: pat, domain: dom});
    }
    
    function checkNumberFields(e, k){ //проверка на число
			var str = jQuery(e).val();
            if(str=="0")
               str="1";
			var new_str = s = "";
			for(var i=0; i < str.length; i++){
				s = str.substr(i,1);
				if(s!=" " && isNaN(s) == false){
					new_str += s;
				}
			}
			jQuery(e).val(new_str);
	}
	$(".count").live("keyup",function(event){
		checkNumberFields(this, event);
        pereschet(this);
	}).live("keypress", function(event){
		checkNumberFields(this, event);
        pereschet(this);
	}).live("click", function(){
		this.select();
	});
    
    //очистка корзины   
    $("button#erase").live("click", function(){
        if(confirm("Очистить?")) {
            $('div#trash_dialog').dialog("close");
            $.cookie("product_price",null,{expires:0, path: window.pat, domain: window.dom});
            $.cookie("product_count",null,{expires:0, path: window.pat, domain: window.dom});
            $.cookie("product_items",null,{expires:0, path: window.pat, domain: window.dom});
            $.cookie("product_order",null,{expires:0, path: window.pat, domain: window.dom});
            
            window.location.reload();
        }

    });
       
});
