
var ajaxCart = {
	// set cookie via js
setCookie : function(c_name,value,exdays){
   var exdate=new Date();
   exdate.setDate(exdate.getDate() + exdays);
   var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
   document.cookie=c_name + "=" + c_value;
},

getCookie : function(c_name){
	var i,x,y,ARRcookies=document.cookie.split(";");
	for (i=0;i<ARRcookies.length;i++){
      x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
      y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
      x=x.replace(/^\s+|\s+$/g,"");
      if (x==c_name){
        return unescape(y);
      }
    }
},

checkCookie : function(){
   var username=getCookie("username");
   if (username!=null && username!=""){
     alert("Bienvenido de nuevo " + username);
   } else {
     username=prompt("sin uso:","");
     if (username!=null && username!=""){
        ajaxCart.setCookie("test",username,365);
     }
   }
},

//override every button in the page in relation to the cart

    overrideButtonsInThePage : function(){
        //for every 'add' buttons...
        $('.ajax_add_to_cart_button').unbind('click').click(function(){
            var idProduct =  $(this).attr('rel').replace('ajax_id_product_', '');
			if ($(this).attr('disabled') != 'disabled'){
				if (parseInt($(this).parent().parent().find('input.cantidad').val())>0){
                   ajaxCart.add(idProduct, this, parseInt($(this).parent().parent().find('input.cantidad').val()));
				}
			}
            return false;
        });
	    },

	// cart to fix display when using back and previous browsers buttons
	refresh : function(){
		//send the ajax request to the server
		$.ajax({
			type: 'GET',
			url: 'carrito.php',
			async: true,
			cache: false,
			dataType : "json",
			data: "refresh=SI",
			success: function(jsonData)
			{
				ajaxCart.updateCart(jsonData);
			},
			error: function(XMLHttpRequest, textStatus, errorThrown) {
				alert("ERROR TECNICO: no se pudo recargar la cesta.\n\nDetalles:\nError thrown: " + XMLHttpRequest + "\n" + 'Text status: ' + textStatus);
			}
		});  
	},

    // try to expand the cart
    expand : function(){
        if ($('#cart_block #cart_block_list').hasClass('collapsed'))
        {
            $('#cart_block #cart_block_summary').slideUp(200, function(){
                $(this).addClass('collapsed').removeClass('expanded');
                $('#cart_block #cart_block_list').slideDown({
                    duration: 600,
                    complete: function(){$(this).addClass('expanded').removeClass('collapsed');}
                });
            });
            // toogle the button expand/collapse button
            $('#cart_block h4 span#block_cart_expand').fadeOut('slow', function(){
                $('#cart_block h4 span#block_cart_collapse').fadeIn('fast');
            });
            
            // save the expand statut in the user cookie
			ajaxCart.setCookie("ajax_blockcart_display","expand","&rand=" + new Date().getTime());
			
        
            
        }
    },
	 // try to collapse the cart
    collapse : function(){
        
        if ($('#cart_block #cart_block_list').hasClass('expanded'))
        {
            $('#cart_block #cart_block_list').slideUp('slow', function(){
                $(this).addClass('collapsed').removeClass('expanded');
                $('#cart_block #cart_block_summary').slideDown(700, function(){
                    $(this).addClass('expanded').removeClass('collapsed');
                });
            });
            $('#cart_block h4 span#block_cart_collapse').fadeOut('slow', function(){
                $('#cart_block h4 span#block_cart_expand').fadeIn('fast');
            });
            
            // save the expand statut in the user cookie
			ajaxCart.setCookie("ajax_blockcart_display","collapse","&rand=" + new Date().getTime());

        }
    },	
 // add a product in the cart via ajax
     add : function(idProduct, callerElement, quantity){
        //disabled the button when adding to do not double add if user double click
        $('.ajax_add_to_cart_button').attr('disabled', 'disabled');
 
	//	if ($('#cart_block #cart_block_list').hasClass('collapsed'))
	//		this.expand(); 
 //send the ajax request to the server 

        $.ajax({
            type: "GET",
            url: "carrito.php",
            async: true,
            cache: false,
			dataType : "json",
            data: "cestapaso=1&orden=anadir&id_prod="+((idProduct && idProduct != null) ? idProduct : '0000')+"&cantidad="+((quantity && quantity != null) ? quantity : '1'),
			timeout: 5000,
            success: function(jsonData){
				//apply 'transfert' effect

				var $element = $(callerElement).parent().parent().find('div.pro_6');
				var $picture = $element.clone();
				var pictureOffsetOriginal = $element.offset();
				$picture.css({'position': 'absolute', 'top': pictureOffsetOriginal.top, 'left': pictureOffsetOriginal.left});
				var pictureOffset = $picture.offset();
				var cartBlockOffset = $('#cart_block').offset();
				
				$picture.appendTo('body');
				$picture.css({ 'position': 'absolute', 'top': $picture.css('top'), 'left': $picture.css('left') })
				.animate({ left: cartBlockOffset.left + 15, top: cartBlockOffset.top + 30, opacity: 0.2}, { duration: 1000, step: function( now, fx ){ $element.css( "left", now ); } }).fadeOut(100, function() {
					ajaxCart.updateCart(jsonData);
					//reactive the button when adding has finished
					$('.ajax_add_to_cart_button').removeAttr('disabled');
				});	

        	},
			error: function(request,error){
				if (error == "timeout") {
					        $('.ajax_add_to_cart_button').removeAttr('disabled');
   							ajaxCart.add;
  							} else {
   							alert('ERROR: no se ha podido anadir el producto.\n\n Info:\n por favor, envie email a info@movillab.com con el error\n\n Gracias.');
							$('.ajax_add_to_cart_button').removeAttr('disabled');
  							}
				
			}
			
		});
	
	}, // end add
 
    //genarally update the display of the cart
    updateCart : function(jsonData){
        ajaxCart.updateCartEverywhere(jsonData);
        //ajaxCart.hideOldProducts(html);
        //ajaxCart.displayNewProducts(html);
        //ajaxCart.refreshVouchers(html);
        
        //update 'first' and 'last' item classes
        //$('#cart_block dl.products dt').removeClass('first_item').removeClass('last_item').removeClass('item');
        //$('#cart_block dl.products dt:first').addClass('first_item');
        //$('#cart_block dl.products dt:not(:first,:last)').addClass('item');
        //$('#cart_block dl.products dt:last').addClass('last_item');
        
        //reset the onlick events in relation to the cart block (it allow to bind the onclick event to the new 'delete' buttons added)
       // ajaxCart.overrideButtonsInThePage();
    },
    //update general cart informations everywere in the page
    updateCartEverywhere : function(jsonData) {
        //$('.ajax_cart_total').text(jsonData.productTotal);
        //$('.ajax_cart_shipping_cost').text(jsonData.shippingCost);
        //$('.cart_block_wrapping_cost').text(jsonData.wrappingCost);
        $('.ajax_block_cart_total').text((jsonData.productTotal).toFixed(2)); 
		  if(jsonData.productCount == 0){	
		    $('.ajax_block_cart_count').text('Sin producto(s)'); 
		  } else if(jsonData.productCount == 1) {
		    $('.ajax_block_cart_count').text(jsonData.productCount+' producto');	
		  } else {
		    $('.ajax_block_cart_count').text(jsonData.productCount+' productos');	
		  }		
		 //  $('.cart_block_list').text((jsonData.productCount);	
		//if(jsonData.nbTotalProducts > 0){
            //$('.ajax_cart_no_product:visible').hide();
            //$('.ajax_cart_quantity').text(jsonData.nbTotalProducts);
 
            //$('.ajax_cart_quantity:hidden').fadeIn('slow');
            //$('.ajax_cart_total:hidden').fadeIn('slow');
            
            /*if(jsonData.nbTotalProducts > 1)
            {
                $('.ajax_cart_product_txt:visible').hide();
                $('.ajax_cart_product_txt_s:hidden').show();
            } else {
                $('.ajax_cart_product_txt:hidden').fadeIn('slow');
                $('.ajax_cart_product_txt_s:visible').fadeOut('slow');			
			}*/
		/*} else {
            $('.ajax_cart_quantity:visible, .ajax_cart_product_txt_s:visible, .ajax_cart_product_txt:visible, .ajax_cart_total:visible').fadeOut('slow', function(){
                $('.ajax_cart_no_product:hidden').fadeIn('slow');
            });		*/	
		//}
	}

};

// GOOOOOOOO

$(document).ready(function(){

    // expand/collapse management
    $('#block_cart_collapse').click(function(){
            ajaxCart.collapse();
    });
    $('#block_cart_expand').click(function(){
            ajaxCart.expand();
    });
    ajaxCart.overrideButtonsInThePage();
	ajaxCart.refresh();
	
    
});
