$(document).ready(function(){

    // --------------- DRAGGABLES & DROPPABLES -------------------
    
    $("div.product_container").click(function(){ // Функция онклик, срабатывает, когда пользователь щёлкает грызнуом по товару
        var code = $(this).find("div").attr("id"); //Имещм в диве в котором щёлкнул пользователь, параметр ID
        // Далее, делаем запрос к пхп, отправляем ему только ID товара
        $.get("http://moscenniktorg.ru/modules/shop/addProduct.php", {
            productId: code
        }, function(data){
            var items = data.split("|||") // Перерабатываем ответ от сервера, и получаем массив вида  ["1", "2", "3"]          
            var tovar_id = items[0]; //Вытягиваем из массива ещё раз ID, спрашивается зачем?)))
            var tovar_name = items[1]; // Вытягивем Наименование товара
            var tovar_stoimost_full = items[2]; //Вытягивем стоимость
            //Далее мы проверим, существует ли уже такой товар в корзине
            if ($("#shopping_cart_items_product" + tovar_id).length) { //Если есть, то...
                //alert("Такая штука уже есть!"); //Функция для отлакди, надо незыбть потом закомментить))))
                var kolvo_tovara = parseInt($("#shopping_cart_items_product" + tovar_id).find("input").val()) + 1;//плюсадын =)
                $("#shopping_cart_items_product" + tovar_id).find("input").val(kolvo_tovara); //Заменяем в окошке =)
                $("#shopping_cart_items_product" + tovar_id).find("input").focus();
                
                
                $.get("http://moscenniktorg.ru/modules/shop/polu4it_cenu.php", {
                    productId: tovar_id
                }, function(data){
                    var new_cena = data
                    $("#shopping_cart_items_product" + tovar_id).find(".cart_cena").text(data)
                    // alert ($("#shopping_cart_items_product" + tovar_id).find(".cart_cena").text())
                })
				
				 $.get("http://moscenniktorg.ru/modules/shop/total.php", {
                        productId: tovar_id
                    }, function(data){
                        var new_cena = data
                        $("#shopping_cart_totalprice").text("Всего: " + data +" руб.")
                        //alert(data)
                    })
				
				
            }
            else {
            
                $("#shopping_cart_items").append("<tr id='shopping_cart_items_product" + tovar_id + "'><td><input type='text' id='shopping_cart_items_product_kolvo" + tovar_id + "' class='input'  value='1' /></td><td>" + tovar_name + "</td><td class='cart_cena'>" + tovar_stoimost_full + "</td><td><a href='#'><img class='img' src='http://moscenniktorg.ru/images/remove.gif'/></a></td></tr>");
              
			  $.get("http://moscenniktorg.ru/modules/shop/total.php", {
                        productId: tovar_id
                    }, function(data){
                        var new_cena = data
                        $("#shopping_cart_totalprice").text("Всего: " + data +" руб.")
                        //alert(data)
                    })
			    
            }
            
            
            $(".input").keydown(function(event){
                // alert($(this).parent().parent().attr("id"));
                $(this).parent().parent().find(".img").attr({
                    src: "http://moscenniktorg.ru/images/ok.jpg",
                    id: "ok",
                    alt: "Нажмите, чтобы подтвердить изменения"
                });
                $(this).parent().parent().find(".img").attr("src");
                var tovar_id = $(this).parent().parent().attr("id");
                
                if (event.keyCode == "13") {
                    $(this).parent().parent().find(".img").attr({
                        src: "http://moscenniktorg.ru/images/remove.gif",
                        id: "remove"
                    });
                    // $(this).val();
                    
                    // alert($(this).parent().parent().attr("id"));
                    // alert($(this).val());
                    
                    $.get("http://moscenniktorg.ru/modules/shop/addkolvo.php", {
                        productId: $(this).parent().parent().attr("id"),
                        produkt_kolvo: $(this).val()
                    }, function(data){
                        // alert(data);
                    })
                    
                    
                    $.get("http://moscenniktorg.ru/modules/shop/polu4it_cenu.php", {
                        productId: tovar_id
                    }, function(data){
                        var new_cena = data
                        $("#" + tovar_id).find(".cart_cena").text(data)
                        //alert ($("#shopping_cart_items_product" + tovar_id).find(".cart_cena").text())
                    })
					
					
					 $.get("http://moscenniktorg.ru/modules/shop/total.php", {
                        productId: tovar_id
                    }, function(data){
                        var new_cena = data
                        $("#shopping_cart_totalprice").text("Всего: " + data +" руб.")
                        //alert(data)
                    })
                    
                    
                   
                    
                }
            });
            
            $(".img").click(function(){
                // alert($(this).attr("id"))
                if ($(this).attr("src") == "http://moscenniktorg.ru/images/ok.jpg") {
                    ///alert("ЭЫЫЫы");
                    //alert($(this).parent().parent().parent().attr("id"));
                    
                    $.get("http://moscenniktorg.ru/modules/shop/addkolvo.php", {
                        productId: $(this).parent().parent().parent().attr("id"),
                        produkt_kolvo: $(this).parent().parent().parent().find("input").val()
                    }, function(data){
                    
                        //alert($(this).attr("id"));
                    
                    
                    });
                    //alert($(this).attr("id"));
                    
                    $(this).attr({
                        src: "http://moscenniktorg.ru/images/remove.gif",
                        id: "remove"
                    })
                    
                    
                    var tovar_id = $(this).parent().parent().parent().attr("id");
                    
                    $.get("http://moscenniktorg.ru/modules/shop/polu4it_cenu.php", {
                        productId: tovar_id
                    }, function(data){
                        var new_cena = data
                        $("#" + tovar_id).find(".cart_cena").text(data)
                        //alert ($("#shopping_cart_items_product" + tovar_id).find(".cart_cena").text())
                    })
                    
					
					 $.get("http://moscenniktorg.ru/modules/shop/total.php", {
                        productId: tovar_id
                    }, function(data){
                        var new_cena = data
                        $("#shopping_cart_totalprice").text("Всего: " + data +" руб.")
                        //alert(data)
                    })
                    
                } else {		var pid = $(this).parent().parent().parent().attr("id")		 //alert("Удаляю способ 2" + pid)		//$("#shopping_cart_items").append("ndjz мать!");			 $.get("http://moscenniktorg.ru/modules/shop/delite.php", {                productId: $(this).parent().parent().parent().attr("id"),                produkt_kolvo: $(this).parent().parent().parent().find("input").val()            }, function(data){                            ////alert($(this).attr("id"));                                    });			//$("#shopping_cart_items_product" + productId).replaceWith("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");			$(this).parent().parent().parent().replaceWith("");	 					//$(this).attr({             //   src: "http://moscenniktorg.ru/images/ok.gif",            //    id: "remove"           // })					}
                
            })
            
        });
        
        
        
        
    });
    //вот сюда новую функцию суну 
    
    $(".input").keydown(function(event){
        // alert($(this).parent().parent().attr("id"));
        $(this).parent().parent().find(".img").attr({
            src: "http://moscenniktorg.ru/images/ok.jpg",
            id: "ok",
            alt: "Нажмите, чтобы подтвердить изменения"
        });
        $(this).parent().parent().find(".img").attr("src");
        
        var tovar_id = $(this).parent().parent().attr("id");
        
        if (event.keyCode == "13") {
            $(this).parent().parent().find(".img").attr({
                src: "http://moscenniktorg.ru/images/remove.gif",
                id: "remove"
            });
            // $(this).val();
            
            // alert($(this).parent().parent().attr("id"));
            // alert($(this).val());
            
            $.get("http://moscenniktorg.ru/modules/shop/addkolvo.php", {
                productId: $(this).parent().parent().attr("id"),
                produkt_kolvo: $(this).val()
            }, function(data){
                // alert(data);
            })
            
            $.get("http://moscenniktorg.ru/modules/shop/polu4it_cenu.php", {
                productId: tovar_id
            }, function(data){
                var new_cena = data
                $("#" + tovar_id).find(".cart_cena").text(data)
                //alert ($("#shopping_cart_items_product" + tovar_id).find(".cart_cena").text())
            })
			
			 $.get("http://moscenniktorg.ru/modules/shop/total.php", {
                        productId: tovar_id
                    }, function(data){
                        var new_cena = data
                        $("#shopping_cart_totalprice").text("Всего: " + data +" руб.")
                       // alert(data)
                    })
            
        }
    });
    
    
    $(".img").click(function(){
        // alert($(this).attr("id"))
        if ($(this).attr("src") == "http://moscenniktorg.ru/images/ok.jpg") {
            /////alert("ЭЫЫЫы");
            ////alert($(this).parent().parent().parent().attr("id"));
            
            $.get("http://moscenniktorg.ru/modules/shop/addkolvo.php", {
                productId: $(this).parent().parent().parent().attr("id"),
                produkt_kolvo: $(this).parent().parent().parent().find("input").val()
            }, function(data){
            
                ////alert($(this).attr("id"));
            
            
            });
            // //alert($(this).attr("id"));
            
            $(this).attr({
                src: "http://moscenniktorg.ru/images/remove.gif",
                id: "remove"
            })
            
            var tovar_id = $(this).parent().parent().parent().attr("id");
            
            $.get("http://moscenniktorg.ru/modules/shop/polu4it_cenu.php", {
                productId: tovar_id
            }, function(data){
                var new_cena = data
                $("#" + tovar_id).find(".cart_cena").text(data)
                ////alert ($("#shopping_cart_items_product" + tovar_id).find(".cart_cena").text())
            })
			
			 $.get("http://moscenniktorg.ru/modules/shop/total.php", {
                        productId: tovar_id
                    }, function(data){
                        var new_cena = data
                        $("#shopping_cart_totalprice").text("Всего: " + data +" руб.")
                        //alert(data)
                    })
            
        } else {		var pid = $(this).parent().parent().parent().attr("id")		 //alert("Удаляю способ 2" + pid)		//$("#shopping_cart_items").append("ndjz мать!");			 $.get("http://moscenniktorg.ru/modules/shop/delite.php", {                productId: $(this).parent().parent().parent().attr("id"),                produkt_kolvo: $(this).parent().parent().parent().find("input").val()            }, function(data){                            ////alert($(this).attr("id"));                                    });			//$("#shopping_cart_items_product" + productId).replaceWith("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");			$(this).parent().parent().parent().replaceWith("");	 					//$(this).attr({             //   src: "http://moscenniktorg.ru/images/ok.gif",            //    id: "remove"           // })					}
        
    })
});

