function MM_reloadPage(init) {  //reloads the window if Nav4 resized
      if (init==true) with (navigator) {if ((appName=="Netscape")&&(parseInt(appVersion)==4)) {
        document.MM_pgW=innerWidth; document.MM_pgH=innerHeight; onresize=MM_reloadPage; }}
      else if (innerWidth!=document.MM_pgW || innerHeight!=document.MM_pgH) location.reload();
}

MM_reloadPage(true);

function MM_findObj(n, d) { //v4.01
      var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
        d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
      if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
      for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
      if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_showHideLayers() { //v6.0
      var i,p,v,obj,args=MM_showHideLayers.arguments;
      for (i=0; i<(args.length-2); i+=3) if ((obj=MM_findObj(args[i]))!=null) { v=args[i+2];
        if (obj.style) { obj=obj.style; v=(v=='show')?'visible':(v=='hide')?'hidden':v; }
        obj.visibility=v; 
}
}

function SetExtendedProp(id)
{
    var querystr = document.location.search;
    var _f = document.forms[0];
    if (querystr!=''){
		querystr=querystr.substring(1,querystr.length);
    }
    if (querystr!=''){
        var prop_array = querystr.split('&');
        for (var i=0;i<prop_array.length;i++){
            var prop=prop_array[i].split('=');
            //check if page has field to update requested extended property 
            for (var j = 0; j < _f.elements.length; j++)
            {
                if (_f.elements[j].id.indexOf(id)>-1){ 
                            _f.elements[j].value=prop[1];
                }
            }           
        }
    }
 
}
  
  String.prototype.rtrim = function() {
	return this.replace(/\s+$/,"");
}

function SetLogin(loginname,fieldname)
{
    var mf = GetMainFormName();
    if (mf==null) return;
    var login = GetElementName("hidden_login",mf);
    var field = GetElementName(fieldname,mf);

    if (login!= null)
    {
        document.forms[mf].elements[login].value = loginname.rtrim();
        //alert("loginname apres : "+document.forms[mf].elements[login].value+"**");
    }
    if (field!= null)
    {
        document.forms[mf].elements[field].value = loginname.rtrim();
        //alert("field apres : "+document.forms[mf].elements[field].value+"**");
    }
}
							
function Sethiddenloginvalue(val)
{
	var _f = document.forms[0];
	for (i=0;i<_f.elements.length;i++)
	{
		if (_f.elements[i].id.indexOf('hidden_login') != -1)
			_f.elements[i].value=val;
	}
 }
 									
function GetElementName(n, mf)
{
	if (n==null || n=="") return null;
	var i, s, j;
	for (i=0;i<document.forms[mf].elements.length;i++)
	{
	if (document.forms[mf].elements[i].name.toLowerCase().indexOf(n.toLowerCase()) != -1)
	return document.forms[mf].elements[i].name;

	}
	return null;
}

// CSS Drop Down
var cssdropdown={
    disappeardelay: 250, //set delay in miliseconds before menu disappears onmouseout
    disablemenuclick: false, //when user clicks on a menu item with a drop down menu, disable menu item's link?
    enableswipe: 1, //enable swipe effect? 1 for yes, 0 for no

    //No need to edit beyond here////////////////////////
    dropmenuobj: null, ie: document.all, firefox: document.getElementById&&!document.all, swipetimer: undefined, bottomclip:0,
    dropmenuimg: null, ie: document.all, firefox: document.getElementById&&!document.all, swipetimer: undefined, bottomclip:0,
    
    getposOffset:function(what, offsettype){
//        var totaloffset=(offsettype=="left")? what.offsetLeft : what.offsetTop;
        var totaloffset=0;
        var parentEl=what.offsetParent;
        if (parentEl!=null){
            totaloffset=(offsettype=="left")? totaloffset+parentEl.offsetLeft : totaloffset+parentEl.offsetTop;
            //parentEl=parentEl.offsetParent;
        }
        else
        {
            var totaloffset=(offsettype=="left")? what.offsetLeft : what.offsetTop;
        }
        if (offsettype!="left" && this.ie)
        {
            totaloffset = totaloffset - 1;
        }
        return totaloffset;
    },

    swipeeffect:function(){
        if (this.bottomclip<parseInt(this.dropmenuobj.offsetHeight)){
            this.bottomclip+=10+(this.bottomclip/10) //unclip drop down menu visibility gradually
            this.dropmenuobj.style.clip="rect(0 auto "+this.bottomclip+"px 0)"
        }
        else
            return
        this.swipetimer=setTimeout("cssdropdown.swipeeffect()", 10)
    },

    showhide:function(obj, e){
        try {
             _QuickShop_Class.Hide();
             }
        catch (err) {
        
        }     
        if (this.ie || this.firefox)
            this.dropmenuobj.style.left=this.dropmenuobj.style.top="-500px"
        if (e.type=="click" && obj.visibility==hidden || e.type=="mouseover"){
            this.swapimage(this.dropmenuimg, "on");
            if (this.enableswipe==1){
                if (typeof this.swipetimer!="undefined")
                    clearTimeout(this.swipetimer)
                obj.clip="rect(0 auto 0 0)" //hide menu via clipping
                this.bottomclip=0
                this.swipeeffect()
            }
            obj.visibility="visible"
            
        }
        else if (e.type=="click")
        {
            this.swapimage(this.dropmenuimg, "off");
            obj.visibility="hidden";
             
        }
    },

    iecompattest:function(){
        return (document.compatMode && document.compatMode!="BackCompat")? document.documentElement : document.body
    },

    clearbrowseredge:function(obj, whichedge){
        var edgeoffset=0
        if (whichedge=="rightedge"){
            var windowedge=this.ie && !window.opera? this.iecompattest().scrollLeft+this.iecompattest().clientWidth-15 : window.pageXOffset+window.innerWidth-15
            this.dropmenuobj.contentmeasure=this.dropmenuobj.offsetWidth
            if (windowedge-this.dropmenuobj.x < this.dropmenuobj.contentmeasure)  //move menu to the left?
                edgeoffset=this.dropmenuobj.contentmeasure-obj.offsetWidth
        }
        else{
            var topedge=this.ie && !window.opera? this.iecompattest().scrollTop : window.pageYOffset
            var windowedge=this.ie && !window.opera? this.iecompattest().scrollTop+this.iecompattest().clientHeight-15 : window.pageYOffset+window.innerHeight-18
            this.dropmenuobj.contentmeasure=this.dropmenuobj.offsetHeight
            if (windowedge-this.dropmenuobj.y < this.dropmenuobj.contentmeasure){ //move up?
                edgeoffset=this.dropmenuobj.contentmeasure+obj.offsetHeight
                if ((this.dropmenuobj.y-topedge)<this.dropmenuobj.contentmeasure) //up no good either?
                    edgeoffset=this.dropmenuobj.y+obj.offsetHeight-topedge
            }
        }
        return edgeoffset
    },

    dropit:function(obj, e, dropmenuID, imageID){
        if (this.dropmenuobj!=null) //hide previous menu
        {
            this.dropmenuobj.style.visibility="hidden" //hide menu
            var keepOn = this.dropmenuimg.getAttribute("keepOn");
            if (keepOn == null)
            {
                this.swapimage(this.dropmenuimg, "off"); // turn off image
            }
        }

        /* <Begin> */
        /* F.N This code hides the drop downs if ie 6.0 only */
        try 
        {
            ToggleDropDowns('hidden');
        }
        catch (err) { }
        /*<end> */

        this.clearhidemenu()
        if (this.ie||this.firefox){
            obj.onmouseout=function(){cssdropdown.delayhidemenu()}
            obj.onclick=function(){return !cssdropdown.disablemenuclick} //disable main menu item link onclick?
            this.dropmenuobj=document.getElementById(dropmenuID)
            this.dropmenuimg=document.getElementById(imageID)
            this.dropmenuobj.onmouseover=function(){cssdropdown.clearhidemenu()}
            this.dropmenuobj.onmouseout=function(e){cssdropdown.dynamichide(e)}
            this.dropmenuobj.onclick=function(){cssdropdown.delayhidemenu()}
            this.showhide(this.dropmenuobj.style, e)
            this.dropmenuobj.x=this.getposOffset(this.dropmenuimg, "left")
            this.dropmenuobj.y=this.getposOffset(this.dropmenuimg, "top")
            this.dropmenuobj.style.left=this.dropmenuobj.x-this.clearbrowseredge(obj, "rightedge")+"px"
            this.dropmenuobj.style.top=this.dropmenuobj.y-this.clearbrowseredge(obj, "bottomedge")+obj.offsetHeight+1+"px"
        }
    },

    contains_firefox:function(a, b) {
        while (b.parentNode)
            if ((b = b.parentNode) == a)
                return true;
        return false;
    },

    dynamichide:function(e){
        var evtobj=window.event? window.event : e
        if (this.ie&&!this.dropmenuobj.contains(evtobj.toElement))
            this.delayhidemenu()
        else if (this.firefox&&e.currentTarget!= evtobj.relatedTarget&& !this.contains_firefox(evtobj.currentTarget, evtobj.relatedTarget))
            this.delayhidemenu()
    },
    
    delayhidemenu:function(){
        var keepOn = this.dropmenuimg.getAttribute("keepOn");
        var imgSrc = ""; 
        if (keepOn == null)
        {
            imgSrc = this.getswapimagesrc(this.dropmenuimg, "off");
        }
        else
        {
            imgSrc = this.getswapimagesrc(this.dropmenuimg, "on");
        }
        var cmd = "cssdropdown.dropmenuimg.src='" + imgSrc + "';cssdropdown.dropmenuobj.style.visibility='hidden'";
        this.delayhide=setTimeout(cmd,this.disappeardelay); //hide menu

        /* F.N This code below will show the drop downs if IE 6.0 only */
        try {
            ToggleDropDowns('visible');
        }
        catch (err) {
            //do nothing
        }
    },
    
    swapimage:function(img, imgState)
    {
        img.src=this.getswapimagesrc(img, imgState);
    },

    // Given an image string, return the off/on state src.
    // ASSUME: the image name will be for the form *_[off | on].*
    getswapimagesrc:function(img, imgState)
    {
        var imgSrc = '';
        if (img != null)
        {
	        var imgStateOn = "_on.";
	        var imgStateOff = "_off.";
	        imgSrc = img.src;
	        var imgPathAndFileName = imgSrc.slice(0, imgSrc.lastIndexOf(".") + 1)
	        var imgFileExtension = imgSrc.slice(imgSrc.lastIndexOf(".") + 1, imgSrc.length);

	        if (imgPathAndFileName.indexOf(imgStateOn) > 0 && imgState == 'off')
	        {
		        imgSrc = imgPathAndFileName.slice(0, imgPathAndFileName.indexOf(imgStateOn)) + imgStateOff + imgFileExtension;
	        }
	        if (imgPathAndFileName.indexOf(imgStateOff) > 0 && imgState == 'on')
	        {
		        imgSrc = imgPathAndFileName.slice(0, imgPathAndFileName.indexOf(imgStateOff)) + imgStateOn + imgFileExtension;
	        }
        }
    	
	    return imgSrc;
    },

    clearhidemenu:function(){
        if (this.delayhide!="undefined")
            clearTimeout(this.delayhide)
    },

    startchrome:function(){
        for (var ids=0; ids<arguments.length; ids++){
        var menuitems=document.getElementById(arguments[ids]).getElementsByTagName("a")
        for (var i=0; i<menuitems.length; i++){
            if (menuitems[i].getAttribute("rel")){
                var relvalue=menuitems[i].getAttribute("rel");
                var imageID=menuitems[i].getAttribute("imgID");
                menuitems[i].onmouseover=function(e){
                    var event=typeof e!="undefined"? e : window.event
                    cssdropdown.dropit(this,event,this.getAttribute("rel"),this.getAttribute("imgID"))
                }
            }
        }
    }
    }
}

//Validate zipcode: Zip should have 5 numeric characters
function ValidateZip(zipTextbox)
{		
	//Check if zip code length is 5
	if(zipTextbox.value.length != 5)
	{
		return false;
	}				
	else			
	{
		//If zipcode length is 5, only allow 0-9 to be entered as the characters
		var checkOK = "0123456789";
		var allValid = true;
		for (var i=0; i < zipTextbox.value.length; i++) 
		{ 
			ch = zipTextbox.value.charAt(i);
			
			for (var j = 0;  j < checkOK.length;  j++)
			{							
				if (ch == checkOK.charAt(j))
					break;							
			}
			
			if (j == checkOK.length)
			{							
				allValid = false;
				break;
			}
		}
		if (!allValid) 
		{
			return false;
		}	
		else
		{
			return true;
		}						
	}
}
// This function will reset the information about
// the shopping cart in the header so that it is empty.
function ClearCartContents()
{
    try
    {
        document.all.ShoppingCartBubble_TotalItems_header.innerHTML = "0";
        document.all.ShoppingCartBubble_SubTotal_header.innerHTML = "$0.00";
    }
    catch (err)
    {
        // Do nothing - continue
    }
}        

/*
This function validates the form fields value.
*/
function ValidateFieldsSearch(absoluteURL,caller)
{
    //alert("ValidateFieldsSearch avec url : "+absoluteURL);
    var mf = GetMainFormName();
    if (mf==null) return;
    var skeywords = GetElementName("SearchKeywords",mf);
    if (skeywords!= null)
    {
      var fieldVal = "";
      var regExpr = "[a-z0-9& -]+";        
      var regExp = new RegExp(regExpr, "gi");
        
      fieldVal = document.forms[mf].elements[skeywords].value;
      //alert("fieldVal : "+fieldVal);
      if (fieldVal.length <= 0 || fieldVal.match(regExp) != fieldVal)        
      {
        //alert("The search field contains characters which are not allowed !");
        document.forms[mf].elements[skeywords].value="search";
        //alert("new value : "+document.forms[mf].elements[skeywords].value);
        //_SearchError_Class.ShowBubbleLostFocus(absoluteURL,document.forms[mf].elements[skeywords].value);
        _SearchError_Class.ShowBubbleLostFocus(absoluteURL,caller);
      }
      else
      {
        //alert("appel ShowBubbleLostFocus ");
        _SearchError_Class.ShowBubbleLostFocus(absoluteURL,caller);
      }
    }
}

function gosearchLostFocus(absoluteURL,caller)
{
    //alert("appel gosearchLostFocus avec caller : "+caller.value);
    //alert("appel gosearchLostFocus avec absoluteURL : "+absoluteURL);
    var mf = GetMainFormName();
    if (mf==null) return;
    var skeywords = GetElementName("SearchKeywords",mf);
    if (skeywords!= null)
    {
      var fieldVal = "";
      var regExpr = "[a-z -]+";        
      var regExp = new RegExp(regExpr, "gi");
        
      fieldVal = document.forms[mf].elements[skeywords].value;
      if (fieldVal.length <= 0 || fieldVal.match(regExp) != fieldVal)        
      {
        //alert("The search field contains characters which are not allowed !");
        //caller.value = "search";
        document.forms[mf].elements[skeywords].value="search";
        //_SearchError_Class.ShowBubbleLostFocus(absoluteURL,caller);
        _SearchError_Class.ShowBubbleLostFocus(absoluteURL,document.forms[mf].elements[skeywords].value);
      }
      else
      {
        //alert("appel ShowBubbleLostFocus avec caller : "+caller.value);
        //_SearchError_Class.ShowBubbleLostFocus(absoluteURL,caller);
        _SearchError_Class.ShowBubbleLostFocus(absoluteURL,caller);
      }            
    }
    
	//_SearchError_Class.ShowBubbleLostFocus(absoluteURL,caller);
}


function gosearch(absoluteURL)
{
	_SearchError_Class.ShowBubble(absoluteURL);
	
	/*var mf = GetMainFormName();		
	if (mf==null) return;
	var searchVal = document.forms[mf].elements["SearchKeywords"].value;
	searchVal = searchVal.toLowerCase();
	if (typeof(absoluteURL)!='undefined') {
	document.forms[mf].action=absoluteURL + "search/search.aspx?Search=" + searchVal;
	}
	else {
	document.forms[mf].action="search/search.aspx?Search=" + searchVal;
	}
	document.forms[mf].submit();*/
}	

function search_onfocus(el)
{
	var mf = GetMainFormName();
	if (mf==null) return;
	//el.value = '';
	document.forms[mf].target = "_top";
	document.forms[mf].action="search/search.aspx?Search=" + document.forms[mf].elements["SearchKeywords"].value;
}
function isEnter(e,absoluteURL)
{
	if (e.keyCode == 13)
	{		if (typeof(absoluteURL)!='undefined') {
		    gosearch(absoluteURL);
		   }
		   else {
		       gosearch();
		  }
	}	
	return true;
}

function isEnterLostFocus(e,absoluteURL,caller)
{
  //alert("function isEnterLostFocus");
	if (e.keyCode == 13)
	{
		  //alert("isEnterLostFocus avec entree");
			if (typeof(absoluteURL)!='undefined') 
	    {
	      //alert("appel gosearchLostFocus");
		    gosearchLostFocus(absoluteURL,caller);
		  }
		  else 
		  {
		    //alert("appel gosearch")
		    gosearch();
		  }
	}	
	return true;
}

var SUBMIT_ID='ctl00$ctl00$brandlayout0$ctl00$mainbody0$ctl00$ctl02$ctl00$ctl00$submit';
var SUBMIT_ID_STEP1_CHECKOUT="ctl00$ctl00$brandlayout0$ctl00$mainbody0$ctl00$ctl05$ctl00$ctl00$submit";

/*
This function submit the form when enter is pressed
*/
function SubmitForm_OnEnterPressed(e,buttonID) {
   if (e.keyCode == 13) {

          // var mf = GetMainFormName();
          //if (mf==null) return;
          //var _submitid=GetElementName(buttonID,mf);
          //__doPostBack(_submitid, '') ;
            __doPostBack(buttonID, '') ;
    }

}

/*
This function submit the form when enter is pressed and disable the submit 
*/
function SubmitFormDisableSubmit_OnEnterPressed(e,buttonID) {
   if (e.keyCode == 13) 
   {
			if(disableSubmit())
			{
				__doPostBack(buttonID, '') ;
			}
    }

}

function search_GoToURL(url)
{
	if (url!="") document.location.href= url;
}

//
// FLASH ACTIVATION
function CreateControl(DivID, CLSID, ObjectID, WIDTH, HEIGHT, URL, FLASHVARS, AUTOSTART,BGCOLOR)
{
  var d = document.getElementById(DivID);
  var objectTag = '<object classid=' + CLSID + ' id=' + ObjectID + ' width=' + WIDTH + ' height=' + HEIGHT +' codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,0,0">';
  objectTag = objectTag + '<param name="allowScriptAccess" value="sameDomain">';
  objectTag = objectTag + '<param name="movie" value=' + URL + '>'
  objectTag = objectTag + '<param name="FlashVars" value=' + FLASHVARS + '>';
  objectTag = objectTag + '<param name="quality" value="high">'  
  //objectTag = objectTag + '<param name="bgcolor" value="#000000">'  
  objectTag = objectTag + '<param name="bgcolor" value=' + BGCOLOR +'>'  
  objectTag = objectTag + '<param name="autoStart" value=' + AUTOSTART + '/>';
  objectTag = objectTag + '<embed src="' + URL + '" flashVars="' + FLASHVARS + '" quality="high" bgcolor="' + BGCOLOR + '"  width="' + WIDTH + '" height="' + HEIGHT +'" name="main" align="middle" allowscriptaccess="sameDomain" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer">';
  objectTag = objectTag + "</object>";
  d.innerHTML = objectTag;
}
				
function CreateTransparentControl(DivID, CLSID, ObjectID, WIDTH, HEIGHT, URL, FLASHVARS, AUTOSTART)
{
  var d = document.getElementById(DivID);
  var objectTag = '<object classid=' + CLSID + ' id=' + ObjectID + ' width=' + WIDTH + ' height=' + HEIGHT +' codebase="http://fpdownload.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,0,0">';
  objectTag = objectTag + '<param name="allowScriptAccess" value="sameDomain">';
  objectTag = objectTag + '<param name="movie" value=' + URL + '>'
  objectTag = objectTag + '<param name="FlashVars" value=' + FLASHVARS + '>';
  objectTag = objectTag + '<param name="quality" value="high">'  
  objectTag = objectTag + '<param name="autoStart" value=' + AUTOSTART + '/>';
  
  objectTag = objectTag + '<param name="wmode" value="transparent" />'
				
  objectTag = objectTag + '<embed wmode="transparent" src="' + URL + '" flashVars="' + FLASHVARS + '" quality="high" bgcolor="#000000" width="' + WIDTH + '" height="' + HEIGHT +'" name="main" align="middle" allowscriptaccess="sameDomain" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer">';
  objectTag = objectTag + "</object>";
  d.innerHTML = objectTag;
}

function swipeDown(menu, clipSize)
{
    var dropmenuobj = $get(menu);
    clipSize = parseInt(clipSize);
    if (clipSize < parseInt(dropmenuobj.offsetHeight)){
        clipSize+=10+(clipSize/10) //unclip drop down menu visibility gradually
        dropmenuobj.style.clip="rect(0 auto "+clipSize+"px 0)"
    }
    else
        return
    
    setTimeout("swipeDown('" + menu + "', '" + clipSize + "')", 10);
}

function swipeUp(menu, clipSize)
{
    var dropmenuobj = $get(menu);
    clipSize = parseInt(clipSize);
    if (clipSize > 0){
        clipSize -= 10+(clipSize/10) //unclip drop down menu visibility gradually
        dropmenuobj.style.clip="rect(0 auto "+clipSize+"px 0)"
    }
    else
        return
    
    setTimeout("swipeUp('" + menu + "', '" + clipSize + "')", 10);
}

function showFSBanner(menu, img, autoHide)
{
    var dropmenuobj = $get(menu);
    var dropmenuimg = $get(img);
    
    cssdropdown.dropmenuobj = dropmenuobj;
    cssdropdown.dropmenuimg = dropmenuimg;
        
    dropmenuobj.x=cssdropdown.getposOffset(dropmenuimg, "left");
    dropmenuobj.y=cssdropdown.getposOffset(dropmenuimg, "top");
    dropmenuobj.style.left=dropmenuobj.x-cssdropdown.clearbrowseredge(dropmenuobj.style, "rightedge")+"px";
    dropmenuobj.style.top=dropmenuobj.y-cssdropdown.clearbrowseredge(dropmenuobj.style, "bottomedge")+dropmenuimg.offsetHeight+1+"px";
    dropmenuobj.style.clip="rect(0 auto 0 0)"; //hide menu via clipping
    dropmenuobj.style.visibility="visible";
    swipeDown(menu, '0');
    if (autoHide != null)
    {
        setTimeout('swipeUp(\'' + menu + '\', \'' + dropmenuobj.offsetHeight + '\')', 10000);
    }
}

function hideFSBanner(menu)
{
    var dropmenuobj = $get(menu);    
    swipeUp(menu, dropmenuobj.offsetHeight);
}	


function getswapimagesrc(img, imgState)
{
    var imgSrc = '';
    if (img != null)
    {
        var imgStateOn = "_on.";
        var imgStateOff = "_off.";
        imgSrc = img.src;
        var imgPathAndFileName = imgSrc.slice(0, imgSrc.lastIndexOf(".") + 1).toLowerCase();
        var imgFileExtension = imgSrc.slice(imgSrc.lastIndexOf(".") + 1, imgSrc.length);

        if (imgPathAndFileName.indexOf(imgStateOn) > 0 && imgState == 'off')
        {
	        imgSrc = imgPathAndFileName.slice(0, imgPathAndFileName.indexOf(imgStateOn)) + imgStateOff + imgFileExtension;
        }
        if (imgPathAndFileName.indexOf(imgStateOff) > 0 && imgState == 'on')
        {
	        imgSrc = imgPathAndFileName.slice(0, imgPathAndFileName.indexOf(imgStateOff)) + imgStateOn + imgFileExtension;
        }
    }
	
    img.src = imgSrc;
}


function HideQuickShopiIcon() {

   try {
             _QuickShop_Class.Hide();
             }
        catch (err) {
        
        }   

}

/* 
 * Prevents user from entering more than specific number of characters in a textbox/textarea
 */
function LimitTextLength(textArea, maxLength)
{		
	if (maxLength == 0)
		maxLength = 150;

	if(textArea.value.length > maxLength )
	{		
		textArea.value = textArea.value.substring(0, maxLength);
		textArea.focus();
	}			
}	

function SwapVideo(videoPath){
    CreateTransparentControl("flashDiv",
        "clsid:d27cdb6e-ae6d-11cf-96b8-444553540000",
        "video", 
        "326", /*width*/ 
        "260", /*height*/
        videoPath,
        "",
        "1",
        "1");
}


/**
 * Function "fixPNG" is used to FIX the display of PNG in IE6 - standard version - (used for example on the "quick shop icon")
 * => Call on onload image : <img src="SOURCE" alt="" onload="fixPNG(this)" />
 */
function fixPNG(myImage) 
{
    //alert("fixPNG image : "+myImage);
		var arVersion = navigator.appVersion.split("MSIE")
		var version = parseFloat(arVersion[1]) 		
    
    if ((version >= 5.5) && (version < 7) && (document.body.filters)) 
    {
       //alert("avant fonction pour IE");
       var imgID = (myImage.id) ? "id='" + myImage.id + "' " : ""
                   var imgClass = (myImage.className) ? "class='" + myImage.className + "' " : ""
                   var imgTitle = (myImage.title) ? 
                                             "title='" + myImage.title  + "' " : "title='" + myImage.alt + "' "
                   var imgStyle = "display:inline-block;" + myImage.style.cssText
                   var strNewHTML = "<span " + imgID + imgClass + imgTitle
                  + " style=\"" + "width:" + myImage.width 
                  + "px; height:" + myImage.height 
                  + "px;" + imgStyle + ";"
                  + "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
                  + "(src=\'" + myImage.src + "\', sizingMethod='scale');\"></span>"
                   myImage.outerHTML = strNewHTML    
    }
}

/**
 * Function "fixAlignPNG" is used to FIX the display of PNG in IE6 with a specific alignement (used on "values-campaigns" page for example)
 * => Call on onload image : <img src="SOURCE" alt="" onload="fixAlignPNG(this,'left')" />
 * @author	Alsy
 */
function fixAlignPNG(myImage,myAlign) 
{
   	var arVersion = navigator.appVersion.split("MSIE")
		var version = parseFloat(arVersion[1])
     
    if ((version >= 5.5) && (version < 7) && (document.body.filters)) 
    {
       var imgID = (myImage.id) ? "id='" + myImage.id + "' " : ""
                   var imgClass = (myImage.className) ? "class='" + myImage.className + "' " : ""
                   var imgTitle = (myImage.title) ? 
                                             "title='" + myImage.title  + "' " : "title='" + myImage.alt + "' "
                   var imgStyle = "display:inline-block;" + myImage.style.cssText
                   var strNewHTML = "<img src=\"/images/_ww/_ww/common/pixel.gif\" align="+ myAlign+ " " + imgID + imgClass + imgTitle
                  + " style=\"" + "width:" + myImage.width 
                  + "px; height:" + myImage.height 
                  + "px;" + imgStyle + ";"
                  + "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
                  + "(src=\'" + myImage.src + "\', sizingMethod='scale');\" />"
                   myImage.outerHTML = strNewHTML    
    }
}

/**
 * Function "InitfixPNG" is used to FIX the display of PNG TABS on PRODUCT PAGE
 */
function InitfixPNG() 
{
	//if(navigator.appName == 'Microsoft Internet Explorer') {
	var arVersion = navigator.appVersion.split("MSIE");
	var version = parseFloat(arVersion[1]);
     
	if ((version >= 5.5) && (version < 7) && (document.body.filters)) 
	{
		var png = /\.png$/i;
		var imgs = $get('MoreDetailsTab').getElementsByTagName('img');
		for(var i = 0, l = imgs.length; i < l; i++) 
		{
			if(png.test(imgs.item(i).src)) 
			{
				imgs.item(i).style.width = imgs.item(i).offsetWidth;
				imgs.item(i).style.height = imgs.item(i).offsetHeight;
				imgs.item(i).style.filter = 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\'' + imgs.item(i).src + '\',sizingMethod=\'image\')';
				imgs.item(i).src = '/images/_ww/_ww/common/pixel.gif';
			}
		}
	}
}




/* 
 * look up address
 */
var AddressResultList;
function OnCompleteFuncName(AddResList)
{
//breakpoint
  AddressResultList = AddResList;
  DoDefaultWithoutEvent();     // stop the wait function

  if ((AddressResultList!=null)&&(AddressResultList.length>0))
  {
    var mf = GetMainFormName();
	  var btrefresh = document.getElementById("addressList");
	  
    if (AddressResultList.length ==1)
    {
      btrefresh.options.length = 0;
      var AddressResult = AddressResultList[0];   							        
      btrefresh = GetElementName("address_line1",mf);
      document.forms[mf].elements[btrefresh].value = AddressResult.Line1 + ' ' + AddressResult.Line2;
      btrefresh = GetElementName("address_line2",mf);
      document.forms[mf].elements[btrefresh].value = AddressResult.Line4;
      btrefresh = GetElementName("address_ext1",mf);
      document.forms[mf].elements[btrefresh].value = AddressResult.Line3;
      btrefresh = GetElementName("address_line3",mf);
      document.forms[mf].elements[btrefresh].value = AddressResult.Line5;
      btrefresh = GetElementName("address_city",mf);
      document.forms[mf].elements[btrefresh].value = AddressResult.City;
      btrefresh = GetElementName("address_country",mf);
      document.forms[mf].elements[btrefresh].value = AddressResult.Country;
      btrefresh = GetElementName("address_ext2",mf);
      document.forms[mf].elements[btrefresh].value = AddressResult.County;
      btrefresh = GetElementName("address_zip",mf);
      document.forms[mf].elements[btrefresh].value = AddressResult.PostCode;	
    }
    else
    {
      showHideQuickShopTip('QasSearch');
      btrefresh.style.visibility="visible";
      btrefresh.options.length = AddressResultList.length +1;
        
      for(i=0;i<AddressResultList.length;i++)
      {
        var AddressResult = AddressResultList[i];
        var optionElementName = "";
        if (AddressResult.Line1!=null)
        {
            optionElementName = optionElementName + AddressResult.Line1;
        }
        if (AddressResult.Line2!=null)
        {
            optionElementName = optionElementName + ","+AddressResult.Line2;
        }
        if (AddressResult.Line3!=null)
        {
            optionElementName = optionElementName + ","+AddressResult.Line3;
        }
        if (AddressResult.Line4!=null)
        {
            optionElementName = optionElementName + ","+AddressResult.Line4;
        }
        if (AddressResult.Line5!=null)
        {
            optionElementName = optionElementName + ","+AddressResult.Line5;
        }
        if (AddressResult.PostCode!="")
        {
            optionElementName = optionElementName + "," + AddressResult.PostCode;
        }
        if (AddressResult.City!="")
        {
            optionElementName = optionElementName + "," + AddressResult.City;
        }
        if (AddressResult.County!="")
        {
            optionElementName = optionElementName + ","+AddressResult.County;
        }
       
        var option = new Option(optionElementName,"",true,true);
        btrefresh.options[i]=option;
      }
      btrefresh.selectedIndex = -1;
    }
  }
  else 
  {
    alert("The postcode is invalid !");
  }
  return 1;
}

function GetAddress()
{
  DoWait();
    
  var mf = GetMainFormName();
  var btrefresh = GetElementName("search_zip",mf);
  
  if (btrefresh!=null)
  { 
    var postCode = document.forms[mf].elements[btrefresh].value;
    try
      {
      btrefresh = GetElementName("address_line1",mf);
      document.forms[mf].elements[btrefresh].value = "";
      btrefresh = GetElementName("address_line2",mf);
      document.forms[mf].elements[btrefresh].value = "";
      btrefresh = GetElementName("address_line3",mf);
      document.forms[mf].elements[btrefresh].value = "";
      btrefresh = GetElementName("address_ext1",mf);
      document.forms[mf].elements[btrefresh].value = "";
      btrefresh = GetElementName("address_city",mf);
      document.forms[mf].elements[btrefresh].value = "";
      btrefresh = GetElementName("address_country",mf);
      document.forms[mf].elements[btrefresh].value = "";
      btrefresh = GetElementName("address_ext2",mf);
      document.forms[mf].elements[btrefresh].value = "";
      btrefresh = GetElementName("address_zip",mf);
      document.forms[mf].elements[btrefresh].value = "";	
      btrefresh = document.getElementById("addressList");
      btrefresh.style.visibility="hidden";
      btrefresh.options.length = 0;
      
      MicrosoftFrance.MCS.Commerce.WS.AJAXProject.QAS_WebService.GetAddressFromPostCode(postCode,eval(OnCompleteFuncName));							      				
      }
    catch (e)  
    {
      alert( "error ="+e.message);
    }
  }                         
} 
function optionAddressChanged()
{
  var mf = GetMainFormName();
  var btrefresh = document.getElementById("addressList");
  var AddressResult = AddressResultList[btrefresh.selectedIndex];
  
  // building number
  btrefresh = GetElementName("address_line1",mf);
  if (AddressResult.Line1!=null)
  {
      document.forms[mf].elements[btrefresh].value = AddressResult.Line1;
  }
  //Building name
  if (AddressResult.Line2!=null)
  {
      document.forms[mf].elements[btrefresh].value += ' ' + AddressResult.Line2;
  }
  // comany name
  btrefresh = GetElementName("address_ext1",mf);
  if (AddressResult.Line3!=null)
  {
      document.forms[mf].elements[btrefresh].value = AddressResult.Line3;
  }
  //thoroughfare
  btrefresh = GetElementName("address_line2",mf);
  if (AddressResult.Line4 !=null)
  {
      document.forms[mf].elements[btrefresh].value = AddressResult.Line4;
  }
  //locality
  btrefresh = GetElementName("address_line3",mf);
  if (AddressResult.Line5 !=null)
  {
      document.forms[mf].elements[btrefresh].value =  AddressResult.Line5;
  }
  //city
  btrefresh = GetElementName("address_city",mf);
  if (AddressResult.City !=null)
  {
      document.forms[mf].elements[btrefresh].value = AddressResult.City;
  }
  //country
  btrefresh = GetElementName("address_country",mf);
  if (AddressResult.Country !=null)
  {
      document.forms[mf].elements[btrefresh].value = AddressResult.Country;
  }
  //county
  btrefresh = GetElementName("address_ext2",mf);
  if (AddressResult.County !=null)
  {
      document.forms[mf].elements[btrefresh].value = AddressResult.County;
  }
  //PostCode
  btrefresh = GetElementName("address_zip",mf);
  if (AddressResult.PostCode !=null)
  {
      document.forms[mf].elements[btrefresh].value = AddressResult.PostCode;
  }
}
       		    
/*
This function validates a form field.
field: the field to check.
errorMsg: the error message to show.
regExpr: the regular expression used to check the field.
*/
function ValidateField(field, errorMsg, regExpr, mandatory, fieldname)
{
  if ((field.value == null) || (field.value == ''))
  {
    if (mandatory == 'true')
    {
      alert("The "+fieldname +" field is mandatory");
      return false;
    }
    else
    {
      return true;
    }
  }
  
  if (field != null)
  {
    var fieldVal = "";        
    var regExp = new RegExp(regExpr, "gi");
        
    fieldVal = field.value;
    if (fieldVal.length <= 0 || fieldVal.match(regExp) != fieldVal)        
    {
      alert(errorMsg);
      return false;
    }
      return true;            
  }
  return false;
}

/*
This function validates the phone numbers fields.
*/
function ValidatePhoneNumber()
{
    var mf = GetMainFormName();
    var phoneName = GetElementName("phone",mf);
    var phone_extName = GetElementName("phone_ext",mf);
    
    if (document.forms[mf].elements[phoneName].value.length > 0)
    {
        if (ValidateField(document.forms[mf].elements[phoneName], 'The home phone number field contains characters which are not allowed !', "[a-z0-9 ]+"))
        {
            if (document.forms[mf].elements[phoneName].value.length > 15) 
            {
                alert('The phone is longer than 15 digits !');
                return false;
            }
        }
        else
            return false;
    }
    
    if (phone_extName != null)
    {
      if (document.forms[mf].elements[phone_extName].value.length > 0)
      {
        if (ValidateField(document.forms[mf].elements[phone_extName], 'The mobile phone field contains characters which are not allowed !', "[a-z0-9 ]+"))
        {        
            if (document.forms[mf].elements[phone_extName].value.length > 15)
            {
                alert('The mobile phone is longer than 15 digits !');
                return false;
            }
        }
        else
            return false;
        }
      }
    
    return true;
}

/*
This function validates the email fields.
*/
function ValidateEmail(emailField)
{
    var mf = GetMainFormName();
    var emailName = GetElementName(emailField,mf);

    if (document.forms[mf].elements[emailName].value.length > 0)
    {
        //if (ValidateField(document.forms[mf].elements[emailName], 'The email field contains characters which are not allowed !', "[a-z0-9_-]+\.[a-z0-9_-]+@[a-z0-9_-]+\.([a-z]{2,3})+\.([a-z]{2,3})$"))
        //if (ValidateField(document.forms[mf].elements[emailName], 'The email field contains characters which are not allowed !', "^[a-z0-9_-]+(\.[a-z0-9_-]+){0,4}@[a-z0-9_-]+\.([a-z]{2,3})(\.[a-z]{2,3})*$"))
        //if (ValidateField(document.forms[mf].elements[emailName], 'The email field contains characters which are not allowed !', "^[a-z]+([a-z0-9_-]+){0,}(\.[a-z]+([a-z0-9_-]+){0,}){0,4}@[a-z]+([a-z0-9_-]+){0,}\.([a-z]{2,3})(\.[a-z]{2,3})*$"))
        //if (ValidateField(document.forms[mf].elements[emailName], 'The email field contains characters which are not allowed !', "^[a-z]+([a-z0-9_-]+){0,}(\.[a-z]+([a-z0-9_-]+){0,}){0,4}@[a-z]+([a-z0-9_-]+){0,}(\.[a-z]+([a-z0-9_-]+){0,}){0,4}\.([a-z]{2,3})*$"))
        //if (ValidateField(document.forms[mf].elements[emailName], 'The email field contains characters which are not allowed !', "^[a-z]+([a-z0-9_-]+){0,}(\.[a-z]+([a-z0-9_-]+){0,}){0,4}@([a-z0-9_-]+){0,}(\.([a-z0-9_-]+){0,}){0,4}\.([a-z]{2,3})*$"))
        if (ValidateField(document.forms[mf].elements[emailName], 'Please enter a valid email address.', "[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?"))
            return true;
        else
            return false;
    }
    else
    {
      alert("The email field is mandatory");
      return false;
    }
  
    return true;
}

/*
This function validates the email fields.
*/
function ValidatePassword(passwordField)
{
    //alert("appel ValidatePassword avec :"+passwordField);
    var mf = GetMainFormName();
    var passwordName = GetElementName(passwordField,mf);
  
    if (passwordName != null)
    {
      if (document.forms[mf].elements[passwordName].value.length > 0)
      {
          if (ValidateField(document.forms[mf].elements[passwordName], 'The password field contains characters which are not allowed !', "[a-z0-9\"\[!#$%&'()*+-./:;<=>?@^_‘{|}~]+"))
              return true;
          else
              return false;
      }
    }
    
    return true;
}

/*
This function indicates whether the terms and conditions check box is checked.
field: the field to check.
errorMsg: the error message to show.
*/
function TermsAndConditionsIsChecked(field, errorMsg)
{
    if (!field.checked)
    {
        alert(errorMsg);
        return false;
    }
    
    return true;
}

/*
This method checks whether the given field is not empty.
field: the field to check.
errorMsg: the error message to show.
*/
function FieldIsNotEmpty(field, errorMsg)
{
    if (field.value.length <= 0)
    {
        alert(errorMsg);
        return false;
    }
    
    return true;
}

/*
This function disable the action if it has already been submitted
*/
function disableSubmit(){
if(submitted){ alert("Your request has already been submitted."); return false; }
submitted = true;
return true;
}

/*
This function checks if the submit can be done and disable it if it has already been submit
*/
function CheckSubmit()
{
	if(submitEnabled == true)
	{
		return disableSubmit();
	}
	else
	{
		return false;
	}
}

/*
This function validates the form fields value.
*/
function ValidateFieldsCheckout()
{
    //alert("alert ValidateFieldsCheckout");
    var mf = GetMainFormName();
    var fnameName = GetElementName("fname",mf);
    var lnameName = GetElementName("lname",mf);
    var address_line1Name = GetElementName("address_line1",mf);
    var address_ext1Name = GetElementName("address_ext1",mf);
    var address_line2Name = GetElementName("address_line2",mf);
    var address_line3Name = GetElementName("address_line3",mf);
    var address_cityName = GetElementName("address_city", mf);
    var address_countyName = GetElementName("address_ext2", mf);
    var address_zipName = GetElementName("address_zip", mf);
    var emailField = "email";
    var passwordField = "password";
        
    if (
        ValidateField(document.forms[mf].elements[fnameName], 'The first name field contains characters which are not allowed !', "^[a-z0-9 '-]+$")
        && ValidateField(document.forms[mf].elements[lnameName], 'The last name field contains characters which are not allowed !', "^[a-z0-9 '-]+$")
        && ValidateField(document.forms[mf].elements[address_line1Name], 'The house name/number field contains characters which are not allowed !', "^[a-z0-9 '-]+$")
        && ValidateField(document.forms[mf].elements[address_ext1Name], 'The company name field contains characters which are not allowed !', "^[a-z0-9 '-]+$")
        && ValidateField(document.forms[mf].elements[address_line2Name], 'The address1 field contains characters which are not allowed !', "^[a-z0-9 '-]+$")
        && ValidateField(document.forms[mf].elements[address_line3Name], 'The address2 field contains characters which are not allowed !', "^[a-z0-9 '-]+$")
        && ValidateField(document.forms[mf].elements[address_cityName], 'The city field contains characters which are not allowed !', "^[a-z0-9 '-]+$")
        && ValidateField(document.forms[mf].elements[address_countyName], 'The county field contains characters which are not allowed !', "^[a-z0-9 '-]+$", "true", "County")
        && ValidateField(document.forms[mf].elements[address_zipName], 'Post code entered is invalid !', "^[a-z0-9 ]+$")
        && ValidatePhoneNumber()
        && ValidateEmail(emailField)
        && ValidatePassword(passwordField)
        )
    {
		  /*if(submitEnabled == true)
		  {
			  return true;
			  //return disableSubmit();
		  }
		  else
		  {
			  return false;
		  }*/
		return CheckSubmit();
    }
    
    return false;
}
function ValidateTermsAndConditions()
{
  var mf = GetMainFormName();
  var ep1cbTermAgreementName = GetElementName("ep1cbTermAgreement", mf);
  
  if (TermsAndConditionsIsChecked(document.forms[mf].elements[ep1cbTermAgreementName], 'Please confirm you have read, understood and agree to the terms & conditions and the privacy policy before proceeding.'))
    {
        return true;
    }
    
    return false;
}


function checkValidLyb(myLyb,mypath)
{
	//alert("alert checkValidLyb");
  var mf = GetMainFormName();
	if (mf==null) return;

  var lyb = GetElementName("ep0itMemberCardNumber",mf);
  var ep0cbLYBMember = GetElementName("ep0cbLYBMember",mf);
 
  document.forms[mf].elements[ep0cbLYBMember].checked = false;
  
  if (lyb != null)
  {
    if ( ValidateField(document.forms[mf].elements[lyb], 'The LYB number field contains characters which are not allowed (only 9 digit) !', "^[0-9]{9}") )
    {
      lybvalue = document.forms[mf].elements[lyb].value;
      if (lybvalue.length > 0)
      {
          if (	(lybvalue.length!=9) || ((lybvalue.substring(0,1)!="6") && (lybvalue.substring(0,1)!="7") && (lybvalue.substring(0,1)!="8") && (lybvalue.substring(0,1)!="9"))	)
          {
            alert("You have entered an invalid Love Your Body ™ number, please correct your entry.");
            return false;
          }
          else 
          { 
	          //check if this LYB number is not already registered into the database
	          var ok = false;
	          new Ajax.Request(mypath + lybvalue, 
					          {
						          asynchronous: false,
						          method: 'post',
						          postBody: '',
						          onSuccess: function(request) 
						          {
							          var rep = request.responseText;																		
        								
							          if(rep.indexOf("true") != -1)
							          {
								          ok = true;
										  document.forms[mf].elements[ep0cbLYBMember].checked = true;
							          }
							          else
							          {
								          alert("LYB number already registered");										
							          }
						          },
						          onFailure: function(requester){alert('Error during the query !');},
						          on404: function(requester){alert('Error 404 : File not found !');}
					          }
					          );
	           return ok;
          }
      }
      else
      {
        return true;
      }    
    }
    else
    {
      return false;
    }
  }

//return true;
}

/*
This function indicates whether any communications option check box are checked.
fieldx: the field to check.
errorMsg: the error message to show.
*/
function ComOptionIsChecked(field1, field2, field3, field4, errorMsg)
{
    
  if ( (!field1.checked) && (!field2.checked) && (!field3.checked) && (!field4.checked) )
  {
      ShowModalPopUp('CommOption');
  }
  else
  {
      return true;
  }
    
    /*
    else
    {
      if ( (field1.checked) && (!field2.checked) && (!field3.checked) && (!field4.checked) )
      {
        alert(errorMsg);
        return false;
      }
    }
    */
}

function ShowModalPopUp(popUpControlId)
{
  _CoreModalPopUp._PopupControlID = popUpControlId;
	_CoreModalPopUp.ShowModal();
}

function ValidateCommOption(myLyb,mypath,mypage)
{
  //alert("appel ValidateCommOption");
  var mf = GetMainFormName();
  var edithiddenName = GetElementName("edithidden", mf);

  if (document.forms[mf].elements[edithiddenName].value.length == 0)
  {
    var ep0cboptinemailName = GetElementName("ep0cboptinemail", mf);
    var ep0cboptinpostName = GetElementName("ep0cboptinpost", mf);
    var ep0cboptinphoneName = GetElementName("ep0cboptinphone", mf);
    var ep0cboptinsmsName = GetElementName("ep0cboptinsms", mf);
    
    if ( (!document.forms[mf].elements[ep0cboptinemailName].checked) && (!document.forms[mf].elements[ep0cboptinpostName].checked) && (!document.forms[mf].elements[ep0cboptinphoneName].checked) && (!document.forms[mf].elements[ep0cboptinsmsName].checked) )
    {
        ShowModalPopUp('CommOption');
        return false; 
    }
    else
    {		
		if(mypage != "index_payment")
		{
			if(validglobalregister(myLyb,mypath) == true)
			{
				return true;
			}
			else
			{
				return false;
			}
		}
		else
		{
		    return CheckSubmit();
		}		
    }
  }
  else
  {
      if (document.forms[mf].elements[edithiddenName].value == "true")
      { 
		if(mypage != "index_payment")
		{
			if(validglobalregister(myLyb,mypath) == true)
			{
				return true;
			}
			else
			{
				return false;
			}
		}
		else
		{
		    return CheckSubmit();
		}
      }
      else
      {
        document.forms[mf].elements[edithiddenName].value = "";
        return false;
      }
  }
}

function validglobalregister(myLyb,mypath)
{
  //alert("appel validglobalregister"); 
  //return (checkValidLyb(myLyb,mypath) && ValidateTermsAndConditions() && ValidateFieldsCheckout());
  return (checkValidLyb(myLyb,mypath) && ValidateFieldsCheckout());
}

function showHideQuickShopTip(divObj)
{
  _CoreModalPopUp._PopupControlID = divObj;
  _CoreModalPopUp.ShowModal();
}

function ConvertExpirationDate(inputdate)
{
  //var d=new Date("@@Container_Member.ExpirationDate@@");
  var d=new Date(inputdate);
  //alert("d : "+d);
  var mylocaldate=d.toLocaleString();
  //alert("mylocaldate : "+mylocaldate);
  if (mylocaldate.indexOf(" ") != -1)
  {
    var my_date=mylocaldate.split(" ");
    mymonth=my_date[1];
  }
  var myday=d.getDate();
  var myyear=d.getYear();

  var date=myday+" "+mymonth+" "+myyear; 
  document.write(date);
}

/*
Theses functions (GoToPage, SetItemStart, SetPageIndex, DisplayPageNumber) are used for the pagination in the loyalty pages.
*/
function GoToPage(Index, ItemsMax)
{
  //alert("GoToPage avec index : " + Index + " / ItemMAx : " + ItemsMax);
  var mf = GetMainFormName();
  if (mf==null) return;

  SetPageIndex(mf, Index);
  //SetItemStart(mf, Index, ItemsMax);
  
  //alert("GoToPage : " + Index);
  //ResetTestGroupName(mf);	

  //document.forms[mf].submit();
  var start = ((Index - 1) * ItemsMax) + 1;
  var num = document.location.href.indexOf('?');
  var url;
  if(num == -1)
  {
	url = document.location.href + "?ItemStart="  + start + "&currentIndex=" + Index;
  }
  else
  {
    url = document.location.href.substring(0,num) + "?ItemStart="  + start + "&currentIndex=" + Index;
  }
  document.location.href = url ;
  
}

/*
This function is used for updated the control concerning the parameter ItemStart.
*/
function SetItemStart(mf, Index, itemsCount)
{
  //alert("SetItemStart avec index : " + Index + " / ItemMAx : " + itemsCount);
  var mf = GetMainFormName();
	var indexCtrl = GetElementName("ItemStart",mf);
	//alert("SetItemStart indexCtrl : " + indexCtrl);
	if (indexCtrl!= null)
		document.forms[mf].elements[indexCtrl].value = ((Index - 1) * itemsCount) + 1 ;
	//alert("Hiden_ItemStart = " + document.forms[mf].elements[indexCtrl].value);
}

/*
This function is used for updated the control concerning the parameter SelectedIndex.
*/
function SetPageIndex(mf, Index)
{
  //alert("SetPageIndex avec index : " + Index);
	var indexCtrl = GetElementName("SelectedIndex",mf);
	if (indexCtrl!= null)
		document.forms[mf].elements[indexCtrl].value = Index;
	//alert("Hiden_PageIndex = " + document.forms[mf].elements[indexCtrl].value);
}

/*
This function is used for write the pagination.
*/
function DisplayPageNumber(ItemsTotalCount, ItemsMax, currentIndex)
{
  //alert("DisplayPageNumber avec ItemsTotalCount : " + ItemsTotalCount + " / ItemMAx : " + ItemsMax);
  var custUserTotalCount = ItemsTotalCount;
  var i = 1;
  //var currentIndex = 1;
  var mf = GetMainFormName();
  if (mf==null) return;
  var indexCtrl = GetElementName("SelectedIndex",mf);
  //alert("indexCtrl : "+indexCtrl);
  //var custUserItemsMax = document.forms[mf].elements[indexCtrl].value;
  //alert("custUserItemsMax : "+custUserItemsMax);

  /*if (custUserItemsMax != 0)
  {
    currentIndex = 0;
  }
  else
  {    
    if (indexCtrl!= null)
    {
      currentIndex = document.forms[mf].elements[indexCtrl].value;
    }
  }*/
  if(currentIndex==null || currentIndex== '')
  {
	currentIndex = 1;
  }
  //alert("currentIndex : "+currentIndex);

  for (i; i <  (custUserTotalCount / ItemsMax) + 1; i++)
  {
    //alert("I = "+i);
    /*if (i == custUserItemsMax)
    {
      //alert("i == custUserItemsMax");
      document.write("<font size=2px color=#74bf02> | </font><font size=2px> <b>" + i + "</b></font>");
    }
    else*/ if (i == currentIndex)
         {
           //alert("I == currentIndex");
           document.write("<font size=2px color=#74bf02> | </font><font size=2px><b>" + i + "</b></font>");
         }
         else
         {
           //alert("I = autre");
           document.write("<font size=2px color=#74bf02> | </font><a href=\"#\" onclick=\"GoToPage(" + i + ',' + ItemsMax +");\"><font size=2px color=#74bf02>" + i + "</font></a>");
         }
  }
  document.write("<font size=2px color=#74bf02> | </font>");
}

//To upper a string for coremetrics
function ToUpperCM(input)
{
  if(input)
  {
	  input = input.replace(/([àáâãäåāăæ])/, 'a');
	  input = input.replace(/([çćĉċ])/, 'c');
	  input = input.replace(/([èéêë])/, 'e');
	  input = input.replace(/([ìíîï])/, 'i');
	  input = input.replace(/([ñ])/, 'n');
	  input = input.replace(/([òóôõö])/, 'o');
	  input = input.replace(/([ùúûü])/, 'u');
	  input = input.replace(/([ýÿ])/, 'y');
    input = input.toUpperCase();
  }
  return input;
}

function ActiveButtonSubmit(e,idboutton)
  {
    if (e.keyCode == 13)
    {
      var monParent = document.getElementById(idboutton);
      var monLien = monParent.childNodes[0];
      if (monLien !=null)
      {
        monLien.click();
      }
    }
  }
  function ActiveButtonSubmit_bis(e,idboutton,indice)
  {
    if (e.keyCode == 13)
    {
      var monParent = document.getElementById(idboutton);
      var monLien = monParent.childNodes[indice];
      if (monLien !=null)
      {
        monLien.click();
      }
    }
  }
  

/**
 * Function "ActiveBtnHref" is used for the onKeyPress event on input type text element
 * => Check if the event MyEvent keycode is the ENTER key (13)
 * => If yes, redirection on the href <a> element contained in the element ID MyID
 *
 * @param  	MyEvent		The event generated on the onKeyPress 
 * @param  	MyID			The ID of the <a> container to find
 * @return	false if the event key was ENTER
 * @author	Alsy
 */
function ActiveBtnHref(MyEvent,MyID)
{
	if (MyEvent.keyCode == 13)
	{
		document.location.href = document.getElementById(MyID).getElementsByTagName('a')[0].href;
	  return false;
	}
	return true;
}


/**
 * Function "SetCookie"
 *
 * @param  	name			The name of the cookie 
 * @param  	value			The value of the cookie
 */
function SetCookie(name, value)
{
	var argv=SetCookie.arguments;
	var argc=SetCookie.arguments.length;
	var expires=(argc > 2) ? argv[2] : null;
	var path=(argc > 3) ? argv[3] : null;
	var domain=(argc > 4) ? argv[4] : null;
	var secure=(argc > 5) ? argv[5] : false;
	document.cookie=name+"="+escape(value)+
	((expires==null) ? "" : ("; expires="+expires.toGMTString()))+
	((path==null) ? "" : ("; path="+path))+
	((domain==null) ? "" : ("; domain="+domain))+
	((secure==true) ? "; secure" : "");
}

/**
 * Function "getCookieVal" and "ReadCookie"
 *
 * @param  	name			The name of the cookie 
 * @return	value			The value of the cookie if name cookie exist (or null)
 */
function getCookieVal(offset)
{
	var endstr=document.cookie.indexOf (";", offset);
	if (endstr==-1) endstr=document.cookie.length;
	return unescape(document.cookie.substring(offset, endstr));
}

function ReadCookie(name)
{
	var arg=name+"=";
	var alen=arg.length;
	var clen=document.cookie.length;
	var i=0;
	while (i<clen)
	{
		var j=i+alen;
		if (document.cookie.substring(i, j)==arg) return getCookieVal(j);
		i=document.cookie.indexOf(" ",i)+1;
		if (i==0) break;
	}
	return null;
}

(function($){

/* [Bof new "order by"/"pagination" treatment on the "/_en/_gb/catalog/list.aspx" page // Added on 2010.11.02 // s.lassausse and o.billioque */
/*******************************************************************************************/	
// jquery.pajinate.js - version 0.2
// A jQuery plugin for paginating through any number of DOM elements
// 
// Copyright (c) 2010, Wes Nolte (http://wesnolte.com)
// Liscensed under the MIT License (MIT-LICENSE.txt)
// http://www.opensource.org/licenses/mit-license.php
// Created: 2010-04-16 | Updated: 2010-04-26
/*******************************************************************************************/

	$.fn.pajinate = function(options){
		// Set some state information
		var current_page = 'current_page';
		var items_per_page = 'items_per_page';
		
		var meta;
	
		// Setup default option values
		var defaults = {
			item_container_id : '.content',
			items_per_page : 12,			
			nav_panel_id : '.page_navigation',
			num_page_links_to_display : 20,			
			start_page : 0,
			nav_label_first : 'First',
			nav_label_prev : 'Prev',
			nav_label_next : 'Next',
			nav_label_last : 'Last',
			page_current : 1
		};
		var options = $.extend(defaults,options);
		var $item_container;
		var $page_container;
		var $items;
		var $nav_panels;
	
		return this.each(function(){
			$page_container = $(this);
			$item_container = $(this).find(options.item_container_id);
			$items = $page_container.find(options.item_container_id).children();
			meta = $page_container;
			
			// Initialise meta data
			meta.data(current_page,0);
			meta.data(items_per_page, options.items_per_page);
					
			// Get the total number of items
			var total_items = $item_container.children().size();
			
			// Calculate the number of pages needed
			var number_of_pages = Math.ceil(total_items/options.items_per_page);
			
			var navigation_html = '<span>Page &nbsp;</span>';
			var current_link = 0;
			while(number_of_pages > current_link){
				navigation_html += '<a class="page_link AGrey11pxB" href="" longdesc="' + current_link +'">|&nbsp;'+ (current_link + 1) +'&nbsp;</a>';
				current_link++;
			}
			navigation_html += '<a class="display_all" style="cursor:pointer;">|&nbsp;see all</a>';
			
			// if (!$page_container.find(options.nav_panel_id).chlidren().hasClass('active')) {
				navigation_html += '<span class="displayOf">&nbsp;-&nbsp;';
				navigation_html += options.page_current;
				navigation_html += '&nbsp;of&nbsp;';
				navigation_html += number_of_pages;
				navigation_html += '&nbsp;displayed.&nbsp;</span>';
			// }

			// And add it to the appropriate area of the DOM	
			$nav_panels = $page_container.find(options.nav_panel_id);			
			$nav_panels.html(navigation_html).each(function(){
			
				$(this).find('.page_link:first').addClass('first');
				$(this).find('.page_link:last').addClass('last');
				
			});
			
			// Hide the more/less indicators
			// $nav_panels.children('.ellipse').hide();
			
			// Set the active page link styling
			// $nav_panels.find('.previous_link').next().next().addClass('active_page');
			
			/* Setup Page Display */
			// And hide all pages
			$items.hide();
			// Show the first page			
			$items.slice(0, meta.data(items_per_page)).show();

			/* Setup Nav Menu Display */
			// Page number slices
			
			var total_page_no_links = $page_container.children(options.nav_panel_id+':first').children('.page_link').size();
			options.num_page_links_to_display = Math.min(options.num_page_links_to_display,total_page_no_links);
			
			// And only show the number we should be seeing
			$nav_panels.each(function(){
				$(this).children('.page_link').slice(0, options.num_page_links_to_display).show();			
			});
			
			/* Bind the actions to their respective links */
			
			// Event handler for each 'Page' link
			$page_container.find('.page_link').click(function(e){
				e.preventDefault();
				goto($(this).attr('longdesc'), number_of_pages);
			});
			
			$page_container.find('.display_all').click(function(e){
				e.preventDefault();
				displayItemAll();
			});	
			
			// Goto the required page
			goto(parseInt(options.start_page), number_of_pages);
			
		});
			
		function goto(page_num, number_of_pages){
			
			var ipp = meta.data(items_per_page);
			
			var isLastPage = false;
			
			// Find the start of the next slice
			start_from = page_num * ipp;
			
			// Find the end of the next slice
			end_on = start_from + ipp;
			// Hide the current page	
			$items.hide()
					.slice(start_from, end_on)
					.show();
			
			$page_container.find(options.nav_panel_id).children('.active_page').removeClass('active_page AGreen11pxR').addClass('AGrey11pxB');
					
			// Reassign the active class
			$page_container.find(options.nav_panel_id).children('.page_link[longdesc=' + page_num +']').addClass('active_page AGreen11pxR')
													 .siblings('.active_page')
													 .removeClass('active_page');
			
			//  1 of 2 displayed.
			if ($(".page_navigation").children().hasClass('displayOf')) {
				$page_container.find(options.nav_panel_id).children('.displayOf').html('<span class="displayOf">&nbsp;-&nbsp;'+(parseFloat($('.page_link.active_page').attr('longdesc'))+1)+'&nbsp;of&nbsp;'+number_of_pages+'&nbsp;displayed.&nbsp;</span>')
			}
			else {
				$page_container.find(options.nav_panel_id).append('<span class="displayOf">&nbsp;-&nbsp;'+(parseFloat($('.page_link.active_page').attr('longdesc'))+1)+'&nbsp;of&nbsp;'+number_of_pages+'&nbsp;displayed.&nbsp;</span>');
			}		 
			
			// Set the current page meta data							
			meta.data(current_page,page_num);
			
			// Hide the more and/or less indicators
		};
		function displayItemAll() {
			$page_container.find(options.nav_panel_id).children('.active_page').removeClass('active_page AGreen11pxR').addClass('AGrey11pxB');
			$items.hide().show();
			$page_container.find(options.nav_panel_id).children('.display_all').addClass('active_page AGreen11pxR');
			$page_container.find(options.nav_panel_id).children('.displayOf').remove();
		}
		
	};
	
	jQuery.format = function(source, params) {
		if (arguments.length == 1)
			return function() {
				var args = jQuery.makeArray(arguments);
				args.unshift(source);
				return jQuery.validator.format.apply(this, args);
			};
		if (arguments.length > 2 && params.constructor != Array) {
			params = jQuery.makeArray(arguments).slice(1);
		}
		if (params.constructor != Array) {
			params = [params];
		}

		jQuery.each(params, function(i, n) {
			source = source.replace(new RegExp("\\{" + i + "\\}", "g"), n);
		});
		return source;
	};
	
})(jQuery);

var Loreal = Loreal || {};
$.extend(Loreal, {
	sortByPriceAsc: function () {
    Loreal.sortPaging('a.paging_price_asc', Loreal.sortPriceAsc);
    return false;
  },
  sortByPriceDesc: function () {
    Loreal.sortPaging('a.paging_price_desc', Loreal.sortPriceDesc);
    return false;
  },
  sortByNameAsc: function () {
    Loreal.sortPaging('a.paging_name_asc', Loreal.sortNameAsc);
    return false;
  },
  sortByNameDesc: function () {
    Loreal.sortPaging('a.paging_name_desc', Loreal.sortNameDesc);
    return false;
  },
  sortByBestSellerAsc: function () {
    Loreal.sortPaging('a.paging_best_seller_asc', Loreal.sortBestSellerAsc);
    return false;
  },
  sortPaging: function (element, sortfunc) {
    var $pageselect = $("a[id^='pagingpage'].selected_sort_page_link");
    $("#body_sort_paging a").removeClass("selected_sort_page_link");
    $(element).blur().addClass("selected_sort_page_link");
    var mylist = $("#content_item_product_list");
	  mylist.find("body_content_item").show();
    var listitems = mylist.find(".body_content_item").removeClass("body_content_item_spacer");
    listitems.sort(sortfunc); //Sort table
    $.each(listitems, function (index, item) { mylist.append(item); }); //Append new sort
    if ($("#pagingseeall:visible").length) {
      $pageselect.click();
    }
    $('#pageMAIN').pajinate();
  },
  sortPriceAsc: function (a, b) {
    var compA = Loreal.getPrice(a);
    var compB = Loreal.getPrice(b);
    return (compA < compB) ? -1 : (compA > compB) ? 1 : 0;
  },
  sortPriceDesc: function (a, b) {
    var compA = Loreal.getPrice(a);
    var compB = Loreal.getPrice(b);
    return (compA < compB) ? 1 : (compA > compB) ? -1 : 0;
  },
  sortNameAsc: function (a, b) {
    var compA = Loreal.getName(a);
    var compB = Loreal.getName(b);
    return (compA < compB) ? -1 : (compA > compB) ? 1 : 0;
  },
  sortNameDesc: function (a, b) {
    var compA = Loreal.getName(a);
    var compB = Loreal.getName(b);
    return (compA < compB) ? 1 : (compA > compB) ? -1 : 0;
  },
  sortBestSellerAsc: function (a, b) {
    var compA = Loreal.getBestSeller(a);
    var compB = Loreal.getBestSeller(b);
    return (compA < compB) ? -1 : (compA > compB) ? 1 : 0;
  },
  getBestSeller: function (element) {
  	var $bestSeller = $(element).find("input:hidden").val().replace(" ", "").replace(",", ".");
  	if ($bestSeller == "") {
  		$bestSeller = 999;
  	}
    return $bestSeller;
  },
  getPrice: function (element) {
    var $element = $(element);
    var $price = $element.find(".product_amount_new");
    if ($price.length == 0) {
      $price = $element.find(".product_amount");
    }
    return parseFloat($price.text().replace("£", "").replace(" ", "").replace(",", "."));
  },
  getName: function (element) {
    return $(element).find("a.AGreen11pxB").text().toLowerCase().replace('"', "");
  },
 
//Manage giftWrapping 
  
  maxLength: function () {
    var $this = $(this);
    var max = parseInt("255");
    var originalVal = $this.val();
    var val = originalVal.replace(/\^+/g, ""); //Remove ' ^ ' character.
    if (val.length > max) {
		val = val.substr(0, max);
    }

    if (originalVal != val) {
      var scrollTop = $this.attr("scrollTop"); //Save scroll bar position
      var selectionStart = $this.attr("selectionStart"); //Save selection start
      var selectionEnd = $this.attr("selectionEnd"); //Save selection end
      $this.val(val);
      $this.attr("scrollTop", scrollTop);  //Set old scroll bar position
      $this.attr("selectionStart", selectionStart);  //Set old selection start
      $this.attr("selectionEnd", selectionEnd);  //Set old selection end
    }

    var text = $.format("{0} characters remaining.", max - $this.val().length);
    $("#length_left").html(text);

  },

  addGiftWrapping: function () {
    $("#giftwrappingerror").hide();
    $("#giftwrappingload").hide();
    var $giftwrap = $("INPUT[type=radio][name=giftwrap]:checked");
    var from = encodeURIComponent($("#giftwrapfrom").val());
    var to = encodeURIComponent($("#giftwrapto").val());
    var message = encodeURIComponent($("#giftwrapmessage").val());

    if ($giftwrap.length) {
      if ($giftwrap.val() == Basket.specialvarcode.giftmsg) {
        if (from.replace("%20", "") != "" && to.replace("%20", "") != "" && message.replace("%20", "") != "") {
          var code = encodeURIComponent($giftwrap.val());
          var url = $.format("/_en/_gb/ajax/giftwrapping.aspx?action=add&code={0}&from={1}&to={2}&message={3}", code, from, to, message);
          $("#giftwrappingload").load(url, Loreal.addGiftWrappingOK);
        }
        else {
          $("#giftwrappingerror").show();
        }
      } else {
        var code = encodeURIComponent($giftwrap.val());
        var url = $.format("/_en/_gb/ajax/giftwrapping.aspx?action=add&code={0}&from={1}&to={2}&message={3}", code, from, to, message);
        $("#giftwrappingload").load(url, Loreal.addGiftWrappingOK);
      }
    } else {
      $("#giftwrappingerror").show();
    }
    return false;
  },

  removeGiftWrapping: function () {
    $.get("/_en/_gb/ajax/giftwrapping.aspx?action=remove", Loreal.removeGiftWrappingOK);
    return false;

  },

  addGiftWrappingOK: function () {
    if ($("#addgiftwrapsuccess").length) {
		window.location.reload();
    }
    else {
      $("#giftwrappingload").show();
    }
  },
  
  removeGiftWrappingOK: function () {
	  window.location.reload();
  },
  
  closeGiftWrapping: function () {
    _CoreModalPopUp.Hide();
    return false;
  }


});

$(document).ready(function() {
  /*[Search #pagename] => to find which page the customer browse, and which JavaScript need to be executed => need to integrate on the HTML page (see example on index_basket_browse.html page) : <input type="hidden" value="@@@pagename@@@" id="pagename" /> */
  if( $("#pagename").length>0 ) {
   var isPage = $("#pagename").val().toLowerCase().replace(".aspx", "");
  }
  /*[/Search #pagename]*/

  /*Current page : index_basket_browse.html*/
  if (isPage == "index_basket_browse"){
    /* load popin gift wrap info*/
    $("#load_gift_popin").click(function (e) {
      e.preventDefault();
      showHideQuickShopTip('giftwrappinglayout');
      $("#addgiftwrapping").click(Loreal.addGiftWrapping);
      $("#giftwrapmessage").keyup(Loreal.maxLength);
      Loreal.maxLength.apply($("#giftwrapmessage"));
      $("#giftwrappinglayout .closeBtn").click(function () {
        _CoreModalPopUp.Hide();
      });
      return false;
    });

    $("#removegiftwrapping").click(Loreal.removeGiftWrapping);

    //When a basket contains at least 1 product whose extended property IsGiftWrap=0, then add gift wrap link display none
    //If user have already gift wrap in his basket and then add a product IsGiftWrap=0, then we remove the gift wrap using JS
    //Per default, the wrap options checked is the JS value of Basket.specialvarcode.giftmsg (define in page \_en\_gb\checkout\index_basket_browse.html)
    var displayGiftWrap = true;
    var isGiftWrapInBasket =  $("#jslinegiftoption").length > 0 ? true : false ;
    $("input[id*='isGiftWrap_']").each(function () {
      if (($(this).val() != "") && ($(this).val() == 0)) {
        displayGiftWrap = false;
      }
    });
    if(!isGiftWrapInBasket){
      if (!displayGiftWrap) {
        $("#giftw").css("display", "none");
      } else {
        $("#giftw").css("display", "block");
         $("input[value='" + Basket.specialvarcode.giftmsg + "']").attr("checked","checked");
      }
    } else if (isGiftWrapInBasket && !displayGiftWrap){
      $("#removegiftwrapping").click();
    }

  }

	
	
});
//$(Loreal.onReady);
/* [/Eof new "order by"/"pagination" treatment on the "/_en/_gb/catalog/list.aspx" page // Added on 2010.11.02 // s.lassausse and o.billioque */
