﻿$(document).ready(function() {
    $('#menuup li').hover(function(){
        $(this).addClass('hover');
    }, function(){
        $(this).removeClass('hover');
    });
    $("#well_ajax_enter").fancybox({
        'hideOnContentClick': false,
        'frameWidth': 300,
        'frameHeight': 380
    });
    $('div.banners').each(function(){
        var span  = $(this).find('span');
        if(span){
            swfobject.embedSWF(span.attr('id'),this.id, span.width(), span.height(), "10",false,false,{
                wmode:'opaque'
            });
        }
    });
    $(".preview_pic").fancybox({
        'zoomSpeedIn': 300,
        'zoomSpeedOut': 300,
        'overlayShow': true,
        'hideOnContentClick': false
    });
    $(".preview_podrob_o_fili").fancybox({
        'zoomSpeedIn': 300,
        'zoomSpeedOut': 300,
        'frameWidth': 790,
        'frameHeight': 450
    });
    $("#pick_color").fancybox({
        'hideOnContentClick': false,
        'frameWidth': 400,
        'frameHeight': 500
    });
    $(".details").attr('onclick','');
    $(".details").fancybox({
        'hideOnContentClick': false,
        'frameWidth': 800,
        'frameHeight': 500
    });
    $(".store_status a").attr('onclick','');
    $(".store_status a").fancybox({
        'hideOnContentClick': false,
        'frameWidth': 400,
        'frameHeight': 400
    });
    $(".probnik a").fancybox({
        'hideOnContentClick': false,
        'frameWidth': 710,
        'frameHeight': 430
    });
    $(".share").click(function(){
        window.open(this.href,'Share',"location,width=700,height=400");
        return false
    });
    //$('.cart_add a').fancybox({'hideOnContentClick': false, 'frameWidth': 500, 'frameHeight': 480});
    $('.no-ie-active').fadeOut('slow').fadeIn('slow').fadeOut('slow').fadeIn('slow').fadeOut('slow').fadeIn('slow',function(){
        $(this).attr('class','no-ie');
    });
    $(".page_active").bind("mouseenter",function(){
        $(this).addClass("page_hover");
    }).bind("mouseleave",function(){
        $(this).removeClass("page_hover");
    }).bind("click", function(){
        var hrefka = $(this).children("a").attr("href");
        $("#submitka").attr("action",hrefka).submit();
    })
    $(".cart_hover").bind("mouseenter",function(){
        $(this).stop().attr("src","/etc/img/icons/add_to_shopping_cart_hover.png").animate({
            "opacity": "0.6"
        }, 350);
    }).bind("mouseleave",function(){
        $(this).stop().attr("src","/etc/img/icons/add_to_shopping_cart.png").animate({
            "opacity": "1"
        }, 350);
    });
    $('.cartCntProduce').keyup(function(){
        var id = this.id.replace('cnt_','');
        var sum =  parseFloat($('#sum_'+id).text());
        var cnt = parseInt($(this).val(),10);
        if(!cnt)
            cnt = 0;
        var price = parseFloat($('#price_'+id).text());
        var disc = false;
        var newprice = false;
        $('#disc_'+id).find('.disccnt').each(function(){
            if(cnt >= parseInt($(this).text())){
                disc = parseInt($('#discper_' + this.id.replace('disccnt_','')).text());
                newprice = parseFloat($('#discprice_' + this.id.replace('disccnt_','')).text());
            }
        });
        if(disc){
            price = Math.round((price*cnt - (price/100*disc))*100)/100;
            $('#sum_'+id).text(price+ ' .руб').css({
                color:'green'
            }).append('<img style="float:right;margin:0;cursor:pointer;" alt="С учетом скидки ' + disc + '%" src="/etc/img/q.gif" title="С учетом скидки ' + disc + '%"/>');
        }
        else if(newprice){
            price = Math.round(newprice * cnt*100)/100;
            $('#sum_'+id).text(price+ ' .руб').css({
                color:'green'
            }).append('<img style="float:right;margin:0;cursor:pointer;" alt="С учетом новой цены ' + newprice + ' руб" src="/etc/img/q.gif" title="С учетом новой цены ' + newprice + ' руб"/>');
        }
        else {
            price = Math.round(price*cnt * 100)/100;
            $('#sum_'+id).text(price + ' .руб').css({
                color:'#000'
            });
        }
        var summ = Math.round((parseFloat($('#allPrice').text())+price - sum)*100)/100;
        $('#allPrice').html( summ+ ' .руб');
        $('#cart_summ').html(summ + ' .руб');
        cnt = 0;
        $('.cartCntProduce').each(function(){
            cnt+= parseInt($(this).val(),10);
        });
        if(!cnt)
            cnt = 0;
        $('#cart_cnt').html(cnt);
    }).blur(function(){
          var id = this.id.replace('cnt_','');
          var cnt = parseInt($(this).val(),10);
          var min_cnt = parseInt($('#min_cnt_'+id).val(),10);
          var mnoj = $('#mnoj_'+id).val().split(',');
          if(cnt < min_cnt){
            cnt = min_cnt;
            $(this).val(cnt);
            $(this).keyup();
           alert('Минимальное количество товара "'+$('#name_'+id).text()+'" для заказа ' + min_cnt);
           return false;
          }
          var  ost = 0;
          var i = 0;
          for (i=0; i<mnoj.length; i++) {
            if(mnoj[i] > 0){
                ost = cnt%parseInt(mnoj[i],10);
                if (ost == 0)
                    break;
            }
         }
         if (ost != 0){
            alert('Вы можете указать значение количества товара только кратное '+mnoj[0]+', например, '+mnoj[0]+', '+ mnoj[0]*2+','+ mnoj[0]*3+' и т.д.');
            ost = cnt%parseInt(mnoj[0],10);
            if(ost >parseInt( mnoj[0],10)/2)
                $(this).val(cnt + parseInt(mnoj[0],10)-ost);
            else
                $(this).val(cnt - ost);
            $(this).keyup();
          }
          return true;
    });
    $('.input_count').keyup(function(){
        var val = parseInt($(this).val(),10);
        var disc = false;
        var newprice = false;
        $(this).parent().parent().parent().find('.discount .disccnt').each(function(){
            if(val >= parseInt($(this).text())){
                disc = parseInt($('#discper_' + this.id.replace('disccnt_','')).text(),10);
                newprice = parseFloat($('#discprice_' + this.id.replace('disccnt_','')).text());
            }
        });
        var price = parseFloat($('#price_'+this.id).text());
        var sum = $(this).val() * price;
        sum =  Math.round(sum * 100) /100;
        if(disc){
            sum -=(sum/100*disc);
            $('#summ_'+this.id).text(sum + ' .руб ').css({
                color:'green'
            }).append('<img style="float:right;margin:0;cursor:pointer;" alt="С учетом скидки ' + disc + '%" src="/etc/img/q.gif" title="С учетом скидки ' + disc + '%"/>');;
        }
        else if(newprice){
            sum = newprice * $(this).val();
            $('#summ_'+this.id).text(sum+ ' .руб').css({
                color:'green'
            }).append('<img style="float:right;margin:0;cursor:pointer;" alt="С учетом новой цены ' + newprice + ' руб" src="/etc/img/q.gif" title="С учетом новой цены ' + newprice + ' руб"/>');
        }
        else
            $('#summ_'+this.id).text(sum + ' .руб').css({
                color:'grey'
            });
    })
    $('.discount .disccnt').click(function(){
        var p = $(this).parent().parent().find('.input_count');
        p.val(parseInt($(this).text()));
        p.keyup();
    });
    $(".pod_item input").change(function(){
        var id = this.id;
        if (document.getElementById(id).checked == true) {
            $('#cat_'+id).show("slow");
            if (id != "city_0") {
                document.getElementById('city_0').checked = true;
            //$('#cat_city_0').show("slow");
            }
        } else {
            $('#cat_'+id).hide("slow");
        }

    });
});

function well_ajax_exit() {
    var answer = confirm("Вы действительно хотите выйти ?!?")
    if(answer) {
        $.get('/index.php?well=auth_reg/do_exit', function(data) {
            if(data=="OK") window.location.reload(true);
        })
    }
}

function cart_add(id_,min_cnt,mnoj) {
    var count_ = document.getElementById(id_).value;
    if(count_ >= min_cnt) {
        var error = null;
        for (var i=0; i<mnoj.length; i++) {
            error = i;
            if (count_ % mnoj[i] == 0){
                error = null;
                break;
            }
        }
        if(error == null){
            $.post("/internet_magazin/add_to_cart/"+id_+"/"+count_,
                function(data){
                    if(data == "OK") {
                        alert("Товар успешно добавлен в корзину!");
                        mini_cart_refresh();
                        var summ = parseInt($('#cart_summ').text());
                        if(summ <= 1000){
                            $('#cart_100').show();
                        }
                        else
                            $('#cart_500').hide();
                    }
                });
        }
        else {
            alert('Вы можете указать значение количества товара только кратное '+mnoj[0]+', например, '+mnoj[0]+', '+ mnoj[0]*2+','+ mnoj[0]*3+' и т.д.')
        }


    }
    else
        alert('Минимальное количество товара для заказа ' + min_cnt);
}

function mini_cart_refresh() {
    var i = Math.round(10000*Math.random());
    $("#mini_cart").load("/internet_magazin/mini_cart/echo/"+i);
}
function checkCart(redirect){
    var summ = parseInt($('#cart_summ').text());
    if(summ <= 1000){
        var summ = $('#allPrice').text();
        if(!summ || parseInt(summ) <= 1000){
            alert('Вы не можете оформить заказ на сумму меньше 1000 руб. Обратитесь, пожалуйста, в один из наших торговых залов для совершения данной покупки или увеличьте объем заказа для Интернет-магазина. Приносим извинения за возможные неудобства!');
            return false;
        }
    }
    if(redirect)
        window.location.href='/index.php?well=internet_magazin&cart=oformit';
    return true;
}

function cart_empty(tt) {
    var answer = confirm("Вы действительно хотите очистить корзину ?!?")
    if(answer) {
        $.get("/internet_magazin/cart_empty", function(data) {
            if(data=="OK") {
                mini_cart_refresh();
                if(tt==1) window.location.reload(true);
            }
        });
    }
}

function disable_filter() {
    $(".filter_select").removeAttr("onChange");
/*
	$("#pick_color").remove();
	$(".reset_color").removeAttr("onClick");
	*/
}

function change_filter() {
    disable_filter();
    document.forms.submitka.submit();
}

function reset_filter(fl) {
    document.getElementById(fl).value = "no";
    disable_filter();
    document.forms.submitka.submit();
}

function reset_color() {
    disable_filter();
    document.getElementById('pick_color_bg').style.background = "";
    document.getElementById('col_9').value = "";
    document.forms.submitka.submit();
}

function sortbyprice(pp) {
    if(pp=="1") document.getElementById('sort_by_price').value = "1";
    else if(pp=="0") document.getElementById('sort_by_price').value = "0";
    else document.getElementById('sort_by_price').value = "no"
    document.forms.submitka.submit();
}

function cart_delete_item(x) {
    $.post("/internet_magazin/cart_delete_item", {
        id:x
    },
    function(data) {
        if(data == "OK") {
            alert("Товар успешно удалён!");
            window.location.reload(true);
        }
    })
}

function show_nomer(n) {
    $(".nomer").hide();
    $("#nomer_"+n).show();
}
