var defaultDwrPath = "dwr";

// début fonctions ajax
function updateList(autocompleter, token) {
	GlobalGeoServiceFacade._path = defaultDwrPath;
	GlobalGeoServiceFacade.find(token, function(data) {
		autocompleter.setChoices(data)
	});
}
function updateCityList(autocompleter, token) {
	GlobalGeoServiceFacade._path = defaultDwrPath;
	GlobalGeoServiceFacade.findOnlyCities(token, function(data) {
		autocompleter.setChoices(data)
	});
}
function updatePoiList(autocompleter, token) {
	PoiServiceFacade._path = defaultDwrPath;
	PoiServiceFacade.findCompletePoiTitles(token, function(data) {
		autocompleter.setChoices(data)
	});
}
function updateCityListWithCountryArg(autocompleter, token) {
	CityServiceFacade._path = defaultDwrPath;
	CityServiceFacade.findCompleteCityNames(token, document
			.getElementById("countryCode").value, function(data) {
		autocompleter.setChoices(data)
	});
}
function updateCountryList(autocompleter, token) {
	CityServiceFacade._path = defaultDwrPath;
	CityServiceFacade.findCompleteCountryNames(token, function(data) {
		autocompleter.setChoices(data)
	});
}
function emailList(autocompleter, token) {
	idSociete = document.getElementById("idSociete");
	UserServiceFacade._path = defaultDwrPath;
	UserServiceFacade.getCompleteEmail(token, idSociete.value, function(data) {
		autocompleter.setChoices(data)
	});
}
function updateHotelNameList(autocompleter, token) {
	HotelServiceFacade._path = defaultDwrPath;
	HotelServiceFacade.getCurrentHotelNameList(token, function(data) {
		autocompleter.setChoices(data)
	});
}
function updateAgencyList(setterFunction, zipCode, micrositeId) {
	UserServiceFacade._path = defaultDwrPath;
	UserServiceFacade.findAgenciesByZipCode(zipCode, micrositeId, setterFunction);
}

function nameValueSelector(tag) {
	return tag;
}

// ###### City Code
var requestSent = 0;
var responseReceived = 0;

function doSubmit(nbMax) {
	if (nbMax > 0) {
		var searchString0 = DWRUtil.getValue('name0');
		if (searchString0 != "") {
			requestSent++;
			GlobalGeoServiceFacade._path = defaultDwrPath;
			GlobalGeoServiceFacade
					.findGlobalGeoByName(fillCity0, searchString0);
		}
	}

	if (nbMax > 1) {
		var searchString1 = DWRUtil.getValue('name1');
		if (searchString1 != "") {
			requestSent++;
			GlobalGeoServiceFacade._path = defaultDwrPath;
			GlobalGeoServiceFacade
					.findGlobalGeoByName(fillCity1, searchString1);
		}
	}

	if (nbMax > 2) {
		var searchString2 = DWRUtil.getValue('name2');
		if (searchString2 != "") {
			requestSent++;
			GlobalGeoServiceFacade._path = defaultDwrPath;
			GlobalGeoServiceFacade
					.findGlobalGeoByName(fillCity2, searchString2);
		}
	}

	if (nbMax > 3) {
		var searchString3 = DWRUtil.getValue('name3');
		if (searchString3 != "") {
			requestSent++;
			GlobalGeoServiceFacade._path = defaultDwrPath;
			GlobalGeoServiceFacade
					.findGlobalGeoByName(fillCity3, searchString3);
		}
	}

	if (nbMax > 4) {
		var searchString4 = DWRUtil.getValue('name4');
		if (searchString4 != "") {
			requestSent++;
			GlobalGeoServiceFacade._path = defaultDwrPath;
			GlobalGeoServiceFacade
					.findGlobalGeoByName(fillCity4, searchString4);
		}
	}
	waitForRequestDone();
}

function waitForRequestDone() {
	if (responseReceived < requestSent) {
		// timeout 1s appel en récursif waitForRequestDone
		setTimeout("waitForRequestDone()", 5);
	} else {
		clearTimeout("waitForRequestDone()");
		//setTimeout("showWaitDisplay()", 200);
		showWaitDisplay();
		document.getElementById("hotelsSearchForm").submit();
	}
}

function fillCity0(aGeo) {
	if (aGeo != null) {
		hiddenCodeInput = document.getElementById("code0");
		if (aGeo.isCitySet) {
			hiddenCodeInput.value = aGeo.cityTO.cityCode;
		} else if (aGeo.isPoiSet) {
			hiddenCodeInput.value = aGeo.poiTO.id;
		}
		responseReceived++;
	} else {
		responseReceived++;
	}
}
function fillCity1(aGeo) {
	if (aGeo != null) {
		hiddenCodeInput = document.getElementById("code1");
		if (aGeo.isCitySet) {
			hiddenCodeInput.value = aGeo.cityTO.cityCode;
		} else if (aGeo.isPoiSet) {
			hiddenCodeInput.value = aGeo.poiTO.id;
		}
		responseReceived++;
	} else {
		responseReceived++;
	}
}
function fillCity2(aGeo) {
	if (aGeo != null) {
		hiddenCodeInput = document.getElementById("code2");
		if (aGeo.isCitySet) {
			hiddenCodeInput.value = aGeo.cityTO.cityCode;
		} else if (aGeo.isPoiSet) {
			hiddenCodeInput.value = aGeo.poiTO.id;
		}
		responseReceived++;
	} else {
		responseReceived++;
	}
}
function fillCity3(aGeo) {
	if (aGeo != null) {
		hiddenCodeInput = document.getElementById("code3");
		if (aGeo.isCitySet) {
			hiddenCodeInput.value = aGeo.cityTO.cityCode;
		} else if (aGeo.isPoiSet) {
			hiddenCodeInput.value = aGeo.poiTO.id;
		}
		responseReceived++;
	} else {
		responseReceived++;
	}
}
function fillCity4(aGeo) {
	if (aGeo != null) {
		hiddenCodeInput = document.getElementById("code4");
		if (aGeo.isCitySet) {
			hiddenCodeInput.value = aGeo.cityTO.cityCode;
		} else if (aGeo.isPoiSet) {
			hiddenCodeInput.value = aGeo.poiTO.id;
		}
		responseReceived++;
	} else {
		responseReceived++;
	}
}
// ###### City Code
// fin fonctions ajax

// ################################################
// DEBUT METHODES POUR LE LANCEMENT DE LA RECHERCHE

var SEARCH_ACCOMS_WITH_ADDRESS = "SEARCH_ACCOMS_WITH_ADDRESS";
var SEARCH_ACCOMS_WITH_CODES = "SEARCH_ACCOMS_WITH_CODES";

function launchHotelsSearch() {
    var continueProcess = true;
    var beginDate = document.getElementById("byDayBeginDate");
    if (beginDate != null){
        if (isDateLessThanJPlus3(beginDate.value)){
            alert("Départ non autorisé moins de 48h après la réservation");
            continueProcess = false;
        }
    }
    
    if (continueProcess == true){
        document.getElementById("actionRequested").value = "SEARCH_ACCOMS";

        var searchType = document.getElementById("searchType");
        if (searchType != null) {
            if (searchType.value == SEARCH_ACCOMS_WITH_CODES) {
                launchHotelsSearchWithCodes();
            } else if (searchType.value == SEARCH_ACCOMS_WITH_ADDRESS) {
                launchHotelsSearchWithAddress();
            }
        }
    }
    
    
}

function launchHotelsSearchWithThisAdress(nb) {
	document.getElementById("actionRequested").value = "SEARCH_ACCOMS";

	//setTimeout("showWaitDisplay()", 200);
	showWaitDisplay();
	var form = document.getElementById("hotelsSearchForm");
	form.selectedGeoAdr.value = nb;

	form.submit();
}

function launchHotelsSearchWithCodes() {
	// on conserve l'id de la ville dans la variable cityCode (utilisée dans le
	// controleur)
	var nbCitySearched = 0;
	var nbMax = document.getElementById("maxNbOfPossibleCity").value;

	for ( var i = 0; i < nbMax; i++) {
		if (trim(document.getElementById("name" + i).value) != "") {
			nbCitySearched++;
		}
	}

	if (nbCitySearched == 0) {
		document.getElementById("name0").focus();
		alert("La saisie d'une destination est obligatoire.");
	} else {
		if (trim(document.getElementById("byDayBeginDate").value) != ""
				&& trim(document.getElementById("byDayEndDate").value) != "") {
			// Lancement de la recherche
			doSubmit(nbMax);
		} else {
			alert("Veuillez saisir une date de départ et une date d'arrivée.");
		}
	}
}

function launchHotelsSearchWithAddress() {
	if (searchAccomsWithAddressFieldsCheck()) {
		//setTimeout("showWaitDisplay()", 200);
		showWaitDisplay();
		document.getElementById("hotelsSearchForm").submit();
	}
}

// validation champs saisies pour la recherche par adresse
function searchAccomsWithAddressFieldsCheck() {
	var addressExists = "false";
	var cityExists = "false";

	var address = document.getElementById("address");
	if (address != null && address.value != null && address.value.length > 0) {
		addressExists = "true";
	}

	if (addressExists == "true") {
		return true;
	} else {
		alert("Recherche par adresse / La saisie d'une adresse est obligatoire");
	}
	return false;
}

// ################################################
// FIN METHODES POUR LE LANCEMENT DE LA RECHERCHE

function searchCountryCode() {
	var searchString = DWRUtil.getValue('searchCountry');
	CityServiceFacade.findCountryCodeByCountryName(searchString,
			fillCountryCode);
}

function fillCountryCode(data) {
	if (data == null || data == "") {
		document.getElementById("searchCountry").value = "Tous";
		document.getElementById("countryCode").value = "";
	} else {
		document.getElementById("countryCode").value = data;
	}
}

function showWaitDisplay() {
	document.location.href = "#"; // on remonte la page
	displayAndBlockElement('lightboxbg-search');
	displayAndBlockElement('wait-anim');

	// //hideElement("contentZone");
	// getSearchedCriterias();
	// //displayAndBlockElement('waitZone');
	// displayAndBlockElement('searchSummaryFieldset');

	hideElementsSelect();

	return true;
}

function hideElementsSelect() {
	// on cache les select qui reste au dessus dans IE6
	var tags = document.getElementsByTagName("SELECT");
	if (tags != null && tags.length) {
		for ( var i = 0; i < tags.length; i++) {
			tags[i].style.display = "none";
			tags[i].style.visibility = "hidden";
		}
	}

}

function showElementsSelect() {
	// on cache les select qui reste au dessus dans IE6
	var tags = document.getElementsByTagName("SELECT");
	if (tags != null && tags.length) {
		for ( var i = 0; i < tags.length; i++) {
			tags[i].style.display = "";
			tags[i].style.visibility = "visible";
		}
	}

}

function hideElement(elementName) {
	var element = document.getElementById(elementName);
	if (element != null) {
		element.style.visibility = "hidden";
		element.style.display = "none";
	}
}

function showElement(elementName) {
	var element = document.getElementById(elementName);
	if (element != null) {
		element.style.visibility = "visible";
		element.style.display = "block";
	}
}

function showHideElement(elementName) {

	if (elementName != "mailBlock")
		hideElement("mailBlock");

	var element = document.getElementById(elementName);
	if (element != null) {
		if (element.style.visibility == "visible"
				|| element.style.display == "block") {
			hideElement(elementName);
		} else {
			showElement(elementName);

			if (elementName == "mailBlock") {
				var newUrl = "#" + "mailBlockEncre";
				document.location.href = newUrl;
			}
		}
	}
	if (document.getElementById('downloadEmail') != null)
		document.getElementById('downloadEmail').focus();

}

function showHideElementAndRenameButton(elementName, buttonName, buttonValue0,
		buttonValue1) {
	showHideElement(elementName);
	if (elementName == 'detailedSearchBlock') {
		showHideElement('detailedSearchBlock_budget');
	}
	var button = document.getElementById(buttonName);
	if (button != null) {
		if (button.value == buttonValue0) {
			button.value = buttonValue1;
		} else {
			button.value = buttonValue0;
		}
	}
}

function switchCheckbox(checkboxId) {
	var chk = document.getElementById(checkboxId);
	if (chk != null) {
		if (chk.checked || chk.checked == "checked") {
			chk.checked = false;
		} else {
			chk.checked = "checked";
		}
	}
}

function emailIsValid(email) {
	var regexp = "^([_a-z0-9-]+)(.[_a-z0-9-]+)*@([a-z0-9-]+)(.[a-z0-9-]+)*(.[a-z]{2,4})$";
	if (email.match(regexp)) {
		return true;
	}
}

function dateIsValid(mydate) {
	var regexp = "^((0?[0-9])|([12][0-9])|(3[01]))\/((0?[0-9])|(1[012]))\/([0-9]{4})$";
	if (mydate.match(regexp)) {
		return true;
	}
	return false;
}

function inputIsEmpty(inputObject) {

	if (inputObject != null) {
		var textValue = inputObject.value;
		if (textValue == "") {
			return true;
		}
	}
	return false;
}

function goSubmitPaxGetInfo(formName) {
	var formToSubmit = document.getElementById(formName);
	if (formToSubmit != null) {
		formToSubmit.getUserInfo.value = true;
		formToSubmit.submit();
	}
}

// Outil de sélection de checkbox multiple pour les centrales de réservations.
function checkTarget(target) {
	var checkALL = document.getElementById('ALL').checked;

	var GTA = document.getElementById('selectedSupplier_GTA');
	var BOS = document.getElementById('selectedSupplier_BOS');
	var CHA = document.getElementById('selectedSupplier_CHA');
	var ALB = document.getElementById('selectedSupplier_ALB');
	var TRH = document.getElementById('selectedSupplier_TRH');
	var MIK = document.getElementById('selectedSupplier_MIK');

	if (target == 'ALL' && checkALL == true) {
		// griser les autres.
		if (GTA != null) {
			GTA.disabled = true;
		}
		if (BOS != null) {
			BOS.disabled = true;
		}
		if (CHA != null) {
			CHA.disabled = true;
		}
		if (ALB != null) {
			ALB.disabled = true;
		}
		if (TRH != null) {
			TRH.disabled = true;
		}
		if (MIK != null) {
			MIK.disabled = true;
		}
	} else {
		if (target == 'ALL') {
			// ALL est décoché, activer tous les autres.
			if (GTA != null) {
				GTA.disabled = false;
			}
			if (BOS != null) {
				BOS.disabled = false;
			}
			if (CHA != null) {
				CHA.disabled = false;
			}
			if (ALB != null) {
				ALB.disabled = false;
			}
			if (TRH != null) {
				TRH.disabled = false;
			}
			if (MIK != null) {
				MIK.disabled = false;
			}
		}
	}
}

function refreshCityWithPossibleCity(codeGiven, nameNb, fieldNb) {

	var code = document.getElementById('code' + fieldNb);
	var name = document.getElementById('name' + fieldNb);
	var geoName = document.getElementById('geoName' + nameNb);
	var nbMax = document.getElementById("maxNbOfPossibleCity").value;

	code.value = codeGiven;
	name.value = geoName.value;

	// showHideElement('possibleDestinationsDiv' + fieldNb);

	// var changeDisplay = true;

	// for (var j = 0; j < nbMax; j++) {
	// var codeToTest = document.getElementById('code' + j);
	// var nameToTest = document.getElementById('name' + j);

	// changeDisplay = changeDisplay && (nameToTest.textLength < 3 ||
	// codeToTest.value != "");
	// }

	// if (changeDisplay) {
	// showHideElement("possibleDestinationsDiv");
	// showHideElement("standardFormDiv");
	// showHideElement("onglet");
	// }

}

function showCityList(index) {
	document.getElementById("actionRequested").value = "SEARCH_CITIES";
	document.getElementById("cityToSet").value = index;
	document.getElementById("hotelsSearchForm").submit();
}

function addPOI() {
	document.getElementById("actionRequested").value = "ADD_POI";
	document.getElementById("hotelsSearchForm").submit();
}

function changeElementCssName(elementName, newCssName) {
	if (elementName != null) {
		var elementObject = document.getElementById(elementName);
		if (elementObject != null) {
			elementObject.className = newCssName;
		}
	}
}

function changeElementCssNameByObject(elementObject, newCssName) {
	if (elementObject != null) {
		elementObject.className = newCssName;
	}
}

function setValue(elementName, elementValue) {
	if (elementValue != null && elementValue.length > 0) {
		var elementObject = document.getElementById(elementName);
		if (elementObject != null) {
			elementObject.value = elementValue;
		}
	}
}

function getSearchedCriterias() {
	// TODO Améliorer le contenu + rajouter les champs adresse.
	var theDiv = document.getElementById("searchSummaryDiv");

	// var theString = theDiv.innerHTML;
	var theString = "";

	var name0 = document.getElementById("name0");

	theString += name0.value;
	theString += " pour ";

	var numberOfNights = document.getElementById("nightsNumber");
	theString += numberOfNights.value;

	theString += " nuit(s) ";
	theString += " à partir du ";

	var byDayBeginDate = document.getElementById("byDayBeginDate");
	theString += byDayBeginDate.value;

	theString += "<br/>";

	var roomsNumber = document.getElementById("roomsNumber").value * 1 + 1 * 1;
	theString += roomsNumber;

	theString += " chambre(s):";

	theString += "<br/>";

	// var room_type_0 = document.getElementById("room_type_0");
	var roomLine_0 = document.getElementById("roomLine_0");
	var room_adults_0 = document.getElementById("room_adults_0");
	var room_children_0 = document.getElementById("room_children_0");
	var room_infants_0 = document.getElementById("room_infants_0");
	// if (room_type_0 != null && roomLine_0.style.visibility == "visible") {
	if (roomLine_0.style.visibility == "visible") {
		// theString += "1. " + getRoomNameWithValue(room_type_0.value);
		theString += "Chambre 1 : ";
		// theString += " avec ";
		theString += room_adults_0.value;
		theString += " adulte(s) ";
		if (room_children_0.value != null && room_children_0.value != 0) {
			theString += " et " + room_children_0.value + " enfant(s) ";
		}
		if (room_infants_0.value != null && room_infants_0.value != 0) {
			theString += " et " + room_infants_0.value + " bébé(s) ";
		}
		theString += "<br/>";
	}

	// var room_type_1 = document.getElementById("room_type_1");
	var roomLine_1 = document.getElementById("roomLine_1");
	var room_adults_1 = document.getElementById("room_adults_1");
	var room_children_1 = document.getElementById("room_children_1");
	var room_infants_1 = document.getElementById("room_infants_1");
	// if (room_type_1 != null && roomLine_1.style.visibility == "visible") {
	if (roomLine_1.style.visibility == "visible") {
		// theString += "2. " + getRoomNameWithValue(room_type_1.value);
		theString += "Chambre 2 : ";
		// theString += " avec ";
		theString += room_adults_1.value;
		theString += " adulte(s) ";
		if (room_children_1.value != null && room_children_1.value != 0) {
			theString += " et " + room_children_1.value + " enfant(s) ";
		}
		if (room_infants_1.value != null && room_infants_1.value != 0) {
			theString += " et " + room_infants_1.value + " bébé(s) ";
		}
		theString += "<br/>";
	}

	// var room_type_2 = document.getElementById("room_type_2");
	var roomLine_2 = document.getElementById("roomLine_2");
	var room_adults_2 = document.getElementById("room_adults_2");
	var room_children_2 = document.getElementById("room_children_2");
	var room_infants_2 = document.getElementById("room_infants_2");
	// if (room_type_2 != null && roomLine_2.style.visibility == "visible") {
	if (roomLine_2.style.visibility == "visible") {
		// theString += "3. " + getRoomNameWithValue(room_type_2.value);
		theString += "Chambre 3 : ";
		// theString += " avec ";
		theString += room_adults_2.value;
		theString += " adulte(s) ";
		if (room_children_2 != null && room_children_2.value != 0) {
			theString += " et " + room_children_2.value + " enfant(s) ";
		}
		if (room_infants_2.value != null && room_infants_2.value != 0) {
			theString += " et " + room_infants_2.value + " bébé(s) ";
		}
	}

	theDiv.innerHTML = theString;
}

function getRoomNameWithValue(roomValue) {
	if (roomValue == "SG") {
		return 'Individuelle';
	}
	if (roomValue == "DB") {
		return 'Double';
	}
	if (roomValue == "TW") {
		return 'Lits jumeaux';
	}
	if (roomValue == "TP") {
		return 'Triple';
	}
	if (roomValue == "QD") {
		return 'Quadruple';
	}
	return '';
}

function cryptoInfo() {
	alert("Ce cryptogramme est le dernier bloc de trois chiffres que l'on trouve sur le panneau signature au verso des cartes bancaires.");
}

function getElementsByClass( searchClass, domNode, tagName) {
    if (domNode == null) domNode = document;
    if (tagName == null) tagName = '*';
    var el = new Array();
    var tags = domNode.getElementsByTagName(tagName);
    var tcl = " "+searchClass+" ";
    for(i=0,j=0; i<tags.length; i++) {
        var test = " " + tags[i].className + " ";
        if (test.indexOf(tcl) != -1)
            el[j++] = tags[i];
    }
    return el;
}

//vérifie que la date demandée n'est pas la date du jour ni la date du lendemain ni la date du sur lendemain
//en paramètre on reçoit une date en string au format jj/mm/aaaa
function isDateLessThanJPlus3(dateToTest){
  if (dateToTest != null){
      var dateToTestStr = new String(dateToTest);
      if (dateToTestStr != null){
          var yearDateToTestStr = dateToTestStr.substr(6, 4); //pour l'année
          var monthDateToTestStr = dateToTestStr.substr(3, 2); //...
          var dayDateToTestStr = dateToTestStr.substr(0, 2); //...
          var dateToTestDte = new Date(yearDateToTestStr+'/'+monthDateToTestStr+'/'+dayDateToTestStr);        
              
          if (dateToTestDte != null){
              var todayDte = new Date();
              if (todayDte != null){
                  var todayPlus1Dte = new Date();
                  todayPlus1Dte.setDate(todayDte.getDate() + 1);
                  
                  var todayPlus2Dte = new Date();
                  todayPlus2Dte.setDate(todayDte.getDate() + 2);
                  
                  if (areDatesEquals(dateToTestDte, todayDte) || areDatesEquals(dateToTestDte, todayPlus1Dte) || areDatesEquals(dateToTestDte, todayPlus2Dte)){
                      return true;
                  }
              }               
          }
      }       
  }
  return false;
}

//retourne vrai si les jours, mois et annee des deux dates sont identiques
function areDatesEquals(date1, date2){
  if (date1 instanceof Date && date2 instanceof Date){
    if (date1.getDate() == date2.getDate() && date1.getDay() == date2.getDay() && date1.getMonth() == date2.getMonth() && date1.getYear() == date2.getYear()){
        return true;
    }
  }
  return false;       
}
