  /*******************/
  /*      AndLI      */
  /*******************/
  
$(document).ready(function() {
    
    var ind = "";
    var inditem = "";
    var BK_open = false;
    var food = $.cookie("addfood") ? six_arr_cookie( "addfood" ) : new Array();       
    var myPizza = $.cookie("mypizza") ? dual_arr_cookie( "mypizza" ) : new Array();
    var itemClasses = [ ['catalog_item_add_pizza','dashed_pizza'],        // 0
                        ['catalog_item_add_sushi', 'dashed_sushi' ],      // 1
                        ['catalog_item_add_euro', 'dashed_euro'],         // 2
                        ['catalog_item_add_desert', 'dashed_desert' ],    // 3
                        ['catalog_item_add_drink', 'dashed_drink' ]       // 4
                      ];
    
    // Выбор веса продукта
   $('.catalog_item_weight > span.dashed').click( function() {
      var non_selected = '#' + $(this).parent().attr('id').slice(0,-4) + '_' 
                       + (( $(this).parent().attr('id').slice(-3,-2) == '2') ? '1' : '2') + '_w';
      //alert (non_selected);
      $(this).parent().parent().removeClass().addClass('catalog_item_select_2').append(
        $(non_selected).parent().removeClass().addClass('catalog_item_select_1').children('.catalog_item_quantity') 
      );      
    });
    
    function dual_arr_cookie( cookie_name ){
        var linearr = $.cookie( cookie_name ).split(',');
        var arr = new Array();
        var val,key;
        $.each( linearr, function(k,v) {
          if (k%2 == 0)
            key = v;
          else
          {
            val = v;
            arr.push([key,val]);
          }
        });        
        return arr;
      };
      
    function six_arr_cookie( cookie_name ) {
        var linearr = $.cookie( cookie_name ).split(',');
        var arr = new Array();
        var i,n,w,p,c;
        $.each( linearr, function(k,v) {
          if (k%6 == 0)
            i = v;        // index
          if (k%6 == 1)
            n = v;        // name
          if (k%6 == 2)
            w = v;        // weight
          if (k%6 == 3)
            p = v;        // price
          if (k%6 == 4)
            c = v;        // count
          if (k%6 == 5)
          {
            classNum = v;
            arr.push([i,n,w,p,c,classNum]);
          }
        });
        return arr;
    };
      
 
/***********************       Вывод  продуктов в корзину    ******************/    
      function print_added_food(arr) {
        var str = "";
        var price = 0;
        $('#positions').text( '' );        
        $.each(arr, function(k,v){       // v = [inditem, n, w, p, c]
          str = '<div class="basket_item"><a class="' + itemClasses[(v[5]-0)][1] + '">' + v[1] + '</a> ';
          /*************    add My Pizza component   **********/
          $.each(myPizza, function(myK, myV) {
            if ( v[0] == myV[0] )
            {
              str += '<span class="basket_item_ingredients">(' + myV[1] + ')</span> ';
            }
          });
          /************    end My Pizza component   ***********/ 
          str += '<span class="basket_item_nobr"><span class="basket_item_weight">' + v[2] + '</span> '; 
          str += '<span class="basket_item_price">' + v[3] + '&nbsp;р.</span> (';
          str += '<span class="basket_item_count"></span></span></div>';
          $(str).appendTo( '#positions' ).attr('id', 'basket_item_' + v[0]);          
          /************** delete 1 count of item from basket *************/       
          $('<a href="#" class="basket_item_minus"><img src="images/minus2.png" border="0px" /></a>').appendTo('#basket_item_'+v[0]+' .basket_item_count')
          .click( function(){
            inditem = v[0];
            var index = ind_inArray(inditem,food);
            if (index != -1 ) {    //  if item exist in set
              if (food[index][4] == 1)         // last item
              {
                food = $.grep(food, function(n) { return n[0] != inditem } );
                myPizza = $.grep(myPizza, function(n) { return n[0] != inditem } );  // array filter
                $.cookie("mypizza", myPizza.join(','), {expires:0.125});
              }
              else
                food[index][4] = food[index][4] - 1;
              print_added_food(food);
              $.cookie("addfood", food.join(','), {expires:0.125});            
            }
            if (food.length == 0)   //hide  BB if no items
             $('.popup_close > a').click();
            return false;		      
		      });
          $( '#basket_item_' + v[0] + ' .basket_item_count' ).append(' ' + v[4] + '&nbsp;шт. ');		      
          /***************** click plus item *************************/        
          $('<a href="#" class="basket_item_plus"><img src="images/plus2.png" border="0px"/></a>').appendTo('#basket_item_'+v[0]+' .basket_item_count')
          .click( function(){
              inditem = v[0];
              add_item(true);
              return false;        
          });
          $( '#basket_item_' + v[0] + ' .basket_item_count' ).append( ')');		      
          /******* delete item (all count of clicked item) from basket  *******/       
          $('<a href="#" class="basket_item_delete" title="!!!Удалить"></a></span>').appendTo( '#basket_item_' + v[0] + ' .basket_item_nobr' )
          .click( function(){            
            inditem = v[0];
            var index = ind_inArray(inditem,food);
            if (index != -1 ) {    //  if item exist in set
              food = $.grep(food, function(n) { return n[0] != inditem } );  // array filter
              print_added_food(food);
              $.cookie("addfood", food.join(','), {expires:0.125});
              myPizza = $.grep(myPizza, function(n) { return n[0] != inditem } );  // array filter
              $.cookie("mypizza", myPizza.join(','), {expires:0.125});                            
            }
            if (food.length == 0)   //hide  BB if no items
              $('.popup_close > a').click();
            return false;		      
		      });
          //$('#positions').append( '<br />' );
          price += (v[4]-0) * (v[3]-0);
        });                
        $('#positions').append('<div id="basket_small_summ"><span>Сумма заказа</span> ' + price + '&nbsp;р.</div>');        
        if (BK_open) $('.basket_item_plus, .basket_item_minus').show()
        else
          if (food.length != 0)
          { 
            //$('#basket_small_order_link').show();
            $('#basket_small').fadeIn('fast');            
          }
          else
          {
            //$('#basket_small_order_link').hide();
            //alert();
            $('#basket_small').hide();            
          }
      }; //    function print_added_food()   end
/******************************************************************************/
     
      print_added_food(food);
      
      // find index 'ind' in array 'arr'
      function ind_inArray(ind, arr) {
        var index = -1;
        $.each(arr, function(k,v){ 
          if ( v[0]==ind ) 
          {
            index = k;
            return false;
          }
        });
        return index; 
      };
      
      // return array element where element[0]==index
      function by_ind(index, arr) {
        var i = ind_inArray(index,arr);
        return (i != -1) ? food[i] : null;                    
      }        
/*********************   Добавление продуктов     *****************************/      
      function add_item( plus ){
        var index = ind_inArray(inditem,food);
        var count = (plus) ? 1 : ($('#' + ind + '_count').val() - 0);
        var classNum = -1;
        if (count) {                 
          if ( index != -1 )             //  if item exist in set
            food[index][4] = (food[index][4] - 0) + count;
          else
          {
            $.each(itemClasses, function(k,v){
              if ( $('#'+ind+'_a').parent().hasClass(v[0]) ) 
              {
                classNum = k;
                return true;
              }
            });
            food.push([ inditem, 
                        $('#'+ind+'_n').text(),
                        $('#'+inditem+'_w').text(),
                        $('#'+inditem+'_p').text(),
                        count,
                        classNum    // number of css class for small bascket 
                      ]);
          }
          print_added_food(food);
          $.cookie("addfood", food.join(','), {expires:0.125});
          return true;
        }
        else
         return false;
      }

      // click add item
      
        //Catalog        
        $('.catalog_item_add_link').click( function() {
          ind = $(this).attr('id').slice(0,-2);    //delete last 2 symbol from id  sample1_a -> sample1
          if ( $('#' + ind + '_p').parent().parent().hasClass('catalog_item_select') )
          {
            inditem = ind;
          }
          else
          {
            inditem = ind + (( $('#' + ind + '_1_w').parent().hasClass('catalog_item_select_2') ) ? '_1' : '_2');
          }
          //alert ( inditem );
          if (add_item()) 
          {        
            var ja = by_ind(inditem, food);
            var count = $('#' + ind + '_count').val() - 0;                                                 
            var str = '<span class="popup_item_title">' + ja[1] + '</span> <span class="popup_item_weight">'
               + ja[2] + '</span> <span class="popup_item_price">'+ (count * ja[3]) 
               + '&nbsp;р.</span> <span class="popup_item_quantity">(' + count 
               + '&nbsp;шт.) </span><div class="popup_add">добавлена!</div>';
            $('#popup_content').html( str );          
            $('#popup_window').fadeIn('fast');
            //$('#popup_window').delay(1000).css('opacity','1.0');
          }
          return false;        
        } );
        
/*******************          Сборная Пицца       *****************************/
        $('#my_pizza_2_r').click(); // need for backup in FF  ( FF dont reset radio & ckeckboxes)
        myPizzaPrice();
                                                                                 
        $('#my_pizza_a').click( function() {
          if ( $('input:checkbox:checked').length ) 
          {
            var ingrPrice = $('.my_pizza_price span:first').text() - 0;
            var price = 0;
            var Num = 0;
            var IndNumItem = '';            
            var index = 0; 
            do
            {
              Num++;
              IndNumItem = 'my_pizza_'+Num;
              index = ind_inArray(IndNumItem, myPizza);
            } while (index != -1)
            var Item = new Array();
            $('input.my_pizza_ingredients:checkbox:checked').each( function(k,v){
                Item.push( $(this).next().text() );
                price += (ingrPrice - 0);
            });
            myPizza.push([IndNumItem, Item.join('; ')]);
            var Name = "Сборная" + (Num>1?' '+Num:'');
            var IndItem = 'my_pizza_'+( $('#my_pizza_1_w').parent().hasClass('my_pizza_item_select_2')?'1':'2' );            
            price +=  ($('#'+IndItem+'_p').text() - 0);            
            food.push([ IndNumItem, 
                        Name,
                        $('#'+IndItem+'_w').text(),
                        price,
                        1,
                        0
                      ]);
            print_added_food(food);
            $.cookie("addfood", food.join(','), {expires:0.125});
            $.cookie("mypizza", myPizza.join(','), {expires:0.125});
            
            var v = by_ind(IndNumItem, food);
            var str = '<span class="popup_item_title">' + v[1] + '</span>';
            /*******    add My Pizza component   *****/
            $.each(myPizza, function(myK, myV) {
            if ( v[0] == myV[0] )
            {
              str += '<span class="basket_item_ingredients">(' + myV[1] + ')</span> ';
            }
            });
            /*******    end My Pizza component   *****/
            str += '<span class="popup_item_weight">'
               + v[2] + '</span> <span class="popup_item_price">'+ price 
               + '&nbsp;р.</span> <div class="popup_add">добавлена!</div>';
            $('#popup_content').html( str );          
            $('#popup_window').fadeIn('fast');          
          }
          //else
            //alert('Сначала выберете ингридиенты.');
          return false;        
        } );
        
        function myPizzaPrice(){
          var price = 0;
          var ingrPrice = $('.my_pizza_price span:first').text() - 0;
          $('input.my_pizza_ingredients:checkbox:checked').each( function(k,v){
             price += ingrPrice;
          });
          price += $('.my_pizza_item_select_2 > .my_pizza_item_price > span:first').text() - 0;
          //alert(price);
          $('#my_pizza_summ span:first').text( price ); 
        }
    
        $('input.my_pizza_ingredients:checkbox').click(function(){
          myPizzaPrice();
        });
        
        // Выбор веса сборной пицы
        $('input.my_pizza_item_select_radio:radio').click( function() {
          $(this).parent().removeClass().addClass('my_pizza_item_select_2');
          var non_selected = '#my_pizza_' 
                       + (( $(this).attr('id').slice(-3,-2) == '2') ? '1' : '2') + '_r';
          //alert(non_selected );
          $(non_selected).parent().removeClass().addClass('my_pizza_item_select_1');
          myPizzaPrice();     
        }); 
/*******************       End Сборная Пицца      *****************************/
      
        // confirm to order 
        $('#popup_link_order').click( function() {
          $('#popup_window').hide();
          $('#basket_small_order_link').click();          
          return false;
        });
/*******************      End  Добавление продуктов     ***********************/
     
/*******************           Close PopUp          ***************************/       
        $('.popup_close > a, #popup_link_else').click( function(){
          if (BK_open) {
            $('.formError').click();             //  hide error divs
            if (food.length != 0)
              $('#basket_small').fadeIn('fast');
            $('#popup_order').fadeOut('fast');
            BK_open = false;
            $('.basket_item_plus, .basket_item_minus').hide();
            $('#positions').appendTo('#basket_small_content');
          }
          else
            $('#popup_window').fadeOut('fast');
                       
          return false        
        });

/*******************    Отправка формы заказа  ********************************/		   
      $('#basket_small_order_link').click( function() {
        if ( $.cookie("user") ) {
          var user =  dual_arr_cookie( "user" );
          $.each(user, function(k,v){      
            $('#' + v[0]).val( v[1] );
          });
        }
        $('#basket_small').hide();
        BK_open = true;
        // если эти 2 ф-ии в fadeIn корзина появляется рывками
			   $('.basket_item_plus, .basket_item_minus').show();
  			 $('#positions').appendTo('#big_basket_content_copy');
        //        
        $('#popup_order').fadeIn('fast',function(){
        });
        scrollToEl('#popup_order');
        $("#big_basket_form").validationEngine({ validationEventTriggers:"keyup blur",
                                                 success :  function() { sendOrder()  },                     //   вместо submit
                                                 failure : function() {  } //   Ajax  отправка формы 
                                              });  //Плагин проверки полей 
        return false;
      });
      
      function scrollToEl(el) {
      destination = $(el).offset().top;
        if ($.browser.msie || $.browser.opera || $.browser.mozilla)
          $("html").animate({ scrollTop: destination}, 1100 );
        else
          $("*").animate({ scrollTop: destination}, 1100 );
      }
/*******************    End Отправки формы заказа  ****************************/      
      
      $('#big_basket_form_save').click( function() {
        var user = new Array();
        user.push( ['name', $('#name').val()],
                   ['surname', $('#surname').val()],
                   ['phone', $('#phone').val()],
                   ['adress', $('#adress').val()],
                   ['summ', $('#summ').val()],
                   ['euro', $('#euro').val()],
                   ['japan', $('#japan').val()],
                   ['addition', $('#addition').val()],
                   ['promo', $('#promo').val()]
        );
        $.cookie("user", user.join(','), {expires:360});
        return false;
      });
      
      $('#reverse_open').click( function() {
        //$('#big_basket_layer').show();  
        $('#reverse').show(300);        
        $("#reverse_form").validationEngine({validationEventTriggers:"keyup blur"});  //Плагин проверки полей
      });

/***************            Ajax Send Mail    *********************************/      

var timeInterval = false;

function sendOrder() {
  $('.popup_close > a').click();    // close BK
  $('#popup_success_content').html('<br />Отправка заказа...<br /><br />');
  $('#popup_success').fadeIn('fast');
  scrollToEl('body');

  /*******    send Ajax      *********/
  var formData = "";
  $('input.textinput').each( function(){
    formData += $(this).attr('name') + '=' + $(this).val() + '&';
  } );
  $('textarea.textinput').each( function(){
    formData += $(this).attr('name') + '=' + $(this).val() + '&';
  } );
  //var result = "";
  $.ajax({
    type: "POST",
    url: "send_order.php",
    data: formData,
    success: function(result){
      if (result.slice(-8,-1) == 'success')
      { 
        setTimeout(function(){clearAll()}, 100 );
        var t = 300;
        /******            Timer       *******/
        function timer() {
          var str = "";
          str = (parseInt(t/60)) + ':' + ( ( (t % 60) < 10 ) ? '0' : '' ) + (t % 60);    
          $('#popup_success_timer').text(str);
          t--;
          if ( (t % 20) == 0 )
          {
            $.ajax({
              type: "POST",
              url: "/reports/file_exist.php",
              data: "filename="+result.slice(0,-9),
              success: function(fileExist){
                //alert(fileExist);
                if (fileExist == 'exist')
                { 
                  clearInterval(timeInterval);
                  $('#popup_success_timer').html('');
                  $('#popup_success_timer_text').html('');
                  //$('#popup_success_close').show();
                  $('#popup_success_content').html('<br /><br />Спасибо за заказ!<br />До скорой встречи и приятного аппетита.<br /><br />');
                  $('#popup_success_content_2').html('');            
                }
              }
            });
          }
          if (t<0) 
          {
            clearInterval(timeInterval);
            /******    Отправка аджакс письма о просроченном заказе   *****/
            $('#popup_success_timer').html('');
            $('#popup_success_timer_text').html('');
            $('#popup_success_content').html('...');
            $('#popup_success_content_2').html('');
            $.ajax({
              type: "POST",
              url: "resend.php",
              data: "resend="+result.slice(0,-9),
              success: function(resendResult){
                $('#popup_success_close').show();
                if (resendResult == 'success')
                { 
                  $('#popup_success_content').html('<br /><br />Вот не задача! Приносим извинения за задержку.<br /><br />«Гарсон!» искупит свою вину приятным бонусом.');
                }
                else
                  $('#popup_success_content').html('<br />Ошибка на сервере.<br /><br />');
              }
            });
          }    
        }
        /******           End Timer       *******/
        $('#popup_success_content').html("Спасибо, заказ принят.<br />Оператор свяжется с вами не позднее:");
        $('#popup_success_timer').html('5:00');
        $('#popup_success_timer_text').html("минут");
        $('#popup_success_content_2').html("Просьба, до связи с оператором<br />не закрывать данную страницу.");
        if (timeInterval)
        {
          clearInterval(timeInterval);
        }
        timeInterval = setInterval( function(){timer()}, 1000 );
      }
      else
      {
        $('#popup_success_close').show();
        $('#popup_success_content').html('<br />Ошибка на сервере. Заказ не отправлен.<br /><br />');
      }
    }
  });
}

$('#popup_success_close').click( function() {
  $('#popup_success').fadeOut('fast');
} );
/***************            End Ajax Send Mail    *****************************/

function clearAll() {
  $.cookie("addfood", '');
  $.cookie("mypizza", '');
  food = new Array();       
  myPizza = new Array();
  $('#basket_small').fadeOut('fast');
}
       
     });     
