var bzakazat_bool = false;

$(document).ready(function(){ 
   $('#oformit').bind('click', function(even){
        $('#shop').slideToggle();
        $('#forma_oformit').slideToggle();

        if ($(this).attr('rel') == "0"){
            $(this).text("<<< Вернуться").attr('rel', '1').hide();
            $('#oformit_2').show(); 

            _itog_sum = itog_sum();  
            discount = getDiscountOfPrice(_itog_sum);
            $('#forma_oformit #price').text(number_format(gPriceD(_itog_sum, discount), 2, '.', ' ') + ' руб.');
            $('#forma_oformit_count').text(itog_count());
        }else{
           $(this).text("Оформить заказ >>>").attr('rel', '0');
        }
   }); 
   
   $('#oformit_2').bind('click', function(even){
        $('#shop').slideToggle();
        $('#forma_oformit').slideToggle();

        $('#oformit').text("Оформить заказ >>>").attr('rel', '0').show(); 
   });      
   
   $("#shop a:has(img.product_image)").fancybox({
        hideOnContentClick: true,
        overlayShow: true,
        overlayOpacity: 0.7,
        zoomSpeedIn: 500,
        zoomSpeedOut:400
    });
    
    
    $("#shop :input[name^=e_count_]").keyup(function(even){
       f = $(this);
       if(!/^\d+$/.test($.trim(f.val()))){
          f.addClass('inputerror');
          f.focus(); 
          price = '';   
       }else{
          f.removeClass('inputerror');
          price = f.val() * $('#e_price_'+f.attr('rel')).val();
       }
       
       if (f.attr('maxCount') != '-1' && $.trim(f.val()) > f.attr('maxCount')) {
            f.val(f.attr('maxCount'));  
            alert('На скаладе всего '+ f.attr('maxCount') +' шт.');  
       }
       $('#itog_price_'+f.attr('rel')).text(number_format(price, 2, '.', ' ') + ' руб.');
       
       _itog_sum = itog_sum();  
       discount = getDiscountOfPrice(_itog_sum);
       $('.discount_itog').text(discount + ' %');
       $('#itog_price').text(number_format(gPriceD(_itog_sum, discount), 2, '.', ' ') + ' руб.');
    });  
    
    $('#bzakazat').bind('click', function(){
      bzakazat_bool = true;   
    });
    
    if(typeof getDiscountOfPrice == 'function') {
        _itog_sum = itog_sum();  
        discount = getDiscountOfPrice(_itog_sum);
        $('.discount_itog').text(discount + ' %');
        $('#itog_price').text(number_format(gPriceD(_itog_sum, discount), 2, '.', ' ') + ' руб.');
    }
});
  
function gPriceD(price, discount) {
    return price * (1 - discount/100);
}  

function itog_sum(){
   var sum = 0;
   $("#tbasket :input[name^=e_count_]").each(function(even){
       f = $(this);
       if(!/^\d+$/.test($.trim(f.val()))){
          f.addClass('inputerror');
          f.focus(); 
          var price = 0;   
       }else{
          f.removeClass('inputerror');
          var g1 = $('#e_price_'+f.attr('rel')).val();
          var g2 = f.val();
          var price = 1*g1*g2;
       }
       
       sum = sum*1 + 1*price;
    });
   
   return sum;
} 

function itog_count(){
   var count = 0;
   $("#tbasket :input[name^=e_count_]").each(function(){
       f = $(this);
       if(/^\d+$/.test($.trim(f.val()))){
          count = count*1 + f.val() * 1;
       }
    });
   return count;
}  
  
  
function addBasket(key, maxCount, number, price, other){ 
    
    _f = $(':input[name=basket_'+key+']');
    f = _f.val();

    if (f <= 0) {
        alert('Количество должно быть больше нуля!');
        return false;
    }
    
    if (maxCount != -1 && f > maxCount) {
        alert('На складе всего '+ maxCount +' шт., а не '+f);
        _f.val(maxCount);
        return false;
    }
    
    $.post('/ajax/basket/addBasket',
        {
            number: number,
            price: price,
            other: other,
            count: f,
            maxCount: maxCount
        },
        function(data){
            if (data != '#0'){
                _data = data.split('#');
                
                $("#basket  #count").text(_data[0]);    
                $("#basket  #count_price").text(_data[1]);    
                $('#message_shop_addBasket').fadeIn(2000, function() {
                    var f = $(this);
                    setTimeout(function() {
                        f.fadeOut();
                    }, 1000);
                });
            }
        });       
}

function removeBasket(key){
 $.post('ajax/basket/delete',
        {
            key: $('#shop #basket_'+key).attr('rel')
        },
        function(data){
           if (data != '#0'){
                _data = data.split('#');
                //alert(data);
                //$("#basket  #count").text(_data[0]);    
                $("#basket  #count_price").text(_data[1]); 
                
                
               count = _data[0];
               //if (count >= 0) {
                $("#basket  #count").text(count);
               //}
                              
               $('#shop #basket_'+key).fadeOut(400, function(){
                   if (count <= 0) {
                      $('#shop').fadeOut(400, function(){
                        $('#oformit').fadeOut();
                        $('#Basket_empty').slideToggle();
                      });
                   }    
               }).remove();
               
               i = 0;
               $('[rtype=el]').each(function() {
                    $(this).attr('rel', i++);
                });
                
                _itog_sum = itog_sum();  
                discount = getDiscountOfPrice(_itog_sum);
                $('.discount_itog').text(discount + ' %');
                $('#itog_price').text(number_format(gPriceD(_itog_sum, discount), 2, '.', ' ') + ' руб.');  
            }           
        });       
}

function FSuccessZakaz(){
   if (ZValidate())
      return bzakazat_bool;
   else
      return false;
}

function ZValidate(){
   phone = $.trim($('#e_phone').val());
   email = $.trim($('#e_email').val());
   name = $.trim($('#e_name').val());
   
   if (name == ''){
      alert('Введите Ваше Имя!');  
      $('#e_name').focus();
      f.addClass('inputerror');  
      return false 
   } 
   
   if (phone == '' && email == ''){
      alert('Введите E-Mail или Контактный телефон!');
      return false;
   }
   
   if (email != '' && !/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i.test(email)){
      alert('E-Mail введен неверно!');
      return false;  
   }

    return true;
}

function number_format( 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://getsprink.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
    // +    revised by: Luke Smith (http://lucassmith.name)
    // +     bugfix by: Diogo Resende
    // +     bugfix by: Rival
    // %        note 1: For 1000.55 result with precision 1 in FF/Opera is 1,000.5, but in IE is 1,000.6
    // *     example 1: number_format(1234.56);
    // *     returns 1: '1,235'
    // *     example 2: number_format(1234.56, 2, ',', ' ');
    // *     returns 2: '1 234,56'
    // *     example 3: number_format(1234.5678, 2, '.', '');
    // *     returns 3: '1234.57'
    // *     example 4: number_format(67, 2, ',', '.');
    // *     returns 4: '67,00'
    // *     example 5: number_format(1000);
    // *     returns 5: '1,000'
    // *     example 6: number_format(67.311, 2);
    // *     returns 6: '67.31'
 
    var n = number, prec = decimals;
    n = !isFinite(+n) ? 0 : +n;
    prec = !isFinite(+prec) ? 0 : Math.abs(prec);
    var sep = (typeof thousands_sep == "undefined") ? ',' : thousands_sep;
    var dec = (typeof dec_point == "undefined") ? '.' : dec_point;
 
    var s = (prec > 0) ? n.toFixed(prec) : Math.round(n).toFixed(prec); //fix for IE parseFloat(0.55).toFixed(0) = 0;
 
    var abs = Math.abs(n).toFixed(prec);
    var _, i;
 
    if (abs >= 1000) {
        _ = abs.split(/\D/);
        i = _[0].length % 3 || 3;
 
        _[0] = s.slice(0,i + (n < 0)) +
              _[0].slice(i).replace(/(\d{3})/g, sep+'$1');
 
        s = _.join(dec);
    } else {
        s = s.replace('.', dec);
    }
 
    return s;
}
