// Generic functions
function OpenPopupWindow(url, windowName, width, height)
{
	window.open(url, windowName, "width=" + width + ",height=" + height + ",menubar=no,resizable=no,scrollbars=no,status=no,toolbar=no");
}  

function OpenPopupWindow(url, windowName, width, height, scrollbars)
{
	window.open(url, windowName, "width=" + width + ",height=" + height + ",menubar=no,resizable=no,scrollbars=" + scrollbars + ",status=no,toolbar=no,location=no");
}
function OpenPopupWindow(url, windowName, width, height, scrollbars, menubar,left,top,status,resizable,toolbar,location )
{
	window.open(url, windowName, "left=" + left + ",top=" + top + ",width=" + width + ",height=" + height + ",scrollbars=" + scrollbars + ",menubar=" + menubar + ",resizable=" + resizable + ",status=" + status + ",toolbar=" + toolbar + ",location=" + location);
}
function printpage(id)
{
	window.print();return false;
}

function OpenFiche(fiche, target)
{
	var oWin;
	oWin = window.open(fiche, target, "left=10,top=20,width=1000,height=630,status=yes,scrollbars=yes,resizable=yes");
}

function ShowModalWindow(url, width, height)
{
  var features = "dialogWidth: " + width + "px;" +
                  "dialogHeight: " + height + "px;" + 
                  "center: yes;" +
                  "edge: Raised;" +
                  "help: no;" +
                  "status: no";
  
  var result = window.showModalDialog(url, "window", features);
  
  return (result == null ? 0 : result);
}
	
/*
'=======================================================================================
' Function		: popup
' By			: Jean-Paul Lacombe
' Modifier le	: 19 juin 2001
' Goal			: Ouvre le popup pour la description longue
'=======================================================================================
*/
function popup(strUrl) 
{
	w = open(strUrl,'popup','width=530,height=350,scrollbars=yes,left=10,top=10,screenX=10,screenY=10,resizable=yes');	
}

// Does not support negative number.
function IsNumber(str)
{
	
	if (str.indexOf("-") > 0)
		return false;
		
	var onlyDigit = /[^0-9]/;

	return !onlyDigit.test(str);
	
}

function IsInt(str)
{
	if (!IsNumber(str))
		return false;
	
	if (str.indexOf(".") > -1)
		return false;
		
	if (str.indexOf(",") > -1)
		return false;
		
	return true;
}

function IsFloat(str)
{
	if (str.indexOf("-") > 0)
		return false;

	var num = parseFloat(str);
	return !isNaN(num);
}

function IsPrice(str)
{
	var validPrice = false;
	var commaPos = str.indexOf(",");
	var price;
		
	if (commaPos > 0)
	{
		var commaPattern = /\b,\b/ig;
		str = str.replace(commaPattern,".");
	}
	
	validPrice = IsFloat(str);
	
	if (validPrice)
	{
		price = parseFloat(str);
		validPrice = (price > 0);
	}
	
	return validPrice;
}

function IsYear(str, min, max)
{
	var year;
	
	if (!IsInt(str))
	{
		return false;
	}
	
	year = parseInt(str, 10);
	
	return ((year >= min) && (year <= max))
}

function IsMonth(str)
{
	var month;
	
	if (!IsInt(str))
	{
		return false;
	}
	
	month = parseInt(str, 10);
	
	return ((month >= 1) && (month <= 12))
}

function IsDay(str)
{
	var day;
	
	if (!IsInt(str))
	{
		return false;
	}
	
	day = parseInt(str, 10);
	
	return ((day >= 1) && (day <= 31))
}

function SynchronizeInputValue(inputSourceId, inputDestinationId)
{
	inputSource = document.getElementById(inputSourceId);
	inputDestination = document.getElementById(inputDestinationId);
	
	if ((inputSource != null) && (inputDestination != null))
	{
		inputDestination.value = inputSource.value;
	}
}

/* This function assumes that the sDate parameters have the yyyy-mm-dd format */
function GetDaysBetween(sDate1, sDate2)
{

	var SECOND = 1000; // the number of milliseconds in a second
	var MINUTE = SECOND * 60; // the number of milliseconds in a minute
	var HOUR = MINUTE * 60; // the number of milliseconds in an hour
	var DAY = HOUR * 24; // the number of milliseconds in a day
	var WEEK = DAY * 7; // the number of milliseconds in a week

	var yr1 = sDate1.substr(0,4);
	var mo1 = sDate1.substr(5,2);
	var dy1 = sDate1.substr(8,2);
	
	dy1 = parseInt(dy1,10) + 1;
	
	var yr2 = sDate2.substr(0,4);
	var mo2 = sDate2.substr(5,2);
	var dy2 = sDate2.substr(8,2);
	dy2 = parseInt(dy2,10) + 1;
	
	var utcTime1 = Date.UTC(yr1, mo1 - 1, dy1);
	var utcTime2 = Date.UTC(yr2, mo2 - 1, dy2);
	// Bruno Drouin 2004-05-26 Removed the Math.abs() function to return the real number of days between dates.
	var diffTime = utcTime2 - utcTime1
	return Math.round(diffTime / DAY);
	
}

function GetPageHeight()
{
	var windowHeight = 0;
	
	if (parseInt(navigator.appVersion) > 3)
	{
		if (navigator.appName.indexOf("Microsoft") != -1)
		{
			windowHeight = document.body.offsetHeight;
		}
		
		if (navigator.appName == "Netscape") 
		{
			windowHeight = window.innerHeight;
		}
	}

	return windowHeight;
}

function GetPageWidth()
{
	var windowWidth = 0;
	
	if (parseInt(navigator.appVersion) > 3)
	{
		if (navigator.appName.indexOf("Microsoft") != -1)
		{
			windowWidth = document.body.offsetWidth;
		}
		
		if (navigator.appName == "Netscape") 
		{
			windowWidth = window.innerWidth;
		}
	}
	
	return windowWidth
}

function KeyDownHandler(btnClientId)
{
	// process only the Enter key
	if (event.keyCode == 13)
	{
		btn = document.getElementById(btnClientId);
		
		if (btn != null)
		{
			// cancel the default submit
			event.returnValue=false;
			event.cancel = true;
			// submit the form by programmatically clicking the specified button
			btn.click();
		}
	}
}


/**************************************************************************************************
Cut and paste functions
**************************************************************************************************/
// Global variables
var globalValue = "";
var globalArray = new Array();

function CopyValue(source)
{
	globalValue = source;
}

function CopyOptions(source)
{
	for(var optionIndex = 0; optionIndex < source.options.length; optionIndex++)
	{
		globalArray[optionIndex] = new Option(source.options[optionIndex].text, source.options[optionIndex].value, false, false);
	}
}

function PasteValue(destination)
{
	destination.value = globalValue;
}

function PasteOptions(destination, clearDestination)
{
	var startIndex;
	
	if ((clearDestination) || (destination.options.length <= 0))
	{
		startIndex = 0;
	}
	else
	{
		startIndex = destination.options.length;
	}
	
	for(var optionIndex = 0; optionIndex < globalArray.length; optionIndex++)
	{
		destination.options[optionIndex + startIndex] = new Option(globalArray[optionIndex].text, globalArray[optionIndex].value, false, false);
	}
}

/**************************************************************************************************
End cut and paste functions
**************************************************************************************************/

// Function obtained by Manu
function newImage(arg) {
	if (document.images) {
		rslt = new Image();
		rslt.src = arg;
		return rslt;
	}
}

function changeImagesArray(array) 
{
	if (document.images && (preloadFlag == true)) 
	{
		for (var i=0; i<array.length; i+=2) 
		{
			document[array[i]].src = array[i+1];
		}
	}
}

function changeImages() 
{
	
	changeImagesArray(changeImages.arguments);
}

function toggleImages() {
	for (var i=0; i<toggleImages.arguments.length; i+=2) {
		if (selected == toggleImages.arguments[i])      changeImagesArray(toggleImages.arguments[i+1]);
	}
}

/**************************************************************************************************
* Function		: CountWord
* Description	: Count the number of word in a TextArea or TextBox
* Author		: Louis-David Malo (1st version obtained in RHRI)
* Date			: 06/30/2004
*
* Remark		: This function count 2 word when it get the "'"(ascii code 39) character.
*				  Ex.: Rock'n'roll  --> 3 words
* Return		: The number of word count.
**************************************************************************************************/
function CountWord(txtTextId, maxWord)
{
	var wordCount = 0;
	var lastCharacter = "";
	var beforeLastCharacter = " ";
	var currentCharacter;
	var twoReturn;
	var wordCount;
	var txtText = document.getElementById(txtTextId);
	var text = Trim(txtText.value);
	
	for (indexCharacter = 0; indexCharacter < text.length; indexCharacter++)
	{  
		currentCharacter = text.charCodeAt(indexCharacter); 
		twoReturn = (currentCharacter == 10 && !document.all && lastCharacter == 10) || 
					(currentCharacter == 10 && !document.all && lastCharacter == 10) || 
					(document.all && currentCharacter == 10 && beforeLastCharacter == 10) || 
					(document.all && currentCharacter == 10 && beforeLastCharacter == 32) || 
					(document.all && currentCharacter == 10 && beforeLastCharacter == 39);
		wordCount = (currentCharacter == 32 || currentCharacter == 39 || currentCharacter == 10) && (currentCharacter != lastCharacter) && !twoReturn? wordCount + 1: wordCount;
		beforeLastCharacter = lastCharacter;
		lastCharacter = currentCharacter;
	}
	
	wordCount = lastCharacter != 10 && text.length > 0? wordCount + 1:wordCount;
	
	return wordCount;
}

/**************************************************************************************************
* Function		: TrimTextValue
* Description	: Trim the text value of a TextArea or TextBox if exeeds maxChar.
* Author		: Louis-David Malo (1st version obtained in RHRI)
* Date			: 07/01/2004
*
* Remark		: -
* Return		: -
**************************************************************************************************/
function TrimTextValue(txt, maxChar)
{
	if (txt.value.length > maxChar)
	{
		txt.value = txt.value.substr(0, maxChar);
	}	
}

function ToUpper(id)
{
	var obj = document.getElementById(id);
	obj.value = obj.value.toUpperCase();
}

function Trim(s) 
{
  // Remove leading spaces and carriage returns
  
  while ((s.substring(0,1) == ' ') || (s.substring(0,1) == '\n') || (s.substring(0,1) == '\r'))
  {
    s = s.substring(1,s.length);
  }

  // Remove trailing spaces and carriage returns

  while ((s.substring(s.length-1,s.length) == ' ') || (s.substring(s.length-1,s.length) == '\n') || (s.substring(s.length-1,s.length) == '\r'))
  {
    s = s.substring(0,s.length-1);
  }
  return s;
}

/* Functions used to transfert element from a select to an other select */
/* Transfert functions begin */

function TransfertElement(sourceListId, destinationListId)
{	
	var i;
	var sourceList = document.getElementById(sourceListId);
	var destinationList = document.getElementById(destinationListId);
	
	for(i = 0; i < sourceList.length; i++)
	{
		if (sourceList[i].selected)
		{
			// Check if element is in destination list.
			if (SearchElement(sourceList[i].value, destinationListId) == -1)
			{
				AddElement(destinationListId, sourceList[i].value, sourceList[i].innerText);
			}
			
		}
	}

	for (i = 0; i < sourceList.length; i++)
	{
		if (sourceList[i].selected)
		{
			// Remove element from source list.
			sourceList.remove(i);

			i--;
		}
	}
}

function SearchElement(element, listId)
{
	var i;
	var list = document.getElementById(listId);
	
	for (i = 0; i < list.length; i++)
	{
		if (list[i].value == element)
			return i;
	}

	return -1;
}

function SearchTextElement(element, listId)
{
	var i;
	var list = document.getElementById(listId);

	for (i = 0; i < list.length; i++)
	{
		if (list[i].innerText.toLowerCase() == element.toLowerCase())
			return i;
	}

	return -1;
}


function AddElement(listId, value, text)
{
	var option;
	var list = document.getElementById(listId);
	
	// Create option object
	option = document.createElement("OPTION");

	// Add element in the list.
	option.value = value;
	option.text = text;
	list.add(option);

	// Clean up.
	option = null;
}

function RemoveElement(listId, element)
{
	var elementPosition;
	var list = document.getElementById(listId);
	
	elementPosition = SearchElement(element, listId);
	
	if (elementPosition != -1)
	{
		list.remove(elementPosition);
	}
}

function SelectAllElement(listId)
{
	var list = document.getElementById(listId);
	
	for(i = 0; i < list.length; i++)
	{
		list[i].selected = true;
	}
}

/* Transfert functions end*/

/* Cookie functions start */
/**
 * Sets a Cookie with the given name and value.
 *
 * name       Name of the cookie
 * value      Value of the cookie
 * [expires]  Expiration date of the cookie (default: end of current session)
 * [path]     Path where the cookie is valid (default: path of calling document)
 * [domain]   Domain where the cookie is valid
 *              (default: domain of calling document)
 * [secure]   Boolean value indicating if the cookie transmission requires a
 *              secure transmission
 */
function setCookie(name, value, expires, path, domain, secure)
{
    document.cookie= name + "=" + escape(value) +
        ((expires) ? "; expires=" + expires.toGMTString() : "") +
        ((path) ? "; path=" + path : "") +
        ((domain) ? "; domain=" + domain : "") +
        ((secure) ? "; secure" : "");
}

/**
 * Gets the value of the specified cookie.
 *
 * name  Name of the desired cookie.
 *
 * Returns a string containing value of specified cookie,
 *   or null if cookie does not exist.
 */
function getCookie(name)
{
    var dc = document.cookie;
    var prefix = name + "=";
    var begin = dc.indexOf("; " + prefix);
    if (begin == -1)
    {
        begin = dc.indexOf(prefix);
        if (begin != 0) return null;
    }
    else
    {
        begin += 2;
    }
    var end = document.cookie.indexOf(";", begin);
    if (end == -1)
    {
        end = dc.length;
    }
    return unescape(dc.substring(begin + prefix.length, end));
}

/**
 * Deletes the specified cookie.
 *
 * name      name of the cookie
 * [path]    path of the cookie (must be same as path used to create cookie)
 * [domain]  domain of the cookie (must be same as domain used to create cookie)
 */
function deleteCookie(name, path, domain)
{
    if (getCookie(name))
    {
        document.cookie = name + "=" + 
            ((path) ? "; path=" + path : "") +
            ((domain) ? "; domain=" + domain : "") +
            "; expires=Thu, 01-Jan-70 00:00:01 GMT";
    }
}

/* Cookie functions end */

function getAscendingTops(elem)
{
	if (elem == null)
	{
		return 0;
	}
	else 
	{
		return elem.offsetTop + getAscendingTops(elem.offsetParent);
	}
}

function getDimensions(elemID) {
    var base = document.getElementById(elemID);
    
    var offsetTrail = base;
    var offsetLeft = 0;
    var offsetTop = 0;
    while (offsetTrail) {
        offsetLeft += offsetTrail.offsetLeft;
		offsetTop += offsetTrail.offsetTop;
        offsetTrail = offsetTrail.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, width:base.offsetWidth, height:base.offsetHeight};
}

function ajustToWindow(elemID)
{
	var elem = document.getElementById(elemID);
	var offsetLeft;
	var offsetTop;
	
    if(elem.offsetTop + elem.offsetHeight > document.body.clientHeight)
    {
		offsetTop = document.body.clientHeight - elem.offsetHeight;
		elem.style.top = offsetTop;
    }
	
    if(elem.offsetLeft + elem.offsetWidth > document.body.clientWidth)
    {
		offsetLeft = document.body.clientWidth - elem.offsetWidth;
		elem.style.left = offsetLeft
    }
    return {left:offsetLeft, top:offsetTop}
}

/* Begin TEMP FOR DEMO */
function ShowHide(showId, hideId)
{
	showControl = document.getElementById(showId);
	hideControl = document.getElementById(hideId);
	
	showControl.style.display = "inline";
	hideControl.style.display = "none";
}

function DeleteItem(trListId, trEditId)
{
	trListControl = document.getElementById(trListId);
	trEditControl = document.getElementById(trEditId);
	
	if (confirm('Êtes-vous certain de vouloir supprimer cet enregistrement ?'))
	{
		trListControl.style.display = "none";
		trEditControl.style.display = "none";
	}
}

function ShowOrHide(controlId, show)
{
	var control = document.getElementById(controlId);

	if (show)
	{
		control.style.display = "inline";
	}
	else
	{
		control.style.display = "none";
	}
}

function ShowOrHideTextBox(txtId, ddlId)
{
	txt = document.getElementById(txtId);
	ddl = document.getElementById(ddlId);
	
	if (ddl[ddl.selectedIndex].value != "-1")
	{
		txt.style.display = "none";
	}
	else
	{
		txt.style.display = "inline";
	}
}

function ShowHideChild(trChildId, trChild2Id, imgId, imgPathShow, imgPathHide, imgChildId, imgChildPath)
{
	var trChild = document.getElementById(trChildId);
	var trChild2;
	var img = document.getElementById(imgId);
	var imgChild;
	
	if (trChild.style.display == "none")
	{
		trChild.style.display = "inline";
		img.src = imgPathShow;
	}
	else
	{
		if (trChild2Id.length > 0)
		{
			trChild2 = document.getElementById(trChild2Id);
			trChild2.style.display = "none";
		}
		
		trChild.style.display = "none";
		img.src = imgPathHide;
		
		if (imgChildId.length > 0)
		{
			imgChild = document.getElementById(imgChildId);
			imgChild.src = imgChildPath;
		}
	}
}

function EnabledOrDisabled(controlId, enabled)
{
	var control = document.getElementById(controlId);

	control.disabled = !enabled;
}

/* End TEMP FOR DEMO */

function ConfirmForMonitoring(msgDelete)
{
	var deleteConfirm = confirm(msgDelete);
	
	if (deleteConfirm)
	{
		needToConfirm = false;
		return true;
	}
	else
	{
		needToConfirm = true;
		return false;
	}
}

// Call sample: DisableListItems('checkBoxList1', new Array('1','2'), true);
function DisableListItems(checkBoxListId, chkArray, disable)
{
	// Get the checkboxlist object.
	objCtrl = document.getElementById(checkBoxListId);
	
	// Does the checkboxlist not exist?
	if(objCtrl == null)
	{
		return;
	}

	var i = 0;
	
	// iterate through listitems that need to be enabled or disabled
	for(i = 0; i < chkArray.length; i++)
	{
		objItem = document.getElementById(checkBoxListId + '_' + chkArray[i]);

		if(objItem == null)
		{
			continue;
		}

		// Disable/Enable the checkbox.
		objItem.disabled = disable;
	}
}

// Call sample: AddToolTipToListItems('checkBoxList1', new Array('1','2'), 'Permission inactive');
function AddToolTipToListItems(checkBoxListId, chkArray, toolTip)
{
	// Get the checkboxlist object.
	objCtrl = document.getElementById(checkBoxListId);
	
	// Does the checkboxlist not exist?
	if(objCtrl == null)
	{
		return;
	}

	var i = 0;
	
	// iterate through listitems that need to be enabled or disabled
	for(i = 0; i < chkArray.length; i++)
	{
		objItem = document.getElementById(checkBoxListId + '_' + chkArray[i]);

		if(objItem == null)
		{
			continue;
		}

		// Add the tooltip to the checkbox.
		objItem.title = toolTip;
	}
}

// Call sample: AddCursorToListItems('checkBoxList1', new Array('1','2'), 'help');
function AddCursorToListItems(listId, objArray, cursor)
{
	// Get the list object.
	objCtrl = document.getElementById(listId);
	
	// Does the list not exist?
	if(objCtrl == null)
	{
		return;
	}

	var i = 0;
	
	// iterate through listitems
	for(i = 0; i < objArray.length; i++)
	{
		objItem = document.getElementById(listId + '_' + objArray[i]);

		if(objItem == null)
		{
			continue;
		}

		// Add the cursor to the item.
		objItem.style.cursor = cursor;
	}
}

// Call sample: AddOnclickToListItems('checkBoxList1', new Array('1','2'), "ShowOrHide('tblProduct', true)");
function AddOnclickToListItems(listId, objArray, onclickContent)
{
	// Get the list object.
	objCtrl = document.getElementById(listId);
	
	// Does the list not exist?
	if(objCtrl == null)
	{
		return;
	}

	var i = 0;
	
	// iterate through listitems
	for(i = 0; i < objArray.length; i++)
	{
		objItem = document.getElementById(listId + '_' + objArray[i]);

		if(objItem == null)
		{
			continue;
		}

		// Add the onclick to the item.
		objItem.onclick = onclickContent;
	}
}

function OpenWebSite(webSiteTextBoxId)
{
	var webSiteTextBox = document.getElementById(webSiteTextBoxId); 
	
	if (webSiteTextBox.value.length > 0) 
	{
		if (webSiteTextBox.value.substring(0, 4).toLowerCase() != "http")
		{
			webSiteTextBox.value = "http://" + webSiteTextBox.value;
		}
		window.open(webSiteTextBox.value);
	}

}

function AddToBasket(responseText, context)
{
	var contextArray = context.split('_|_');
	var responseTextArray = responseText.split('_|_');
	
	var productID = contextArray[0];
	var pageProduit = contextArray[1];
	
	var respType = responseTextArray[0];
	if(respType == "1")
	{
		alert(responseTextArray[1]);
	}
	else
	{
		window.location = responseTextArray[1];
	}

}

function SelectAll(chk, checked)
{
	for(var i = 0; i < document.forms[0].length; i++)
	{
		if (document.forms[0][i].name.indexOf(chk) > -1)
		{
			document.forms[0][i].checked = checked;
		}
	}
}

// *************************************************************************
// Function pour la recuperation de la touche "Enter"
// *************************************************************************
function HandleEnter(e, triggerElementID)
{
	var char    = e.which || e.keyCode;
	var element = null;
	
	// Si la touche enfoncee est "Enter"
	if (char != null && char == 13)
	{
		// Si la navigateur de l'usager utilise la plateforme Mozilla, 
		// la premiere methode est disponible uniquement pour cette implementation DOM.
		if (e.preventDefault) 
		{ 
			e.preventDefault();
		}
		else                  
		{ 
			window.event.returnValue = false; 
		}
		
		// Rend le focus au control puis l'execute
		element = document.getElementById(triggerElementID);
		
		if (element != null)
		{
			element.focus(); 
			element.click();
		}
	}
	else
	{
		return true;
	}
}

// *************************************************************************
// Fonctions pour le transfert de focus sur different champs
// *************************************************************************
var activeField = null;

function AutoJump_OnKeyDown(fieldName)
{
	var field = document.getElementById(fieldName);

	activeField = field;

	field.lastValue = field.value;
}

function AutoJump_OnKeyUp(fieldName, nextFieldName, maxLength)
{
	var field     = document.getElementById(fieldName);
	var nextField = document.getElementById(nextFieldName);
	
	if (field == activeField && field.value != field.lastValue && field.value.length >= maxLength)
	{
		nextField.focus();
		
		if (nextField.tagName == "INPUT")
		{
			nextField.select();
		}

		activeField = null;
	}
}


// *************************************************************************
// Fonction pour la désactivation d'un bouton selon un texte de confirmation
// puis l'envoi du formulaire
// *************************************************************************
function DisableOnSubmit(button, confirmMessage, values)
{
	// Remplace les valeurs pour le message de confirmation
	if (values != 'undefined' && values.length > 0)
	{
	  for (var i = 0; i < values.length; i++)
	  {
	    var expression = "\\{" + i + "\\}";	          
	    var regEx      = new RegExp(expression);
		  
		  confirmMessage = confirmMessage.replace(regEx, values[i]);
	  }
	}
  
	// Récupération de la confirmation    	
	if (confirm(confirmMessage))
	{
		button.disabled = true;
		__doPostBack(button.name, '');
	}
  
	// Retourne false, pour que le bouton n'exécute pas son code sur le "onclick"
	return false;
}