$(document).ready(function() {
	// Au chargement de la page on appele le Webservice Action Marketing
	callWS();

	// En cas de saisie d'un code avantage ou code chèque
	$(".btvalidavantage").click(function() {
		checkCodeAvantage($('#codeAvantage').val());
		return false;
	});
	
});

// Controle un code avantage ou code cheque fidélité
// Si Valide, on l'ajoute au panier
function checkCodeAvantage(codeAvantage) {
	
	$.ajax({
		   type: "GET",
		   data: PARAMGLOBAL + "&codeAvantage=" + codeAvantage,
		   cache: false,
		   url: PATHRACINE+"/CodeAvantage",
		   success: function(data) {
				if($.trim(data) == null || $.trim(data) == ""){
					// Si il n'y a pas eu d'erreur, on appel le Webservice Action marketing pour appliquer le code avantage / code chèque
					callWS();
					// On vide le champs code avantage
					$('#codeAvantage').val('');
				} else {
					// Sinon affichage du message d'erreur
					Box.open({
						modal: true,
						url: PATHRACINE+"/CodeAvantageError",
						urldata: PARAMGLOBAL + "&error=" + data,
						show: function() {
							$(".errorSearchMag_fermer").click(function(){ Box._close(); return false; });
							$(".errorCodeAvantageOk").click(function(){ Box._close(); return false; });			
						}
					});
				}
			}
		});	

	return false;
}

// Fonction d'appel du WS Action Marketing
function callWS() {
	openWaitBox();
	
	$.ajax({
		type: "GET",
		data: PARAMGLOBAL,
		url: "AjaxCallAM",
		cache: false
	});	
	
	launchTimer('AjaxCheckRemiseCart', 'true');
}

var flag= false
var Panier = {
	
	/*
	 * Gestion des lignes paniers
	 */
	Line: {
	
		// Suppression de toutes les lignes du panier
		removeAll : function() {
			// Suppression des lignes Sku
			$("tr[id^=panierligne]").fadeOut("slow", function() { $(this).remove(); });

			// Suppression des lignes model
			$("tr[id^=model]").fadeOut("slow", function() { $(this).remove(); });

			// Suppression des lignes model composant
			$("tr[id^=panierligne_model_]").fadeOut("slow", function() { $(this).remove(); });
		},
	
		Sku: {
			// suppression d'une ligne du panier
			removeLine: function(id, lineId) {
				if (confirm($.i18n._('msgRemoveLine'))) {
					$.ajax({
					   type: "POST",
					   data: PARAMGLOBAL + "&skuId=" + id + "&action=remove&lineId=" + lineId,
					   cache: false,
					   url: PATHRACINE+"/ActionPanierSku",
					   success: function(data) {
							eval(data);
							callWS();
						}
					});
				}
				
				return false;
			},
			
			/*
			 * Gestion de la quantité pour une ligne sku
			 */
			updateQteSku: function(skuId, stock) {
				// Affichage
				setQte(stock, $('#quantite' + skuId));
				// BDD
				this.updateQteSkuAjax(skuId, $('#quantite' + skuId).val());
			},
			
			incrementeQteSku: function(skuId, stock) {
				//flag = variable global pour evité 2 appel du WS et ainsi eviter d'avoir des prix negatif 
				if ( flag == false){
				// Affichage
				incremente($('#quantite' + skuId), stock);
				// BDD
				this.updateQteSkuAjax(skuId, $('#quantite' + skuId).val());
				}
			},
			
			decrementeQteSku: function(skuId) {
				//flag = variable global pour evité 2 appel du WS et ainsi eviter d'avoir des prix negatif 
				if ( flag == false){
				// Affichage
				decremente($('#quantite' + skuId));
				// BDD
				this.updateQteSkuAjax(skuId, $('#quantite' + skuId).val());
				}
			},
			
			updateQteSkuAjax: function(skuId, qte) {
				flag= true;
				$('#encartError').html("");
				
				$.ajax({
				   type: "POST",
				   data: PARAMGLOBAL + "&skuId=" + skuId + "&qte=" + qte + "&action=update",
				   cache: false,
				   url: PATHRACINE + "/ActionPanierSku",
				   success: function(data) {
						eval(data);
						flag= false;
						callWS();
				   },
				   error: function() {
					   $('#encartError').html($.i18n._('msgErreurMajQuantite'));
				   }
					
				});
		
				return false;
			}
		},
		
		Modele: {
			// suppression d'une ligne modèle
			removeLineModele: function(idModele, idModeleSku, idCompSku, lineId) {
				if (confirm($.i18n._('msgRemoveLine'))) {
					$.ajax({
					   type: "POST",
					   data: PARAMGLOBAL+"&idModele="+idModele+"&idModeleSku="+ idModeleSku +"&ModelComposantskuId="+idCompSku+"&action=remove&lineId="+lineId,
					   cache: false,
					   url: PATHRACINE+"/ActionPanierModel",
					   success: function(data) {
							eval(data);
							callWS();
						}
					});
				}
		
				return false;
			},
			
			/*
			 * Gestion de la quantité pour une ligne de modèle
			 */
			updateQteModel: function(modelId, modelSkuId, compSkuId, stock) {
				// Affichage
				setQte(stock, $('#quantite_model_' + modelSkuId + '_' + compSkuId));
				// BDD
				this.updateQteModelAjax(modelId, modelSkuId, compSkuId, $('#quantite_model_' + modelSkuId + '_' + compSkuId).val());
			},
			
			incrementeQteModel: function(modelId, modelSkuId, compSkuId, stock) {
				// Affichage
				incremente($('#quantite_model_' + modelSkuId + '_' + compSkuId), stock);
				// BDD
				this.updateQteModelAjax(modelId, modelSkuId, compSkuId, $('#quantite_model_' + modelSkuId + '_' + compSkuId).val());
			},
			
			decrementeQteModel: function(modelId, modelSkuId, compSkuId) {
				// Affichage
				decremente($('#quantite_model_' + modelSkuId + '_' + compSkuId));
				// BDD
				this.updateQteModelAjax(modelId, modelSkuId, compSkuId, $('#quantite_model_' + modelSkuId + '_' + compSkuId).val());
			},
			
			updateQteModelAjax: function(modelId, modelSkuId, compSkuId, qte) {
				$('#encartError').html("");
				
				$.ajax({
				   type: "POST",
				   data: PARAMGLOBAL + "&idModele="+modelId+"&idModeleSku="+ modelSkuId +"&ModelComposantskuId="+compSkuId+ "&qte=" + qte + "&action=update",
				   cache: false,
				   url: PATHRACINE + "/ActionPanierModel",
				   success: function(data) {
						eval(data);
						
						callWS();
				   },
				   error: function() {
					   $('#encartError').html($.i18n._('msgErreurMajQuantite'));
				   }
					
				});
		
				return false;
			},
			
			/*
			 * Un catalogue appartenant a un modèle
			 */
			Catalogue: {
				htmlCatalogue: "",
				htmlDiscriminant: "",
				ajaxUrl: "AddCatalogueToModel",
				
				open: function(idModele, idModeleSku) {
					param = "idModele=" + idModele + "&idModeleSku=" + idModeleSku; 
					$.getScript(this.ajaxUrl +"?"+ PARAMGLOBAL +"&"+ param);
				},
				
				addDebutCatalogue: function(modelSkuId, catalogueSkuId, img, intitule, refBiz, linkFP) {
					htmlCatalogue = "";
					htmlDiscriminant = "";
					
					htmlCatalogue += '<tr class="gris" id="panierligne_model_' + modelSkuId + '_' + catalogueSkuId +'">';
						htmlCatalogue += '<td class="col_1_1"><a href="' + linkFP + '"><img src="' + PATHIMAGES + '/' + img + '" width="48" height="66" border="0" alt="' + intitule + '"></a></td>';	
						htmlCatalogue += '<td class="col_1_2"><b><a href="' + linkFP + '">' + intitule + '</a></b><br>ref.' + refBiz + '</td>';
						htmlCatalogue += '<td class="sep"><div>&nbsp;</div></td>';
				},
				
				addDiscriminant: function(discriminant) {
					htmlDiscriminant += discriminant;
				},
				
				addFinCatalogue: function(modelId, modelSkuId, catalogueSkuId, lineId, totalLine, prix, prixBarre, stock, decote) {
						if (htmlDiscriminant == "") {
							htmlCatalogue += "<td class='col_2'>&nbsp;</td>";
						} else {
							htmlCatalogue += "<td class='col_2'>" + htmlDiscriminant + "</td>";
						}
						
						htmlCatalogue += "<td class='sep'><div>&nbsp;</div></td>";
						htmlCatalogue += "<td class='col_3'>";
						
						if(decote != null && decote != ''){
							htmlCatalogue += "<img class='sticker' src='" + PATHRES + "/img/00-commun/sticker-reduc-" + decote + ".gif'>";
						}
						
						htmlCatalogue += "<div class='prix'>"+prix+" &euro;</div>";
						
						if (prixBarre != null) {
							htmlCatalogue += "<div class='prixbarre'>"+prixBarre+"</div>";
						}
						
						htmlCatalogue += '</td>';
						htmlCatalogue += '<td class="sep"><div>&nbsp;</div></td>';
						htmlCatalogue += '<td class="col_4">';
							htmlCatalogue += '<input type="text" id="quantite_model_'+modelSkuId+'_'+ catalogueSkuId +'" value="1" class="petit" style="float:left;" onblur="Panier.Line.Modele.updateQteModel(\''+ modelId +'\', \''+ modelSkuId +'\', \''+ catalogueSkuId +'\', \''+ stock +'\');">';
							htmlCatalogue += '<div class="quantiteimgs">';
								htmlCatalogue += '<a href="#" title="'+$.i18n._('titleIncremente')+'" onclick="Panier.Line.Modele.incrementeQteModel(\''+ modelId +'\', \''+ modelSkuId +'\', \''+ catalogueSkuId +'\', \''+ stock +'\');"><img src="' + PATHRES + '/img/00-commun/incremente.gif" width="19" height="10" border="0" alt=""></a>';
								htmlCatalogue += '<a href="#" title="'+$.i18n._('titleDecremente')+'" onclick="Panier.Line.Modele.decrementeQteModel(\''+ modelId +'\', \''+ modelSkuId +'\', \''+ catalogueSkuId +'\', \''+ stock +'\');"><img src="' + PATHRES + '/img/00-commun/decremente.gif" width="19" height="11" border="0" alt=""></a>';
							htmlCatalogue += '</div>';
						htmlCatalogue += '</td>';
						htmlCatalogue += '<td class="sep"><div>&nbsp;</div></td>';
						htmlCatalogue += "<td class='col_5' id='remise" + lineId + "'>&nbsp;</td>";
						htmlCatalogue += "<td class='sep'><div>&nbsp;</div></td>";
						htmlCatalogue += '<td class="col_6" id="totalLine' + lineId + '">' + totalLine + '&euro;</td>';
						htmlCatalogue += '<td class="sep"><div>&nbsp;</div></td>';
						htmlCatalogue += '<td class="col_7">';
							htmlCatalogue += '<a href="#" title="'+$.i18n._('titleSupprimer')+'" onclick="Panier.Line.Modele.Catalogue.removeCatalogue(\''+ modelId +'\', \''+ modelSkuId +'\', \''+ catalogueSkuId +'\', \'' + lineId + '\');">';
								htmlCatalogue += '<img class="btsuppr" id="bt_5" src="' + PATHRES + '/img/00-commun/croix.gif" alt="" border="0">';
							htmlCatalogue += '</a>';
						htmlCatalogue += '</td>';		
					htmlCatalogue += '</tr>';

					// Insertion après la dernière ligne de ce modèle
					$('tr[id^=panierligne_model_' + modelSkuId + '_]:last').after(htmlCatalogue);
					
					// Suppression du lien 'Je commande le catalogue avec les explications tricot'
					$('#linkCmdCat' + modelSkuId).html("&nbsp;");
					$('#catalogueExplNok' + modelSkuId).hide();
					
					// Appel du WS action marketing
					callWS();
				},

				removeCatalogue: function(idModele, idModeleSku, idCompSku, lineId) {
					if (confirm($.i18n._('msgRemoveLine'))) {
						$.ajax({
							   type: "POST",
							   data: PARAMGLOBAL+"&idModele="+idModele+"&idModeleSku="+ idModeleSku +"&ModelComposantskuId="+idCompSku+"&action=remove&catalogue=true&lineId="+lineId,
							   cache: false,
							   url: PATHRACINE+"/ActionPanierModel",
							   success: function(data) {
									eval(data);
									callWS();
								}
						});

						// Ajout du lien d'ajout du catalogue au model
						$('#linkCmdCat' + idModeleSku).html('<a href="#" class="catalogue" onclick="Panier.Line.Modele.Catalogue.open(\''+idModele+'\', \''+idModeleSku+'\')">'+$.i18n._('explicationTricot')+'</a>');
						$('#catalogueExplNok' + idModeleSku).show();
					}

					return false;
				}
			}
		},
	
		/*
		 * Gestion des cadeaux
		 */
		Cadeau: {
			countCadeau: 0,
			htmlCadeau: "",
			htmlDiscriminant: "",
			
			removeCadeaux: function(){
				countCadeau = 0;
				$("#tabPanier .cadeauLine").remove();
			},
			
			addDebutCadeau: function(img, intitule, refBiz, linkFP) {
				htmlCadeau = "";
				htmlDiscriminant = "";
				
				htmlCadeau += "<tr class='rose cadeauLine' id='cadeauLine" + countCadeau + "'>";
				htmlCadeau += "<td class='col_1_1'><a href='" + linkFP + "'><img src='" + PATHIMAGES + "/" + img + "' width='48' height='66' border='0' alt='" + intitule + "'></a></td>";	
				htmlCadeau += "<td class='col_1_2'><b><a href='" + linkFP + "'>" + intitule + "</a></b><br>ref." + refBiz + "</td>";
				htmlCadeau += "<td class='sep'><div>&nbsp;</div></td>";
			},
			
			addDiscriminant: function(discriminant) {
				htmlDiscriminant += discriminant;
			},
			
			addFinCadeau: function(skuId) {
				if (htmlDiscriminant == "") {
					htmlCadeau += "<td class='col_2'>&nbsp;</td>";
				} else {
					htmlCadeau += "<td class='col_2'>" + htmlDiscriminant + "</td>";
				}
				
				htmlCadeau += "<td class='sep'><div>&nbsp;</div></td>";
				htmlCadeau += "<td class='col_3'>&nbsp;</td>";
				htmlCadeau += "<td class='sep'><div>&nbsp;</div></td>";
				htmlCadeau += "<td class='col_4'>1</td>";
				htmlCadeau += "<td class='sep'><div>&nbsp;</div></td>";
				htmlCadeau += "<td class='col_5'>&nbsp;</td>";
				htmlCadeau += "<td class='sep'><div>&nbsp;</div></td>";
				htmlCadeau += "<td class='col_6'>CADEAU</td>";
				htmlCadeau += "<td class='sep'><div>&nbsp;</div></td>";
				htmlCadeau += "<td class='col_7'><a href='#' title='"+$.i18n._('titleSupprimer')+"' onclick='Panier.Line.removeLineGift("+ skuId +", "+ countCadeau +");'><img class='btsuppr' id='bt_5' src='" + PATHRES + "/img/00-commun/croix.gif' alt='' border='0'></a></td>";		
				htmlCadeau += "</tr>";
				
				countCadeau++;
				
				$("#tabPanier").append(htmlCadeau);
			},
			
			// suppression d'une ligne cadeau
			removeLineGift: function(id, nbCado) {
				if (confirm($.i18n._('msgRemoveCadeau'))) {
					$.ajax({
					   type: "POST",
					   data: PARAMGLOBAL + "&skuId=" + id + "&action=removeGift&nbCado=" + nbCado,
					   cache: false,
					   url: PATHRACINE+"/ActionPanierSku",
					   success: function(data) {
							eval(data);
					   }
					});
				}
				
				return false;
			}
		}
	},

	/*
	 * Gestion des remises
	 */
	Remise: {
		majRemiseLine: function(lineId, valueRemise) {
			$("#remise" + lineId).html(valueRemise);
		},
		
		majTotalLine: function(lineId, valueLine) {
			$("#totalLine" + lineId).html(valueLine);
		},
		
		majTotalModelLine: function(modelSkuId, valueTotalModelLine) {
			$("#totalModel" + modelSkuId).html(valueTotalModelLine);
		},
		
		majTotalArticle: function(valueTotalArticle) {
			$("#montant").html(valueTotalArticle);
		}
	},
	
	/*
	 * Gestion du bloc avantage (message)
	 */
	Avantage: {
		countMessageAvantage: 0,
		htmlMessageAvantage: "",
		
		clean: function() {
			countMessageAvantage = 0;
			htmlMessageAvantage = "";
			$('#encartMessageAvantage').html(htmlMessageAvantage);
		},
		
		init: function() {
			htmlMessageAvantage += "<img class='titre' src='"+PATHRES+"/img/09-Commande/text-vosavantages.gif' alt='' border='0'><br><br>"
		},
		
		add: function(message) {
			htmlMessageAvantage += "<img src='"+PATHRES+"/img/00-commun/chevron.gif' width='6' height='6' alt='' border='0'> <b>" + message + "</b><br>";
			countMessageAvantage++;
		},

		addWithId: function(id, message) {
			htmlMessageAvantage += "&nbsp;<img src='"+PATHRES+"/img/00-commun/chevron.gif' width='6' height='6' alt='' border='0'> <b>";
			htmlMessageAvantage += message;
			htmlMessageAvantage += "</b>";
			htmlMessageAvantage += "<a style='float:right; margin-right:10px' onclick=Panier.Avantage.removeAdvantage('";
			htmlMessageAvantage += id ;
			htmlMessageAvantage += "'); title='Supprimer' href='#'>";
			htmlMessageAvantage += "<img border='0' alt='Supprimer' src='/VAD/Ressources/fr_FR/img/00-commun/croix.gif'>";
			htmlMessageAvantage += "</a>" ;
			htmlMessageAvantage += "<br>";
			countMessageAvantage++;
		},
		
		removeAdvantage: function(id) {
			$.ajax({
				   type: "POST",
				   data: PARAMGLOBAL + "&opCom=" + id,
				   cache: false,
				   url: PATHRACINE+"/AjaxRemoveCodeAvantage",
				   success: function(data) {
				   }
				});
			callWS();
		},
		
		addError: function(id, message) {
			htmlMessageAvantage += ""
				+ "<div class='filet'></div>"
				+ "<div class='errorDiv'>"
					+ "<div class='image'><img src='"
										+ PATHRES
										+ "/img/09-Commande/Danger-20x20.jpg' width='20' height='20' alt=''>"
					+ "</div>"
					+ "<a style='float:right; margin-right:10px' onclick=Panier.Avantage.removeAdvantage('"
						+ id
						+ "'); title='Supprimer' href='#'>"
						+ "<img border='0' alt='Supprimer' src='/VAD/Ressources/fr_FR/img/00-commun/croix.gif'>"
					+ "</a>"
					+ "<div class='message'>"
						+ message
					+ "</div>"
				+ "</div>";
			countMessageAvantage++;
		},
		
		show: function() {
			if (countMessageAvantage > 0) {
				$('#encartMessageAvantage').html(htmlMessageAvantage);
			}
		}
	},
	
	Error : {
		showError: function(msgKey) {
			$('#encartError').html($.i18n._(msgKey) + "<br><br>");
		}
	},
	
	majRappelPanier : function(nbProduit, prix){
		doMajRappelPanier(nbProduit, prix);
	}
}
