function in_array(arr, val)
{
    for(var i = 0; i < arr.length; i++)
        if(arr[i] == val) return true;

    return false;
}

$(function(){
   $('#city_selector').change(function(){
        $('#city_selector_form').submit();
   });

   if($('#shoppingcartsubmit').get(0) != undefined)
   {
       dirty = new Array();
       
       $('.shoppingcart_deleterow').click(function(){
            if( confirm('Вы действительно хотите удалить выбранный товар из корзины?') )
            {
                var id = $(this).val();
                var tr = $(this).parent().parent();
                $.post("/shop/personal/delete", {id: id},
                   function(data){
                     if(data == '1')
                        tr.remove();
                     else
                        document.location.reload();
                });
            }
            return false;
       });

       $('.buttonup').click(function(){

            var element = $(this).parent().parent().parent().children('td').eq(0).children('input');
            if ( isNaN(element.val()) )
                element.val(1);
            else
            {
                var count = element.val();
                count++;
                element.val(count);
            }
            element.change();
            return false;
       });

       $('.buttondown').click(function(){

            var element = $(this).parent().parent().parent().children('td').eq(0).children('input');
            if ( isNaN(element.val()) )
                element.val(1);
            else
            {
                var count = element.val();
                count--;
                if( count <= 0 ) count = 1;
                element.val(count);
            }
            element.change();
            return false;
       });

       $('.productcount').change(function(){
           $('#saveshoppingcartcount').css('display', 'inline');
           if( !in_array(dirty, $(this).attr('name')) ) dirty.push($(this).attr('name'));
       });


       $('#saveshoppingcartcount').click(function(){

           var data = '{"products": [';

           for(var i = 0; i < dirty.length; i++)
           {
               var id = dirty[i];
               var count = $("[name='"+id+"']").val();

               if(i+1 == dirty.length)
                   data += ' {"id": "'+id+'", "count": "'+count+'"} ';
               else
                   data += ' {"id": "'+id+'", "count": "'+count+'"}, ';
           }

           data += '] }';
           

           $.post("/shop/personal/update", {'json': data},
                   function(data){
                     if(data == '1')
                     {
                         $('#saveshoppingcartcount').css('display', 'none');
                         dirty = new Array();
                         window.location.reload();
                     }
                     else alert('Произошла ошибка при обновлении количества продуктов. Попробуйте еще раз.');//alert(data);
                });
       });

       $('#shoppingcartsubmit').click(function(){
           if( dirty.length > 0)
           {
               alert('Вы изменили количество товаров. Сначала сохраните изменения.');
               return false;
           }
           return true;
       });
   }

});
