// ToolBox

function analyticsLog(data) {
	try {
		_gaq.push(['_trackPageview', data]);
	} catch(err) {}
}

function display(id,property) {
	if (document.getElementById(id)) {
		document.getElementById(id).style.display = property;
	}
}
function reloadBasket() {
	parent.basketListFrameName.location.replace("/leshop/Basket.do");
	//parent.basketListFrameName.location.replace(parent.basketListFrameName.location);
	//parent.basketTotalFrameName.location.replace(parent.basketTotalFrameName.location);
}
function reloadMainContent() {
	parent.mainContentFrameName.location.reload();
}

function addToCart(type, alt, link, property1String) {
    switch (type) {
    	case "ADD2CART" :
	    	var field = eval(property1String) ;
	    	if (field != null && field.value == "??") {
	    		alert(top.sizeAlertStr);
	    	} else {
	        	if (field != null) {
	        		link += "&property1=" + field.value;
	        	}
	        	
	        	// JLT : add basket update timestamp to link
	        	var basketUpdateTimestamp = new Date().getTime();
       	    	link += "&basketUpdateTimestamp=" + basketUpdateTimestamp;
       	    	
	        	parent.basketListFrameName.location.replace(link);
	    	}
	        break ;
     	case "PDU" :
     		top.mainContentFrameName.document.location.href = link;
     		break ;
        default :
        	alert(alt);
        break;
	}
}

function getElementsByAttribute(oElm, strTagName, strAttributeName, strAttributeValue){
	var arrElements = (strTagName == "*" && oElm.all)? oElm.all : oElm.getElementsByTagName(strTagName);
	var arrReturnElements = new Array();
	var oAttributeValue = (typeof strAttributeValue != "undefined")? new RegExp("(^|\\s)" + strAttributeValue + "(\\s|$)", "i") : null;
	var oCurrent;
	var oAttribute;
	for(var i=0; i<arrElements.length; i++){
		oCurrent = arrElements[i];
		oAttribute = oCurrent.getAttribute && oCurrent.getAttribute(strAttributeName);
		if(typeof oAttribute == "string" && oAttribute.length > 0){
			if(typeof strAttributeValue == "undefined" || (oAttributeValue && oAttributeValue.test(oAttribute))){
				arrReturnElements.push(oCurrent);
			}
		}
	}
	return arrReturnElements;
}

function getElementsByClassName(oElm, strTagName, oClassNames){/*
// usage:
	To get all a elements in the document with a “info-links” class.
    getElementsByClassName(document, "a", "info-links");

	To get all div elements within the element named “container”, with a “col” and a “left” class.
    getElementsByClassName(document.getElementById("container"), "div", ["col", "left"]); */

    var arrElements = (strTagName == "*" && document.all)? document.all : oElm.getElementsByTagName(strTagName);
    var arrReturnElements = new Array();
    var arrRegExpClassNames = new Array();
    if(typeof oClassNames == "object"){
        for(var i=0; i<oClassNames.length; i++){
            arrRegExpClassNames.push(new RegExp("(^|\\s)" + oClassNames[i].replace(/\-/g, "\\-") + "(\\s|$)"));
        }
    }
    else{
        arrRegExpClassNames.push(new RegExp("(^|\\s)" + oClassNames.replace(/\-/g, "\\-") + "(\\s|$)"));
    }
    var oElement;
    var bMatchesAll;
    for(var j=0; j<arrElements.length; j++){
        oElement = arrElements[j];
        bMatchesAll = true;
        for(var k=0; k<arrRegExpClassNames.length; k++){
            if(!arrRegExpClassNames[k].test(oElement.className)){
                bMatchesAll = false;
                break;
            }
        }
        if(bMatchesAll){
            arrReturnElements.push(oElement);
        }
    }
    return (arrReturnElements)
}

function getElementByClassNamePart(part,tag,oElm) {
	if(!tag && !oElm) {
		tag = "";
		oElm = document;
	}
	if(!oElm) oElm = document;
	var outArray = new Array();
	if (document.evaluate){
		if (tag == "") tag = "*";
		var toEvaluate = "//"+tag+"[@class[contains(.,'"+part+"')]]";
		var xpathResult = document.evaluate(toEvaluate, oElm, null, 0, null);
		var item; while (item = xpathResult.iterateNext()) outArray[outArray.length] = item;
		return outArray;
	}
	else {
		var liste = oElm.getElementsByTagName(tag);
		var toMatch = "/^(.*)"+part+"(.*)$/";
		for (var i=0; i<liste.length; i++){
			if (liste[i].className && liste[i].className.match(eval(toMatch)) != null) outArray[outArray.length] = liste[i];
		}
		return outArray;
	}
}

function getElementPosition(elem) {/*
// usage:
	dim = getElementPosition(oElm);
	window.alert(dim.left + ' ' + dim.top); */

    var offsetLeft = 0;
    var offsetTop = 0;
    while (elem) {
        offsetLeft += elem.offsetLeft;
        offsetTop += elem.offsetTop;
        elem = elem.offsetParent;
    }
    if (navigator.userAgent.indexOf("Mac") != -1 &&
        typeof document.body.leftMargin != "undefined") {
        offsetLeft += document.body.leftMargin;
        offsetTop += document.body.topMargin;
    }
    return {left:offsetLeft, top:offsetTop};
}

function getStyle(oElm, strCssRule){
// usage: getStyle(document.getElementById("container"), "font-size");

	var strValue = "";
	if(document.defaultView && document.defaultView.getComputedStyle){
		strValue = document.defaultView.getComputedStyle(oElm, "").getPropertyValue(strCssRule);
	}
	else if(oElm.currentStyle){
		strCssRule = strCssRule.replace(/\-(\w)/g, function (strMatch, p1){
			return p1.toUpperCase();
		});
		strValue = oElm.currentStyle[strCssRule];
	}
	return strValue;
}

function joinNodeLists(list1,list2) {/*
// usage: used to concat getElementsByTagName("p")
	and getElementsByTagName("h1") results */
	var i = list2.length - 1;
	do{ list1[list1.length] = list2[i];
	}
	while(i--);
	return list1;
}

function changeClassName(oElm, cl, newCl) {/*
// usage: change className when using multiclass */
	var newClass = "";
	var multiclass = oElm.className.split(" ");
	for (var j in multiclass) {
		if (multiclass[j] == cl) multiclass[j] = newCl;
		newClass += multiclass[j];
		if (j < (multiclass.length - 1)) newClass += " ";
	}
	oElm.className = newClass;
}

function changeTagName(oElm,tagName) {/*
// usage: to change tagName for another */
	var newNode = document.createElement(tagName);
	if (oElm.className != "") newNode.className = oElm.className;
	if ((oElm.getAttribute("id") != "")&&(oElm.getAttribute("id") !=  null)) newNode.setAttribute('id',oElm.getAttribute("id"));
	for (var k=0; k<oElm.childNodes.length; k++) {
		newNode.appendChild(oElm.childNodes[k]);
	}
	oElm.parentNode.replaceChild(newNode,oElm);
}

function poupeeRusse(oElm,listeDiv) {/*
// (Eric.Andrieux) usage:
	to wrap an element with a series of divs
	listeDiv is an array containing the divs classNames)*/
	var conteneur_page;
	var memory = oElm.cloneNode(true);
	var parent = oElm.parentNode; // memorisation du noeud parent
	for (var i in listeDiv) {
		divTemp = document.createElement('div'); // creation d'une nouvelle div
		divTemp.className = listeDiv[i]; // attribution de classe
		divTemp.appendChild(memory); // on y attache le contenu
		memory = divTemp; // la div creee devient le nouveau contenu
	}
	conteneur_page = divTemp;
	parent.replaceChild(conteneur_page,oElm);
}

function textNode(someData) {
	var textNode = document.createTextNode('text');
	textNode.data = someData;
	return textNode;
}

function extractFromPx(sizeInPx) {
	if (typeof sizeInPx != 'undefined') return Number(sizeInPx.substr(0,sizeInPx.indexOf("px")));
	else return 0;
}
function getStylePx(oElm,style) {/*
// usage: getStylePx(document.getElementById("container"), "padding-top");
	retourne la valeur en px */
	return extractFromPx(getStyle(oElm,style));
}

function setImgs() {/*
//	Sorry for IE, we now have to use gif imgs */
	var Src, Png;
	var wholeImgs = document.getElementsByTagName("img");
	for (var i=0; i<wholeImgs.length; i++) {
		Src = unescape(wholeImgs[i].getAttribute('src'));
		png = Src.match(/-trans.png$/);
		if (png ) {
			Src = Src.replace(/-trans.png$/,"-trans.gif");
			wholeImgs[i].src = Src;
		}
	}
}

/* cookies part *
// source and usage: http://www.actulab.com/les-cookies-en-javascript.php */
function EcrireCookie(nom, valeur) {
	var argv=EcrireCookie.arguments;
	var argc=EcrireCookie.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=nom+"="+escape(valeur)+
	((expires==null) ? "" : ("; expires="+expires.toGMTString()))+
	((path==null) ? "" : ("; path="+path))+
	((domain==null) ? "" : ("; domain="+domain))+
	((secure==true) ? "; secure" : "");
}
function getCookieVal(offset) {
	var endstr=document.cookie.indexOf (";", offset);
	if (endstr==-1) endstr=document.cookie.length;
	return unescape(document.cookie.substring(offset, endstr));
}
function LireCookie(nom) {
	var arg=nom+"=";
	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 EffaceCookie(nom) {
	date=new Date;
	date.setFullYear(date.getFullYear()-1);
	EcrireCookie(nom,null,date);
}
function scrollOmatic(nameId) {/*
//	window.location.href="#___" replacement
	takes Id or oElm as argument */
	if((typeof nameId)=="string") nameId = document.getElementById(nameId);
	oElmDim = getElementPosition(nameId);
	window.scrollTo(oElmDim.left,oElmDim.top);
}
function addElement(tag, elmProperties, styleProperties) {/*
//	manually creates oElm
	usage:
	var styleProperties = new Array('position|absolute', 'top|0');
	var imgProperties = new Array('src|/images/_A0/topLogo.gif', 'width|1', 'height|1');
	var  myElement = addElement("img", imgProperties, styleProperties));*/
	var newElement = document.createElement(tag);
	for (var property in elmProperties) {
		var detail = elmProperties[property].split('|');
		newElement.setAttribute(detail[0],detail[1])
	}
	for (var property in styleProperties) {
		var detail = styleProperties[property].split('|');
		newElement.style[detail[0]] = detail[1];
	}
	return newElement;
}
function gup(name, source) {/*
get url parameter */
	if (source == null) source = window.location.href ;
	name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
	var regexS = "[\\?&]"+name+"=([^&#]*)";
	var regex = new RegExp( regexS );
	var results = regex.exec( source );
	if( results == null ) return "";
	else return results[1];
}

function GetElementById(oElm, id) {/*
get element by id starting from specified node */
	var dResult = null;
	if ( oElm.getAttribute('id') == id ) return oElm;
	for ( var i = 0; i < oElm.childNodes.length; i++ ) {
		if ( oElm.childNodes[i].nodeType == 1 ) {
			dResult = GetElementById( oElm.childNodes[i], id );
			if ( dResult != null ) break;
		}
	}
	return dResult;
}

function nextContainer(oElm) {
	if (oElm.nextSibling != null) {
		oElm = oElm.nextSibling;
		while ((oElm != null) && (oElm.nodeType != 1)) {
			oElm = oElm.nextSibling;
		}
	}
	return oElm;
}

/**
 * Part for input highlighting in forms controls.
 * Needs the jQuery core to be imported.
 */

var errorMessageStartTag = '<div class="error">';
var errorMessageEndTag = '</div>';

var errorMessageRowClass = 'info';
var errorMessageRow = 
	'<tr class="' + errorMessageRowClass + '">' +
	'<td class="leftLabelLight"><img src="/images/Warning14x.GIF" alt="" /></td>' +
	'<td class="rightWarning">#errorMessage#</td>' +
	'</tr>';

function insertErrorMessageRowNextToInput(inputName, errorMessage, before) {
	before = (before == null ? true : before);
	var input = $("[name='" + inputName + "'][type!='hidden']");
	var row = getParentWhereElementIs(input, 'tr');
	var targetRow = (before ? row.prev() : row.next());	
	if (!targetRow.hasClass(errorMessageRowClass)) {
		var rowToInsert = errorMessageRow.replace("#errorMessage#", errorMessage);
		if (before) {
			$(rowToInsert).insertBefore(row);
		} else {
			$(rowToInsert).insertAfter(row);
		}
	} else {
		targetRow.show();
	}
}

function removeErrorMessageRowNextToInput(inputName, before) {
	before = (before == null ? true : before);
	var input = $("[name='" + inputName + "'][type!='hidden']");
	var row = getParentWhereElementIs(input, 'tr');
	var targetRow = (before ? row.prev() : row.next());	
	if (targetRow.hasClass(errorMessageRowClass)) {
		targetRow.remove();
	}
}

function checkEmail(email) { 
	var reg = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]{2,}[.][a-zA-Z]{2,4}$/
	return (reg.exec(email)!=null)
}

/**
 * 
 * @param element
 * @param selector
 * @return
 */
function getParentWhereElementIs (element, selector) {
	var result = element.parentsUntil(selector).parent(selector);
	if (result.length == 0) {
		result = element.parent(selector);
	}
	return result;
}

/**
 * 
 * @return
 * This function removes the error message next to the field
	and removes the red color from it.
 */
var removeErrorMessage =
function () {
	//$(this).css('background-color', 'white');
	var column = getParentWhereElementIs($(this), 'td');
	column.children('.error').fadeOut(1000);
}

function highlightErrorInput(inputName, errorMessage) {
	defaultHighlighter (inputName, errorMessage);
}

var defaultHighlighter = function (inputName, errorMessage) {
	var input = $("[name='" + inputName + "'][type!='hidden']");
	var column = getParentWhereElementIs(input, 'td');
	var row = getParentWhereElementIs(input, 'tr');
	row.addClass('warningsPlace');
	column.append(errorMessageStartTag + errorMessage + errorMessageEndTag);
	//input.css('background-color', '#CCCCCC');
}

/**
 * 
 * @param bodyText
 * @param searchTerm
 * @param highlightStartTag
 * @param highlightEndTag
 * @return the text with searchTerm highlighted in a case-unsensitive way.
 */
function doHighlight(bodyText, searchTerm, highlightStartTag, highlightEndTag) {
	// the highlightStartTag and highlightEndTag parameters are optional
	if ((!highlightStartTag) || (!highlightEndTag)) {
		highlightStartTag = "<span class='highlight'>";
		highlightEndTag = "</span>";
	}  
	var newText = "";
	var i = -1;
	var lcSearchTerm = searchTerm.toLowerCase();
	var lcBodyText = bodyText.toLowerCase();

	while (bodyText.length > 0) {
		i = lcBodyText.indexOf(lcSearchTerm, i+1);
		if (i < 0) {
			newText += bodyText;
			bodyText = "";
		} else {
			if (bodyText.lastIndexOf(">", i) >= bodyText.lastIndexOf("<", i)) {
				if (lcBodyText.lastIndexOf("/script>", i) >= lcBodyText.lastIndexOf("<script", i)) {
				newText += bodyText.substring(0, i) + highlightStartTag + bodyText.substr(i, searchTerm.length) + highlightEndTag;
				bodyText = bodyText.substr(i + searchTerm.length);
				lcBodyText = bodyText.toLowerCase();
				i = -1;
				}
			}
		}
	}

	return newText;
}

function writeInConsole (text) {
    if (typeof console !== 'undefined') {
        var dt = new Date(); 
    	
    	console.log(dt + " : "+text);    
    }
}

function getIFrameDocument( iframe ) {

	if (iframe.contentDocument) {
		// For NS6
		return iframe.contentDocument; 
	} else if (iframe.contentWindow) {
		// For IE5.5 and IE6
		return iframe.contentWindow.document;
	} else if (iframe.document) {
		// For IE5
		return iframe.document;
	} else {
		return null;
	}
}

