

var ns4 = (document.layers);
var ie4 = (document.all && !document.getElementById);
var ie5 = (document.all && document.getElementById);
var ns6 = (!document.all && document.getElementById);

// HD0079217: Empêcher une action lors de l'appuie de la touche ENTER si aucun focus
var isEnterPressed = false;


///
/// Script au chargement
///
function setMiniCartNoActionOnEnter()
{
    // Récupérer tous les boutons de la liste
    var buttonsArray = document.getElementsByTagName("input");    
    var btnCart;
    
    // Recherche automatique du bouton du cart
    for(var i = 0; i < buttonsArray.length; i++)
    {
        if(buttonsArray[i].type == "submit")
        {
            var btnId = buttonsArray[i].id;
            
            if(btnId.search(/"viewcart"/i) == -1)
            {
                btnCart = document.getElementById(btnId);
                break;
            }
        }
    }
    
    // Assignation de l'event onclick du bouton du cart
    btnCart.onclick = function()
    {
        // Vérifie si on submit ou pas         
        if(isEnterPressed)
            isSubmitted = false;
        else
            isSubmitted = true;
        
        // Réinitialisation de la touche   
        isEnterPressed = false;
        
        if(isSubmitted)
            AuthorizedUnload = true;
             
        return isSubmitted;
    }
}

///
/// BODY - onkeydown
///
function isEnterKeyPressed()
{
    if(event.keyCode == 13)
        isEnterPressed = true;
    else
        isEnterPressed = false;
}

///
///
///
function Back()
{
	window.history.back();
}

///
///
///
function ChangeCustomPrompt(productId, promptId, Sequence, PromptValue)
{
	document.location = 'Actions/ChangeCustomPrompt.aspx?ProductId=' + productId + '&PromptId=' + promptId + '&Sequence=' + Sequence + '&PromptValue=' + PromptValue;
}

///
///
///
function ChangeQuantity(productId,orderId,Qty)
{	
	document.location = 'Actions/ChangeQuantity.aspx?ProductId=' + productId + '&OrderId=' + orderId + '&Qty=' + Qty;	
}

///
///
///
function ChangeLineNote(productId, orderId, LineNote, prevPage)
{	  
      document.location = 'Actions/ChangeLineNote.aspx?ProductId=' + productId + '&OrderId=' + orderId + '&LineNote=' + URL_Encode(LineNote) + '&PrevPage=' + prevPage;	
}

///
///
///
function GetElement(id){
	// Netscape 4
	if(ns4){
		return(document.layers[id]);
	}
	// Explorer 4
	else if(ie4){
		return(document.all[id]);
	}
	// W3C - Explorer 5+ and Netscape 6+
	else if(ie5 || ns6){
		return(document.getElementById(id));
	}
}

function RedirectToInkAndToner(page)
{
    window.open(page);
}

///
///
///
function InvertDisplaySate(diplayState)
{
	if (diplayState == '')
	{		
		document.getElementById('ButtonQuickAdd').src = "../images/Quick Add Arrow.jpg";					
		return('none');
	}
	else
	{		
		document.getElementById('ButtonQuickAdd').src = "../images/Quick Add Arrow left.jpg";		
		return('');
	}
}

///
///
///
function ShowProductImage(url, width, height)
{
    window.open(url,'ProductImage','toolbar=no,scrollbars=no,resizable=yes,width=' + width +',height=' + height);
}


///
///
///
function SubmitControl(id)
{
	var element = document.getElementById(id);
	
	if (element != null)
	{
		element.click();
	}
	else
	{
		element = document.all[id];
		if (element != null)
		{
			element.click();
		}
	}
	return(false);
}

///
///
///

function SelectCartView(TabToView, Language, txtTabSelectionID)
{
	var CartViewsTableCtl;
	var display;
	var image;
	var tabCtl;
	var txtTabSelection;
	var ViewIndex = 0;

	tabCtl = document.getElementById('_ctl0_ContentPlaceHolder1_tdProductTabImage');
	txtTabSelection = document.getElementById(txtTabSelectionID);
	
	if (tabCtl != null)
	{
		if (TabToView == 'ProductTabImage')
		{
			//tabCtl.src = '../images/' + Language + '/tab_product_active.gif';
			if (Language == 'en')
			{
			    tabCtl.className = 'GrayBorderNoBottom  cellWidth120 cursorPointer FontCartTab';
			}
			else
			{
			    tabCtl.className = 'GrayBorderNoBottom  cellWidth140 cursorPointer FontCartTab';    
			}
			ViewIndex = 0;
			txtTabSelection.value = 1;
		}
		else
		{
			//tabCtl.src = '../images/' + Language + '/tab_product_inactive.gif';
			if (Language == 'en')
			{
			    tabCtl.className = 'GrayBorderNoBottom LightGreyBg2  cellWidth120 cursorPointer FontCartTab';
			}
			else
			{
			    tabCtl.className = 'GrayBorderNoBottom LightGreyBg2  cellWidth140 cursorPointer FontCartTab';    
			}
		}
	}
	
	tabCtl = document.getElementById('_ctl0_ContentPlaceHolder1_tdCustomPromptTabImage');
	if (tabCtl != null)
	{
		if (TabToView == 'CustomPromptTabImage')
		{
			//tabCtl.src = '../images/' + Language + '/tab_customprompt_active.gif';
			if (Language == 'en')
			{
			    tabCtl.className = 'GrayBorderNoLeftNoBottom   cellWidth120 cursorPointer FontCartTab';
			}
			else
			{
			    tabCtl.className = 'GrayBorderNoLeftNoBottom   cellWidth140 cursorPointer FontCartTab';    
			}
			ViewIndex = 1;
			txtTabSelection.value = 2;
		}
		else
		{
			//tabCtl.src = '../images/' + Language + '/tab_customprompt_inactive.gif';
			if (Language == 'en')
			{
			    tabCtl.className = 'GrayBorderNoLeftNoBottom LightGreyBg2  cellWidth120 cursorPointer FontCartTab';
			}
			else
			{
			    tabCtl.className = 'GrayBorderNoLeftNoBottom LightGreyBg2  cellWidth140 cursorPointer FontCartTab';    
			}
		}
		
	}
	
	CartViewsTableCtl = document.getElementById('CartViewsTable');
	if (CartViewsTableCtl)
	{
		
		for(var i = 0; i < 3; i++)
		{
			if (i == ViewIndex)
			{
				display = '';
			}
			else
			{
				display = 'none';
			}
			CartViewsTableCtl.rows[i].style.display = display;
		}
	}

	return false;
}


///
///
///
function SelectProductView(TabToView, Language)
{
	var ProductViewsTableCtl;
	var display;
	var image;
	var tabCtl;
	var ViewIndex = 0;
	
	tabCtl = document.getElementById('AdditionalInfoTabImage');
	if (tabCtl != null)
	{
		if (TabToView == 'AdditionalInfoTabImage')
		{
			tabCtl.src = '../images/' + Language + '/tab_addinfo_active.gif';
			ViewIndex = 1;
		}
		else
		{
			tabCtl.src = '../images/' + Language + '/tab_addinfo_inactive.gif';
		}
	}
	
	tabCtl = document.getElementById('PackInfoTabImage');
	if (tabCtl != null)
	{
		if (TabToView == 'PackInfoTabImage')
		{
			tabCtl.src = '../images/' + Language + '/tab_cartonformat_active.gif';
			ViewIndex = 2;
		}
		else
		{
			tabCtl.src = '../images/' + Language + '/tab_cartonformat_inactive.gif';
		}
		
	}


	ProductViewsTableCtl = document.getElementById('ProductViewsTable');
	if (ProductViewsTableCtl)
	{
		
		for(var i = 1; i < 3; i++)
		{
			if (i == ViewIndex)
			{
				display = '';
			}
			else
			{
				display = 'none';
			}
			ProductViewsTableCtl.rows[i].style.display = display;
		}
	}

	return false;
}

///
///
///
function UpdateDisplayOfQuickAddRows(NumberOfQuickAddLines)
{
	var CurrentRow;
	
	for (var i = 1; i < NumberOfQuickAddLines; i++)
	{
		CurrentRow = document.getElementById('_ctl0_ContentPlaceHolder1_QuickAdd_row' + i );
		if (CurrentRow)
		{
			CurrentRow.style.display = InvertDisplaySate(CurrentRow.style.display);				
		}
	}
}

///
///
///
function RemoveProduct(productId, Qty)
{
	document.location = 'Actions/RemoveProductFromCart.aspx?ProductId=' + productId;
	return true;
}

// /////////////////////////////////////////////////////////////////////////

// ====================================================================
//       URLEncode and URLDecode functions
//
// Copyright Albion Research Ltd. 2002
// http://www.albionresearch.com/
//
// You may copy these functions providing that 
// (a) you leave this copyright notice intact, and 
// (b) if you use these functions on a publicly accessible
//     web site you include a credit somewhere on the web site 
//     with a link back to http://www.albionresarch.com/
//
// If you find or fix any bugs, please let us know at albionresearch.com
//
// SpecialThanks to Neelesh Thakur for being the first to
// report a bug in URLDecode() - now fixed 2003-02-19.
// ====================================================================
function URL_Encode(URL)
{
	// The Javascript escape and unescape functions do not correspond
	// with what browsers actually do...
	var SAFECHARS = "0123456789" +					// Numeric
					"ABCDEFGHIJKLMNOPQRSTUVWXYZ" +	// Alphabetic
					"abcdefghijklmnopqrstuvwxyz" +
					"-_.!~*'()";					// RFC2396 Mark characters
	var HEX = "0123456789ABCDEF";

	var URL_corrected = "";
	for (var i = 0; i < URL.length; i++ ) {
		var ch = URL.charAt(i);
	    if (ch == " ") {
		    URL_corrected += "+";				// x-www-urlencoded, rather than %20
		} else if (SAFECHARS.indexOf(ch) != -1) {
		    URL_corrected += ch;
		} else {
		    var charCode = ch.charCodeAt(0);
			if (charCode > 255) {
			    alert( "Unicode Character '" 
                        + ch 
                        + "' cannot be encoded using standard URL encoding.\n" +
				          "(URL encoding only supports 8-bit characters.)\n" +
						  "A space (+) will be substituted." );
				URL_corrected += "+";
			} else {
				URL_corrected += "%";
				URL_corrected += HEX.charAt((charCode >> 4) & 0xF);
				URL_corrected += HEX.charAt(charCode & 0xF);
			}
		}
	} // for

	return URL_corrected;
}


//-------------------------------------------------------------
// Select all the checkboxes
//-------------------------------------------------------------
function SelectAllCheckboxes(theBox, dg, boxId)
{
    xState=theBox.checked;    
    elm = theBox.form.elements;
    
    for(i=0;i<elm.length;i++)
    {
		if(	elm[i].type == "checkbox" && 
			elm[i].id != theBox.id && 
			elm[i].id.indexOf(dg, 0) >= 0 &&
			elm[i].id.indexOf(boxId, 0) >= 0)
		{	
			if(elm[i].checked != xState)
				elm[i].click();
		}
    }
}

//--------------------------------------------------------------
//Limit the number of character entered in a multiline textbox
//--------------------------------------------------------------
function TextboxMultilineMaxNumber(txt, maxLen)
{
	return (txt.value.length <= (maxLen-1));
}

function TextCounter(field, maxlimit) 
{
	if (field.value.length > maxlimit)
	{
		field.value = field.value.substring(0, maxlimit);
	}
}
		
function WriteCookieNoExpire(name, value) 
{
	//ajout du path du cookie pour que celui-ci soit accessible 
	//dans tous les path de l'application
	document.cookie = name + "=" + escape(value) + ";path=/";
}
function ReadCookie(Name) 
{   
	var search = Name + "="   
	if (document.cookie.length > 0)
	{
		// if there are any cookies
		offset = document.cookie.indexOf(search);
		if (offset != -1)
		{
			// if cookie exists
			// set index of beginning of value
			offset += search.length;
			// set index of end of cookie value
			end = document.cookie.indexOf(";", offset);
			if (end == -1)
				end = document.cookie.length;
			return unescape(document.cookie.substring(offset, end))      
		}    
	}
}

function OpenPublicationByDocument(catalogue)
{
    alert('<scr' + 'ipt language=javascript src="' + catalogue + '"></sc' + 'ript>');
    document.write ('<scr' + 'ipt language=javascript src="' + catalogue + '"></sc' + 'ript>');
}

function OpenPublication(iFrameWebSiteID, catalogue)
{
    var frame = document.getElementById(iFrameWebSiteID);
    var url = catalogue
    frame.src = url;
    var ifr = parent.document.getElementById(product_frame);
    ifr.parentNode.removeChild(ifr);
    
  /*var selectedCount = 0; 
  var element; 
 
  for (var i = 0; i < document.forms[0].elements.length; i++) 
  { 
    element = document.forms[0].elements[i]; 
 
    alert(element.id); 
  }*/
}

function CloseMiniPDPPopUp()
{
    //window.opener = "IE"; 
    //window.open('','_parent','');
    //window.close(); 
    parent.parent.iFrameWebSite.close();
    parent.parent.productDetail.close();
}

var MaskType =
{
    CardType_Amex:
	{
		format: "9999 999999 99999",
		regex: /\d/
	},
	
    CardType_Visa_Master:
	{
		format: "9999 9999 9999 9999",
		regex: /\d/
	},
	
    CreditCard_Holder_Name:
    {
		format: "9999999999999999999999999999",
		regex:  /\w/
	}
};

/*
** Objet qui gère les mask
*/
var MaskHandler = 
{
	/*
	** Propriétés communes à tous les mask
	*/
	Properties: 
	{
		specialChars: new Array(8, 9, 13, 17),
		delimiterChars: new Array("9", "A")
	},
	
	/*
	** Fonction qui exécute le mask:
	**	- Assigner à l'event onkeypress
	**	- Exemple d'utilisation
	**		- onkeypress="return MaskHandler.ApplyMask(event, this.id, this.value, MaskType.Phone);"
	*/
	ApplyMask: function (e, id, val, mask)
	{
		var pos = val.length;
		
		if (mask == MaskType.CreditCard_Holder_Name)
		{
		    MaskHandler.Properties.specialChars = new Array(8, 9, 13, 17, 32, 45, 46, 192, 194, 196, 200, 201, 202, 203, 204, 206, 207, 210, 212, 214, 217, 219, 220, 224, 226, 228, 232, 233, 234, 235, 236, 238, 239, 242, 244, 246, 249, 251, 252);           
		}
		
		if (pos <= mask.format.length)
		{
			if (!e)
				var e = window.event;
			
			var key = e.keyCode ? e.keyCode : e.which;
			
			for (var i = 0, l = MaskHandler.Properties.specialChars.length; i < l; ++i)
			{
				if (key === MaskHandler.Properties.specialChars[i])
					return true;
			}
			
			if (pos != mask.format.length)
			{
				var c = String.fromCharCode(key);
				
				if (mask.regex.test(c))
				{
					var delimiter = mask.format.charAt(pos);
					var isDelimiter = false;
					
					for (var j = 0, len = MaskHandler.Properties.delimiterChars.length; j < len; j++)
					{
						if (delimiter == MaskHandler.Properties.delimiterChars[j])
						{
							isDelimiter = true;
							break;
						}
						
						if (!isDelimiter)
						{
							document.getElementById(id).value = val + delimiter + c;
							return false;
						}
					}
					
					return true;
				}
			}
		}
		if (document.selection && (document.selection.createRange().text.length == mask.format.length)
		    || (document.selection.createRange().text.length - 1 == mask.format.length && mask == MaskType.Expiration_Date))
		{
		    document.getElementById(id).value = '';
		    return true;
		}
		
		return false;
	}
};

function IsNumeric(input) 
{ 
   return (input - 0) == input && input.length > 0; 
} 

/*
** Verify when DOM is ready to call the function
** Params: - The function to call
*/
function isDomReady(callback)
{
		var checkDom = setInterval(function() { 
						if(document.body && document.getElementById)
						{
								clearInterval(checkDom);
								callback();
						}
				}, 10
		);
}
 
/*
** Set the visibility state of the element
** Params: - The element
**         - The visibility state (block, inline, none...)
*/
function setVisibility(ele, visibilityState)
{
		if (ele != null) { ele.style.display = visibilityState; }
}

/*
** Add onload event
** Params: func => The function to add on load
*/
function addLoadEvent(func) 
{
    var oldload = window.onload;

    if (typeof(window.onload) != 'function') {
        window.onload = func;
    } 
    else {
        window.onload = function () {
            if (oldload) {
                oldload();
            }
            func();
        }
    }
}
 
/*
** Get elements by classname 
** Params: - The classname to search
**         - The HTML tag element (optional)
**         - The node (optional)
*/
function getElementsByClass(className, tag, node) 
{
		// Optional parameters
		if (node == null) node = document;
		if (tag == null) tag = '*';     
		
		var classElements = new Array();
		var elements = node.getElementsByTagName(tag);
		var elementsLen = elements.length;
		var pattern = new RegExp('(^|\\\\s)' + className + '(\\\\s|$)');
		
		for (var i = 0, j = 0; i < elementsLen; i++) 
		{
				if (pattern.test(elements[i].className)) 
				{
						classElements[j] = elements[i];
						j++;
				}
		}
		
		return classElements;
}

/***************************************************
** Montre le mini cart extender
** Params: miniCartId         => The mini cart ID
**         linesInCartHtml    => The lines in cart HTML
**         btnCheckoutId      => The checkout button ID
**         miniCartExtenderId => The mini cart extender ID
** Return: Aucune
***************************************************/
function ShowMiniCartDropDown(miniCartId, linesInCartHtml, btnCheckoutId, miniCartExtenderId) {
    var curLeft = 0;
    var btnCheckOut = document.getElementById(btnCheckoutId);
    var divMiniCart = document.getElementById(miniCartId);

    if (divMiniCart.offsetParent) {
        do {
            curLeft += divMiniCart.offsetLeft;
        } while (divMiniCart = divMiniCart.offsetParent)
    }

    if (btnCheckOut != null || linesInCartHtml != "0") {
        var divDropDown = document.getElementById(miniCartExtenderId);

        if (divDropDown != null) {
            divDropDown.style.left = curLeft;
            divDropDown.style.display = "block";
        }
    }
}

/***************************************************
** Cache le mini cart extender
** Params: miniCartId => The mini cart extender ID
** Return: Aucune
***************************************************/
function HideMiniCartDropDown(miniCartId) {
    var divDropDown = document.getElementById(miniCartId);

    if (divDropDown != null) {
        divDropDown.style.display = "none";
    }  
}

/* Pour faire afficher le popup du Back Button */
var AuthorizedUnload = false;

function SetAuthorizedUnload() {
    try
    {
        eval('AuthorizedUnload=true;');
        eval('parent.AuthorizedUnload=true;');
        eval('parent.parent.AuthorizedUnload=true;');
    }
    catch(ex)
    {
        // Just ignore errors
    }
}

function OnUnloadPage(message) {
    if (window.screenTop > 10000) {
        var temp = false;
    }
    else {
        if (AuthorizedUnload == false) {
          /*  alert(message); */
        }
    }
}

/**************************************************************************
** These functions are used for the promotion control
** Note: These functions used "Getter" function in the promotion control
**       to be able to retrieve correctly the page elements client ID
***************************************************************************/
function OnLessMinize(ShowPromo, HidePromo, cookieName, minimizedState, maximizePath) {
    WriteCookieNoExpire(cookieName, minimizedState);

    getPromoMinMaxImg().src = maximizePath;
    getPromoBottomRow().style.visibility = "hidden";
    getPromoLeftContent().className = "left_bottom_table_grey ";
    getPromoRightContent().className = " right_bottom_table_grey";
    getPromoTopBottomBorder().className = " backgroundGrey cellBorderBottomGrey";
    getPromoStatusTextbox().value = minimizedState;
    getPromoMinMaxImg().innerHTML = ShowPromo;
    getPromoCenterBottomCell().className = "backgroundGrey";
    panel = $find(getPromoCollapserID());
    panel._doClose(true);
}

function OnClickMinMax(buyerDefaultState, ShowPromo, HidePromo, cookieName, cookieMoreName, minimizedState, maximizedState, displayLessOptionState) {
    var stateBeforeClick = getPromoStatusTextbox().value;

    if (stateBeforeClick == "") {
        stateBeforeClick = buyerDefaultState;
    }

    if (stateBeforeClick == minimizedState) {
        WriteCookieNoExpire(cookieName, maximizedState);

        getPromoBottomRow().style.visibility = "visible";
        getPromoLeftContent().className = "backgroundGrey cellBorderLeftGrey";
        getPromoRightContent().className = " backgroundGrey cellBorderRightGrey";
        getPromoTopBottomBorder().className = " backgroundGrey";
        getPromoStatusTextbox().value = maximizedState;

        if (getPromoDetailsTable().style.display != "inline") {
            getPromoTable1().style.display = "inline";

            var stateMore = ReadCookie(cookieMoreName);
            if (stateMore == displayLessOptionState) {
                getPromoTable2().style.display = "inline";
            }
        }

        getPromoCenterBottomCell().className = "backgroundGrey cellBorderBottomGrey FontSize1";
        getPromoMinMaxImg().innerHTML = HidePromo;
    }
    else {
        WriteCookieNoExpire(cookieName, minimizedState);

        getPromoBottomRow().style.visibility = "hidden";
        getPromoLeftContent().className = "left_bottom_table_grey ";
        getPromoRightContent().className = " right_bottom_table_grey";
        getPromoTopBottomBorder().className = " backgroundGrey cellBorderBottomGrey";
        getPromoCenterBottomCell().className = "backgroundGrey ";
        getPromoStatusTextbox().value = minimizedState;
        getPromoMinMaxImg().innerHTML = ShowPromo;
    }
}

function OnClickMoreLess(moreText, lessText, cookieName, displayLessOptionState, displayMoreOptionState) {
    var stateBeforeClick = ReadCookie(cookieName);

    if (stateBeforeClick == undefined || stateBeforeClick == "" || stateBeforeClick == displayMoreOptionState) {
        WriteCookieNoExpire(cookieName, displayLessOptionState);
        getPromoTable2().style.display = "inline";
        getPromoMoreLessLink().innerHTML = lessText;
        getPromoTable1().style.display = "";
    }
    else {
        WriteCookieNoExpire(cookieName, displayMoreOptionState);
        getPromoMoreLessLink().innerHTML = moreText;
    }
}
/**************************************************************************
** End of promotion functions using the promotion control "Getter" function
***************************************************************************/

function textboxMultilineMaxNumber(txt,maxLen){  
try{  
 if(txt.value.length > (maxLen-1))return false;  
 }catch(e){  
 }  
 }  


