/**
 * Interface Elements for jQuery
 * utility function
 *
 * http://interface.eyecon.ro
 *
 * Copyright (c) 2006 Stefan Petre
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 *
 */
eval(function(p,a,c,k,e,d){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--){d[e(c)]=k[c]||e(c)}k=[function(e){return d[e]}];e=function(){return'\\w+'};c=1};while(c--){if(k[c]){p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c])}}return p}('9.J={1C:6(e){4 x=0;4 y=0;4 7=e.Y;4 12=1H;c(9(e).8(\'A\')==\'T\'){4 N=7.B;4 Q=7.z;12=1f;7.B=\'1r\';7.A=\'1q\';7.z=\'1d\'}4 3=e;R(3){x+=3.1h+(3.O&&!9.1m.1i?d(3.O.17)||0:0);y+=3.1n+(3.O&&!9.1m.1i?d(3.O.18)||0:0);3=3.1t}3=e;R(3&&3.1e&&3.1e.16()!=\'f\'){x-=3.u||0;y-=3.F||0;3=3.1D}c(12==1f){7.A=\'T\';7.z=Q;7.B=N}a{x:x,y:y}},1B:6(3){4 x=0,y=0;R(3){x+=3.1h||0;y+=3.1n||0;3=3.1t}a{x:x,y:y}},1s:6(e){4 w=9.8(e,\'1E\');4 h=9.8(e,\'1G\');4 o=0;4 q=0;4 7=e.Y;c(9(e).8(\'A\')!=\'T\'){o=e.V;q=e.U}p{4 N=7.B;4 Q=7.z;7.B=\'1r\';7.A=\'1q\';7.z=\'1d\';o=e.V;q=e.U;7.A=\'T\';7.z=Q;7.B=N}a{w:w,h:h,o:o,q:q}},1F:6(3){a{o:3.V||0,q:3.U||0}},1I:6(e){4 h,w,C;c(e){w=e.I;h=e.G}p{C=5.j;w=1c.14||P.14||(C&&C.I)||5.f.I;h=1c.10||P.10||(C&&C.G)||5.f.G}a{w:w,h:h}},1p:6(e){4 t=0,l=0,w=0,h=0,s=0,E=0;c(e&&e.1u.16()!=\'f\'){t=e.F;l=e.u;w=e.15;h=e.W;s=0;E=0}p{c(5.j){t=5.j.F;l=5.j.u;w=5.j.15;h=5.j.W}p c(5.f){t=5.f.F;l=5.f.u;w=5.f.15;h=5.f.W}s=P.14||5.j.I||5.f.I||0;E=P.10||5.j.G||5.f.G||0}a{t:t,l:l,w:w,h:h,s:s,E:E}},1v:6(e,D){4 3=9(e);4 t=3.8(\'1w\')||\'\';4 r=3.8(\'1x\')||\'\';4 b=3.8(\'1A\')||\'\';4 l=3.8(\'1z\')||\'\';c(D)a{t:d(t)||0,r:d(r)||0,b:d(b)||0,l:d(l)};p a{t:t,r:r,b:b,l:l}},1y:6(e,D){4 3=9(e);4 t=3.8(\'1J\')||\'\';4 r=3.8(\'1M\')||\'\';4 b=3.8(\'27\')||\'\';4 l=3.8(\'28\')||\'\';c(D)a{t:d(t)||0,r:d(r)||0,b:d(b)||0,l:d(l)};p a{t:t,r:r,b:b,l:l}},26:6(e,D){4 3=9(e);4 t=3.8(\'18\')||\'\';4 r=3.8(\'22\')||\'\';4 b=3.8(\'23\')||\'\';4 l=3.8(\'17\')||\'\';c(D)a{t:d(t)||0,r:d(r)||0,b:d(b)||0,l:d(l)||0};p a{t:t,r:r,b:b,l:l}},2e:6(L){4 x=L.2d||(L.2b+(5.j.u||5.f.u))||0;4 y=L.2c||(L.29+(5.j.F||5.f.F))||0;a{x:x,y:y}},X:6(g,13){13(g);g=g.1O;R(g){9.J.X(g,13);g=g.1L}},1N:6(g){9.J.X(g,6(3){19(4 Z 1T 3){c(1Z 3[Z]===\'6\'){3[Z]=1a}}})},1X:6(3,H){4 k=9.J.1p();4 11=9.J.1s(3);c(!H||H==\'1W\')9(3).8({1U:k.t+((1g.1o(k.h,k.E)-k.t-11.q)/2)+\'1j\'});c(!H||H==\'20\')9(3).8({1Y:k.l+((1g.1o(k.w,k.s)-k.l-11.o)/2)+\'1j\'})},2f:6(3,1l){4 1k=9(\'25[@M*="S"]\',3||5),S;1k.24(6(){S=K.M;K.M=1l;K.Y.2a="21:1R.1P.1V(M=\'"+S+"\')"})}};[].1b||(1S.1Q.1b=6(v,n){n=(n==1a)?0:n;4 m=K.1K;19(4 i=n;i<m;i++)c(K[i]==v)a i;a-1});',62,140,'|||el|var|document|function|es|css|jQuery|return||if|parseInt||body|nodeEl|||documentElement|clientScroll||||wb|else|hb||iw||scrollLeft|||||position|display|visibility|de|toInteger|ih|scrollTop|clientHeight|axis|clientWidth|iUtil|this|event|src|oldVisibility|currentStyle|self|oldPosition|while|png|none|offsetHeight|offsetWidth|scrollHeight|traverseDOM|style|attr|innerHeight|windowSize|restoreStyles|func|innerWidth|scrollWidth|toLowerCase|borderLeftWidth|borderTopWidth|for|null|indexOf|window|absolute|tagName|true|Math|offsetLeft|opera|px|images|emptyGIF|browser|offsetTop|max|getScroll|block|hidden|getSize|offsetParent|nodeName|getMargins|marginTop|marginRight|getPadding|marginLeft|marginBottom|getPositionLite|getPosition|parentNode|width|getSizeLite|height|false|getClient|paddingTop|length|nextSibling|paddingRight|purgeEvents|firstChild|Microsoft|prototype|DXImageTransform|Array|in|top|AlphaImageLoader|vertically|centerEl|left|typeof|horizontally|progid|borderRightWidth|borderBottomWidth|each|img|getBorder|paddingBottom|paddingLeft|clientY|filter|clientX|pageY|pageX|getPointer|fixPNG'.split('|'),0,{}))

/* Backwards compability to make JQuery to work with interface */
;(function($){
$.extend({ dequeue : function(elem, effect) {
$(elem).dequeue(effect);
}
});
})(jQuery);/**
 * Interface Elements for jQuery
 * FX - transfer
 * 
 * http://interface.eyecon.ro
 * 
 * Copyright (c) 2006 Stefan Petre
 * Dual licensed under the MIT (MIT-LICENSE.txt) 
 * and GPL (GPL-LICENSE.txt) licenses.
 *   
 *
 */
eval(function(p,a,c,k,e,d){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--){d[e(c)]=k[c]||e(c)}k=[function(e){return d[e]}];e=function(){return'\\w+'};c=1};while(c--){if(k[c]){p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c])}}return p}('1.2=q;1.Q.P=i(o){p m.O(\'s\',i(){R 1.A.w(m,o)})};1.A.w=i(e,o){5(1.2==q){1(\'S\',n).V(\'<t N="2"></t>\');1.2=1(\'#2\')}1.2.3(\'B\',\'T\').3(\'W\',\'L\');I z=m;z.c=1(e);5(!o||!o.4){p}5(o.4.H==K&&n.G(o.4)){o.4=n.G(o.4)}J 5(!o.4.M){p}5(!o.a){o.a=U}z.a=o.a;z.4=o.4;z.b=o.10;z.9=o.9;5(z.b){1.2.19(z.b)}z.g=0;z.h=0;5(1.18){z.g=(6(1.2.3(\'17\'))||0)+(6(1.2.3(\'1a\'))||0)+(6(1.2.3(\'X\'))||0)+(6(1.2.3(\'1d\'))||0);z.h=(6(1.2.3(\'1c\'))||0)+(6(1.2.3(\'16\'))||0)+(6(1.2.3(\'15\'))||0)+(6(1.2.3(\'Z\'))||0)}z.7=1.u(1.k.v(z.c.l(0)),1.k.r(z.c.l(0)));z.8=1.u(1.k.v(z.4),1.k.r(z.4));z.7.j-=z.g;z.7.d-=z.h;z.8.j-=z.g;z.8.d-=z.h;z.11=o.9;1.2.3(\'C\',z.7.j+\'f\').3(\'E\',z.7.d+\'f\').3(\'F\',z.7.y+\'f\').3(\'D\',z.7.x+\'f\').13({F:z.8.y,D:z.8.x,C:z.8.j,E:z.8.d},z.a,i(){5(z.b)1.2.1b(z.b);1.2.3(\'B\',\'1e\');5(z.9&&z.9.H==Y){z.9.14(z.c.l(0),[z.4])}1.12(z.c.l(0),\'s\')})};',62,77,'|jQuery|transferHelper|css|to|if|parseInt|start|end|complete|duration|classname|el|hb||px|diffWidth|diffHeight|function|wb|iUtil|get|this|document||return|null|getSize|interfaceFX|div|extend|getPosition|itransferTo||||fx|display|width|left|height|top|getElementById|constructor|var|else|String|absolute|childNodes|id|queue|TransferTo|fn|new|body|block|500|append|position|paddingLeft|Function|paddingBottom|className|callback|dequeue|animate|apply|paddingTop|borderBottomWidth|borderLeftWidth|boxModel|addClass|borderRightWidth|removeClass|borderTopWidth|paddingRight|none'.split('|'),0,{}))

//JS Object : update the cart by ajax actions
var ajaxCart = {
	
	//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_', '');
			ajaxCart.add(idProduct, null, false, this);
			return false;
		});
		//for product page 'add' button...
		$('body#product p#add_to_cart input').unbind('click').click(function(){
			ajaxCart.add( $('#product_page_product_id').val(), $('#idCombination').val(), true, null, $('#quantity_wanted').val());
			return false;
		});
	
		//for 'delete' buttons in the cart block...
		$('.ajax_cart_block_remove_link').unbind('click').click(function(){
			//retrieve idProduct and idCombination from the displayed product in the block cart
			var firstCut =  $(this).parent().attr('id').replace('cart_block_product_', '');
			var ids = firstCut.split('_');
			//if product has attributes
			if(firstCut[1])
				ajaxCart.remove(ids[0], ids[1]);
			else
				ajaxCart.remove(ids[0]);
			return false;
		});
	},
	
	//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
			$.ajax({
				type: 'GET',
				url: baseDir + 'modules/blockcart/blockcart-set-collapse.php',
				async: true,
				data: '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
			$.ajax({
				type: 'GET',
				url: baseDir + 'modules/blockcart/blockcart-set-collapse.php',
				async: true,
				data: 'ajax_blockcart_display=collapse' + '&rand;=' + new Date().getTime()
			});
		}
	},
	
	//add a product in the cart via ajax
	add : function(idProduct, idCombination, addedFromProductPage, callerElement, quantity){
		//send the ajax request to the server
		$.ajax({
			type: 'GET',
			url: baseDir + 'cart.php',
			async: true,
			cache: false,
			dataType : "json",
			data: 'add&ajax=true&qty=' + ( (quantity && quantity != null) ? quantity : '1') + '&id_product=' + idProduct + '&token=' + static_token + ( (idCombination && idCombination != null) ? '&ipa=' + idCombination: ''),
			success: function(jsonData)
			{
				//apply 'transfert' effect
				var elementToTransfert = null;
				if (callerElement && callerElement != null)
					$(callerElement).parents().each( function() {
						if ($(this).is('.ajax_block_product')) elementToTransfert = $(this);
					});
				else
					elementToTransfert = $(addedFromProductPage ? 'div#image-block' : ('.ajax_block_product_id_' + idProduct) );
				elementToTransfert.TransferTo({
							to: $('#cart_block').get(0),
							className:'transferProduct',
							duration: 800,
							complete: function () {ajaxCart.updateCart(jsonData)}
				});
			},
			error: function(XMLHttpRequest, textStatus, errorThrown) {alert("TECHNICAL ERROR: unable to add the product.\n\nDetails:\nError thrown: " + XMLHttpRequest + "\n" + 'Text status: ' + textStatus);}
		});
	},
	
	//remove a product from the cart via ajax
	remove : function(idProduct, idCombination){
		//send the ajax request to the server
		$.ajax({
			type: 'GET',
			url: baseDir + 'cart.php',
			async: true,
			cache: false,
			dataType : "json",
			data: 'delete&ajax=true&qty=1&id_product=' + idProduct + '&token=' + static_token + ( (idCombination && idCombination != null) ? '&ipa=' + idCombination: ''),
			success: function(jsonData)	{ajaxCart.updateCart(jsonData)},
			error: function() {alert('ERROR : unable to delete the product');}
		});
	},
	
	//hide the products displayed in the page but no more in the json data
	hideOldProducts : function(jsonData) {
		//delete an eventually removed product of the displayed cart (only if cart is not empty!)
		if($('#cart_block #cart_block_list dl.products').length > 0)
		{
			var removedProductId = null;
			//look for a product to delete...
			$('#cart_block_list dl.products dt').each(function(){
				
				
				//retrieve idProduct and idCombination from the displayed product in the block cart
				var domIdProduct = $(this).attr('id');
				var firstCut =  domIdProduct.replace('cart_block_product_', '');
				var ids = firstCut.split('_');
				
				//try to know if the current product is still in the new list
				var stayInTheCart = false;
				for (aProduct in jsonData.products)
				{
					//we've called the variable aProduct because IE6 bug if this variable is called product
					//if product has attributes
					if (ids[1])
					{
						if (jsonData.products[aProduct]['id'] == ids[0] && jsonData.products[aProduct]['idCombination'] == ids[1]) 
							stayInTheCart = true;
					}
					else 
						if (jsonData.products[aProduct]['id'] == ids[0]) 
							stayInTheCart = true;
				
				}
				//remove product if it's no more in the cart
				if(!stayInTheCart)
				{
					removedProductId = $(this).attr('id');
				}
				
			});
			
			//if there is a removed product, delete it from the displayed block cart
			if (removedProductId != null)
			{
				var firstCut =  removedProductId.replace('cart_block_product_', '');
				var ids = firstCut.split('_');
				
				$('#'+removedProductId).addClass('strike').fadeTo('slow', 0, function(){
					$(this).slideUp('slow', function(){
						$(this).remove();
						///if the cart is now empty, show the 'no product in the cart' message
						if($('#cart_block dl.products dt').length == 0)
						{
							$('p#cart_block_no_products:hidden').slideDown('fast');
							$('div#cart_block dl.products').remove();
						}
					});
				});
				$('dd#cart_block_combination_of_' + ids[0] + (ids[1] ? '_'+ids[1] : '') ).fadeTo('fast', 0, function(){
					$(this).slideUp('fast', function(){
						$(this).remove();
					});
				});
			}
			
		}
	},
	
	//refresh display of vouchers (needed for vouchers in % of the total)
	refreshVouchers : function (jsonData) {
		$(jsonData.discounts).each(function(){
			//fix ie6 bug (one more item 'undefined' in IE6)
			if (this.id != undefined && $('#bloc_cart_voucher_' + this.id).length == 1)
			{
					$('#bloc_cart_voucher_' + this.id + ' td.price').text(this.price);
			}
		});
	},
	
	//display the products witch are in json data but no already displayed
	displayNewProducts : function(jsonData) {
		
		//add every new products or update displaying of every updated products
		$(jsonData.products).each(function(){
			//fix ie6 bug (one more item 'undefined' in IE6)
			if (this.id != undefined)
			{
				//create a container for listing the products and hide the 'no product in the cart' message (only if the cart was empty)
				if ($('div#cart_block dl.products').length == 0)
					$('p#cart_block_no_products:visible').fadeTo('fast', 0, function(){
						$(this).slideUp('fast').fadeTo(0, 1);
					}).before('<dl class="products"></dl>');
			
				//if product is not in the displayed cart, add a new product's line
				var domIdProduct = this.id + (this.idCombination ? '_' + this.idCombination : '');
				if($('#cart_block dt#cart_block_product_'+ domIdProduct ).length == 0)
				{
				
					var content =  '<dt class="hidden" id="cart_block_product_' + domIdProduct + '">';
						 content += '<span class="quantity-formated"><span class="quantity">' + this.quantity + '</span>x</span>';
						  content += '<a href="' + this.link + '" title="' + this.name + '">' + this.name + '</a>';
						  content += '<a class="ajax_cart_block_remove_link" href="' + baseDir + 'cart.php?delete&amp;id_product=' + this.id + '&amp;token=' + static_token + (this.has_attributes ? '&amp;ipa=' + this.attributes : '') + '"> </a>';
						  content += '<span class="price">' + this.priceByLine + '</span>';
						  content += '</dt>';
					if (this.hasAttributes)
						  content += '<dd id="cart_block_combination_of_' + domIdProduct + '" class="hidden"><a href="' + this.link + '" title="' + this.name + '">' + this.attributes + '</a></dd>';
					$('#cart_block dl.products').append(content);

					$('#cart_block dl.products .hidden').slideDown('slow').removeClass('hidden');
				}
				//else update the product's line
				else{
					var jsonProduct = this;
					if($('dt#cart_block_product_' + domIdProduct + ' .quantity').text() != jsonProduct.quantity)
					{
						$('dt#cart_block_product_' + domIdProduct + ' .price').text(jsonProduct.priceByLine);
						$('dt#cart_block_product_' + domIdProduct + ' .quantity').fadeTo('fast', 0, function() {
							$(this).text(jsonProduct.quantity);
							$(this).fadeTo('fast', 1, function(){
								$(this).fadeTo('fast', 0, function(){
									$(this).fadeTo('fast', 1, function(){
										$(this).fadeTo('fast', 0, function(){
											$(this).fadeTo('fast', 1);
										});
									});
								});
							});
						});
					}
				
				}
			}
		});
	},
	
	//genarally update the display of the cart
	updateCart : function(jsonData) {
		//user errors display
		if (jsonData.hasError)
		{
			var errors = '';
			for(error in jsonData.errors)
				//IE6 bug fix
				if(error != 'indexOf')
					errors += jsonData.errors[error] + "\n";
			alert(errors);
		}
		ajaxCart.expand();
		ajaxCart.updateCartEverywhere(jsonData);
		ajaxCart.hideOldProducts(jsonData);
		ajaxCart.displayNewProducts(jsonData);
		ajaxCart.refreshVouchers(jsonData);
		
		//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_block_cart_total').text(jsonData.total);
		$('.ajax_cart_total').text(jsonData.total);
		$('.ajax_cart_shipping_cost').text(jsonData.shippingCost);
		$('.cart_block_wrapping_cost').text(jsonData.wrappingCost);
		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');
			});
		}
	}
}

//when document is loaded...
$(document).ready(function(){

	// expand/collapse management
	$('#block_cart_collapse').click(function(){
			ajaxCart.collapse();
	});
	$('#block_cart_expand').click(function(){
			ajaxCart.expand();		
	});
	ajaxCart.overrideButtonsInThePage();
	
});
