/*
 *  Contains the Javascript used by Air France homepage
 *  For performance issues, HP must include minimum javascript files, so the functions in this file
 *  must be used by the homepage or FB header, or moved to another place.
 */  
 
/* call on HP onload event */
function initHP() {
	if ($('bookingContainer')) {
		showMineBeTab('standard');
		initCountriesStopover();
		printFormatedDate($('libJourAller'), $('moisAller').value.substring(0, 4), $('moisAller').value.substring(4), $('jourAller').value);
		printFormatedDate($('libJourRetour'), $('moisRetour').value.substring(0, 4), $('moisRetour').value.substring(4), $('jourRetour').value);
		if ($('idOneWay').checked) { /* aller simple */
			hp_AllerSimple();
		}
		
		updateMiniBeForUM();
	}
}

/* a light version of 'function $' from the Prototype library */
function $(element) {
	if (typeof element == 'string') {
  		element = document.getElementById(element);
	} 
	
	if (eval("Object.extend")) { 
		/* prototype.js available */
	 	return Element.extend(element);
	} else {
		/* prototype.js not available: no enhancement */
		return element;
	}
}

function toggleToolBox(id) {
	var box = $(id);
	var button = $(id + 'Btn');
	if (button) {
		if (box.style.display == 'none') {
			  box.style.display = 'block';
			  button.src = '/FR/common/common/img/pictos/pushDownBlue.gif';
		} else {
			  box.style.display = 'none';
			  button.src = '/FR/common/common/img/pictos/pushRightBlue.gif';
		}	
	}
}

var isClickInsideFBLayer;
var captureClickDoc_fb = function() {if (!isClickInsideFBLayer){toggleFBLogguedDiv();};isClickInsideFBLayer=false;}
var captureClickLayer_fb = function() {isClickInsideFBLayer=true;}
var captureEscape_fb = function(e) {var keyID=(window.event)?event.keyCode:e.keyCode; if (keyID==27){toggleFBLogguedDiv();}}


function toggleFBLogguedDiv() {
	var box = $('FBlogguedRolldown');
	var toShow = box.style.display == 'none';
			
	box.style.display = toShow ? 'block' : 'none';
	/** ajout refonte **/
	$('fbLogguedButton').style.backgroundImage = toShow ? 'url(/FR/common/common/img/background/p_FB_close.gif)' : 'url(/FR/common/common/img/background/p_FB_open.gif)';
	/** suppression refonte
	$('fbLogguedButton').src = toShow ? '/FR/common/common/img/pictos/pullUpWhite.gif' : '/FR/common/common/img/pictos/pullDownWhite.gif';
	$('fbLogguedButton').style.top  = toShow ? '0px' : '-2px';
	**/
	$('libBoutonDepliant').innerHTML = toShow ? libBoutonDepliantHide : libBoutonDepliantShow;
	
	if (isWinIE6ouMoins()) {  // hide or show the Select inputs under the div
		setSelectVisibility(!toShow,box);
	}
	
	// handlers
	if (toShow) {
		isClickInsideFBLayer = true;
		document.onclick = captureClickDoc_fb;
		box.onclick = captureClickLayer_fb;
		document.onkeyup = captureEscape_fb;
	} else {
		document.onclick = null;
		box.onclick = null;
		document.onkeyup = null;
	}
}

var idCurrentTab;
function showMineBeTab(id) {
	var box = $(id + 'Content');
	if (box) {
		var tab = $(id + 'Tab');
		var currentBox = $(idCurrentTab + 'Content');
		var currentTab = $(idCurrentTab + 'Tab');
		
		// hide current
		if (idCurrentTab) {
			currentBox.style.display = 'none';
			currentTab.className = currentTab.className.replace("selected", "notSelected");
		}
		
		// show tab
		box.style.display = 'block';
		tab.className = tab.className.replace("notSelected", "selected");
		
		idCurrentTab = id;
	}
}

function showLogguedFB(loggued) {
	  if (loggued) {
	  	 $('FBNotLoggued').style.display = 'none';
	  	 $('FBLoggued').style.display = 'block';
			 /** ajout refonte **/
			 if($('toggleLogoFB')) {
		  	 $('toggleLogoFB').style.display = 'none';	  	 
		  	 $('logoFB').style.display = 'block';
		   }  	 
	  } else {
	  	 $('FBlogguedRolldown').style.display = 'none';
	  	 $('FBLoggued').style.display = 'none';
	  	 $('FBNotLoggued').style.display = 'block';	  	 
			 /** ajout refonte **/
			 if($('toggleLogoFB')) {
		  	 $('toggleLogoFB').style.display = 'block';	  	 
		  	 $('logoFB').style.display = 'none';
	  	 }	 
	  }
}

function fillLogguedFB() {
	fillLogguedFBwithParams(fb_user, fb_number, fb_solde, fb_last_operation, fb_level, fb_mmb, fb_last_name);
}

function fillLogguedFBwithParams(identity, number, solde, last_operation, level, pnrs, lastName) {
	$('FBLogguedIdentity').innerHTML = identity;
	$('cardNumber').innerHTML = number;
	$('milesAccount').innerHTML = solde;
	$('lastOperation').innerHTML = last_operation;
	
	var mmbContent = "";
	if (pnrs.length > 0) {
		for (var i = 0; i < pnrs.length && i < 3*3; i+=3) {
			var trajet = pnrs[i];
			var pnrDate = pnrs[i+1];
			var pnrNumber = pnrs[i+2];
			mmbContent += "<a href=\"javascript:af_go('/'+cu_Marche+'/'+cu_Langue+'/local/process/standard/rebooking/ValidateSearchPnrAction.do?recordLocator=" + pnrNumber + "&lastName="+escape(lastName)+"', '');\" class='lienMineur'><span class='noBreak'>" + trajet + "</span> " + pnrDate + " "+labelRef+"&nbsp;" + pnrNumber + "</a>";
		}
		if (pnrs.length > 3*3) {
			mmbContent += "<a href=\"javascript:af_go('/'+cu_Marche+'/'+cu_Langue+'/local/process/standard/rebooking/TripListAction.do','')\">"+msgOtherReservations+"</a>"; 
		}
		$('idFbEcheckin').style.display = "inline";
	} else {
		mmbContent = msgNoReservation;
		$('idFbEcheckin').style.display = "none";
	}
	$('pnrsList').innerHTML = mmbContent;

	fb_level = level;
	
	if (level == 7) {
		$('fbLevelCard').src = '/' + cu_Marche + '/common/common/img/visuels/cartes/Platinium_53x34.gif';
	} else if (level == 6) {
		$('fbLevelCard').src = '/' + cu_Marche + '/common/common/img/visuels/cartes/gold_53x34.gif';
	} else if (level == 5) {
		$('fbLevelCard').src = '/' + cu_Marche + '/common/common/img/visuels/cartes/Jeune_53x34.gif';
	} else if (level == 4) {
		$('fbLevelCard').src = '/' + cu_Marche + '/common/common/img/visuels/cartes/Jeune_53x34.gif';
	} else if (level == 3) {
		$('fbLevelCard').src = '/' + cu_Marche + '/common/common/img/visuels/cartes/Club2000_53x34.gif';
	} else if (level == 2) {
		$('fbLevelCard').src = '/' + cu_Marche + '/common/common/img/visuels/cartes/silver_53x34.gif';
	} else {
		$('fbLevelCard').src = '/' + cu_Marche + '/common/common/img/visuels/cartes/ivory_53x34.gif';
	} 
	$('fbLevelName').innerHTML = libNiveauxTier[level-1];
	
	var hrefs = $('FBlogguedRolldown').getElementsByTagName("a");
	for (var i = 0; i < hrefs.length; i++) {
		if (hrefs[i].href.indexOf('toggleFBLogguedDiv') == -1 && hrefs[i].id != 'idFbLogguedHide') {
			hrefs[i].href = "javascript:toggleFBLogguedDiv();" + hrefs[i].href.substr("javascript:".length);
		}
	} 
}

var ImgOFF="/FR/common/common/img/pictos/img-erreur_off_1px.gif";
var ImgON="/FR/common/common/img/pictos/img-erreur_on.gif";


function header_login() { 
	errorMessage = '';       
	$('imgFbNumber').style.display = 'none';
	$('imgFbPassword').style.display = 'none';

	var fbLogin = trim($('idFbNumber').value);
	var fbPassword = trim($('idFbPassword').value);
	
	var loginEmpty = emptyField(fbLogin, msgMandatoryField, 'imgFbNumber');
	var pwdEmpty = emptyField(fbPassword, msgMandatoryField, 'imgFbPassword');
	if (!loginEmpty && !pwdEmpty) {
			controlAlphaNum(fbLogin, msgFbNumberAlphaNum, 'imgFbNumber');
			controlAlphaNum(fbPassword, msgFbPasswordAlphaNum, 'imgFbPassword');
			controlLength(fbLogin, 6, 16, msgFbNumberLength, 'imgFbNumber');
			controlLength(fbPassword, 4, 10, msgFbPasswordLength, 'imgFbPassword');
	}	
	saveLoginInCookie(fbLogin);

	if (!showErrorMessage()) {
		$('btnHeaderLogin').id = 'btnHeaderLoginHidden'; /* change id to change css style */
		$('idFbLinks').style.display = 'none';
		$('fbAjaxLoading').style.display = 'block';
		var params = chaineLien + '&login=' + fbLogin + '&pwd=' + fbPassword;
		doRequestXml(urlLoginXml, "POST", "batchXmlLoginResponse", params);
		document.body.style.cursor = "wait"
	}
}

function batchXmlLoginResponse(xmlResponse) {
	document.body.style.cursor = "default";
	$('fbAjaxLoading').style.display = 'none';
	$('idFbLinks').style.display = '';
	$('btnHeaderLoginHidden').id = 'btnHeaderLogin'; /* change id to change css style */


	if (!xmlResponse) { /* badly formatted response, probably a session time out */
		goToHome();
	}
	
	var response = xmlResponse.documentElement;
	var loginResult = response.getAttribute("result");

	if (loginResult == "3") { /* login ok */
		/* update loggued block */
		var identity = xmlResponse.getElementsByTagName("identity")[0].firstChild.data;
		var number = xmlResponse.getElementsByTagName("number")[0].firstChild.data;
		var solde = xmlResponse.getElementsByTagName("solde")[0].firstChild.data;
		var lastOperation = xmlResponse.getElementsByTagName("lastOperation")[0].firstChild.data;
		var level = xmlResponse.getElementsByTagName("level")[0].firstChild.data;
		var pnrs = eval(xmlResponse.getElementsByTagName("pnrs")[0].firstChild.data);
		var lastName = xmlResponse.getElementsByTagName("lastname")[0].firstChild.data;
		var codeDepPref = xmlResponse.getElementsByTagName("codeDepPref")[0].firstChild.data;
		var codeArrPref = xmlResponse.getElementsByTagName("codeArrPref")[0].firstChild.data;		
		var iseatzXml = xmlResponse.getElementsByTagName("iseatzParams")[0].firstChild;
		if (iseatzXml) {
			document.iseatzParams = iseatzXml.data;
		}
		
		$('codeDepPref').value = codeDepPref;
		$('codeArrPref').value = codeArrPref;
		fillLogguedFBwithParams(identity, number, solde, lastOperation, level, pnrs, lastName);
		/* show it */
		showLogguedFB(true);
		toggleFBLogguedDiv();
		sendWebTrendsFBLogin(level, solde);
		/* do page specific action */
		if (document.onLoginFB) { 
			document.onLoginFB();
		}
	} else if (loginResult == "4" || loginResult == "12")  {
		af_go('/' + cu_Marche + '/' + cu_Langue + '/local/voyageurfrequent/ffp/AdhesionFFP.do', '');
	} else if (loginResult == "14")  {
		af_go('/' + cu_Marche + '/' + cu_Langue + '/local/personnalisation/loggue/transitionFFP.do', '');
	} else if (loginResult == "16" || loginResult == "17" || loginResult == "18")  {
		af_go('/' + cu_Marche + '/' + cu_Langue + '/common/personnalisation/nonloggue/modifierMonAirfranceFFPSecurise.do', '');
	} else {
		showLoginError(xmlResponse.documentElement.firstChild.data);
	}
}

var errorMessage;
function emptyField(value, msg, imgName) {
	if (value == '') {
		$(imgName).style.display = 'inline';
		if (errorMessage.indexOf(msg) == -1) {
			errorMessage += msg + '\n';
		}
		return true;
	}
	return false;
}
function controlRegExp(Motif, value, msg, imgName) {
	if (Motif.test(value)) {
		$(imgName).style.display = 'inline';
		errorMessage += msg + '\n';
  }
}
function controlAlphaNum(value, msg, imgName) {
	controlRegExp(/[^a-zA-Z0-9]/gi, value, msg, imgName);
}
function controlAlpha(value, msg, imgName) {
	controlRegExp(/[^a-zA-Z]/gi, value, msg, imgName);
}
function controlNum(value, msg, imgName) {
	controlRegExp(/[^0-9]/gi, value, msg, imgName);
}
function controlLength(value, min, max, msg, imgName) {
	if (value.length < min || value.length > max) {
		$(imgName).style.display = 'inline';
		errorMessage += msg + '\n';
	}
}
function showErrorMessage() {
	if (errorMessage) {
		alert(errorMessage);
		return true;
	}
	return false;
}
function trim(strText) {
    /* this will get rid of leading spaces*/
    while (strText.substring(0,1) == ' ')
        strText = strText.substring(1, strText.length);

    /*this will get rid of trailing spaces*/
    while (strText.substring(strText.length-1,strText.length) == ' ')
        strText = strText.substring(0, strText.length-1);

   return strText;
}
function getSelectValue(champ) {
	return champ.options[champ.selectedIndex].value;
}

function iseatzUrl() {
	if (document.iseatzParams) {
		var url = document.urlIseatzAvecResa;
		var sep = url.indexOf('?') == -1 ? '?' : '&';
		return url + sep + iseatzParams;
	} else {
		return document.urlIseatzSansResa;
	}
}

/* --------------------------- */

function hp_rechercher() {
	var moisAnneeAller = $("moisAller").value;
	var annneAller = moisAnneeAller.substr(0, 4);
	var moisAller = parseInt(moisAnneeAller.substr(4, 2), 10) - 1;;
	var jourAller =  $("jourAller").value;

	var rangSelectionneTypeRecherche;
	$("plusOptions").value = "";

	saveOrigineInCookie();

	hp_majArrivee()
	hp_majClasses();

	var babies = getSelectValue($('idNbBebes'));
	var children = getSelectValue($('idNbEnfants'));
	var adults = getSelectValue($('nbAdults'));
	var typoAdults = getSelectValue($('typoPassagersAdulte'));
	
	if (adults == 0) { 
		submitRechercherForm(); /* UM search page */
	} else {	
		if (babies > adults || (babies > 0 && typoAdults == 'YTH_MIN')) {
			alert(errCompatibiliteBebeAdulte);
			return;
		}	
		if (children > 0 && typoAdults == 'YTH_MIN') {
			alert(errCompatibiliteMineurEnfant);
			return;
		}
		if (cu_Marche == 'FR') { 
			var nbAdults = getSelectValue($("nbAdults"));
			var typoPax = getSelectValue($('typoPassagersAdulte'));
			var nbChildren = getSelectValue($("idNbEnfants"));
			var nbBabies = getSelectValue($("idNbBebes"));
			if((nbAdults == "2" && (typoPax=="ADT"||typoPax=="YTH_MAJ")) 
				|| (nbAdults == "1" && (typoPax=="ADT"||typoPax=="YCD"||typoPax=="YTH_MAJ") && (nbChildren > 0 || nbBabies > 0))){
				/* on affiche la popup famille si 2 adultes/jeunes majeurs + eventuellement enfants  ou  si un adulte + enfant(s) */
				isCouple();
				return;
			}
		}
		
		submitRechercherForm();
	}
}

function hp_rechercherPlusOptions() {
	$("plusOptions").value = "PLUSOPTIONS";
	hp_majArrivee()
	hp_majClasses();
	submitRechercherForm();
}
function hp_majArrivee() {
	/* Si l'utilisateur n'a pas utilisé la completion */
	if ($("idArrivalTrip1Input").value == '') {
		$("idArrivalTrip1Input").value = $("idArrivalTrip1").value;
	}
	/* Type de trajet */
	if ($("idRoundTrip").checked) {
		/* Mise à jour du champ origine du 2eme itineraire */
		$("idDepartureTrip2").value = $("idArrivalTrip1Input").value;
		/* Mise à jour du champ destination du 2eme itineraire */
		$("idArrivalTrip2Input").value = $("idDepartureTrip1").options[$("idDepartureTrip1").selectedIndex].value;
	} else {
		/* Aller simple */
		$("idDepartureTrip2").value = "";
		$("idArrivalTrip2Input").value = "";
	}
}
function hp_majClasses() {
/*	var cabineNFS = $("idCabin").value;
	var cabine = cabineNFS.substring(0, 1);
	var ssCabine = cabineNFS.substr(1);
	$("cabine").value = cabine;
	$("ssCabine").value = ssCabine;*/
}
function updateMiniBeForUM() {
    var nbAdults = parseInt(getSelectValue($("nbAdults")), 10);
	var isUM = (nbAdults == 0);
	$('idTypoChild').innerHTML = isUM ? typoChildUM : typoChildStandard;
	$('typoPassagersAdulte').disabled = isUM;
	$('idNbBebes').disabled = isUM;
	if (isUM) {
		updateOptions($('idNbEnfants'), 1, nbChildrenUM);
	} else {
		/* user cannot select more than 9 passengers */
		var maxChild = Math.min(nbChildrenStandard, 9 - nbAdults)
		updateOptions($('idNbEnfants'), 0, maxChild);
	}
	$('frmMiniBe').action = isUM ? urlMiniBeUM : urlMiniBe;
	

}
function updateOptions(input, newMin, newMax) {
	
	var currentMin = parseInt(input.options[0].value, 10);
	var currentMax = parseInt(input.options[input.options.length - 1].value, 10);
	var currentSelected = input.value;
	
	if (newMin > currentMin) {
		for (var i = 0; i < newMin - currentMin; i++) {
			input.remove(0);
		}
	} else if (newMin < currentMin) {
		for (var i = currentMin - 1; i >= newMin; i--) {
			addOption(input, i, 0);
		}	
	}
	if (newMax < currentMax) {
		for (var i = 0; i < currentMax - newMax; i++) {
			input.remove(input.options.length - 1);
		}
	} else if (newMax > currentMax) {
		for (var i = currentMax + 1; i <= newMax; i++) {
			addOption(input, i, input.options.length);
		}	
	}
		
	if (currentSelected < newMin) {
		input.options[0].selected = true;
	} else if (currentSelected > newMax) {
		input.options[input.options.length-1].selected = true;
	}
	
}
function addOption(input, value, position) {
	var newOption = document.createElement("option");
	newOption.text = value;
	newOption.value = value;	
	input.options.add(newOption, position);
}
function loginAbonnes() {
	errorMessage = '';       
	$('imgNumeroAbonne').style.display = 'none';
	$('imgNameAbonne').style.display = 'none';
	$('imgNumeroFBAbonne').style.display = 'none';
	$('imgPasswordFBAbonne').style.display = 'none';

	var abLogin = trim($('idNumeroAbonne').value);
	var abName = trim($('idNameAbonne').value);
	var fbLogin = trim($('idNumeroFBAbonne').value);
	var fbPassword = trim($('idPasswordFBAbonne').value);

  if (abLogin != "" || abName != "" || (fbLogin == "" && fbPassword == "")) {
		if (!emptyField(abLogin, msgMandatoryField, 'imgNumeroAbonne') && !emptyField(abName, msgMandatoryField, 'imgNameAbonne')) {
			controlNum(abLogin, msgAbonneNumberNum, 'imgFbNumber');
			/*controlAlpha(abName, msgAbonneNameAlpha, 'imgNameAbonne');*/
			controlLength(abLogin, 8, 16, msgAbonneNumberLength, 'imgFbNumber');
			controlLength(abName, 2, 30, msgAbonneNameLength, 'imgNameAbonne');
		}
  } else {
  	if (!emptyField(fbLogin, msgMandatoryField, 'imgNumeroFBAbonne') && !emptyField(fbPassword, msgMandatoryField, 'imgPasswordFBAbonne')) {
			controlAlphaNum(fbLogin, msgFbNumberAlphaNum, 'imgNumeroFBAbonne');
			controlAlphaNum(fbPassword, msgFbPasswordAlphaNum, 'imgPasswordFBAbonne');
			controlLength(fbLogin, 6, 16, msgFbNumberLength, 'imgNumeroFBAbonne');
			controlLength(fbLogin, 4, 10, msgFbPasswordLength, 'imgPasswordFBAbonne');
		}
  }
  
  if (!showErrorMessage()) {
  		$('abonneForm').submit();
  }	
}

/* -------------------------- */


function validFormEcheckin() {
	var identType = $('identType').options[$('identType').selectedIndex].value;
	var identNumber = trim($('identNumber').value);
	var theForm  = $('formEcheckin');
  
	if (identType == '' && identNumber == '') {
		af_go('/' + cu_Marche + '/' + cu_Langue + '/local/core/engine/echeckin/action/TransitionFlyPaxAction.do', echeckinPopupParam);
	} else {
		if (echeckinPopupParam) {
			// open popup
			window.open('', 'echeckinPopup', echeckinPopupParam);
			theForm.target = 'echeckinPopup';	
		}
		if (theForm.action == '') {
			theForm.action = 'https://www2.klm.com/gs/ici/checkin/Main/FlightPax';
		}
	theForm.submit();
}
}

/* -------------------------- */


function validFormMMB() {
		errorMessage = '';       
		$('imgMmbRefPnr').style.display = 'none';
		$('imgMmbName').style.display = 'none';
		
    var name = trim($('idName').value);
    var refPnr = trim($('idRefPnr').value);

		if (!emptyField(refPnr, msgMandatoryField, 'imgMmbRefPnr') && !emptyField(name, msgMandatoryField, 'imgMmbName')) {
			controlAlphaNum(refPnr, msgRecLocAlphaNum, 'imgMmbRefPnr');
			/*controlAlpha(name, msgNomAlphaAvecEspace, 'imgMmbName');*/
			controlLength(refPnr, 6, 6, msgRecLoc, 'imgMmbRefPnr');
			controlLength(name, 2, 30, msgNomPlageLong, 'imgMmbName');
		}

    if (!showErrorMessage()) {
			 submitFormMMB();
    }
}

function submitFormMMB() {
	if (mmbPopupParam) {
		// open popup
		window.open('', 'mmbPopup', mmbPopupParam);
		$('mesReservationsForm').target = 'mmbPopup';	
	}
		$('mesReservationsForm').submit();  
} 

/* --------------------------- */

function hp_showFlexibility(isShow) {
	var visibility = isShow ? 'visible' : 'hidden';  /* valeur du style 'visibility' */
	$('heureOuFlexibiliteAller').style.visibility = visibility;
	$('heureOuFlexibiliteRetour').style.visibility = visibility;
}

/* --------------------------- */

function saveOrigineInCookie() {
  var date=new Date;
  date.setFullYear(date.getFullYear()+10);
  EcrireCookie("aeroportDepartDefaut", $("idDepartureTrip1").value, date, "/");
  EcrireCookie("outboundCountryDefaut", $("idOutboundCountry").value, date, "/");
}
function loadLoginFromCookie() {
	var savedLogin = LireCookie("login");
	if (savedLogin != null && savedLogin != "none") {
	    return savedLogin;
	} else {
	    return "";
	}
}
function saveLoginInCookie(newLogin) {
	var existingLogin = LireCookie("login");
	/* si la valeur est "none", cela signifie qu'il a decoche la case rememberMe dans une des page de login */
	/* si ce n'est pas le cas, on sauvegarde son login */   
	if (existingLogin != "none") {
		// sauvegarde cookie
		date=new Date;
		date.setFullYear(date.getFullYear()+10);
		EcrireCookie("login", newLogin, date, '/');
	}
}


/* -------  Escales  ------ */

// Dev listes countries
function hp_cleanStopover() {
  while($('idDepartureTrip1').length>0) {
    $('idDepartureTrip1').options[$('idDepartureTrip1').length-1] = null;
  }
}

function hp_updateStopover() {
   hp_cleanStopover();
   var selectedCountry = $('idOutboundCountry').options[$('idOutboundCountry').selectedIndex].value;
   hp_fillStopover(selectedCountry);
}

var hp_countriesStopoverTab = new Array();
/* departDefault vient de miniBeInit.jsp */
stopoverToSelect = "";
countryToSelect = "";

function hp_fillStopover(country) {
    for(var j = 0;j <$('idOriginStopoverTranslatedByCountryMap').options.length ;j++) {
       var iata = $('idOriginStopoverTranslatedByCountryMap').options[j].value;
       if (hp_countriesStopoverTab[iata] == country) {
          var newElmt = document.createElement("option");
          newElmt.setAttribute("value", iata);
          newElmt.innerHTML = $('idOriginStopoverTranslatedByCountryMap').options[j].text;
          if (iata == stopoverToSelect ) {
            newElmt.setAttribute("selected", "true");
          }          
          $('idDepartureTrip1').appendChild(newElmt);

        }
    }
    document.onChangeStopover();
}

function hp_updateCountryListSelection() {
  if (countryToSelect != "") {
    var countries = $('idOutboundCountry');
    countries.selectedIndex = -1;
    for (var j = 0;j<countries.length; j++) {
      if (countries.options[j].value == countryToSelect) {
        countries.selectedIndex = j;
        break;
      }
    } 
  }
}

/* --------  Flight Type  --------------- */

function hp_AllerSimple() {
    /* Griser les champs */
    $("jourRetour").disabled = true;
    $("heureOuFlexibiliteRetour").disabled = true;
    $("libJourRetour").className = "libDateDisabled";
	$("libJourRetour").disabled = true;
}
function hp_AllerRetour () { 
    /* Reactive les champs  */
    $("jourRetour").disabled = false;
    $("heureOuFlexibiliteRetour").disabled = false;
    $("libJourRetour").className = "libDate";
	$("libJourRetour").disabled = false;
}

/*----------  Ajax (Login) ------------- */

function getHTTPObject() {
  var xmlhttp;
  /*@cc_on
  @if (@_jscript_version >= 5)
    try {
      xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
      try {
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
      } catch (E) {
        xmlhttp = false;
      }
    }
  @else
  xmlhttp = false;
  @end @*/
  if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
    try {
      xmlhttp = new XMLHttpRequest();
    } catch (e) {
      xmlhttp = false;
    }
  }
  return xmlhttp;
}
var http = null;
var func_callback = "";
function doRequest(URL,method, callback, params) {
	if(func_callback!="")
	{
		return -1; /*Request already processing*/
	}
	func_callback = callback;
	http = getHTTPObject(); // We create the HTTP Object
	if(!http)
	{
		return -2; /*Navigator can't create connexion due to older navigator*/
	}
	if (!params) {
		params = null;
	}
	try {
		http.onreadystatechange = handleHttpResponse;		
		http.open(method,URL, true);
		if (params) {
			http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
			http.setRequestHeader("Content-length", params.length);
			http.setRequestHeader("Connection", "close");
		}
	  	http.send(params);
	} catch (e) 
	{
		return -3; /*Navigator can't connect to server or can't change domain*/
	}
  	
}

function doRequestXml(URL, method, callback, params) {
	if(func_callback!="")
	{
		return -1; /*Request already processing*/
	}
	func_callback = callback;
	http = getHTTPObject(); // We create the HTTP Object
	if(!http)
	{
		return -2; /*Navigator can't create connexion due to older navigator*/
	}
	if (!params) {
		params = null;
	}
	try {
		http.onreadystatechange = handleHttpResponseXml;		
		http.open(method, URL, true);
 		if (params) {
			http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
			http.setRequestHeader("Content-length", params.length);
			http.setRequestHeader("Connection", "close");
		}
	  	http.send(params);
	} catch (e) 
	{
		return -3; /*Navigator can't connect to server or can't change domain*/
	}
  	
}

function handleHttpResponse() {
  if (http.readyState == 4) {
    results = http.responseText;
    var toeval = func_callback+"("+results+")";
    func_callback="";
    eval(toeval);
  }
}

function handleHttpResponseXml() {
  if (http.readyState == 4) {
    results = http.responseXML;
    var toeval = func_callback+'(http.responseXML)';
    func_callback="";
    eval(toeval);
  }
}

/* -------- Comops -------------- */


function parseXml(text) {
	try {
		//Internet Explorer
		xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
		xmlDoc.async="false";
		xmlDoc.loadXML(text);
	} catch(e) {
		try {
			//Firefox, Mozilla, Opera, etc.
			parser=new DOMParser();
			xmlDoc=parser.parseFromString(text,"text/xml");
		} catch(e) {
			alert(e.message);
			return;
		}
	}
	
	return xmlDoc;
};

function showComops() {
	if (!xmlComops) {
		return;
	}
	
	var xmlElement = parseXml(xmlComops);
	var affichage = xmlDoc.getElementsByTagName("affichage")[0].childNodes[0].nodeValue

	if (affichage == 'true') {
		var ccoLanguage = (cu_Langue == 'fr') ? 'fr' : 'en';

		var libelle_1 = getXmlValue(xmlDoc, "libelle_1_" + ccoLanguage);
		var url_1 = getXmlValue(xmlDoc, "url_1_" + ccoLanguage);
		var url_visuel_1 = getXmlValue(xmlDoc, "url_visuel_1_" + ccoLanguage);
		var libelle_2 = getXmlValue(xmlDoc, "libelle_2_" + ccoLanguage);
		var url_2 = getXmlValue(xmlDoc, "url_2_" + ccoLanguage);
		var url_visuel_2 = getXmlValue(xmlDoc, "url_visuel_2_" + ccoLanguage);

		if (libelle_1) {
			if (url_visuel_1) {
				$('ccoImg1').src = replaceJspCode(url_visuel_1);
			} else {
				$('ccoImg1').style.visibility = "hidden";
				$('ccoImg1').style.height = "1px";
				$('ccoImg1').src = "/FR/common/common/img/pixel/pixtrans.gif";
			}
			$('ccoLib1').innerHTML = replaceJspCode(libelle_1);
			if (url_1) {
			$('ccoLib1').onclick = function() {af_go(replaceJspCode(url_1), '')};
		}
		}
		if (libelle_2) {
			if (url_visuel_2) {
				$('ccoImg2').src = replaceJspCode(url_visuel_2);
			} else {
				$('ccoImg2').style.visibility = "hidden";
				$('ccoImg2').style.height = "1px";
				$('ccoImg2').src = "/FR/common/common/img/pixel/pixtrans.gif";
			}
			$('ccoLib2').innerHTML = replaceJspCode(libelle_2);
			if (url_2) {
			$('ccoLib2').onclick = function() {af_go(replaceJspCode(url_2), '')};
		}
		}
		if (!url_1 && !url_2) {
			$('bandeauCCO').style.cursor = 'default';
		}
		$('bandeauCCO').style.display = 'block';
	}
}
function showCrise() {
	if (!xmlCrise) {
		return;
	}

	var xmlElement = parseXml(xmlCrise);
	var affichage = xmlDoc.getElementsByTagName("affichage")[0].childNodes[0].nodeValue
	var listeMarches = xmlDoc.getElementsByTagName("listeMarches")[0].childNodes[0].nodeValue

	if (affichage == 'true' && (listeMarches && listeMarches.indexOf(cu_Marche) >= 0)) {
		var libelle = getXmlValue(xmlDoc, "libelle");
		var url = getXmlValue(xmlDoc, "url");
		var popup = getXmlValue(xmlDoc, "popup");
		
		$('criseLib').innerHTML = libelle;
		$('bandeauCrise').onclick = function() {af_go(replaceJspCode(url), popup)};
		
		$('criseImg1').src = "/FR/common/common/img/pictos/crisisWarning.gif";
		
		$('bandeauCrise').style.display = 'block';
	}
}
function getXmlValue(xmlDoc, key) {
	var tags = xmlDoc.getElementsByTagName(key);
	if (tags && tags.length > 0) {
		var nodes = tags[0].childNodes;
		if (nodes && nodes.length > 0) {
			return nodes[0].nodeValue
		}
	}
	return "";
}
function replaceJspCode(txt) {
	if (txt) {
		return txt.replace(/<%= *codeMarche *%>/, cu_Marche).replace(/<%= *codeLangue *%>/, cu_Langue)
	}
}




/* -------- Languages list -------------- */

function showLanguagesList() {
    var languageList  = $("listOtherLanguages");
    languageList.style.display = (languageList.style.display == 'none') ? 'block' : 'none';
}

/* -------- Search in site -------------- */

function searchInSite(url) {
	document.location = url + $('idSearchSite').value;
}


/* --------  Hack IE7  ------------------ */

function isWinIE7() {
	if (/MSIE (\d+\.\d+);/.test(navigator.userAgent)){ 
		var ieversion=new Number(RegExp.$1) // capture x.x portion and store as a number
		return ieversion>=7;
	} else {
		return false;
	}
}
function isWinIE6ouMoins() {
	return isWinIE() && !window.XMLHttpRequest;
}
function isWinIE() {
	var infoNav = navigator.userAgent.toLowerCase();
	return infoNav.indexOf("msie") != -1 && infoNav.indexOf("mac") == -1;
}
function isMacIE() {
	var infoNav = navigator.userAgent.toLowerCase();
	return infoNav.indexOf("msie") != -1 && infoNav.indexOf("mac") != -1;
}
function isSafari() {
	return navigator.userAgent.toLowerCase().indexOf("safari") != -1;
}
function isMacFF() {
	var infoNav = navigator.userAgent.toLowerCase();
	return infoNav.indexOf("firefox") != -1 && infoNav.indexOf("mac") != -1;
}
function isMozilla() {
	var infoNav = navigator.userAgent.toLowerCase();
	return infoNav.indexOf("mozilla") != -1;
}
function isMac() {
	var infoNav = navigator.userAgent.toLowerCase();
	return infoNav.indexOf("mac") != -1;	
}
function getSize(sizeWithPx) {
	return sizeWithPx.substring(0, sizeWithPx.length - 2);
}


// The function below was developed by John Resig
// For additional info see:
// http://ejohn.org/projects/flexible-javascript-events
// http://www.quirksmode.org/blog/archives/2005/10/_and_the_winner_1.html
function addEvent(obj, type, fn){
	if (typeof obj == 'undefined' || !obj) return false;
	if(obj.addEventListener){
		obj.addEventListener(type, fn, false);
	}
	else if(obj.attachEvent){
		obj["e" + type + fn] = fn;
		obj[type + fn] = function(){
				obj["e" + type + fn](window.event);
			}
		obj.attachEvent("on" +type, obj[type+fn]);
	}
}

function getPosX(obj) {
	var curleft = 0;
	if (obj.offsetParent) {
		while (obj.offsetParent) {
			curleft += obj.offsetLeft
			obj = obj.offsetParent;
		}
	} else if (obj.x) {
		curleft += obj.x;
	}
	return curleft;
}
function getPosY(obj) {
	var curtop = 0;
	if (obj.offsetParent) {
		while (obj.offsetParent) {
			curtop += obj.offsetTop
			obj = obj.offsetParent;
		}
	} else if (obj.y) {
		curtop += obj.y;
	}
	return curtop;
}
function getMarginLeft(obj) {
	return obj.style.marginLeft;
}
function getWidth(obj) {
	return obj.offsetWidth;
}
function getHeight(obj) {
	return obj.offsetHeight;
}

function getWindowWidth() {
   if (navigator.appName=="Netscape") {
     return window.innerWidth-16;
   } else {
     return document.body.offsetWidth-20;
   }
}
function getWindowHeight() {
   if (navigator.appName=="Netscape") {
     return window.innerHeight-16;
   } else {
     return document.body.offsetHeight-20;
   }
}
function getDiv(divId) {
	if (document.getElementById) {
		return document.getElementById(divId);
	} else if (document.all) {
		return document.all[divId];
	} else if (document.layers)	{
		return document.layers[divId];
	}
}
function DstepRoll(ImgNam,Chemimg,Mylayon){
	var ns4=(document.layers)?true:false;
	var ie4=(document.all)?true:false;
	var ns6=(document.getElementById && !document.all)?true:false;
	var imgToRoll;
	if(Mylayon==0){
		if(document.images){imgToRoll=document.images[ImgNam];}
	} else {
		if (ns4){imgToRoll=document.layers[Mylayon].document.images[ImgNam];}
		if (ie4||ns6) {imgToRoll=document.images[ImgNam];}
	}
	
	if (imgToRoll) {
		imgToRoll.src=Chemimg;
	}
}
/*-----------  Gestion des elements select -----------------*/
/**
 * visible: true ou false, pour afficher ou masquer les select
 * elemMenu: l'element du menu qui définit la zone à masquer/afficher
 */
function setSelectVisibility(visible,elemMenu){ 

	var x = getPosX(elemMenu);
	var y = getPosY(elemMenu);
	var w = getWidth(elemMenu);
	var h = getHeight(elemMenu)

	var selx,sely,selw,selh,i 
	var sel=document.getElementsByTagName("SELECT") 
	for(i=0;i<sel.length;i++){ 
		selx=0; sely=0; var selp; 
		if(sel[i].offsetParent){ 
			selp=sel[i]; 
			while(selp.offsetParent){ 
				selp=selp.offsetParent; 
				selx+=selp.offsetLeft; 
				sely+=selp.offsetTop; 
			} 
		} 
		selx+=sel[i].offsetLeft; 
		sely+=sel[i].offsetTop; 
		selw=sel[i].offsetWidth; 
		selh=sel[i].offsetHeight;
		/*ajout seb pour ne pas masquer tous les select par verif si menu = false*/ 
		if(selx+selw>x && selx<x+w && sely+selh>y && sely<y+h && !sel[i].menu ){
			if(visible){
				if (updateCountHidden(sel[i],-1)==0){
					sel[i].style.visibility="visible"; 				
				}
			}else{
				updateCountHidden(sel[i],+1);
				sel[i].style.visibility="hidden";
			}
		}
	} 
} 
function updateCountHidden(sel, delta) {
	if (!sel.countHidden) {  /* initialize to 0 if sel is displayed, or to 1 if sel is hidden */
		if (sel.style.visibility == 'hidden' || sel.style.display == 'none') {
			sel.countHidden = 1;
		} else {
			sel.countHidden = 0;
		}
	}
	sel.countHidden += delta; 
	return sel.countHidden;
}

/*----------------- Pour eviter des erreurs JS ----------*/

function reloadSiNetscape() {
	
}

/*-------------------------------------------------------*/

function redirectToMobileSite() {

	var agt=navigator.userAgent;
	
	var is_mozilla = (agt.indexOf("Mozilla/") != -1);
	var is_opera = (agt.indexOf("Opera/") != -1);
	var is_operamini = (agt.indexOf("Opera Mini/") != -1);
	var is_operamini_linux = (agt.indexOf("Linux i686") != -1);
	var is_operamini_version = (agt.indexOf("Opera 7.50") != -1);
	var is_googlebot = (agt.indexOf("google") != -1);
	var is_yahoobot = (agt.indexOf("yahoo") != -1);
	var is_msnbot = (agt.indexOf("msn") != -1);

	if( (!is_opera && !is_mozilla && !is_googlebot && !is_yahoobot && !is_msnbot) || is_operamini || (is_operamini_linux && is_operamini_version) ) {
		document.location.replace('http://mobile.airfrance.com?LG='+cu_Langue.toUpperCase());
	} else {
		var minSize=480;
		if (screen.width <= minSize || screen.height <= minSize) {
			document.location.replace('http://mobile.airfrance.com?LG='+cu_Langue.toUpperCase());
		}
	}
}

/*-------------- Webtrends sur login FB -----------------*/

function sendWebTrendsFBLogin(wtLevel, wtSolde){
	if( typeof(_metron) != 'undefined' ){
		var wtIdent = "";
  	switch (parseInt(wtLevel)) {
		 case 0:
		 	wtIdent = "Not logged";
		 break;
		 case 1:
		 	wtIdent = "Ivory";
		 break;
		 case 2:
		 	wtIdent = "Silver";
		 break;
		 case 3:
		 	wtIdent = "Club 2000";
		 break;
		 case 4:
		 	wtIdent = "Jeune";
		 break;
		 case 5:
		 	wtIdent = "Jeune";
		 break;
		 case 6:
		 	wtIdent = "Gold";
		 break;
		 case 7:
		 	wtIdent = "Platinum";
		 break;
		 default: 
		 	wtIdent = "N/A";
		 break;
		}
  	_metron.measureVariable("z_cardLevel", wtIdent);
  	_metron.measureVariable("z_nbMiles", wtSolde);
  	_metron.measureVariable("z_dl", "99");
  	_metron.measuresCommit();
	}
}
