$(document).ready(function() {
    $("#jnotifica_main").live('click', function() {
        $("html,body").animate({
            scrollTop: 0 
        })
    });

    $("select.addtocart_select").each(function(){
        $(this).attr("originalValue", $(this).val());
    });

    $("select.addtocart_select").live('change', function() {
        var thiz = this;
        var name = $(this).attr("name");
        var id = name.split("[")[1].split("]")[0];
        var data = {'addtocart': {}};
        data['addtocart'][id] = $(this).val();
        //$("[name='"+name+"']").attr('value', $(this).val());

        $(this).next("img").removeClass("invisible");
        var oldV = $(thiz).attr("originalValue");
        var newV = $(thiz).val();
        $.ajax({
            type: "post",
            url: "/cart/add/ajaxed/",
            data: data,
            success: function(resp){
                $(thiz).next("img").addClass("invisible");
                $(".cart_wrap").html($(resp)[0].innerHTML);

                var msg;
                if(newV == 0) {
                    msg = $("#goodRemoved").html();
                } else if(oldV == 0) {
                    msg = $("#goodAdded").html();
                } else {
                    msg = $("#goodEdit").html();
                }

                $.jnotifica(msg,{
                    margin    : 10,
                    position  : 'top',
                    align     : 'right',
                    background: '#FF9000',
                    color: "#FFF",
                    padding: 5,
                    width     : 250,
                    opacity: 0.92,
                    close: {
                        text: ''
                    }
                });
                
                $(thiz).attr("originalValue", $(thiz).val());
            }
        });
    });

    //
    //  новый способ добавления товара в корзину
    //
    $("input.add_to_cart").live("click", function() {
        var thiz = this;
        var name = $(this).attr("name");
        var id = name.split("[")[1].split("]")[0];
         var in_cart_div = $(thiz).parents("div.accessory_info").find('div.incart_quantity');
         // ищем предыдущее количество
         var previous_value = document.getElementsByName('in_cart_quantity['+id+']')[0];
         // ищем max количество
         var max_value = document.getElementsByName('max_cart_quantity['+id+']')[0];
         // ищем нужный селект
         var increment_select = document.getElementsByName('addtocart['+id+']')[0];
         //  вычисляем новое
         var new_value = previous_value.value*1 + $(increment_select).val()*1;//$(thiz).parent('div').find("select[name='addtocart']").val();
        //alert(new_value);
        if (new_value*1 == 0) return false;
        var data = {'addtocart': {}};
        //$("[name='"+name+"']").attr('value', $(this).val());

        var oldV = 1*previous_value.value;
        var newV = new_value*1; //$(thiz).val();
        if (newV>(max_value.value*1)) newV = max_value.value*1;
        if (newV == oldV) return false;
        $(this).next("img").removeClass("invisible");
        data['addtocart'][id] = newV;
        $.ajax({
            type: "post",
            url: "/cart/add/ajaxed/",
            data: data,
            success: function(resp){
                $(thiz).next("img").addClass("invisible");
                $(".cart_wrap").html($(resp)[0].innerHTML);

                var msg;
                if(newV == 0) {
                    msg = $("#goodRemoved").html();
                } else if(oldV == 0) {
                    msg = $("#goodAdded").html();
                }else {
                    msg = $("#goodEdit").html();
                }

                $.jnotifica(msg,{
                    margin    : 10,
                    position  : 'top',
                    align     : 'right',
                    background: '#FF9000',
                    color: "#FFF",
                    padding: 5,
                    width     : 250,
                    opacity: 0.92,
                    close: {
                        text: ''
                    }
                });

                $(previous_value).val(newV);
                $(in_cart_div).find('.incart_count').html(newV);
                if (newV>0) $(in_cart_div).removeClass("invisible");
            }
        });
        return false;
    });

    $("input.delete_goods").live("click", function() {
        var thiz = this;
         var in_cart_div = $(thiz).parents("div.accessory_info").find('div.incart_quantity');
        //alert($(in_cart_div).html());
        var name = $(this).attr("name");
        var id = name.split("[")[1].split("]")[0];
         // ищем предыдущее количество
         var previous_value = document.getElementsByName('in_cart_quantity['+id+']')[0];
         var new_value = 0;
        var data = {'addtocart': {}};
        data['addtocart'][id] = new_value;
        //$("[name='"+name+"']").attr('value', $(this).val());

        $(this).next("img").removeClass("invisible");
        //alert(new_value);
        var oldV = 1; //$(thiz).attr("originalValue");
        var newV = new_value; //$(thiz).val();
        $.ajax({
            type: "post",
            url: "/cart/add/ajaxed/",
            data: data,
            success: function(resp){
                $(thiz).next("img").addClass("invisible");
                $(".cart_wrap").html($(resp)[0].innerHTML);

                var msg;
                if(newV == 0) {
                    msg = $("#goodRemoved").html();
                } else if(oldV == 0) {
                    msg = $("#goodAdded").html();
                } else {
                    msg = $("#goodEdit").html();
                }

                $.jnotifica(msg,{
                    margin    : 10,
                    position  : 'top',
                    align     : 'right',
                    background: '#FF9000',
                    color: "#FFF",
                    padding: 5,
                    width     : 250,
                    opacity: 0.92,
                    close: {
                        text: ''
                    }
                });

                $(thiz).parents("div.accessory_info").find('input.add_to_cart').attr("originalValue", 0);
                $(in_cart_div).find('.incart_count').html('');
                $(in_cart_div).addClass("invisible")
                previous_value.value = 0;;
            }
        });
        return false;
    });

    $("input.email_me").live("click", function() {
        var thiz = this;
        // var in_cart_div = $(thiz).parents("div.accessory_info").find('div.incart_quantity');
        //alert($(in_cart_div).html());
        var name = $(this).attr("name");
        var id = name.split("[")[1].split("]")[0];
         // ищем предыдущее количество
        var current_value = document.getElementsByName('email_me_status['+id+']')[0];
        var new_value = current_value ? (current_value.value=='1' ? 0 : 1) : 1;
        var data = {'email_me': {}};
        data['email_me'][id] = new_value;
        //$("[name='"+name+"']").attr('value', $(this).val());

        $(this).next("img").removeClass("invisible");
        //alert(new_value);
        //var oldV = 1; //$(thiz).attr("originalValue");
        //var newV = new_value; //$(thiz).val();
        $.ajax({
            type: "post",
            url: "/cart/add/ajaxed/",
            data: data,
            success: function(resp){
                $(thiz).next("img").addClass("invisible");
                if (current_value) current_value.value = new_value;

                var msg='X';
                var img='X';
                if(new_value == 0) {
                    msg = $("input[name='email_me_template']").val();
                    img = $("input[name='email_me_img']").val();
                } else {
                    msg = $("input[name='dont_email_me_template']").val();
                    img = $("input[name='dont_email_me_img']").val();
                }
                //$(thiz).val(msg);
                $(thiz).attr('src', img);
                $(thiz).attr('alt', msg);
            }
        });
        return false;
    });

    $("input.add_to_wishlist").live("click", function() {
        var thiz = this;
        // var in_cart_div = $(thiz).parents("div.accessory_info").find('div.incart_quantity');
        //alert($(in_cart_div).html());
        var name = $(this).attr("name");
        var id = name.split("[")[1].split("]")[0];
         // ищем предыдущее количество
        var current_value = document.getElementsByName('wishlist_status['+id+']')[0];
        var new_value = current_value ? (current_value.value=='1' ? 0 : 1) : 1;
        var data = {'add_to_wishlist': {}};
        data['add_to_wishlist'][id] = new_value;
        //$("[name='"+name+"']").attr('value', $(this).val());

        $(this).next("img").removeClass("invisible");
        //alert(new_value);
        //var oldV = 1; //$(thiz).attr("originalValue");
        //var newV = new_value; //$(thiz).val();
        $.ajax({
            type: "post",
            url: "/cart/add/ajaxed/",
            data: data,
            success: function(resp){
                $(thiz).next("img").addClass("invisible");
                if (current_value) current_value.value = new_value;

                var msg='X';
                var img='X';
                if(new_value == 0) {
                    msg = $("input[name='add_to_wishlist_template']").val();
                    img = $("input[name='add_to_wishlist_img']").val();
                } else {
                    msg = $("input[name='remove_from_wishlist_template']").val();
                    img = $("input[name='remove_from_wishlist_img']").val();
                }
                //$(thiz).val(msg);
                $(thiz).attr('src', img);
                $(thiz).attr('alt', msg);
            }
        });
        return false;
    });

    $("input.add_to_wishlist").live("mouseover", function() {
        var thiz = this;
        var name = $(this).attr("name");
        var id = name.split("[")[1].split("]")[0];
        var current_value = document.getElementsByName('wishlist_status['+id+']')[0];
        if(current_value.value == 1) {
            msg = $("input[name='remove_from_wishlist_template']").attr('alt');
        } else {
            msg = $("input[name='add_to_wishlist_template']").attr('alt');
        }

        $("#thumb").remove();
        $("body").append('<div id="thumb" style="background:#eee;"><span>' + msg + '</span></div>');
        $("#thumb").hide();
        $("#thumb").css("position","absolute");
        $("#thumb").css("z-index","2");
        var p = $(this).offset();
        $("#thumb").css("left",p.left).css("top",p.top+23);
        $("#thumb").show(150);
        $("#thumb").mouseout(function(){$(this).remove();});
    }).live("mouseout", function() {
        $("#thumb").remove();
    });

    $("input.add_to_wishlist_s").live("click", function() {
        var thiz = this;
        // var in_cart_div = $(thiz).parents("div.accessory_info").find('div.incart_quantity');
        //alert($(in_cart_div).html());
        var name = $(this).attr("name");
        var id = name.split("[")[1].split("]")[0];
         // ищем предыдущее количество
        var current_value = document.getElementsByName('wishlist_status['+id+']')[0];
        var new_value = current_value ? (current_value.value=='1' ? 0 : 1) : 1;
        var data = {'add_to_wishlist': {}};
        data['add_to_wishlist'][id] = new_value;
        //$("[name='"+name+"']").attr('value', $(this).val());

        $(this).next("img").removeClass("invisible");
        //alert(new_value);
        //var oldV = 1; //$(thiz).attr("originalValue");
        //var newV = new_value; //$(thiz).val();
        $.ajax({
            type: "post",
            url: "/cart/add/ajaxed/",
            data: data,
            success: function(resp){
                $(thiz).next("img").addClass("invisible");
                if (current_value) current_value.value = new_value;

                var msg='X';
                var img='X';
                if(new_value == 0) {
                    msg = $("input[name='add_to_wishlist_template']").val();
                    img = $("input[name='add_to_wishlist_s_img']").val();
                } else {
                    msg = $("input[name='remove_from_wishlist_template']").val();
                    img = $("input[name='remove_from_wishlist_s_img']").val();
                }
                //$(thiz).val(msg);
                $(thiz).attr('src', img);
                $(thiz).attr('alt', msg);
            }
        });
        return false;
    });

    $("input.add_to_wishlist_s").live("mouseover", function() {
        var thiz = this;
        var name = $(this).attr("name");
        var id = name.split("[")[1].split("]")[0];
        var current_value = document.getElementsByName('wishlist_status['+id+']')[0];
        if(current_value.value == 1) {
            msg = $("input[name='remove_from_wishlist_template']").attr('alt');
        } else {
            msg = $("input[name='add_to_wishlist_template']").attr('alt');
        }

        $("#thumb").remove();
        $("body").append('<div id="thumb" style="background:#eee;"><span>' + msg + '</span></div>');
        $("#thumb").hide();
        $("#thumb").css("position","absolute");
        $("#thumb").css("z-index","2");
        var p = $(this).offset();
        $("#thumb").css("left",p.left).css("top",p.top+23);
        $("#thumb").show(150);
        $("#thumb").mouseout(function(){$(this).remove();});
    }).live("mouseout", function() {
        $("#thumb").remove();
    });



    $("input.email_me").live("mouseover", function() {
        var thiz = this;
        var name = $(this).attr("name");
        var id = name.split("[")[1].split("]")[0];
        var current_value = document.getElementsByName('email_me_status['+id+']')[0];
        if(current_value.value == 1) {
            msg = $("input[name='dont_email_me_template']").attr('alt');
        } else {
            msg = $("input[name='email_me_template']").attr('alt');
        }

        $("#thumb").remove();
        $("body").append('<div id="thumb" style="background:#eee;"><span>' + msg + '</span></div>');
        $("#thumb").hide();
        $("#thumb").css("position","absolute");
        $("#thumb").css("z-index","2");
        var p = $(this).offset();
        $("#thumb").css("left",p.left).css("top",p.top+23);
        $("#thumb").show(150);
        $("#thumb").mouseout(function(){$(this).remove();});
    }).live("mouseout", function() {
        $("#thumb").remove();
    });

    $("select.shortage_qty").live("change", function() {
        var thiz = this;
        var name = $(this).attr("name");
        var id = name.split("[")[1].split("]")[0];
        var order_id = $(this).prev(".order_id").val();
        var new_quantity = $(this).val();
        var data = 'order_id=' + order_id + '&good_id=' + id + '&new_quantity=' + new_quantity;
        
        $(this).next("img").removeClass("invisible");
        $.ajax({
            type: "post",
            url: "/order/ajax/shortage",
            data: data,
            success: function(resp){
                $(thiz).next("img").addClass("invisible");
                var msg;
                if(new_quantity == 0) {
                    msg = $("#goodRemoved").html();
                } else {
                    msg = $("#goodEdit").html();
                }

                $.jnotifica(msg,{
                    margin    : 10,
                    position  : 'top',
                    align     : 'right',
                    background: '#FF9000',
                    color: "#FFF",
                    padding: 5,
                    width     : 250,
                    opacity: 0.92,
                    close: {
                        text: ''
                    }
                });
            }
        });
        $(this).parent("td").parent("tr").removeClass('shortage_row');
        if (new_quantity>0) $(this).parent("td").parent("tr").addClass('shortage_row');
    });    
    $("select.not_sent_qty").live("change", function() {
        var thiz = this;
        var name = $(this).attr("name");
        var id = name.split("[")[1].split("]")[0];
        var order_id = $(this).prev(".order_id").val();
        var new_quantity = $(this).val();
        var data = 'order_id=' + order_id + '&good_id=' + id + '&new_quantity=' + new_quantity;
        //alert(data);
        $(this).next("img").removeClass("invisible");
        $.ajax({
            type: "post",
            url: "/order/ajax/not_sent",
            data: data,
            success: function(resp){
                $(thiz).next("img").addClass("invisible");
                var msg;
                if(new_quantity == 0) {
                    msg = $("#goodRemoved").html();
                } else {
                    msg = $("#goodEdit").html();
                }

                $.jnotifica(msg,{
                    margin    : 10,
                    position  : 'top',
                    align     : 'right',
                    background: '#FF9000',
                    color: "#FFF",
                    padding: 5,
                    width     : 250,
                    opacity: 0.92,
                    close: {
                        text: ''
                    }
                });
            }
        });
        $(this).parent("td").removeClass('not_sent_cell');
        if (new_quantity>0) $(this).parent("td").addClass('not_sent_cell');
    });


    $("select.addtobonuscart_select").each(function(){
        $(this).attr("originalValue", $(this).val());
    });

    $("select.addtobonuscart_select").live("change", function() {
        var thiz = this;

        var name = $(this).attr("name");
        var id = name.split("[")[1].split("]")[0];
        var data = {'addtobonuscart': {}};
        data['addtobonuscart'][id] = $(this).val();

        $(this).next("img").removeClass("invisible");
        var oldV = $(thiz).attr("originalValue");
        var newV = $(thiz).val();
        $.ajax({
            type: "post",
            url: "/cart/add_for_bonus/ajaxed",
            data: data,
            success: function(resp){
                $(thiz).next("img").addClass("invisible");
                $(".cart_wrap").html($(resp)[0].innerHTML);

                var msg;
                if(newV == 0) {
                    msg = $("#goodRemoved").html();
                } else if(oldV == 0) {
                    msg = $("#goodAdded").html();
                } else {
                    msg = $("#goodEdit").html();
                }

                $.jnotifica(msg,{
                    margin    : 10,
                    position  : 'top',
                    align     : 'right',
                    background: '#FF9000',
                    color: "#FFF",
                    padding: 5,
                    width     : 250,
                    opacity: 0.92,
                    close: {
                        text: ''
                    }
                });
                
                $(thiz).attr("originalValue", $(thiz).val());
            }
        });
    });

    $("div.icon-delivery a,div.icon-spec a,div.icon-hit a").live("mouseover", function() {
        msg = $(this).attr('rel');
        $("#thumb").remove();
        $("body").append('<div id="thumb" style="background:#eee;"><span>' + msg + '</span></div>');
        $("#thumb").hide();
        $("#thumb").css("position","absolute");
        $("#thumb").css("z-index","2");
        var p = $(this).offset();
        $("#thumb").css("left",p.left).css("top",p.top+23);
        $("#thumb").show(150);
        $("#thumb").mouseout(function(){$(this).remove();});
    }).live("mouseout", function() {
        $("#thumb").remove();
    });
});
