var Cart = {
	expand : function(){
			if( !$( 'cart_block_summary') ) return;
			$( 'cart_block_summary').dissolve().get('reveal').chain( function() {
				$('cart_block_summary').addClass('collapsed').removeClass('expanded');
				$('cart_block_list').reveal().addClass('expanded').removeClass('collapsed');
			});
			Cookie.write( 'ajax_blockcart_display', 'expand', 15);	
	},
	collapse : function(){
			if( !$( 'cart_block_summary') ) return;
			$( 'cart_block_list' ).dissolve().get('reveal').chain( function() {
				$('cart_block_list').addClass('collapsed').removeClass('expanded');
				$('cart_block_summary').reveal().addClass('expanded').removeClass('collapsed');
			});			
			Cookie.write( 'ajax_blockcart_display', 'collapse', 15);	
	},
	toggle : function() {
		if ( $('cart_block_list').hasClass('expanded') ) Cart.collapse();
		else Cart.expand();
		return;
	},
	resize : function() {
		cart_height = $('cart_block_list').getElement('.block_content').getSize().y;
		container_height = $('cart_block_list').getSize().y;
		if( cart_height!= container_height)
			$('cart_block_list').getParent().tween('height', cart_height);
	},
	hideOldProducts : function(jsonData) {
		var products_cart = $$('#cart_block_list dl.products dt' );
		if( products_cart.length > 0 ) {
			var removedProductId = null;
			products_cart.each( function( product_cart, key_cart ) {
				var domIdCart = product_cart.get('id');
				var item = domIdCart.replace('cart_block_product_', '');
				
				var stayInTheCart = false;
				$each(jsonData.products, function( product, key ) {
					if (key == item) 
							stayInTheCart = true;
				});
				if(!stayInTheCart)
					removedProductId = product_cart.get('id');								
			} );
			if (removedProductId != null) {
				var firstCut =  removedProductId.replace('cart_block_product_', '');
				var ids = firstCut.split('_');
				
				
				$(removedProductId).addClass('strike');
				( function() {
					$$('#cart_block #cart_block_combination_of_' + ids[0] + (ids[1] ? '_'+ids[1] : '') ).dissolve();
					$(removedProductId).dissolve().get('reveal').chain( function() {
						$(removedProductId).destroy();
						$$('#cart_block #cart_block_combination_of_' + ids[0] + (ids[1] ? '_'+ids[1] : '') ).destroy();
						( function() {
							if($$('#cart_block dl.products dt').length == 0) {
								$('cart_block_no_products').hide().reveal();
								$('cart_block').getElement('dl.products').empty();
								$('cart_block_no_products').get('reveal').chain( function() { Cart.resize(); });
							} else Cart.resize();
						} ).delay(1000);
					});
				} ).delay(1000);
			}
		}
	},
	displayNewProducts : function(jsonData) {
		$each(jsonData.products,function( el, key ){
			if (el.id_product != undefined) {
				if ( $$('cart_block dl.products').length == 0 )
					$('cart_block_no_products').hide();
			
				if( !$('cart_block').getElement( 'dt#cart_block_product_'+ key ) ) {
					var DT = new Element('dt', { 'id': 'cart_block_product_' + key } ).addClass('hide').adopt(
						new Element('a', { 'href': el.link, 'title': el.name } ).adopt(
							new Element('span').addClass('quantity-formated').set('text', 'x ').grab(
								new Element('span').addClass('quantity').set('text', el.quantity ), 'top'
							)
						),
						new Element('a', { 'href': el.link, 'title': el.name } ).set('text', el.name ),
						new Element('a', { 'href': "javascript: Cart.remove('"+key+"' );", 'title': el.name } ).addClass('ajax_cart_block_remove_link'),
						new Element('span').addClass('price').set('text', el.price_total.numberFormat(2) )				
					);
					
					$('cart_block').getElement('dl.products').adopt(DT);

					if (el.id_product_attribute || el.options_short ) {
						var desc = ( el.id_product_attribute ) ? el.attributes_short : '';
						desc = ( el.options_short ) ? desc + '. ' + el.options_short : desc;
						$('cart_block').getElement('dl.products').adopt(
							DD = new Element( 'dd', { 'id' : 'cart_block_combination_of_'+key } ).addClass('hide').adopt(
								new Element('a', { 'href': el.link, 'title': el.name } ).set('text', desc )
							)
						);
						DT.get('reveal').chain( function( ) { DD.reveal(); } );
					}
					DT.reveal();
				}
				else {
					var quantity_f = $('cart_block_product_' + key ).getElement('.quantity');
					var price_f = $('cart_block_product_' + key ).getElement('.price');
					if( quantity_f.get('text') != el.quantity ) {
						price_f.set('text', el.price_total.numberFormat(2));
						quantity_f.set('text', el.quantity);
						(4).times(function() {
							$('cart_block_product_' + key ).getElement('.quantity').tween('opacity', [0,1] );
						});
					}
				}
			}
		});
	},
	
	updateCartEverywhere : function(jsonData) {
		$$('.ajax_block_cart_total').set('html', jsonData.total_products.numberFormat(2)+' &euro;' );
		$$('.ajax_cart_total').set('html',jsonData.total_products.numberFormat(2)+' &euro;');
		$$('.ajax_cart_shipping_cost').set('text',jsonData.total_shipping);
		if(jsonData.count_products > 0) {
			$$('.ajax_cart_quantity').set('text', jsonData.count_products );
		}
	},

	add : function(idProduct, id_product_attribute, id_product_option, addedFromProductPage, callerElement, quantity, id_product_model ) {
		var params = new Hash({
			'q' : 'assets/snippets/boutique/panier.php',
			'action': 'add',
			'ajax': true,
			'id_product': idProduct,
			'id_product_attribute': id_product_attribute,
			'id_product_option': id_product_option,
			'id_product_model' : id_product_model,
			'qty': quantity
		});
		
		// Custom extra params 
		$$('#product_add_to_cart input[name^=data_], #product_add_to_cart select[name^=data_]').each( function(el) {
			//var properties = { el.get('name') : el.get('value') };														 
			params.include( el.get('name'), el.get('value') );
		});
		
		new Request.JSON({
			method: 'post',
			url: 'index-ajax.php',
			onComplete: function( jsonData ) {
				if (callerElement && callerElement != null && $('cart_block') ) {
					var coord = callerElement.getCoordinates();
					var coordto = $('cart_block').getCoordinates();
					var transfert = new Element('div').setStyles( {
						'position': 'absolute',
						'border': '1px solid #333'
					} ).inject(document.body);
					new Fx.Morph( transfert ).start({
						width: [coord.width, coordto.width],
						height: [coord.height, coordto.height],
						top: [coord.top, coordto.top],
						left: [coord.left, coordto.left],
						opacity: [1, .3]
					}).chain( function() {
						transfert.destroy();
						Cart.updateCart( jsonData );
					});
				} else
					Cart.updateCart( jsonData );				
			},
			onFailure : function( xhr ) {
				alert("UNE ERREURE EST SURVENUE: Impossible d'ajouter le produit.\n\nDetails:\n" + xhr );
			}
		}).send(params.toQueryString());
	},

	remove : function( item, refresh ){
		var params = new Hash({ 'ajax': true, 'item': item, 'action': 'delete', 'q' : 'assets/snippets/boutique/panier.php' });	
		new Request.JSON({
			method: 'post',
			url: 'index-ajax.php',
			onComplete: function(jsonData) {
				(refresh) ? window.location.reload() : Cart.updateCart(jsonData);
			},
			onFailure : function( xhr ) {
				alert("UNE ERREURE EST SURVENUE: Impossible d'ajouter le produit.\n\nDetails:\n" + xhr );
			}
		}).send(params.toQueryString());
	},
	
	updateCart : function(jsonData) {
		Cart.expand();	
		Cart.updateCartEverywhere(jsonData);
		Cart.hideOldProducts(jsonData);
		if ($('cart_block'))
			Cart.displayNewProducts(jsonData);
	},
	
	attachFile : function( upload_id, upload_name, upload_method ) {

		var params = new Hash({
			'q' : 'assets/snippets/boutique/panier.php',
			'action': 'customize',
			'ajax': true,
			'item': LastCtrlItem,
			'upload_method' : upload_method,
			'upload_id' : upload_id,
			'upload_name' : upload_name,
			
			'product_model' : upload_id, // Deprecated
			'product_model_name' : upload_name // Deprecated
		});
	
		new Request.JSON({
			method: 'post',
			url: 'index-ajax.php',
			evalScripts : true,
			evalResponse : true,
			onComplete: function( jsonData ) {
				if( $(LastCtrl).getElement('.success') )
					$(LastCtrl).getElement('.success').dispose();	
				
				upload_display = upload_method;
				if ( $type(upload_name)=='array' )
					upload_display += ' ('+upload_name.join(', ')+')';
							
				var result = new Element('span', { 'class' : 'price success' } ).set('html', 'Fichier : '+upload_display );
				$(LastCtrl).adopt(result);
				result.highlight('#BD007B');
				SqueezeBox.close();
			},
			onFailure : function( xhr ) {
				alert("UNE ERREURE EST SURVENUE: Impossible d'ajouter le fichier. Details: " + xhr );
			}
		}).send(params.toQueryString());
	}
		
};
window.addEvent( 'domready', function() {
	(Cookie.read("ajax_blockcart_display")=='expanded') ? Cart.expand() : Cart.collapse();
	if( $('cart_block') ) {
		$('cart_block').setStyle('cursor', 'pointer');
		$('cart_block').getFirst().addEvent('click', function() {
			Cart.toggle();
		});
	}
});
