var shop = {
	
	init:function(){
		// begin change quantity				
				$(".addQuantity").click(function(){
					shop.addQuantity($(this));	
				});
				$(".deleteQuantity").click(function(){
					shop.deleteQuantity($(this));	
				});
		// end change quantity	
	
		// begin change quantity by input field	 
			if ($('#checkStock').val() == 1 ) {
				$(".inputQuantity").blur(function(){
					var elmt = $(this);
					var id = elmt.attr("id");
					var value = elmt.val();
					
					$(document).ready(function(){ shop.checkStockOnChange(id,value)});
				});
			}
		// end change quantity by input field	 
		
		// begin addCartForm validation if necessary
			$('.shop-addFormToCart').each(function(){
				var formId = $(this).attr('id');				
				var addCartWithLightBox;
				addCartWithLightBox = $('#' + formId + ' input[name=addCartWithLightBox]').val();
				if (addCartWithLightBox == '1'){
					shop.initSubmitFormWithLightBox(formId);
				}			
			});
		// end addCartForm validation
	
		}, // end init
		
		initSubmitFormWithLightBox:function(formId)
		{
			$('#' + formId).submit( function() {
					// 1 - get products's info (tab(id => quantity) )				
					var products = new Array();
					var nbProducts = 0;
					var param = '';
					$('#' + formId + ' .inputQuantity').each(function(){
						var elmt = $(this);
						var id = elmt.attr('id');
						var productId = id.split('[');
						productId = productId[1].split(']');
						productId = productId[0];
						var qtite = elmt.val();
						products[productId] = qtite;
						
						if(qtite >= 1){
							param = param + '&products[' + productId + ']=' + qtite;
							nbProducts = nbProducts + parseInt(qtite);
						}
						
					});
					
					// 1.1 - get product MAD (e.g.: boutiquedubois)
					// must have parameters MAD and categoryId 
					if ($('input[name^=MAD]').length > 0){
						// get categoryId
						var categoryId = $('#categoryId').val();
						param += '&categoryId=' + categoryId;
						// get products MAD infos (selects)
						$('select[name^=MAD]').each(function(){// each select begin with 'MAD'
							var elmt = $(this);
							var id = elmt.attr('name');
							var value = elmt.val();
							param += '&' + id + '=' + value;
						});
						// get products MAD infos (inputs)
						$('input[name^=MAD]').each(function(){// each input begin with 'MAD'
							var elmt = $(this);
							var id = elmt.attr('name');
							var value = elmt.val();
							var type = elmt.attr('type');
								
							// case radio, to avoid to send last radio. Send only checked radio
							if (type == 'radio' && elmt.attr('checked') == false){			
									return true;				
							}
							
							// case checkbox, to avoid to send checkbox even if not checked. Send only checked checkbox
							if (type == 'checkbox' && elmt.attr('checked') == false){			
									return true;				
							}
							
							param += '&' + id + '=' + value;
						});						
					} // end products MAD
					
					// 2 - show lightbox
					shop.createAddCartLightBox(formId);
					
					// 3 - get cartPage
					var cartpage = '';
					cartPage = $('#' + formId + ' input[name=page]').val();
					
					// 4 - add to cart
					$.ajax({
					   type: 'POST',
						url: '/index.php?page=' + cartPage,
						data : 'action=addItem' + param,   
						   
						/*error: function(XMLHttpRequestObject, errorString, exceptionObject){
							// update id addCartFrameLightBox for inform user that add to cart has failed
							$('#addCartFrameLightBox').empty();
							$('#addCartFrameLightBox').append('<span id="addCartWithLightBoxErrorMsg">Une erreur est survenue. Le ou les produits n\'ont pu être ajoutés au panier.</span>');	
					   },*/
						success: function(data){
							// update nbProducts displayed
								shop.updateNbProductsInCartDisplayed(nbProducts);
						}
					 });
					
					// return false for cancel form validation
					return false;
				 } );
		
		}, // end initSubmitFormWithLightBox
		
		// update nbProducts displayed in cartButton , eg. : Mon panier (5)
		updateNbProductsInCartDisplayed:function (nbProducts)
		{
			var oldNbProducts = $('#nbProductsInCart').html();
			var newNbProducts = parseInt(oldNbProducts) + parseInt(nbProducts);
			$('#nbProductsInCart').empty();
			$('#nbProductsInCart').append(newNbProducts);
		},
		
		// display a frame on a transparent black background, frame contains information for user
		createAddCartLightBox:function (formId)
		{
			$('div').remove('#addCartBackgroundLightBox');
			$('div').remove('#addCartFrameLightBox');
			// background black transparent
			$('body').append($('<div id="addCartBackgroundLightBox"></div>'));
			$('#addCartBackgroundLightBox').click(function(){
				$(this).css({display : "none" });
				$('#addCartFrameLightBox').css({display : "none" });
			});
			$('#addCartFrameLightBox').click(function(){
				$(this).css({display : "none" });
				$('#addCartBackgroundLightBox').css({display : "none" });
			});
						
			// get frame 
			var frameHTML = $.ajax({
					   type: 'POST',
						url: '/index.php?page=shop/addCartAjax',
					   data : 'action=getLightBoxHTML',
					   dataType: 'json',
					   async: false				   
					 }).responseText;
			// frame is moved by scroll	vertical	 			
			var scrollY = (document.documentElement && document.documentElement.scrollTop) || window.pageYOffset || self.pageYOffset || document.body.scrollTop;
			var boxLeft = (($(window).width())/2-200);
			var boxTop = (($(window).height())/2-100);

			frameHTML = '<div id="addCartFrameLightBox" style="margin-top:' + scrollY + 'px; left:' + boxLeft + 'px;top:' + boxTop + 'px;">' + frameHTML + '</div>';	
			$('body').append(frameHTML);
			$("#addCartFrameLightBox a").corner();
			
			
		}, // end createAddCartLightBox		
		
			// add a quantity
			addQuantity:function (p)
			{
				var productId = (p.attr("id")).split("-");
				var stockOk = true;
				// vérification du stock
				if ($('#checkStock').val() == 1 ) {
					stockOk = shop.checkStock(productId[1], parseInt($('#products\\[' + productId[1] + '\\]').val()) + 1);
				}
				
				if(stockOk){
					var newValue = parseInt($('#products\\[' + productId[1] + '\\]').val()) + 1;
					var elmt = $('#shop-cartFooterInput');					
					
					$('#products\\[' + productId[1] + '\\]').val(newValue);
				}else{
					alert('Le nombre de ce produit en stock est de ' + $('#productsInStock\\[' + productId[1] + '\\]').val() + '. Vous ne pouvez en commander plus.');
				}
			},

			// check stock
			//return boolean : true if product is in stock with quantity asked else false
			 checkStock:function(productId, quantityAsked)
			{
				if ( quantityAsked > $('#productsInStock\\[' + productId + '\\]').val()){
					return false;
				}
				return true;
			},

			// step before use function checkStock when user set quantity in the input field 
			checkStockOnChange:function (inputQId,inputQValue)
			{
				varTmp = inputQId.split('[');
				productId = varTmp[1].split(']');
				productId = productId[0];
				stockOk = shop.checkStock(productId, parseInt(inputQValue));
				if (stockOk == false){
					alert('Le nombre de ce produit en stock est de ' + $('#productsInStock\\[' + productId + '\\]').val() + '. Vous ne pouvez en commander plus.');				
					$('#products\\[' + productId + '\\]').val($('#productsInStock\\[' + productId + '\\]').val());
				}
			},

			//delete a quantity
			deleteQuantity:function (p)
			{
				var productId = (p.attr("id")).split("-");
				if ($('#products\\[' + productId[1] + '\\]').val() > 0){
					var oldValue = parseInt($('#products\\[' + productId[1] + '\\]').val()) - 1;
					$('#products\\[' + productId[1] + '\\]').val(oldValue);	
				}
			}
			
}

var shopCart = {
	init:function(){
		// begin form validation
			// return boolean
			$("#checkout-cartForm").submit( function() {
				var returnValue = true;
				// cgv validation
				var cgvAccepted = $("#checkout-cgvCheckBox").attr('checked');
				if (cgvAccepted == false){
					returnValue = false;// validation stoppée
					alert('Veuillez confirmer avoir pris connaissance des conditions générales de vente.');
					$('#checkout-cgvCheckBoxContainer').fadeTo("slow", '0.1');
					$('#checkout-cgvCheckBoxContainer').fadeTo("slow", '1');
					$('#checkout-cgvCheckBoxContainer').css({border : "1px solid red", background : "#FFE500"});
				}

				return returnValue;
			 } );
		// end form validation	
		}
}

//Event.observe(window, 'load', shop.init, false);// prototype
$(document).ready(function(){ shop.init()});// jquery
$(document).ready(function(){ shopCart.init()});

