
/**
 * Loops over all forms in document and prepare them for being AJAX submited
 * if they can be. A form can be AJAX submited if it has the css class "ajaxForm".
 * this method is to be invoked when
 *   - document is ready
 *   - ajax is complete
 */
function bindForms() {

  // For each form in document
  $("form").each( function() {
    // gets class attribute of form tag
    var currClass = $(this).attr("class");
    // if class attribute exists
    if(currClass) {
      if( currClass.indexOf("ajaxForm") > -1 ) {

        // removes ajaxForm class for not binding anymore
        $(this).toggleClass("ajaxForm");


        // Inits var callback to false
        var callBack = false;
        if(this.elements["callBack"]) {           // If form has input named callBack
          callBack = this.elements["callBack"].value;
        }

        // retrieves form action
        var formAction = $(this).attr("action");
        if (formAction) {
          // adding parameter ajax=true
          formAction = formAction + ((formAction.indexOf("?") > -1) ? "&" : "?") + "ajax=true";
          // changes form action
          $(this).attr("action", formAction);

          // overriding form submit event
          $(this).submit( function() {
            try {
              var thisForm = $(this);

              toggleFormInput(thisForm, false);

              // submits in AJAX
              var options = {
                  success:    function(xmlReturn) {
                      eval(callBack + "(xmlReturn)" );
                      toggleFormInput(thisForm, true);
                  }
              };

              $(this).ajaxSubmit(options);
            } catch(e) {
              // if error occurs
              writeError("[submit] " + e.description);
            }
            // return false to prevent standard submit
            return false;
          } );
        }
      }
    }
  } );
}

/**
 * Activate/deactivate the submission input.
 */
function toggleFormInput(el, show) {
  /* #1557: only for login form */
  if (el.attr("id") == "loginForm" || el.attr("id") == "contactForm" || el.attr("id") == "newsletterForm") {
    if (show) {
      el.find("input[@type=submit]").removeAttr("disabled");
    } else {
      el.find("input[@type=submit]").attr("disabled", true);
    }
  }
}



/**
 * To keep compatibility with old way
 */
function ajaxFormSubmit(form, callBack) {
  $(form).ajaxSubmit(eval(callBack));
}


/**
 * Login form call back
 */
function callBackLogin(xmlReturn) {
   try {






     var goOn = true;

 	$("#loginError div.modal p").remove();
 	var errors = $("#loginError div.modal").html();
        $("error", xmlReturn).each(function() {
          goOn = false;
          errors = errors + "<p>" + $(this).text() + "</p>" ;
        });
        if(goOn) {
          /* refreshing the menu */
          refreshNav();
          $("redirect", xmlReturn).each(function() {
            loadPageWithHistory($(this).text());
          });
        } else {
          //errors = "<a href='#' class='modal-close' onclick='tb_remove();return false'>" + common_close_link + "</a>" + errors;
          $("#loginError div.modal").html(errors);
          var url = '#TB_inline?height=200&width=250&inlineId=loginError&modal=true';
          tb_show('Error',url);
        }
     } catch(e) {
        writeError("[account-login]" + e.description);
     }
}

/**
 * Login form call back
 */
function callBackReserve(xmlReturn) {

  $("redirect", xmlReturn).each(function() {
    var strRedirect = $(this).text();
    strRedirect = strRedirect + "?DISPLAY=RESERVE";
    $("PRODUCTS", xmlReturn).each(function() {
        strRedirect = strRedirect + "&PRODUCTS="+$(this).text();
      });
    loadPageWithHistory(strRedirect);
  });
}

function callBackSendReserve(xmlReturn) {

  $("redirect", xmlReturn).each(function() {
      loadPageWithoutHistory($(this).text() + "?DISPLAY=SENDRESERVE");
  });
}



/**
 *
 */
function submitServicesForm() {
	ajaxFormSubmit($("#tunnel-save-services"), callBackTunnelServices);
	return false;
}

/**
 * Services call back function
 */
function callBackTunnelServices(xmlReturn) {
  try {
    var goOn = true;

    if ($("refresh", xmlReturn).text().replace(/\n/g,"") == "true") {
      refreshPage();
    }

    $("#errorframe p").remove();
    if (typeof($("address", xmlReturn).attr('code')) == 'undefined') {
      $("error", xmlReturn).each(function() {
        goOn = false;
        $("<p>" + $(this).text() + "</p>").appendTo($("#errorframe div.modal"));
        //on enleve la div qui empeche le double click sur le bouton valider (qui cache le bouton valider)
        $(".avoiddoubleclick").hide()
      });
    }

    if ($("address", xmlReturn).attr('code') == 'notadded') {
      goOn = false;
      $("<p>" + error_creatingAddress + "</p>").appendTo($("#errorframe div.modal"));
    }

    if (goOn) {
      $("redirect", xmlReturn).each(function() {
        currentRel = "align.left shutter.true position.right";
        loadPageWithHistory($(this).text());
      });
      $("input[@name=redirect]").val($("input[@name=redirectForReview]").val());
    } else {
      tb_show('Error', '#TB_inline?height=320&width=300&inlineId=errorframe&modal=true');
    }
  } catch(e) {
    writeError("[shipping-service]" + e.description);
  }
}

function submitCheckSamplesForm() {
  ajaxFormSubmit($("#tunnel-check-samples"), callBackCheckSamplesForm);
  return false;
}

/**
 * Services call back function
 */
function callBackCheckSamplesForm(xmlReturn) {
  try {
	if($("issamples", xmlReturn).text().replace(/\n/g,"") == 0) {
		tb_show('','#TB_inline?height=150&width=235&inlineId=samplesMessage&modal=true');

		$("#TB_ajaxContent .message a").click( function () {
	        $("#TB_ajaxContent").hide();
	        setTimeout('$("#TB_ajaxContent").show();', 1000);
        });

		$("#TB_ajaxContent .message a").each( function () {
	        tb_init($(this));
        });
	} else {
		$("redirect", xmlReturn).each(function() {
		      	currentRel = "align.left shutter.true position.right";
		      	loadPageWithHistory($(this).text());
		});
	}
  } catch(e) {
    writeError("[check-samples]" + e.description);
  }
}



/**
 * Basket call back
 */
function returnFromBasket(xmlReturn) {
      try {
        var str="";
        $("#caddieMessage p").remove();

        $("error", xmlReturn).each(function() {
          $("<p>" + $(this).text() + "</p>").appendTo($("#caddieMessage div.modal"));
        });

        $("message", xmlReturn).each(function() {
          $("<p>" + $(this).text() + "</p>").appendTo($("#caddieMessage div.modal"));
        });

        $("nbItemsInCart", xmlReturn).each(function() {
          updateArticle($(this).text().replace(/\n/g,""));
        });

        loadSmartProfile({sp_id: $("#spStat input[@name=catId]").val(), sp_type: $("#spStat input[@name=catType]").val(), sp_added: $("#spStat input[@name=catId]").val(), sp_quantity: $("#quantity").val()});
        tb_show('', '#TB_inline?height=200&width=300&inlineId=caddieMessage&modal=true');
      } catch(e) {
        writeError("[returnFromBasket]" + e.description);
      }
}
function returnFromBasketAfterAddingSelection(xmlReturn) {
    try {
    	
      var str="";
      $("#SelectioncaddieMessage p").remove();

      $("error", xmlReturn).each(function() {
        $("<p>" + $(this).text() + "</p>").appendTo($("#SelectioncaddieMessage div.modal"));
      });

      $("message", xmlReturn).each(function() {
        $("<p>" + $(this).text() + "</p>").appendTo($("#SelectioncaddieMessage div.modal"));
      });

      $("nbItemsInCart", xmlReturn).each(function() {
        updateArticle($(this).text().replace(/\n/g,""));
      });

      //loadSmartProfile({sp_id: $("#spStat input[@name=catId]").val(), sp_type: $("#spStat input[@name=catType]").val(), sp_added: $("#spStat input[@name=catId]").val(), sp_quantity: $("#quantity").val()});
      tb_show('', '#TB_inline?height=200&width=300&inlineId=SelectioncaddieMessage&modal=true');
      setTimeout("stylePopup()",10); 

    } catch(e) {
      writeError("[returnFromBasket]" + e.description);
    }
}
function stylePopup(){
	  $("#TB_window").css({padding:"20px 0px 15px 15px"});
}
function bindThickbox() {
  //pass where to apply thickbox
  $('a.thickbox, area.thickbox, input.thickbox').each(
    function() {
      if(($(this).attr("href"))) {
        if($(this).attr("href").indexOf("/layout-shutter") < 0 ) {
          var brandPath = appContext + appSite + "/";
          var idx = $(this).attr("href").indexOf(brandPath);
          if( idx >= 0) {
            var newHref = $(this).attr("href").substr(0, idx + brandPath.length - 1);
            newHref += "/layout-shutter" + $(this).attr("href").substr(idx + brandPath.length - 1);
            $(this).attr("href", newHref);
          }
        }
      }
      if ($(this).attr("class").indexOf("TBbinded") == -1) {
        tb_init($(this));
        $(this).toggleClass("TBbinded");
      }
    }
  );
}

/* JS Functions for tunnel-modify-caddie-product */
function resultProductModified(xmlReturn) {
  try {
    var hasErrors=false;
    $("error ", xmlReturn).each(function() {
      alert($(this).text());
      hasErrors = true;
    });
    if (!hasErrors) {
		/* rechargement de la page */
	    refreshPage();
		refreshNav();
		setTimeout("tb_remove()", 200);
    }
  } catch(e) {
    writeError("resultProductModified: " + e.description);
  }
}

/* JS Functions for caddie-list */
function resultProductDeleted(xmlReturn) {
  try {
    var goOn=true;

    $("formId", xmlReturn).each(function() {
      formId = $(this).text().replace(/\n/g,'');
    });

    $("#errorframe p").remove();
    $("error", xmlReturn).each(function() {
      goOn = false;
      $("<p>" + $(this).text() + "</p>").appendTo($("#errorframe div.modal"));
    });

    if (goOn) {
	    refreshNav();
	    refreshPage();
	} else {
		tb_show('Error', '#TB_inline?height=200&width=300&inlineId=errorframe&modal=true');
	}
  } catch(e) {
    writeError("[resultProductDeleted]" + e.description);
  }
}

/**
 *
 */
function submitDeleteProduct(productId) {
  var selected = '';
  var selected_price = 0;
  var newTotalTTC = 0;
  var text = '';
  var selected_price = $('input[@name=discard_price_'+productId+']').val();
  var totalTTC = document.forms.frm_discard_selection.elements['totalTTC'];
  var freeShippingThreshold = document.forms.frm_discard_selection.elements['freeShippingThreshold'];
  var realShippingPrice = document.forms.frm_discard_selection.elements['realShippingPrice'];
  var shippingPrice = document.forms.frm_discard_selection.elements['shippingPrice'];
  var shippingPage = document.forms.frm_discard_selection.elements['shippingPage'];

  newTotalTTC = parseFloat(totalTTC.value) - selected_price;
  if(newTotalTTC < parseFloat(freeShippingThreshold.value)
      && parseFloat(freeShippingThreshold.value) != -1
      && parseFloat(totalTTC.value) > 0
      && parseFloat(shippingPrice.value) == 0) {
    text = "removefromcartfreeshippinglost";
  } else {
    text = "removefromcart";
  }
  //If there is no  product select, displays an alert, otherwise submit the form
    tb_show('', $("#confirmUrl").val() + "?height=160&width=235&text=" + text + "&modal=true&formID=frm_discard_selection&callback=resultProductDeleted");
}

function callBackDisplayVariant(xmlReturn) {
	var packshotContainer = $("input[@name=packshotContainer]").val();
	var imgLoadingContainer = $("input[@name=imgLoadingContainer]").val();
	var descriptionContainer = $("input[@name=descriptionContainer]").val();
	var titleContainer = $("input[@name=titleContainer]").val();
	var priceContainer = $("input[@name=priceContainer]").val();
	var design = $("input[@name=design]").val() || null;
	var priceLine = $("input[@name=priceLine]").val() || null;
	var submitButton = $("input[@name=submitButton]").val() || null;
	var isEcom = $("input[@name=isEcom]").val() || null;
	
	var price = $("price", xmlReturn).text().replace(/\n/g,'');
	var error = $("error", xmlReturn).text().replace(/\n/g,'');

	
	if (price == 'null' && priceLine != null && submitButton != null) {
		$("#" + submitButton).hide();
		$("#" + priceContainer).html($("error", xmlReturn).text());
	} else {
		$("#" + submitButton).show();
		$("#" + priceContainer).html(price);
	}
	if(design != 'amasie'){
		var img = new Image();
		if($("#" + packshotContainer + " img").length){
			var l = $("#" + packshotContainer + " img").width() || $("#" + packshotContainer + " img").attr("width") || "";
			var h = $("#" + packshotContainer + " img").height() || $("#" + packshotContainer + " img").attr("height") || "";
		}
		$("#" + packshotContainer).empty();

		$(img).load(function () {
			$(img).addClass("png-noscale");
			$(img).attr("width",l);
			$(img).attr("height",h);
			$("#" + packshotContainer).append(this);
			$("#" + imgLoadingContainer).fadeOut("fast", function() {
				$("#" + packshotContainer).fadeIn();
			});

		}).attr({
	          src: $("packshot", xmlReturn).text().replace(/\n/g,''),
	          title: $("productTitle", xmlReturn).text().replace(/\n/g,'')+" "+$("productSubTitle", xmlReturn).text().replace(/\n/g,''),
	          alt: $("productTitle", xmlReturn).text().replace(/\n/g,'')+" "+$("productSubTitle", xmlReturn).text().replace(/\n/g,'')
	    }).error(function () {
	      // notify the user that the image could not be loaded
			$("#" + imgLoadingContainer).fadeOut("fast", function() {
				$("#" + packshotContainer).fadeIn();
			});	

			return false;
	    });
		
		
		if(isEcom && error == "error.outofstock")
		{
			$("#postForm").hide();
			$("#outOfStock").show();
			$("#variantSelector").attr("class","priceContainer tableborder");
		}
		else if (isEcom){
			$("#postForm").show();
			$("#outOfStock").hide();
			$("#variantSelector").attr("class","priceContainer tableborder1");
		}
		
	}
    $("input[@name=pcid]").val($("pcid", xmlReturn).text().replace(/\n/g,''));
    $("input[@name=sku]").val($("sku", xmlReturn).text().replace(/\n/g,''));
    $("#" + descriptionContainer).html($("description", xmlReturn).text().replace(/\n/g,''));
    $("#" + titleContainer).text($("title", xmlReturn).text().replace(/\n/g,''));
    // re-initialiser le scroll
    $(".highlights p").css("margin-top","0px");
    var id= $(".highlights").attr("id").split("hLights")[1];
    initScroll(id);
}

function callBackDisplayVariantSelection(xmlReturn) {
	var tintNbIdContainer = $("tintNbIdContainer", xmlReturn).text().replace(/\n/g,'');
	var packshotContainer = $("packshotContainer", xmlReturn).text().replace(/\n/g,'');
	var pcidContainer = $("pcidContainer", xmlReturn).text().replace(/\n/g,'');
	var imgLoadingContainer = $("input[@name=imgLoadingContainer]").val();
	var priceContainer = $("priceContainer", xmlReturn).text().replace(/\n/g,'');
	var ppuContainer = $("ppuContainer", xmlReturn).text().replace(/\n/g,'');
	var TotalProductsPrices = $("#selectionTotalPrice").text();
	var beforeTotalPrice = $("currentPrice", xmlReturn).text().replace(/\n/g,'');
	var currentTotal = $("total", xmlReturn).text().replace(/\n/g,'');
	var TotalProductsPricesContainer = $("TotalProductsPricesContainer", xmlReturn).text().replace(/\n/g,'');
	var price = $("price", xmlReturn).text().replace(/\n/g,'');
	var ppu = $("ppu", xmlReturn).text().replace(/\n/g,'');
	currentTotalNew = $("#selectionTotalPrice").html();
	var digitTT = currentTotalNew.replace(',','.');
	
	var calcNewtotal = (parseFloat(digitTT) - parseFloat(beforeTotalPrice) + parseFloat(price));
	$("input[@name=" + pcidContainer + "]").val($("pcid", xmlReturn).text().replace(/\n/g,''));

	var price = parseFloat(price).toFixed(2);
	price = price.toString();
	price = price.replace('.',',');
	//mise à jour du prix produit
	$("#" + priceContainer).text( price);
	$("#" + ppuContainer).text( ppu);
	var total = 0;
	var submitFormItemsId = $('div .bottom_modif_qte form input[@name=pcid]').val();
	var reg=new RegExp("[ , ]", "g");
	var arrayItemsList = submitFormItemsId.split(reg);
	var newItemId =$("pcid", xmlReturn).text();
	var addNewItem = "";
	
	//boucle pour récuperer le prix des produits
	for (i = 0; i<arrayItemsList.length; i++){
		if ($("#productPrice"+(i +1 )).html()){
			var priceTemp = parseFloat($("#productPrice"+( i + 1 )).html().replace(',','.'));
			if(priceTemp){
				total = total + priceTemp;	
				if("pcidContainer"+ (i+1) == pcidContainer){
					arrayItemsList[i] = trim(newItemId);
				}
			}
		}
	}
	
	for (var i=0; i<arrayItemsList.length; i++) {
		var coma ="";
		if(addNewItem != "") coma = ",";
		addNewItem = addNewItem + coma+ arrayItemsList[i];
		
	}
	$('div .bottom_modif_qte form input[@name=pcid]').val(addNewItem)
	//traitement pour l affichage
	var strNewtotal = total.toFixed(2);
	strNewtotal = strNewtotal.toString();
	strNewtotal = strNewtotal.replace('.',',');
	
	$("#selectionTotalPrice").text(strNewtotal);
	//réinitialise les variables pour recalculer le total
	strNewtotal = null;
	total = null;


	var img = new Image();
		var l = 180;
		var h = 219;

	$("#" + packshotContainer).empty();

	$(img).load(function () {
		$(img).addClass("png");
		$("#" + packshotContainer).append(this);
			$(img).attr("width",l);
			$("#" + imgLoadingContainer).fadeOut("fast", function() {
			$(img).attr("height",h);
			$("#" + packshotContainer).fadeIn();
		});
	})
	.attr({
	  width : l,
	  height : h,
      src: $("packshot", xmlReturn).text().replace(/\n/g,''),
      title: $("productTitle", xmlReturn).text().replace(/\n/g,'')+" "+$("productSubTitle", xmlReturn).text().replace(/\n/g,''),
      alt: $("productTitle", xmlReturn).text().replace(/\n/g,'')+" "+$("productSubTitle", xmlReturn).text().replace(/\n/g,'')
    })
    .error(function () {
      // notify the user that the image could not be loaded
		$("#" + imgLoadingContainer).fadeOut("fast", function() {
			$("#" + packshotContainer).fadeIn();
		});
		return false;
    });

}
function trim (myString){
	return myString.replace(/^\s+/g,'').replace(/\s+$/g,'');
}
function callBackTunnelDisplayAddress(xmlReturn) {
	var addressId = $("addressId", xmlReturn).text().replace(/\n/g,'');
	var addressType = $("addressType", xmlReturn).text().replace(/\n/g,'');
	$("#addressFullname-"+addressType).text($("addressFullName", xmlReturn).text().replace(/\n/g,''));
	$("#addressLine1-"+addressType).text($("addressLine1", xmlReturn).text().replace(/\n/g,''));
	$("#addressLine2-"+addressType).text($("addressLine2", xmlReturn).text().replace(/\n/g,''));
	$("#addressZipCity-"+addressType).text($("addressZipcode", xmlReturn).text().replace(/\n/g,'')+" "+$("addressCity", xmlReturn).text().replace(/\n/g,''));
	$("#addressCountry-"+addressType).text($("addressCountry", xmlReturn).text().replace(/\n/g,''));
	if(addressType == 1) {
		$("input[@name=shippingAddressId]").val(addressId);
	}
	if(addressType == 2) {
		$("input[@name=billingAddressId]").val(addressId);
	}
}

/**
 * Order review call back
 */
function callBackRecHistory(xmlReturn) {

  try {
    var goOn = true;
    $("error", xmlReturn).each(function() {
      goOn = false;
    });

    if (goOn) {

    $("redirect", xmlReturn).each(function() {
      loadPageWithHistory($(this).text());
    });

    }
  }
  catch(e) {
    writeError("[callBackRecHistory]" + e.description);
  }
}

/**
 * Order review call back
 */
function callBackForm(xmlReturn) {

  try {
    var goOn = true;
    var error = "";
    $("#errorframe p").remove();
    $("error", xmlReturn).each(function() {
      goOn = false;
      $("<p>" + $(this).text() + "</p>").appendTo($("#errorframe div.modal"));
    });

    if (goOn) {

      $("redirect", xmlReturn).each(function() {
        loadPageWithHistory($(this).text());
      });

    } else {
      tb_show('Error', '#TB_inline?height=200&width=300&inlineId=errorframe&modal=true');
    }
  }
  catch(e) {
    writeError("[callBackForm]" + e.description);
  }
}

function submitPaymentByPhone() {
  $("#acceptLegalTerms").val("false");
  $("#isClickToCall").val("true");
  ajaxFormSubmit($("#tunnel-recap-payment"), callBackPaymentByPhone);
}

function submitInPaymentByPhone(estara_id) {
  $("#acceptLegalTerms").val("false");
  $("#isClickToCall").val("true");
  $("input[@type=submit]").css("visibility", "hidden");
  webVoicePop("Template=" + estara_id);
}

function callBackPaymentByPhone(xmlReturn) {
  try {
    var goOn = true;
    var error = "";
    $("#errorframe p").remove();
    $("error", xmlReturn).each(function() {
      $("<p>" + $(this).text() + "</p>").appendTo($("#errorframe div.modal"));
      goOn = false;
    });

    if (goOn) {
      $("input[@type=submit]").css("visibility", "hidden");
      webVoicePop("Template=" + $("input[@name=estara_id]").val());
    } else {
      tb_show('Error', '#TB_inline?height=200&width=300&inlineId=errorframe&modal=true');
    }
  }
  catch(e) {
    writeError("[callBackPaymentByPhone] " + e.description);
  }
}

/**
 * Order payment call back
 */
function callBackPaymentForm(xmlReturn) {

  try {
    var goOn = true;
    var error = "";;
    $("#paymentMessage p").remove("");
    $("error", xmlReturn).each(function() {
      goOn = false;
      error += "<p>" + $(this).text() + "</p>";
    });

    if (goOn) {
      tb_remove();

      /* refreshing the menu */
      refreshNav();

      $("redirect", xmlReturn).each(function() {
        loadPageWithoutHistory($(this).text());
      });

    } else {
      $("#paymentMessage").append(error);
      tb_show('Error', '#TB_inline?height=200&width=300&inlineId=paymentMessage&modal=true');
    }
  }
  catch(e) {
    writeError("[callBackPaymentForm]" + e.description);
  }
}

/**
 * Order payment call back
 */
function callBackContactForm(xmlReturn) {

  try {
    var goOn = true;
    var message = "";;
    $("#contactMessage p").remove();
    $("#errorcontactMessage p").remove();

    $("error", xmlReturn).each(function() {
      goOn = false;
      message += "<p>" + $(this).text() + "</p>";
    });

    $("message", xmlReturn).each(function() {
      message += "<p>" + $(this).text() + "</p>";
    });


    if (goOn) {
      $("#contactMessage").append(message);
      tb_show('', '#TB_inline?height=200&width=300&inlineId=contactMessage&modal=true');
      $("redirect", xmlReturn).each(function() {
        loadPageWithoutHistory($(this).text());
      });
    } else {
      $("#errorcontactMessage").append(message);
      tb_show('', '#TB_inline?height=200&width=300&inlineId=errorcontactMessage&modal=true');
    }
  }
  catch(e) {
    writeError("[callBackContactForm]" + e.description);
  }
}

function returnFromWl(xmlReturn) {
  try {
    $("#wishlistMessage p").remove();
    $("error", xmlReturn).each(function() {
      $("<p>" + $(this).text() + "</p>").appendTo($("#wishlistMessage div.modal"));
    });
    $("message", xmlReturn).each(function() {
      $("<p>" + $(this).text() + "</p>").appendTo($("#wishlistMessage div.modal"));
      displayAlreadyInWishList();

    });
    tb_show('', '#TB_inline?height=200&width=300&inlineId=wishlistMessage&modal=true');
  } catch(e) {
    writeError("[returnFromWl]" + e.description);
  }
}

function returnFromCaddieWl(xmlReturn) {
  try {
    $("#wishlistMessage p").remove();
    $("error", xmlReturn).each(function() {
      $("<p>" + $(this).text() + "</p>").appendTo($("#wishlistMessage div.modal"));
    });
    $("message", xmlReturn).each(function() {
      $("<p>" + $(this).text() + "</p>").appendTo($("#wishlistMessage div.modal"));
      displayAlreadyInWishList();
    });
    tb_show('', '#TB_inline?height=200&width=300&inlineId=wishlistMessage&modal=true');
  } catch(e) {
    writeError("[returnFromCaddieWl]" + e.description);
  }
}

/*
 * account-registration.jsp
 */
function callBackRegister(xmlReturn) {
   try {
    var goOn = true;
    var errors = "";
    $("#registerError p").remove();
    $("error", xmlReturn).each(function() {
      goOn = false;
      errors = errors + "<p>" + $(this).text() + "</p>";
    });
    if(goOn) {
      //Désactivation du bouton valider pour éviter de créer des doublons de compte.
      $("#createAccount").attr('disabled', 'disabled');
      /* refreshing the menu */
      refreshNav();
       $("redirect", xmlReturn).each(function() {
        loadPageWithoutHistory($(this).text());
       });
    } else {
      $("#registerError").append(errors);
      tb_show('Error','#TB_inline?height=400&width=250&inlineId=registerError&modal=true');
    }
  } catch(e) {
    writeError("[account-login]" + e.description);
  }
}

/*
 * profile.jsp
 */

  function activateFields(name, mode) {
    try {
      var fieldName = "fieldset." + name;

      /* disabling input hidden and putting input in read only */
      if (mode == 'readonly') {
        $(fieldName + " input").attr("readonly", "readonly");
      } else {
        /* showing/hiding address */
        if ($(fieldName).attr("class").indexOf("isFirstAddress") == -1 && $(fieldName).attr("class").indexOf("address") > -1) {
          if ($("fieldset.isFirstAddress").html()) {
            $("fieldset.isFirstAddress ol").hide();
            /* if selectedAdress has been modified, we have to hide cancel button and show modify button */
            if($("fieldset.isFirstAddress").attr("class").indexOf("resume") == -1) {
              $("fieldset.isFirstAddress a.link").each( function() {
                showHideLink($(this));
              });
              $("fieldset.isFirstAddress").toggleClass("resume");
            }
          }
          $("fieldset.isFirstAddress").toggleClass("isFirstAddress");
          $(fieldName + " ol").show();
          $(fieldName).toggleClass("isFirstAddress");
        }
        $(fieldName + " input").removeAttr("readonly");
      }

      showHideSelect(name, mode);
      $(fieldName).toggleClass("resume");
      $(fieldName + " a.link").each(
        function() { showHideLink($(this)); }
      );
    } catch(e) {
      writeError("[activateFields]" + e.description);
    }
  }

  function showHideLink(link) {
    if(link.attr("class") && link.attr("class").indexOf("hidden") == -1) {
      link.hide();
    } else {
      link.show();
    }
    link.toggleClass("hidden");
  }

  function showHideSelect(name, mode) {
    /* hiding select only in readonly mode */
    /* showing select not in readonly mode */
    /* showing / hiding input-select */
    $("fieldset." + name + " input").each(
      function() {
        if ($(this).attr("class")) {
          if ($(this).attr("class").indexOf("unused") > -1 || $(this).attr("class").indexOf("selectbox") > -1) {
            $(this).toggle();
          }
        }
      }
    );
    
    /* showing / hiding non-selectbox select */
	$("fieldset." + name + " select").each(
      function() {
	      if (! $(this).attr("class")) {
	          $(this).toggle();
	        }
	      }
      );
  }


  function resultProfileModified(xmlReturn) {
    try {
      var hasErrors=false;
      var height = "";
      var width = "";
      var divId = "";
      $("#error div.modal p").remove();
      $("error", xmlReturn).each(function() {
        hasErrors = true;
        $("#error div.modal").append("<p>" + $(this).text() + "</p>");
      });
      if (!hasErrors) {
        var addressIdDeleted = $("input[@name=address_to_delete]").val();
        $("fieldset.address" + addressIdDeleted).remove();
        height = "150";
        width = "235";
        divId = "profil";
        refreshNav();
        var oldLogin = $("oldLogin", xmlReturn).text().replace(/\n/g,'');
        var newLogin = $("newLogin", xmlReturn).text().replace(/\n/g,'');
        var addressId = $("addressId", xmlReturn).text().replace(/\n/g,'');
        $("redirect", xmlReturn).each(function() {
          var redirect = $(this).text();
          if (redirect.indexOf("?") > -1) {
            redirect += "&";
          } else {
            redirect += "?";
          }
          loadPageWithoutHistory(redirect +"addressId="+ addressId + "&oldLogin=" + oldLogin + "&newLogin=" + newLogin);
        });
      } else {
        height = "200";
        width = "300";
        divId = "error";
      }
      var url = '#TB_inline?height=' + height + '&width=' + width + '&inlineId=' + divId + '&modal=true';
      tb_show('',url);
    } catch(e) {
      writeError("[resultProfileModified]" + e.description);
    }
  }

  function submitDeleteAddress(id) {
    try {
      $("input[@name=address_to_delete]").val(id);
      ajaxFormSubmit($("#profile-informations"), resultProfileModified);
    } catch(e) {
      writeError("[submitDeleteAddress]" + e.description);
    }
  }

  function closePopup(redirect) {
    //close pop up
    tb_remove();
    loadPageWithoutHistory(redirect);
  }


/*
 * wishlist.jsp
 */

    function callBackSendWl(xmlResponse) {
      var msg = "";
      var hasErrors = false;
      $("#backFromWlError p").remove();
      $("#backFromWlMessage p").remove();

      $("error", xmlResponse).each(function() {
        hasErrors = true;
        $("<p>" + $(this).text() + "</p>").appendTo($("#backFromWlError div.modal"));
      });

      $("message", xmlResponse).each(function() {
        $("<p>" + $(this).text() + "</p>").appendTo($("#backFromWlMessage div.modal"));
      });

      if (!hasErrors) {
        tb_show('','#TB_inline?height=200&amp;width=250&amp;inlineId=backFromWlMessage&amp;modal=true');
        $("#messageSendWl").val("");
        $("#friendEmail").val("");
      } else {
        tb_show('','#TB_inline?height=200&amp;width=250&amp;inlineId=backFromWlError&amp;modal=true');
      }
    }

    function returnFromWlToCart(xmlResponse) {
      var msg = "";
      var hasErrors = false;

      $("#caddieMessage p").remove();

      $("error", xmlResponse).each(function() {
        hasErrors = true;
        $("<p>" + $(this).text() + "</p>").appendTo($("#caddieMessage div.modal"));
      });

      if (hasErrors) {
        tb_show('', '#TB_inline?height=200&width=300&inlineId=caddieMessage&modal=true');
      } else {
        $("caddie", xmlResponse).each(function() {
          updateArticle($(this).text().replace(/\n/g,""));
        });
        $("#addWlToCartButton").hide();
        $("#buyAllList, #addWlToCartDisabledButton").show();
        $("#buyList_" + $("result", xmlResponse).text().replace(/\n/g,'')).show();
      }
    }

    function returnFromOrderHistory(xmlResponse) {
      var msg = "";
      var hasErrors = false;

      $("error", xmlResponse).each(function() {
        hasErrors = true;
        $("<p>" + $(this).text() + "</p>").appendTo($("#caddieMessage div.modal"));
      });

      if (hasErrors) {
        tb_show('', '#TB_inline?height=470&width=500&inlineId=caddieMessage&modal=true');
      } else {

      }
    }

  function clearListCallBack(xmlReturn) {
    var goOn = true;
    var errors = "";
    $("#error div.modal p").remove();
    $("error", xmlReturn).each(function() {
      goOn = false;
      errors = errors + "<p>" + $(this).text() + "</p>";
    });
    if(goOn) {
      var redirect = $("redirect", xmlReturn).text();
      closePopup(redirect);
    } else {
      $("#error div.modal").append(errors);
      //tb_remove();
      var url = '#TB_inline?height=200&width=300&inlineId=error&modal=true';
      tb_show('',url);
    }
  }

  function writeCommentCallBack(xmlReturn) {
    var goOn = true;
    var errors = "";
    $("#error div.modal p").remove();
    $("error", xmlReturn).each(function() {
      goOn = false;
      errors = errors + "<p>" + $(this).text() + "</p>";
    });
    if(goOn) {
      closePopup($("redirect", xmlReturn).text());
    } else {
      $("#error div.modal").append(errors);
      //tb_remove();
      var url = '#TB_inline?height=200&width=300&inlineId=error&modal=true';
      tb_show('',url);
    }
  }


/*
 *
 */
    function bookmarkThis(actionUrl, objectType, id) {
      if (id != null) {
        $.post(
          actionUrl,
          { objectType: objectType, id: id},
          function(xmlReturn) {
            var goOn = true;
            var error = "";
            $("error", xmlReturn).each(function() {
              goOn = false;
              error += "<p>" + $(this).text().replace(/\n/g,'') + "</p>";
            });
            if (!goOn) {
              $("#errorframe").html(error);
              tb_show('Error', '#TB_inline?height=200&width=300&inlineId=errorframe');
            } else {
              $("#notBookmarked").hide();
              $("#bookmarked").show();
            }
          }
        );
      }
    }

/*
 * extranet : orderdetails.jsp
 */
  function callBackForm(xmlReturn) {

    try {
      var goOn = true;
      var error = "";
      $("#errorframe p").remove();
      $("error", xmlReturn).each(function() {
        goOn = false;
        $("<p>" + $(this).text() + "</p>").appendTo($("#errorframe div.modal"));
      });

      if (goOn) {
        tb_remove();
        $("redirect", xmlReturn).each(function() {
          loadPageWithHistory($(this).text() + "&user=" + $("user", xmlReturn).text().replace(/\n/g,'') + "&document=" + $("document", xmlReturn).text().replace(/\n/g,''));
        });

      } else {
        tb_show('Error', '#TB_inline?height=200&width=300&inlineId=errorframe&modal=true');
      }
    }
    catch(e) {
      writeError("[callBackForm]" + e.description);
    }
  }

  /*
   * extranet : customer.jsp
   */
  function listUserCallBack(xmlReturn) {
    try {
      var goOn = true;
      var errors = "";
      var j = 1;
      /* #1309 */
      if (jQuery.browser.msie) {
        $("#searchUserResult tr").hide();
      } else {
        $("#searchUserResult tr").remove();
      }
      $("#errorframe p").remove();
      $("error", xmlReturn).each(function() {
        goOn = false;
        errors = errors + "<p>" + $(this).text().replace(/\n/g,'') + "</p>";
      });
      if(goOn) {
        $("user", xmlReturn).each(function() {
          var result = $(this).text().split("|");
          var i;
          var row;
          if (j%2 == 1) {
            row = "<tr class='exOdd'>";
          } else {
            row = "<tr>";
          }
          for(i=1; i<result.length; i++) {
            if (i == 1) {
              row += "<td><a href='javascript:loginUser(" + result[0] + ")'>" + result[i] + "</a></td>";
            } else {
              row += "<td>" + result[i] + "</td>";
            }
          }

          row += "</tr>";
          $("#searchUserResult").append(row);
          j++;
        });
      } else {
        $("#searchUserResult").append("<tr><td>" + extranet_customer_no_result + "</td></tr>");
        $("#errorframe").append(errors);
        tb_show('', '#TB_inline?height=200&width=300&inlineId=errorframe&modal=true');
      }
    } catch(e) {
      writeError("listUserCallBack: " + e.description);
    }
  }

  function loginUser(id) {
    if (id != null && $("#setSwitchUserAction").val() != null) {
      $.post(
        $("#setSwitchUserAction").val(),
        { id: id},
        function(xmlReturn) {
          var goOn = true;
          var error = "";
          $("#error p").remove();
          $("error", xmlReturn).each(function() {
            goOn = false;
            error += "<p>" + $(this).text().replace(/\n/g,'') + "</p>";
          });
          if (!goOn) {
            $("#error").html(error);
            tb_show('Error', '#TB_inline?height=200&width=300&inlineId=error');
          } else {
            if (id == 0) {
              $("#customerName").html($("message", xmlReturn).text());
              $("#disconnectCustomer").hide();
            } else {
              $("#customerName").html($("name", xmlReturn).text());
              $("#disconnectCustomer").show();
            }
          }
        }
      );
    }
  }

/*
 * extranet : update-document-note-popup.jsp
 */

  function UpdateDocumentNoteCallBack(xmlReturn) {
    var goOn = true;
    var errors = "";
    $("#errorDocumentNote p").remove();
    $("error", xmlReturn).each(function() {
      goOn = false;
      errors = errors + "<p>" + $(this).text().replace(/\n/g,'') + "</p>";
    });
    if(goOn) {
      var row = "<tr>";
      row += "<td>" + $("date", xmlReturn).text() + "</td>";
      row += "<td>" + $("operatorName", xmlReturn).text() + "</td>";
      row += "<td><textarea rows='2' cols='20' readonly='readonly'>" + $("description", xmlReturn).text() + "</textarea></td>";
      row += "</tr>";
      $("#listNotes").append(row);
      $("#noteCount" + $("documentID", xmlReturn).text().replace(/\n/g,'')).text($("documentCount", xmlReturn).text());
    } else {
      $("#errorDocumentNote").append(errors);
      //tb_remove();
      var url = '#TB_inline?height=200&width=300&inlineId=error';
      tb_show('',url);
    }
  }

  /*
   * extranet : cancel-order-popup.jsp
   */

  function cancelDocumentPopupCallBack(xmlReturn) {
    var goOn = true;
    var errors = "";
    $("#errorCancelDocument p").remove();
    $("error", xmlReturn).each(function() {
      tb_remove();
      goOn = false;
      alert($(this).text().replace(/\n/g,''));
      //errors = errors + "<p>" + $(this).text().replace(/\n/g,'') + "</p>";
    });
    if(goOn) {
     $("redirect", xmlReturn).each(function() {
      tb_remove();
      loadPageWithoutHistory($(this).text());
     });
    } /*else {
      $("#errorDocumentNote").append(errors);
      var url = '#TB_inline?height=200&width=300&inlineId=error';
      tb_show('',url);
    }*/
  }

  /*
   * store-locator: search.jsp
   */


  function submitStoreSearch() {
    var countryVal = encodeURIComponent($("#ac-country").val());
    var cityVal = encodeURIComponent($("#ac-city").val());
    var strRedirect = $("#storeForm").attr("action") + "_country=" + countryVal + "&city=" + cityVal;
    
    loadPageWithHistory(strRedirect);
    return false;
  }

  /*
   * store-locator: result.jsp
   */


  function showStores(id, way) {
    var i = 1;
    if (way == "previous") {
      i = -1;
    }
    showStorePane(id, i);
  }

  function showStorePane(id, i) {
    $("#paneright" + id).fadeOut("slow");
    $("#previous" + id).fadeOut("slow");
    $("#next" + id).fadeOut("slow");
    $("#paneleft" + id).fadeOut("slow",
      function() {
        $("#paneleft" + (id + i)).fadeIn("slow");
        $("#paneright" + (id + i)).fadeIn("slow");
        $("#previous" + (id + i)).fadeIn("slow");
        $("#next" + (id + i)).fadeIn("slow");
      }
    );
  }

  function showStoreForm(id) {
    /* hiding links */
    $("table#links").hide();
    /* hiding previous data */
    $("#store-content table").hide();
    $("#store-content div.divbg").hide();
    $("form#" + id).show();
    $("p#foottext").show();
  }

  /*
   * very dior/espace perso : home.jsp
   */

  function showBoudoir() {
    if ($("#boudoir").css("display") == "none") {
      $("#boudoir").show();
    }
    $("#boudoir").css("visibility", "visible");
    $("#boudoir").css("z-index", "1000");
  }
  function hideBoudoir() {
    $("#boudoir").css("visibility", "hidden");
    $("#boudoir").css("z-index", "1");
  }

  /*
   * common
   */

   function disableInput(button) {
     $(button).attr('disabled',true);
   }

   /*
    * tunnel
    */
  function showCaddie(show) {
    /* #1391 le parametre show n'est plus nï¿½cessaire */
    $("div.jScrollPaneContainer div").css("overflow", "hidden");
  }

  /*
   *  forgotton password (tunnel et espace perso)
   */

  function callBackRetrievePassword(xmlReturn) {
    try {
      $("#loginError p").remove();
      $("error", xmlReturn).each(function() {
        $("<p>" + $(this).text() + "</p>").appendTo($("#loginError div.modal"));
      });
      $("message", xmlReturn).each(function() {
        $("<p>" + $(this).text() + "</p>").appendTo($("#loginError div.modal"));
      });
      tb_show('Error','#TB_inline?height=200&amp;width=250&amp;inlineId=loginError&amp;modal=true');
    } catch(e) {
      writeError("[retrieve-password]" + e.description);
    }
  }

  /**
   * Prepares the returned message and display it in the 'message' div...
   */
  function callBackSendEmail(xmlReturn) {
    var msg = "";
    $("error", xmlReturn).each( function() {
      msg += $(this).text() + '<br/>';
    });

    $("message", xmlReturn).each( function() {
      msg += $(this).text() + '<br/>';
    });

    $("#message").html("<p>" + msg + "</p>");
    $("#message").show();
  }

  function callBackProductSendEmail(xmlReturn) {
    var msg = "";
    var error = false;
    $("error", xmlReturn).each( function() {
      msg += $(this).text() + '<br/>';
      error = true;
    });

    $("message", xmlReturn).each( function() {
      msg += $(this).text() + '<br/>';
    });

	if(msg){
	    $("#message").html(msg);
	    $('#aunami_container').hide();
	    $("#message").show();
	    if(error){
		    $("#aunami_container_close").hide();
			$("#aunami_message_close").show();
	    }
		TB_WIDTH = 320;
		TB_HEIGHT = 160;
		$('#TB_ajaxContent').width('');
		$('#TB_ajaxContent').height('');
		tb_position();
		refreshCaptcha();

	}
  }

  function hideErrorMessage(){
	    $('#aunami_container').show();
	    $("#message").hide();

	    $("#aunami_message_close").hide();
	    $("#aunami_container_close").show();

	    TB_WIDTH = 520;
		TB_HEIGHT = 380;
		tb_position();
  }

  /*
   * product-tints.jsp
   */
  var tintArray = new Array();
  function addTint(img, label, color){
      tintArray.push({swatch: img, name: label, color: color});
  }

  function showTint(index){
      $("img#texture").attr("src", tintArray[index].swatch);
      $("span#label").html(tintArray[index].name);
      $("span#color").html(tintArray[index].color);
  }

  function replace_shutter_left(aUrl) {
      var url = aUrl.substr(aUrl.lastIndexOf("/" + lang + "/"),aUrl.length);
      var sharpPosition = url.indexOf('#/' + lang ,0) + ('#/' + lang).length;
      var myUrl = url.substring(sharpPosition, url.length).replace(/\.html/,'/');
      var myUrlLevel = returnLevel(myUrl.replace(/_.*$/, '').replace(/\/$/,''));

      // getting next to last shutter (product page, tint page is the last)
      var shutters = getShutterList();
      var index = 1;
      if (shutters.length > 1) {
        index = $(shutters[shutters.length-2]).attr("id").replace(/shutter/,'');
      }

      replaceShutter(myUrl, myUrlLevel, -1, true, index);
      return false;
  }

  /*
   * newsletter.jsp
   */

   function callBackNewsletterForm(xmlReturn) {
      try {
	    var goOn = true;
	    var msg = "";
	    $("#backFromNewsletterMessage p").remove();

	    $("error", xmlReturn).each(function() {
	      goOn = false;
	      msg = msg + "<p>" + $(this).text() + "</p>";
	    });
	    
	    $("message", xmlReturn).each(function() {
	      msg = msg + "<p>" + $(this).text() + "</p>";
	    });
	    $("#backFromNewsletterMessage").append(msg);
	    if(goOn) {
	       $("redirect", xmlReturn).each(function() {
	         loadPageWithHistory($(this).text());
	       });
	    }
	    if(msg){
	    	tb_show('Error','#TB_inline?height=200&width=250&inlineId=backFromNewsletterMessage&modal=true');
	    }
	  } catch(e) {
	    writeError("[callBackNewsletterForm]" + e.description);
	  }
  }

  function callBackDiscoverToFriend(xmlReturn){
  	try {
	    var goOn = true;
	    var errors = "";
	    var message = "";
	    $("#backFromNewsletterMessage p").remove();
	    $("error", xmlReturn).each(function() {
	      goOn = false;
	      errors = errors + "<p>" + $(this).text() + "</p>";
	    });

	    $("message", xmlReturn).each(function() {
	      message = message + "<p>" + $(this).text() + "</p>";
	    });
	    if(goOn) {
	      /* refreshing the menu */
	       refreshNav();
	       $("redirect", xmlReturn).each(function() {
	        loadPageWithoutHistory($(this).text());
	       });
	       $("#backFromNewsletterMessage").append(message);
	       tb_show('Error','#TB_inline?height=200&width=250&inlineId=backFromNewsletterMessage&modal=true');
	    } else {
	      $("#backFromNewsletterMessage").append(errors);
	      tb_show('Error','#TB_inline?height=200&width=250&inlineId=backFromNewsletterMessage&modal=true');
	   	  refreshCaptcha();
	    }
	  } catch(e) {
	    writeError("[account-login]" + e.description);
	  }
  }

  function refreshCaptcha(){
  		var img = new Image();
		var d = new Date();
		var id = ($('#imgCaptcha2').length == 0)?'':2;
		img.src = $('#imgCaptcha' + id).attr('src').substr(0, $('#imgCaptcha' + id).attr('src').indexOf('?'));
		$("#imgCaptcha" + id).attr('src', img.src + "?conf=conf" + id + "&ts=" + d.getMilliseconds());

  }

  function callBackPersoLogin(xmlReturn) {
    try {
      var goOn = true;
      $("#error div.modal p").remove();
      $("error", xmlReturn).each(function() {
        goOn = false;
        $("#error div.modal").append("<p>" + $(this).text() + "</p>");
      });
      if (goOn) {
        /* refreshing the menu */
        refreshNav();
        $("redirect", xmlReturn).each(function() {
          /* #1470 : problï¿½me de refresh aprï¿½s login */
          var redirect = $(this).text();
          if (redirect.indexOf("?") == -1) {
            redirect += "?refresh=true";
          } else {
            redirect += "&refresh=true";
          }
          loadPageWithoutHistory(redirect);
        });
      } else {
        var url = '#TB_inline?height=200&width=300&inlineId=error&modal=true';
        tb_show('',url);
        $("redirectPerso", xmlReturn).each(function() {
          loadPageWithHistory($(this).text().replace(/\n/g,''));
        });
      }
    } catch(e) {
      writeError("[callBackPersoLogin]" + e.description);
    }
  }

  function callBackPersoSurvey(xmlReturn) {
    $("redirect", xmlReturn).each(function() {
        var redirect = $(this).text();
        loadPageWithoutHistory(redirect);
      });
  }

  function callBackPopupLogin(xmlReturn) {
    try {
      var goOn = true;
      $("#TB_ajaxContent div.modal p.error").remove();
      $("error", xmlReturn).each(function() {
        goOn = false;
        $("#TB_ajaxContent div.modal").append("<p class='error'>" + $(this).text() + "</p>");
      });
      if (goOn) {
        /* refreshing the menu */
        refreshNav();
        /* adding to wishlist */
        $('#addToWl').submit();
      } else {
        var url = '#TB_inline?height=390&width=500&inlineId=error&modal=true';
        tb_show('',url);
      }
    } catch(e) {
      writeError("[callBackPersoLogin]" + e.description);
    }
  }

  /* extranet */

  function callBackExtranet(xmlReturn) {
    try {
      var goOn = true;
      $("#errorframe div.modal p").remove();
      $("error", xmlReturn).each(function() {
        goOn = false;
        $("#errorframe div.modal").append("<p>" + $(this).text() + "</p>");
      });
      if (goOn) {
        location.reload(true);
      } else {
        var url = '#TB_inline?height=200&width=300&inlineId=errorframe&modal=true';
        tb_show('',url);
      }
    } catch(e) {
      writeError("[callBackExtranet]" + e.description);
    }
  }


  /* print functions */
  function printPage(url) {
    showPopup(url, 500, 500);
  }

  function showPopupPage(aUrl, height, width) {
    var indexLang = aUrl.indexOf("/" + lang + "/");
    var layout = "/layout-popup";
    var url = aUrl.substr(0, indexLang) + layout + aUrl.substr(indexLang, aUrl.length);
    showPopup(url, height, width);
  }

  function showPopup(url, height, width) {
    var top=(screen.availHeight-height)/2;
    var left=(screen.availWidth-width)/2;
    window.open(url, "" ,"width=" + width + ",height=" + height + ",left=" + left + ",top=" + top);
  }



/* product-page */
  var isScrolling = false;

  function initScroll(timeStamp) {
    var highlightsID  = 'hLights' + timeStamp;
    var cursorID      = 'cId' + timeStamp;
    var scrollTop     = $('#sTop' + timeStamp);
    var scrollBottom  = $('#sBottom' + timeStamp);
    var highlights    = $('#hLights' + timeStamp);

    if (scrollTop.attr("class") && scrollTop.attr("class").indexOf("binded") == -1) {
      var heightText = 0 ;
      
      $('#' + highlightsID + ' p').each( function(i) {
    	  heightText = heightText  + parseInt($(this).height());
      });
      
      var heightVisible  = parseInt(highlights.height());
      var heightToScroll = parseInt(heightVisible * 3 / 4);
      
      if ( heightText > heightVisible ) {
    	
    	  
        scrollTop.mouseover( function(event) { myFunctionToAdd(event, "up", cursorID, highlightsID, heightToScroll, heightText);} )
                       .mousemove( function(event) { myFunctionToShow(event, cursorID)} )
                       .mouseout ( function(event) { myFunctionToHide(cursorID)} )
                       .toggleClass("binded");

        scrollBottom.mouseover( function(event) { myFunctionToAdd(event, "down", cursorID, highlightsID, heightToScroll, heightText);} )
                          .mousemove( function(event) { myFunctionToShow(event, cursorID)} )
                          .mouseout ( function(event) { myFunctionToHide(cursorID)} );

        highlights.mouseover( function(event) { myFunctionToAdd(event, null, cursorID) } )
                        .mousemove( function(event) { myFunctionToShow(event, cursorID)} )
                        .mouseout ( function(event) { myFunctionToHide(cursorID)} );
      }
    }
  }

  function scrollMe(way, highlightsID, heightToScroll, heightText) {
    var text = $('#' + highlightsID + ' p:first');

    if (!isScrolling) {
      var margin = parseInt(text.css("margin-top").replace("px", ""));

      if (way == 'up') {
        if (margin + heightToScroll < 15) {
          isScrolling = true;
          text.animate({marginTop: margin + heightToScroll}, 500, function() {isScrolling = false;});
        }
      } else if (way == 'down') {    	
        if (margin - heightToScroll > - heightText - 15) {
          isScrolling = true;
          text.animate({marginTop: margin - heightToScroll}, 500, function() {isScrolling = false;});
        }
      }

    }
  }

  function myFunctionToAdd(event, way, cursorID, highlightsID, heightToScroll, heightText) {
    if($('#' + cursorID).size() == 0){
      $("body").append("<div id='" + cursorID + "' class='cursor_scroll' alt='scroll' />");
      $('#' + cursorID).css({
        top: (event.pageY + 11) + 'px',
        left: (event.pageX + 16) + 'px',
        position: 'absolute'
      });
    }
    $('#' + cursorID).show();

    if (way) {
      scrollMe(way, highlightsID, heightToScroll, heightText);
    }
  }

  function myFunctionToHide(cursorID) {
    $('#' + cursorID).hide();
  }

  function myFunctionToShow(event, cursorID) {
    $('#' + cursorID).css({
        top: (event.pageY + 11) + 'px',
        left: (event.pageX + 16) + 'px'
    });
    $('#' + cursorID).show();
  }


  function addToWl(sku) {
    $('#addToWl input').val(sku);
    $('#addToWl').submit();
    $('#addToWl input').val('');
  }

  function limite(zone, max) {
    var max = max || 500;
    if(zone.value.length>=max){
      zone.value=zone.value.substring(0,max);
      zone.scrollTop = zone.scrollHeight;
    }
  }

  /* --- SmartProfile --- */

  function loadSmartProfile(parameters) {
    $.get(
      smart_profile_path,
      parameters,
      function(JSReturn) {
        eval(JSReturn);
      }
    );
  }
  
  function rewriteCustomHeader() {
	var test = $("iframe#custom_header").attr("src");
	$("iframe#custom_header").attr("src", test);
  }	
	
  /* --- Selection popup --- */
  
// gestion du sélecteur de teinte
function updateTintProduct( productId , containerId, capacity) {
	showload();
	var submitForm = $('div #' + containerId).parents("form");
		//var text = $('#' + containerId + " option:selected").text();
	//console.log("productId: " + productId, "containerId=", containerId);
	
	submitForm.submit();
	//$('#variantTintForm').submit();
	
}

function writeError(message) {
    if (window.console && window.console.error) {
        console.error(message);
    }
}