/*
	Scripts for the Digixo application
	(c) 2003 Pierlis Technologies
        
        // (c) Digixo SAS - written by Pierre-Loic Raynaud
        //-------------------------------------------------------------------------
        // $Id: TTScripts.js,v 1.3 2006/10/19 16:12:13 digixo Exp $
        //-------------------------------------------------------------------------

*/

var gWindow = "";
var timeout;
var delai = 300;
var nbMenu = 10;
var clickOk = 0;

function nav(u)
{
	window.open(u,"_self");
}



function askConfirmation(confirmMessage, link)
{	
	var currentPage = window.location;
	var isConfirmed = confirm(confirmMessage);
	if (isConfirmed)
		window.location = link;
}

function setFocusTo(elemID)
{
	var vObj = document.getElementById(elemID);
	vObj.focus();
	vObj.select();
}

function openChooser(theURL, theTitle, IDField, NameField, valueField, pwidth, pheight)
{
    var vFind = getElementVar(NameField).value;
    window.mIDField = getElementVar(IDField);
    window.mNameField = getElementVar(NameField);
    if (valueField != null && valueField != "")
    	window.mValueField = document.getElementById(valueField);
    else
    	window.mValueField = null;
    
    gWindow = window.open(theURL, 'Choix', 'width=' + pwidth + 'px,height=' + pheight + 'px,scrollbars=yes,resizable=yes');
    gWindow.moveTo((screen.width-pwidth)/2, 50);
    gWindow.focus();
}


function openMissionChooser(IDField, NameField, valueField)
{
    var vFind = document.getElementById(NameField).value;
    window.mIDField = document.getElementById(IDField);
    window.mNameField = document.getElementById(NameField);
    if (valueField != null && valueField.length>0)
    	window.mValueField = document.getElementById(valueField);
    else
    	window.mValueField = null;
    gWindow = window.open('missionchooser.php', 'Choisissez', 'width=400px,height=400px,scrollbars=yes,resizable=yes');
}

function setChoosenID(theID, theName, theValue)
{
    window.opener.mIDField.value = theID;
    window.opener.mNameField.value = theName;
    if(window.opener.mNameField.getAttribute("onchange") != null) {
    	window.opener.mNameField.onchange();
    }
    
    if (window.opener.mValueField && window.opener.mValueField.value) {
    	window.opener.mValueField.value = theValue;
    }
    window.close();
    gWindow="";
}

function openDetailWindow(theURL, theFieldName)
{
    window.mDetailField = document.getElementById(theFieldName);
    gWindow = window.open(theURL, 'Detail', 'width=600px,height=400px,scrollbars=yes,resizable=yes');
}

function setDetailValue(theValue)
{
    window.opener.mDetailField.value = theValue;
    window.close();
    gWindow="";
}


function setDetailValueAndRefresh(theValue)
{
    window.opener.mDetailField.value = theValue;
    window.opener.location.reload(true);
    window.close();
    gWindow="";
}

function refreshParentAndClose(parentId)
{
    var sLocation = "" + window.opener.document.location + "";
    
    if (sLocation.lastIndexOf('?') > 0)
    {
        sLocation = sLocation.substring(0, sLocation.lastIndexOf('?'));
        sLocation = sLocation + "?id=" + parentId;
    }
    window.opener.document.location.replace(sLocation);
    window.close();
    gWindow="";
}


function submitParentWithActionAndClose(parentFormName, actionField, actionValue, objectIDField, objectIDValue, objectIDField2, objectIDValue2)
{
    
    getParentElementVar(actionField).value = actionValue;
    if (objectIDField != null && objectIDField != "")
        getParentElementVar(objectIDField).value = objectIDValue;
    if (objectIDField2 != null && objectIDField2 != "")
        getParentElementVar(objectIDField2).value = objectIDValue2;
    
    window.opener.document.forms[parentFormName].submit();
    
    window.close();
    gWindow="";
}

function submitParentAndClose(parentFormName)
{
    window.opener.document.forms[parentFormName].submit();
    window.close();
    gWindow="";
}

function paidBill(MissionID, BillID)
{
    confirm('toto');
    window.location='missiondetail.php?id='+MissionID+'&swapPaid='+BillID;
}

function missionProduct()
{
    document.form.Amount.value = document.form.DayPrice.value * document.form.DayCount.value;
}

function openPopup(theURL, theTitle, pwidth, pheight)
{
	gWindow = window.open(theURL, 'Titre', 'width=' + pwidth + 'px,height=' + pheight + 'px,scrollbars=yes,resizable=yes');
	gWindow.moveTo((screen.width-pwidth)/2, 50);
  	gWindow.focus();
}

function openPopunder(theURL, theTitle, pwidth, pheight)
{
	gWindow = window.open('', 'Titre', 'width=' + pwidth + 'px,height=' + pheight + 'px,scrollbars=yes,resizable=yes');
	gWindow.blur();
	gWindow.location = theURL;
  	window.focus();
}

function loadPopunderOnceInSession(theURL, theTitle, pwidth, pheight){
	if (get_cookie('popunder')==''){
		openPopunder(theURL, theTitle, pwidth, pheight);
		document.cookie="popunder=yes"
	}
}


// ne pas modifier ci-dessous
function get_cookie(Name) {
  var search = Name + "="
  var returnvalue = "";
  if (document.cookie.length > 0) {
    offset = document.cookie.indexOf(search)
    if (offset != -1) { 
      offset += search.length
      end = document.cookie.indexOf(";", offset);
      
    if (end == -1) 
         end = document.cookie.length;
         returnvalue = unescape(document.cookie.substring(offset, end))
      }
   }
  return returnvalue;
}





//	Function compatible "tout" permettant de récupérer un objet de la page, par son ID.
function getElementVar(elementID)
{
  var elementObject = null;
  if (document.layers)
  { // NN4+
    elementObject = document.layers[elementID];
  }
  else if (document.getElementById)
  { // gecko(NN6) + IE 5+
    elementObject = document.getElementById(elementID);
  }
  else if (document.all)
  { // IE 4
    elementObject = document.all[elementID];
  }
  
  return elementObject;
}

//	Function compatible "tout" permettant de récupérer un objet de la page, par son ID.
function getParentElementVar(elementID)
{
  var elementObject = null;
  if (window.opener.document.layers)
  { // NN4+
    elementObject = window.opener.document.layers[elementID];
  }
  else if (document.getElementById)
  { // gecko(NN6) + IE 5+
    elementObject = window.opener.document.getElementById(elementID);
  }
  else if (document.all)
  { // IE 4
    elementObject = window.opener.document.all[elementID];
  }
  
  return elementObject;
}


function enableZone(targetId) {
	var obj = document.getElementById(targetId);
	obj.disabled = true;
}
function disableZone(targetId) {
	var obj = document.getElementById(targetId);
	obj.disabled = false;
}
function disableAllZone(formId) {
	var obj = getElementVar(targetId);
	var count = obj.elements.length;
	for (i=0; i<count; i++) {
		var element = obj.elements[i]; 
		element.disable = true;
	}
}


function showAllZone(targetId)
{
    var arr = document.getElementsByName(targetId);
	var l = arr.length;
	for(var i = 0; i < l; i++) 
	{
		arr[i].style.visibility = "visible";
		arr[i].style.display = "block";
	}
}

function hideAllZone(targetId)
{
	var arr = document.getElementsByName(targetId);
	var l = arr.length;
		
	for(var i = 0; i < l; i++) 
	{
		arr[i].style.visibility = "hidden";
		arr[i].style.display = "none";
	}
}

function showZone(targetId)
{
    var obj = document.getElementById(targetId);
    obj.style.visibility = "visible";
    obj.style.display = "block";
}

function hideZone(targetId)
{
    var obj = document.getElementById(targetId);
    obj.style.visibility = "hidden";
    obj.style.display = "none";
}


function toggleZone( targetId ){
	var obj = document.getElementById(targetId);
    if (obj &&  obj.style.visibility == 'visible')
    {
      obj.style.visibility = "hidden";
      obj.style.display = "none";
    }
    else if (obj)
    {
      obj.style.visibility = "visible";
      obj.style.display = "block";
    }
} 

function showHideZones( zone_prefix, zone_count, zone_selected) {
	
	for(i=1;i <= zone_count; i++) {
		if (i == zone_selected) {
			showZone(zone_prefix+i);
		} else {
			hideZone(zone_prefix+i);
		}
	}
	return false;
}


/* Fonctions pour le menu dynamique */

function stopHide()
{
	window.clearTimeout(timeout);
	timeout = 0;
}

function waitAndHide()
{
	if(!timeout)
	{
		timeout = window.setTimeout('hideMenus2()',delai);
	}
}

function hideMenus()
{
	var i = 0;
	for(i = 1; i <= nbMenu; i++) 
	{
		hideZone("menu"+i);
	}
}

function hideMenus2()
{
	var i = 0;
	for(i = 1; i <= nbMenu; i++) 
	{
		hideZone("menu"+i);
	}
	clickOk=0;
}

function showMenu(zoneID)
{
	stopHide();
	hideMenus();
	clickOk=1;
	var obj = getElementVar(zoneID);
    obj.style.visibility = "visible";
    obj.style.display = "block";
}


function toggleMenuOnglets(elementId) {
	// recherche de l’élément div container
	for (var item = document.getElementById('menu_onglets').firstChild; item; item = item.nextSibling) {
		
		if(item.tagName == 'LI') {
			item_link = item.getElementsByTagName('A')[0];
			item_content = document.getElementById(item.className+'_content');
			
	        if (item.className == elementId) {
	        	item_link.className = 'current';
	        	item_content.className = 'on_content';
	        } else {
	        	item_link.className = 'ghost';
	        	item_content.className = 'off_content';
	        }
	     }
	}
}

function setValue(Field, Value)
{
	getElementVar(Field).value = Value;
}

function setUnchangedValue(Field, Value)
{
	var obj = getElementVar(Field);
	if ( obj.value == '')
		obj.value = Value;
}



function changeValue(Field, Value)
{
	$var=getElementVar(Field).value ;
	if (!($var>0)) 
		getElementVar(Field).value = Value;
}

function setTTCValue(TTCField, HTField)
{
	setTTCValueWithTVA(TTCField, HTField, 0.196);
}

function setTTCValueWithTVA(TTCField, HTField, TVARate)
{
	var HTprice =  getElementVar(HTField).value;
	var TTCprice = HTprice* (1 + TVARate);
	getElementVar(TTCField).value = TTCprice;
}

function setHTValue(TTCField, HTField)
{
	setHTValueWithTVA(TTCField, HTField, 0.196);
}

function setHTValueWithTVA(TTCField, HTField, TVARate)
{
	var TTCprice = getElementVar(TTCField).value;
	var HTprice = TTCprice / (1 + TVARate);
	getElementVar(HTField).value = HTprice;
}

/*
cm/inch/feet converter - credit must stay intact for use
By Ada Shimar ada@chalktv.com
For this script and more,
Visit http://javascriptkit.com
*/
function roundit(which){
return Math.round(which*100)/100
}

function cmToInchConvert(cmField, inchField)
{
	getElementVar(inchField).value = roundit(getElementVar(cmField).value/2.54);
}

function inchToCmConvert(inchField, cmField)
{
	getElementVar(cmField).value = roundit(getElementVar(inchField).value*2.54);
}
function inchToMmConvert(inchField, cmField)
{
	getElementVar(cmField).value = roundit(getElementVar(inchField).value*2.54*10.0);
}


function copySelectValue(selectField, fieldToUpdate)
{
   if (getElementVar(selectField).value != "-")
   	getElementVar(fieldToUpdate).value = getElementVar(fieldToUpdate).value + ' ' + getElementVar(selectField).value;
   	
   getElementVar(selectField).value = "-";
}

function ignoreSpaces(string) {
	var temp = "";
	string = '' + string;
	splitstring = string.split(" ");
	for(i = 0; i < splitstring.length; i++)
	temp += splitstring[i];
	return temp;
}


/*
	Set a string to lowcase, without accent or special characters nor spaces
*/
function formatStringToFlat(str)
{
	str = str.toLowerCase();
	str = ignoreSpaces(str);
	var regExpAccents1     = new RegExp('[ïî]','gi');
	var regExpAccents2     = new RegExp('[éèêë]','gi');
	str = str.replace(regExpAccents1,"i");
	str = str.replace(regExpAccents2,"e");
	
	return str;	
}

function fillImageField(productType, productBrand, imgField, valueSuffix)
{
	var fieldValue;
	if (productType == 1)
		fieldValue = "apn/";
	else if (productType == 2)
		fieldValue = "memorycards/";
	else if (productType == 7)
		fieldValue = "phone/";
	else
		fieldValue = "xxx/";
		
	fieldValue = fieldValue + productBrand + "/";
	
	
	
	var sName = getElementVar('name').value;
	fieldValue = fieldValue + sName + "/";
	fieldValue = fieldValue + sName + valueSuffix;
	
	fieldValue = formatStringToFlat(fieldValue)
	
	getElementVar(imgField).value = fieldValue;
}



function submitWithAction(formName, actionField, actionValue, objectIDField, objectIDValue, objectIDField2, objectIDValue2)
{
	getElementVar(actionField).value = actionValue;
	if (objectIDField != null && objectIDField != "")
		getElementVar(objectIDField).value = objectIDValue;
	if (objectIDField2 != null && objectIDField2 != "")
		getElementVar(objectIDField2).value = objectIDValue2;
	window.document.forms[formName].submit();
}

function setCheckBoxes(formName, checkboxIDlike, setValue) {
    var form = getElementVar(formName);
    if (typeof(form) != 'object')
        return;
    
    for(var i = 0; i < form.length; i++) {
        if (form[i].type == 'checkbox' && form[i].id.indexOf(checkboxIDlike, 0) >= 0)
            form[i].checked = setValue;
    }
}




/**
	Renvoie le nombre de checkboxes cochées dans le formulaire
*/
function countCheckboxesChecked(formulaire) {
	var count = 0;
	
	var formControls = formulaire.elements;
	for (var i = 0; i < formControls.length; i++)
	if (formControls[i].type.toLowerCase() == 'checkbox' && formControls[i].checked) {
		count++;
	}
	
	return count;
}

function appel_ancre(ancre) {
	self.location.hash=ancre;
}

function onglets2007_showMenu(id) {
	var d = getElementVar("ongletsuiste" + id);
	if (d) {
		d.style.display='block';
		getElementVar("ongletdt" + id).className = getElementVar("ongletdt" + id).className.replace(/off/gi,"on");
		getElementVar("ongletspan" + id).className = getElementVar("ongletspan" + id).className.replace(/off/gi,"on");
	}
}
function onglets2007_hideMenu(id) {
	var d = getElementVar("ongletsuiste" + id);
	if (d) {
		d.style.display='none';
		getElementVar("ongletdt" + id).className = getElementVar("ongletdt" + id).className.replace(/on/gi,"off");
		getElementVar("ongletspan" + id).className = getElementVar("ongletspan" + id).className.replace(/on/gi,"off");
	}
}

function checkEmail(email)
{
	if (email.indexOf("@") != "-1" &&
	    email.indexOf(".") != "-1" &&
	    email != "")
	    return true;
	
	return false;
}



/**
 * DHTML date validation script. Courtesy of SmartWebby.com (http://www.smartwebby.com/dhtml/)
 */
// Declaring valid date character, minimum year and maximum year
var dtCh= "/";
var minYear=1900;
var maxYear=2100;

function isInteger(s){
	var i;
    for (i = 0; i < s.length; i++){   
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}

function stripCharsInBag(s, bag){
	var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++){   
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function daysInFebruary (year){
	// February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}
function DaysArray(n) {
	for (var i = 1; i <= n; i++) {
		this[i] = 31
		if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
		if (i==2) {this[i] = 29}
   } 
   return this
}

function isDate(dtStr){
	var daysInMonth = DaysArray(12)
	var pos1=dtStr.indexOf(dtCh)
	var pos2=dtStr.indexOf(dtCh,pos1+1)
	var strDay=dtStr.substring(0,pos1)
	var strMonth=dtStr.substring(pos1+1,pos2)
	var strYear=dtStr.substring(pos2+1)
	strYr=strYear
	if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1)
	if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1)
	for (var i = 1; i <= 3; i++) {
		if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1)
	}
	month=parseInt(strMonth)
	day=parseInt(strDay)
	year=parseInt(strYr)
	if (pos1==-1 || pos2==-1){
		alert("Le format de date doit être : jj/mm/aaaa")
		return false
	}
	
	if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
		alert("Veuillez saisir un jour valide")
		return false
	}
	if (strMonth.length<1 || month<1 || month>12){
		alert("Veuillez saisir un mois valide")
		return false
	}
	if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
		alert("Veuillez saisir une année sur 4 chiffres entre "+minYear+" et "+maxYear)
		return false
	}
	if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
		alert("Veuillez saisir une date valide")
		return false
	}
return true
}

 function HTMLEncode(wText){
if(typeof(wText)!="string"){
wText=wText.toString();};
wText=wText.replace(/&/g, "&amp;") ;
wText=wText.replace(/"/g, "&quot;") ;
wText=wText.replace(/</g, "&lt;") ;
wText=wText.replace(/>/g, "&gt;") ;
wText=wText.replace(/'/g, "&#146;") ;
return wText;};

function setMaxLength() {
	var x = document.getElementsByTagName('textarea');
	var counter = document.createElement('div');
	counter.className = 'counter';
	for (var i=0;i<x.length;i++) {
		if (x[i].getAttribute('maxlength')) {
			var counterClone = counter.cloneNode(true);
			counterClone.relatedElement = x[i];
			counterClone.innerHTML = '<span>0</span>/'+x[i].getAttribute('maxlength');
			x[i].parentNode.insertBefore(counterClone,x[i].nextSibling);
			x[i].relatedElement = counterClone.getElementsByTagName('span')[0];

			x[i].onkeyup = x[i].onchange = checkMaxLength;
			x[i].onkeyup();
		}
	}
}

function checkMaxLength() {
	var maxLength = this.getAttribute('maxlength');
	var currentLength = this.value.length;
	if (currentLength > maxLength)
		this.relatedElement.className = 'red';
	else
		this.relatedElement.className = '';
	this.relatedElement.firstChild.nodeValue = currentLength;
	// not innerHTML
}

function resetBargainView() {
	getElementVar('specialBargainDateFromYear').value= 0;
	getElementVar('specialBargainDateFromMonth').value= 0;
	getElementVar('specialBargainDateFromDay').value= 0;
	
	getElementVar('specialBargainDateToYear').value= 0;
	getElementVar('specialBargainDateToMonth').value= 0;
	getElementVar('specialBargainDateToDay').value= 0;
}

function CKFinderBrowseServer()
{
	// You can use the "CKFinder" class to render CKFinder in a page:
	var finder = new CKFinder() ;
	finder.BasePath = 'common/ckfinder/' ;	// The path for the installation of CKFinder (default = "/ckfinder/").
	finder.Width = 800 ;
	finder.StartupFolderExpanded = true ;
	finder.SelectFunction = CKFinderSetFileField ;
	finder.Popup() ;
}

function CKFinderSetFileField( elementId, fileUrl ) {
	document.getElementById( 'img' ).value = fileUrl ;
}