/**
 * Adding single item to cart, without checking for necessary fields filling
 * @param {integer} Passing item id to the function
 */
function cartAdd(item){
    $('#button'+item).hide();
    $('#loader'+item+' img').show();
    $.post( '/actions/addtocart.php',
            { item: item },
            function(data) { 
               $('#loader'+item+' img').hide();
               $('#button'+item).show();
               updateMiniCart(data);
               showSmallCart(data);
            },
            'json'
    );
}
/**
 *  Updating minicart with the provided data. If json object has status setting as 'error', then message will be alerted,
 *  in other case it will be written to the minicart section of the site 
 * @param {json} 
 * 
 */
function updateMiniCart(data){
    if (data.status == 'error') {
        alert(data.message);
    }
    else {
	    $('.minicart').slideUp('fast',function() {
	    	if(data.cartstate=='full') {
	    		$('.minicart').addClass('minicart-full');
	    	}
	    	else {
	    		$('.minicart').removeClass('minicart-full');
	    	}
	    	$('.minicart').html(data.message).fadeIn('slow'); });
    }
}

/**
 * Function showing small cart contents based on data
 */
function showSmallCart(data) {
   $('#cartSmall .sc_contents').html(data.cartSmall);
   $('#cartSmall .sc_close,#cartSmall .sc_continue').click(function() {$('#cartSmall').fadeOut('fast'); $('#cartOverlay').fadeOut('fast')});
   pageSize = getPageSize();
   pageScroll = getPageScroll();
   cartTop = pageScroll[1] + pageSize[3]/2 - $('#cartSmall').outerHeight()/2; 
   $('#cartOverlay').css({height:pageSize[1]+'px', opacity:0.6}).fadeIn('fast');
   $('#cartSmall').css({top:cartTop+'px'}).fadeIn('fast');
}

/**
 *  Initializing forms and lightbox 
 */
$(document).ready(function(){
    $('.form-addtocart').ajaxForm({
         beforeSubmit: function() { $('#btn_addtocart').hide(); $('#cartloader img').show(); },
         dataType: 'json',
         success: function(data) {
            $('#cartloader img').hide();
            $('#btn_addtocart').show(); 
            updateMiniCart(data);
            showSmallCart(data); 
         } 
    });
    $('#formUpdateCart').ajaxForm({
       beforeSubmit: function() { $('.fullcart .loader').show(); },
       dataType: 'json',
       success: cartUpdate
    });

    $('.form').ajaxForm({
       beforeSubmit: function() {
       	$('.form-message').html(''); 
       	$('.form-overlay').show(); 
       },
       dataType: 'json',
       success: function(data) {
       	$('.form-overlay').hide(); 
       	if(data.status=='error') {
       		$('.form-message').hide().addClass('error').html(data.message).fadeIn('slow');
       	}
       	else {
       		$('.form-message').hide().removeClass('error').html(data.message).fadeIn('slow');
       		$('.form input[type=text]').attr('value','');
       		$('.form textarea').attr('value','');
       	}
       }
    });

    $('.form-subscribe').ajaxForm({
       beforeSubmit: function() {
       	$('.subscribe-message').hide();
       	$('.subscribe .form-overlay').show();
       },
       dataType: 'json',
       success: function(data) {
       	$('.subscribe-close').click(function(){
       		$('.subscribe-message').fadeOut('fast');
       	});
       	$('.subscribe .form-overlay').hide(); 
       	if(data.status=='error') {
       		$('.subscribe-message .msg').html(data.message);
       		$('.subscribe-message').hide().addClass('error').fadeIn('slow');
       	}
       	else {
       		$('.subscribe-message .msg').html(data.message);
       		$('.subscribe-message').hide().removeClass('error').fadeIn('slow');
       		$('.subscribe .form input[type=text]').attr('value','');
       	}
       }
    });

    $('.searchform .example span').click(function() {
    	$('.searchform input.text').attr('value',this.innerHTML);
    	$('.formSearch').submit();
    });

    $('.lightbox, .fancybox').fancybox({
       'titlePosition' : 'over',
       'showNavArrows' : 'true',
       'margin'        : 15,
       'padding'       : 3,
       'transitionIn'  : 'elastic'
    });
    
    //Launching fancybox while clicking on first image
    $('.product-first-image').click(function(){
       $('.product-gallery .images a:first').trigger('click');
       return false;
    });
    
    $('.material').click(function() {
    	$(this).siblings().removeClass('material-active');
    	$(this).addClass('material-active');
    	$(this).siblings('[name*=materials]').attr( 'value', $(this).attr('value') );
    });

    //This is our slider
    var slider=$('.slider');
    //The list
    var listFull=$('.images');
    //All the elements
    var list=$('.images>a');
    //Counting amount;
    var images=list.length;
    //And counting full width
    var fullWidth=images*(107+12);
    
    //If we have less than 5 images - making full width to fit parent width and adding 10 pixels (which are negative margin of the container)
    if(images<5) {
    	fullWidth = listFull.parent().width()+10;
    }
    
    //Makign our list to be enough in width
    listFull.width(fullWidth);
    
    var leftMargin=0-fullWidth+slider.width()+10;
    var rightMargin=0;
    var moveSpeed=10;
    var intervalLength=40;
    var interval=0;
    
    //alert(listFull.css('left'));

    $('.btn-slideRight').bind('mouseover','',function() { interval=setInterval(moveRight,intervalLength)});
    $('.btn-slideLeft').bind('mouseover','',function() { interval=setInterval(moveLeft,intervalLength)});
    $('.btn-slideRight,.btn-slideLeft').bind('mouseout','',function() { clearInterval(interval); });

    function moveRight() { move('right'); } 
    function moveLeft() { move('left'); }
    function move(dir){
       currentLeft = listFull.css('left');
       nopx = currentLeft.substring(0, currentLeft.length - 2);
       
       if (dir == 'left') {
          if ((parseInt(nopx)+parseInt(moveSpeed)) >= rightMargin) {
             nopx = rightMargin;
          }
          else {
             nopx = parseInt(nopx)+parseInt(moveSpeed);
          }
          //alert(nopx);
       }
       else {
          if ((nopx - moveSpeed) <= leftMargin) {
             nopx = leftMargin;
          }
          else {
             nopx -= moveSpeed;
          }
       }
       listFull.css({
          'left': nopx + 'px'
       });
    }

    
});
function updateMini(){
    $.get('/actions/minicart.php', updateMiniCart, 'json' );
}


function cartUpdate(data){
   $('.fullcart .loader').hide();
   if (data.status == 'error') {
       alert(data.message);
       $('#checkoutFlag').remove();
   }
   else {
      if (data.status == 'replace') {
         $('.fullcart').html(data.message);
         updateMini();
      }
      else {
         $('#cartSubTotal').html(data.sum);
         $('#cartShipping').html(data.shipping);
         $('#cartTotal').html(data.total);
         $('#amount').val(data.sumC);
         $('#handling_cart').val(data.shippingC);
         $('#amountPaypal').html(data.total);
         if (data.toremove != '') {
            for (i = 0; i < data.toremove.length; i++) {
               var item = data.toremove[i];
               $('#item_' + item).remove();
               //Getting the number in the list of the products
               name = $('#name_' + item).attr('name');
               index = name.lastIndexOf('_');
               number = name.substring(index + 1);
               
               //Removing hidden fields that holding an item
               $('#name_' + item).remove();
               $('#quantity_' + item).remove();
               $('#amount_' + item).remove();
               
               number++;
               
               //Iterating through all the items which number was greater than removed one and decreasing their number to 1
               while ($('input[name=quantity_' + number + ']').attr('name') == ('quantity_' + number)) {
                  $('input[name=quantity_' + number + ']').attr('name', 'quantity_' + (number - 1));
                  $('input[name=amount_' + number + ']').attr('name', 'amount_' + (number - 1));
                  $('input[name=item_name_' + number + ']').attr('name', 'item_name_' + (number - 1));
                  number++;
               }
            }
         }
         if (data.toupdate != '') {
            for (i in data.toupdate) {
               //item = i;
               amount = data.toupdate[i];
               $('#quantity_' + i).attr('value',amount);
            }
         }

         if(data.checkout!='') {
            $('#'+data.checkout).submit();
         }
         else {
            $('#checkoutFlag').remove();
         }
      }
   }
   updateMini();
}

function getPageSize() {
   var xScroll, yScroll;

   if (window.innerHeight && window.scrollMaxY) {
      xScroll = window.innerWidth + window.scrollMaxX;
      yScroll = window.innerHeight + window.scrollMaxY;
   } else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
      xScroll = document.body.scrollWidth;
      yScroll = document.body.scrollHeight;
   } else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
      xScroll = document.body.offsetWidth;
      yScroll = document.body.offsetHeight;
   }

   var windowWidth, windowHeight;

   if (self.innerHeight) { // all except Explorer
      if(document.documentElement.clientWidth){
         windowWidth = document.documentElement.clientWidth;
      } else {
         windowWidth = self.innerWidth;
      }
      windowHeight = self.innerHeight;
   } else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
      windowWidth = document.documentElement.clientWidth;
      windowHeight = document.documentElement.clientHeight;
   } else if (document.body) { // other Explorers
      windowWidth = document.body.clientWidth;
      windowHeight = document.body.clientHeight;
   }

   // for small pages with total height less then height of the viewport
   if(yScroll < windowHeight){
      pageHeight = windowHeight;
   } else {
      pageHeight = yScroll;
   }


   // for small pages with total width less then width of the viewport
   if(xScroll < windowWidth){
      pageWidth = xScroll;
   } else {
      pageWidth = windowWidth;
   }

   var arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight);
   return arrayPageSize;
}

function getPageScroll(){
   var xScroll, yScroll;

   if (self.pageYOffset) {
      yScroll = self.pageYOffset;
      xScroll = self.pageXOffset;
   } else if (document.documentElement && document.documentElement.scrollTop){  // Explorer 6 Strict
      yScroll = document.documentElement.scrollTop;
      xScroll = document.documentElement.scrollLeft;
   } else if (document.body) {// all other Explorers
      yScroll = document.body.scrollTop;
      xScroll = document.body.scrollLeft;
   }

   var arrayPageScroll = new Array(xScroll,yScroll);
   return arrayPageScroll;
}
   
function cartRemove(item,question){
    if (confirm(question)) {
        $.get('/actions/removecart.php', {
            item: item
        }, function(data){
            if (data.status == 'error') {
                alert(data.message);
            }
            else {
                if (data.status == 'replace') {
                   $('#item_' + data.removed ).slideUp('slow',function() { $('.fullcart').html(data.message); updateMini()});
                }
                else {
                    $('#item_' + data.removed ).slideUp('slow',updateMini());
                    $('#cartSubTotal').html(data.sum);
                    $('#cartShipping').html(data.shipping);
                    $('#cartTotal').html(data.total);
                    $('#amount').val(data.sumC);
                    $('#handling_cart').val(data.shippingC);
                    $('#amountPaypal').html(data.total);
                    
//Getting the number in the list of the products
                    name=$('#name_'+item).attr('name');
                    index=name.lastIndexOf('_');
                    number=name.substring(index+1);
                    
//Removing hidden fields that holding an item
                    $('#name_'+item).remove();
                    $('#quantity_'+item).remove();
                    $('#amount_'+item).remove();
                     
                    number++;
                    
//Iterating through all the items which number was greater than removed one and decreasing their number to 1
                    while($('input[name=quantity_'+number+']').attr('name')==('quantity_'+number)) {
                       $('input[name=quantity_'+number+']').attr('name','quantity_'+(number-1));
                       $('input[name=amount_'+number+']').attr('name','amount_'+(number-1));
                       $('input[name=item_name_'+number+']').attr('name','item_name_'+(number-1));
                       number++;
                    }
                }
            }
        }, 'json');
    }
    else {
        return false;
    }
}
function checkout() {
   $('#formUpdateCart').prepend('<input type="hidden" name="checkout" value="1" id="checkoutFlag">');
   $('#formUpdateCart').submit();
}
