var MSG_MODIFY_TRAVEL_DATE_INVALID = new String("The departure date you have typed is not available. Please select another departure date.");
var MSG_MODIFY_RETURN_DATE_INVALID = new String("The return date you have typed is not available. Please select another return date.");
var MSG_SERVICE_FEE_INTEGER = "Service fee cannot contain any decimals; value is being rounded to the closest valid amount.";
var MSG_SERVICE_FEE_MAX_PRICE_ERROR = "Service fee should be lower than $";
var MSG_FLIGHTPRICE_INTEGER = "Flight price should be a decimal value !!!";
//var MSG_COMMISSION_CONFIRM = new String("This product is commissionable at 50% of what is paid by the vendor.");
var MSG_COMMISSION_CONFIRM = new String("You are about to transfer to a third party provider. This product is commissionable at 50% of what is paid by the provider.");
var MAX_ELEMENTS_PER_PAGE = 50;
var FILTER_VIEW_ALL_INDEX = 0;
var MAXIMUM_PRICE_PER_PASSENGER = 999999;
var MSG_MAX_PRICE_PER_PASSENGER_ERROR = "Price per passenger should be lower than $";

function KeepThis(){ location.href = FORWARD_KEEP_THIS; }

function UpdatePrice(){
   var f = document.myForm;
   f.elements[FN_ACTION].value = ACTION_REFRESH;
   f.submit();
}

function psSFee(sfee){
  if (sfee != '' && (parseFloat(sfee) - Math.floor(sfee) != 0)) {
    alert(MSG_SERVICE_FEE_INTEGER);
    sfee = Math.round(sfee);
  }
  
  if (sfee != '' && parseFloat(sfee) >= parseFloat(FN_SERVICE_FEE_MAX_PRICE)) {
  	alert(MSG_SERVICE_FEE_MAX_PRICE_ERROR + formatMoney(FN_SERVICE_FEE_MAX_PRICE));
  	sfee = parseFloat(FN_SERVICE_FEE_MAX_PRICE) - 1;
  }

  psCTL.setFees((formatMoney(sfee) == '')? 0.00: formatMoney(sfee));
}
function hideUpdateProtectionPlanPrice() {
	document.getElementById("spPSUPPP").style.display = "none";
}

function showUpdateProtectionPlanPrice() {
	document.getElementById("spPSUPPP").style.display = "block"; 
}

function psFPPP(flightPrice, pos){
  if (flightPrice != '' && (parseFloat(flightPrice) - Math.floor(flightPrice) != 0)) {
    alert(MSG_FLIGHTPRICE_INTEGER);
    flightPrice = Math.round(flightPrice);
  }
  if (flightPrice != '' && parseFloat(flightPrice) >= parseFloat(MAXIMUM_PRICE_PER_PASSENGER)) {
  	  alert(MSG_MAX_PRICE_PER_PASSENGER_ERROR + formatMoney(MAXIMUM_PRICE_PER_PASSENGER));
	  flightPrice = 0;
  }
  document.getElementById("fpInput_" + pos).value = formatMoney(flightPrice); 
  showUpdateProtectionPlanPrice();
}

function initFlightPrice() {
	if (INCLUDES_A_FLIGHT_BY_DEFAULT == false) {
		for(var i = 1; i <= FAKE_GATEWAY_COUNT; i++) {
			var price = document.getElementById("fpInput_" + i).value;
			document.getElementById("fpInput_" + i).value = (formatMoney(price) == '')? 0.00: formatMoney(price);
		}
  	}
}
function initSEG(seg, sp){
//debugger;
   var segCount = seg.getSegments().length - 1;
   for (var i = 0; i < segCount; i++){ document.getElementById(sp + (i+1)).innerHTML = floatHours(seg.getStopOverDuration(i)); }
}

/**
 * Sets the price summary value and updates all of the page's displays.
 */
function setPriceSummary(p, t){
   psCTL.setPrice( formatMoney(parseFloat(psCTL.getPrice()) + parseFloat(p)));
   psCTL.setTaxes( formatMoney(parseFloat(psCTL.getTaxes()) + parseFloat(t)));
   updateProtectionPlanPrice();
   updateDisplays();
}

function modifyTravelDates() {
  if (!dcstart.isValid(getModifyTravelDateDepartureDate())){ alert(MSG_MODIFY_TRAVEL_DATE_INVALID);}
  else if (!isNull(dcend) && !dcend.isValid(getModifyTravelDateReturnDate())){ alert(MSG_MODIFY_RETURN_DATE_INVALID); }
  else { document.boxForm.submit(); }
}

function modifyDepartureDate(daycount) {
  if(!daycount){daycount = TRAVEL_DAYS_COUNT}
  var d = getModifyTravelDateDepartureDate();
  if (d != null) {
    d.setDate(d.getDate() + daycount);
    var year = (d.getFullYear() + 100).toString();
    if (document.boxForm.elements[FN_MODIFY_TRAVEL_DATE_RETURN])
      document.boxForm.elements[FN_MODIFY_TRAVEL_DATE_RETURN].value = dateToStr(d,"numeric");
  }
}


function getModifyTravelDateDepartureDate(){ var elm = document.boxForm.elements[FN_MODIFY_TRAVEL_DATE_DEPARTURE]; return (isEmpty(elm.value))? null : strToDate(elm.value); }
function getModifyTravelDateReturnDate(){ var elm = document.boxForm.elements[FN_MODIFY_TRAVEL_DATE_RETURN]; return (!elm || isEmpty(elm.value))? null : strToDate(elm.value); }

/**
 * Updates all of the page's price displays.
 */
function updateDisplays() {
   // destinations
   for (var i = START_DESTINATION_NUMBER; i < DESTINATION_INFO.length; i++) {
      updateFlightDisplay(i);
      updateFlightDisplay(i);
      updateHotelSuggDisplay(i);
      updateCarDisplay(i);
      updateHotelRoomTypesDisplay(i)
   }
}

/**
 * Updates the flight (gateway or connection) suggestions price display for the given destination.
 */
function updateFlightDisplay(dpos) {
     var oldBookingPrice = parseFloat(psCTL.getPrice()) + parseFloat(psCTL.getTaxes()) + parseFloat(psCTL.getDiscount()) + parseFloat(psCTL.getLastMinuteFees()); 
	 for (var x = 1; x <= DESTINATION_INFO[dpos].flightSuggestions.getSuggestionCount(); x++) {
	    var newBookingPrice = oldBookingPrice; 
	    //Prix si ce vol est selectionné
      	newBookingPrice+= DESTINATION_INFO[dpos].flightSuggestions.getDiffTotal(x - 1);
      	//Calculer la difference de Protection Plan
        var diffPP = getDifferenceProtectionPlanPrice(oldBookingPrice, newBookingPrice);
            
    	var diff = diffPP + adjustPriceDifference(DESTINATION_INFO[dpos].flightSuggestions.getDiffTotal(x - 1));
     	var sp = document.getElementById("spSugFlight" + dpos + "_" + x);
		//*<span class="govtax" onclick="javascript:popWin('/PleasantHolidaysWeb/altFlightGovTaxes.do','gov_taxes',400,200,1);">Govt Taxes/Fees</span>"
		if (sp) {
	    	if (diff == 0) { 
	      		sp.innerHTML = "Same Price"; 
	      	}
	      	else if (diff < 0) { 
	      		sp.innerHTML = PHFormatMoney(diff/NON_LAPCHILD_COUNT).replace("-", "- $")  + " / Person"; 
	      	}
	      	else { 
	      		//sp.innerHTML = "+ $" + PHFormatMoney(diff/NON_LAPCHILD_COUNT) + " / Person";
	      		sp.innerHTML = "+ $" + PHFormatMoney(diff/NON_LAPCHILD_COUNT) + " / Person"; 
	      	}
	      	
	      	spanGovTaxes = document.createElement('SPAN');
	      	sp.appendChild(spanGovTaxes);
	      	spanGovTaxes.className = "govtax";
	      	spanGovTaxes.innerHTML = "*";
	      	aLink = document.createElement('A');
	      	spanGovTaxes.appendChild(aLink);	      	
	      	aLink.href = "javascript:popWin('altFlightGovTaxes.do','gov_taxes',400,200,1);";
	      	aLink.innerHTML = "Govt Taxes/Fees";
	      	
	  	}
	}
}

function updateHotelSuggDisplay(dpos){
  var di = DESTINATION_INFO[dpos];
  // hotel suggestions
    if (di.suggestions != null) {
        var oldType = di.suggestions.getSelectedType();
        var oldBookingPrice = parseFloat(psCTL.getPrice()) + parseFloat(psCTL.getTaxes()) + parseFloat(psCTL.getDiscount()) + parseFloat(psCTL.getLastMinuteFees()); 
        for (var x = 1; x < di.suggestions.getTypeCount(); x++) {
            var newBookingPrice = oldBookingPrice; 
	        //Prix des chambres si cet Hotel est selectionnee
      	    newBookingPrice+= di.roomsCount * (di.suggestions.getType(x).total - oldType.total) ;
      	    //Calculer la difference de Protection Plan
            var diffPP = getDifferenceProtectionPlanPrice(oldBookingPrice, newBookingPrice);
            //Ajouter la difference de Protection Plan 
        	var diff = diffPP + adjustPriceDifference(di.roomsCount * (di.suggestions.getType(x).total - di.hotelRooms.getSelectedType().total));
            var sp = document.getElementById("spSugH" + dpos + x);
            if (sp) {
              sp.innerHTML = setTypePriceLabel(x,di.hotelRooms.getSelectedTypeId(),diff,(diff/di.hotelDuration/di.roomsCount)," Per Room, Per Night", false);
            }
         }
    }
}

function updateHotelRoomTypesDisplay(dpos){
    var di = DESTINATION_INFO[dpos];
    // hotel rooms
    if (di.hotelRooms != null) {
      var hrt = di.hotelRooms;
      var oldType = hrt.getSelectedType();
      var oldBookingPrice = parseFloat(psCTL.getPrice()) + parseFloat(psCTL.getTaxes()) + parseFloat(psCTL.getDiscount()) + parseFloat(psCTL.getLastMinuteFees()); 
      for (var x = 1; x < di.hotelRooms.getTypeCount(); x++) {
	      var newBookingPrice = oldBookingPrice; 
	      //Prix si ce type de chambre est selectionnée
      	  newBookingPrice = newBookingPrice + (di.roomsCount * (di.hotelRooms.getDiffTotal(x)));
      	  //Calculer la difference de Protection Plan
          var diffPP = getDifferenceProtectionPlanPrice(oldBookingPrice, newBookingPrice);
		  //Ajouter la difference de Protection Plan          
  	      diff = diffPP + adjustPriceDifference(di.roomsCount * (di.hotelRooms.getDiffTotal(x)));
          var sp = document.getElementById("spRTP" + dpos + "_" + x);
          if (sp) {
             sp.innerHTML = setTypePriceLabel(x,di.hotelRooms.getSelectedTypeId(),diff,(diff/di.hotelDuration/di.roomsCount)," / Night", true);
          }
      }
  }
}

/**
 * Updates the car types display for the given destination.
 */
function updateCarDisplay(dpos) {
   var di = DESTINATION_INFO[dpos];
   var sdest = di.cars;
   
   if (sdest != null) {
      var oldBookingPrice = parseFloat(psCTL.getPrice()) + parseFloat(psCTL.getTaxes()) + parseFloat(psCTL.getDiscount()) + parseFloat(psCTL.getLastMinuteFees()); 
     
      for (var i = 1; i < sdest.getTypeCount(); i++){
         var newBookingPrice = oldBookingPrice; 
      	 newBookingPrice+= sdest.getDiffTotal(i);
         var diff = 0;
         if (getIsLDWChecked(dpos)) { 
         	diff = sdest.getDiffLDW(i); 
         	newBookingPrice+= sdest.getDiffLDW(sdest.getSelectedTypeId()); 
         }
		 var diffPP = getDifferenceProtectionPlanPrice(oldBookingPrice, newBookingPrice);
		 diff = diff + diffPP + sdest.getDiffTotal(i);
         diff = adjustPriceDifference(diff);
         var sp = document.getElementById("spCTP" + dpos + "_" + (i));

         if (sp) {
	         if (i == sdest.getSelectedTypeId()) { 
	         	sp.innerHTML = "Included in Price";
	         	oldBookingPrice = parseFloat(psCTL.getPrice()) + parseFloat(psCTL.getTaxes()) + parseFloat(psCTL.getDiscount()) + parseFloat(psCTL.getLastMinuteFees()); 
	         	newBookingPrice = oldBookingPrice + sdest.getDiffTotal(sdest.getSelectedTypeId());
	         	// Adjust the LDW price to fit with displayed total price.
	         	var ldw = sdest.getType(i).ldwCost;
	         	newBookingPrice+=ldw;
	         	
	         	diffPP = getDifferenceProtectionPlanPrice(oldBookingPrice, newBookingPrice);
	         	var Car_LDWFlag = document.getElementById("Car_LDWFlag_" + dpos);
	         	if(Car_LDWFlag.checked == false) {
	         		ldw = diffPP + adjustPriceDifference(ldw);
	         		document.getElementById("spLDW" + dpos).innerHTML = PHFormatMoney(ldw);
	         	}
	         	
	         } else if (diff == 0 || diff == sdest.getDiffLDW(i)) { 
	         	sp.innerHTML = "Same Price"; 
	         } else if (diff < 0) { 
	         	sp.innerHTML = PHFormatMoney(diff/di.carDuration/di.carsCount).replace("-", "- $")  + " / Day"; 
	         }else { 
	         	sp.innerHTML = "+ $" + PHFormatMoney(diff/di.carDuration/di.carsCount) + " / Day"; 
	         }
	     }
      }
   }
}

function getTotalPrice() {
   if (psCTL != null) { return psCTL.getTotal() ; }
   else { return currentTotal; }
}

function getProtectionPlan() {
   if (psCTL != null) { return psCTL.getProtectionPlan(); }
   else { return 0; }
}

/**
 * This will take a given price difference and adjust it according to the current
 * total price.  Added for Price Rounding module.
 */
function adjustPriceDifference(diff) {
  if (diff == 0) { return 0; }
  else if (diff > 0) {
    var factor = getTotalPrice() - Math.floor(getTotalPrice());
    if (factor == 0) { factor = 1; }  
    return Math.floor(diff + factor);
  }
  else {
    var factor = Math.ceil(getTotalPrice()) - getTotalPrice();
    if (factor == 0) { factor = 1; }
    return Math.ceil(diff - factor);
  }
}

function retrieveCustomer(){ popWin(FORWARD_RETRIEVE_CUSTOMER, "RETRIEVE_CUSTOMER",600,600,1); }

// nice little patch to support voyager/classic
function updateUser(oid) {
  selectCustomer(oid);
}

function selectCustomer(oid){
  var f = document.myForm;
  f.action = FORWARD_SELECT_CUSTOMER + "?" + FN_CUSTOMER_OID + "=" + oid;
    f.submit();
}

function getMoreInfo(action,dest, anc) {
  document.myForm.elements[FN_ACTION].value = action;
  if(dest) { document.myForm.elements[FN_DESTINATIONSEQUENCE].value = dest }
    if(anc) { document.myForm.action += "?#" + anc; }
  post();
}

function changePage(pn, nbResults) {
  // -1 is a special value used to display all the items in one unique page
  var f = document.myForm;
    var chgp = true;
  if (pn == -1 && nbResults > MAX_ELEMENTS_PER_PAGE) { 
      chgp = confirm("We are about to display more than " + MAX_ELEMENTS_PER_PAGE + " items which may take slightly longer to download the page. Continue?"); 
    }
    if (chgp){
      f.elements[FN_CURRENT_PAGE].value = pn;
      f.action = FORWARD_CHANGE_PAGE;
        f.submit();
    }
}

function changeSort() {
  try{
    document.myForm.elements[FN_QUICK_FILTER].selectedIndex = FILTER_VIEW_ALL_INDEX;
  }
  catch(e){}
  changeFilter();
}

function changeFilter(){
  var f = document.myForm;
  f.elements[FN_CURRENT_PAGE].value = 1;
  f.action = FORWARD_CHANGE_PAGE;
  f.submit();
}

function chgPKT(pkt){

  var f = document.myForm;
  f.elements[FN_PACKAGETYPE].value = pkt;
  f.action = FORWARD_PACKAGE_CRITERIA;
  f.submit(); 
}

function refreshPage(anch){
   var f = document.myForm;
   f.action = REFRESH_ACTION + ((anch+"" == "undefined")? "" : "#" + anch);
   f.submit();
}

function filterList() {
  var f = document.myForm;
  f.elements[FN_CURRENT_PAGE].value = 1;
  f.action = FORWARD_CHANGE_PAGE;
  post();
}


function clearOptionList(list){                                            
  for (var index = list.options.length; index >= 0; index = index - 1){
    list.options[index] = null;
  }
}

function fillSelectBox(box, itemList, selectedValue){                      
   var bl = box.length;
  for (i = 0; i < itemList.length; i++){
    box.options[bl + i] = new Option(itemList[i].text, itemList[i].value)
    if (itemList[i].value == selectedValue)
      box.selectedIndex = i;
  }
}

function dateToStr(d,f){
   if (isNull(d)) { return ""; }
   var y = new String(d.getFullYear());
   if (f == "numeric"){
      return leadZero(d.getMonth() + 1) + "/" + leadZero(d.getDate()) + "/" + y.substr(y.length - 2, 2);
   } else {
      var month = new Array("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec");   
      return month[d.getMonth()] + " " + d.getDate() + ", " + y;      
   }
}

function leadZero(v){ return (v < 10) ? ("0" + v) : v; }

function getDateDiff(sd, ed){
   if (isNull(sd) || isNull(ed)){ return 0; }
   else{
      var ddiff = new DateDiff(sd, ed);
      if (ddiff.hours() > 1 || ddiff.minutes() > 0 || ddiff.seconds() > 0){ return ddiff.getTotalDays() + 1; }
      else { return ddiff.getTotalDays(); }
   }
}

function floatHours(f){
   var h, m, fh;
   fh = new String("");
   f = new String(f);
   h = f.substr(0,f.indexOf(":"));
   m = f.substr(f.indexOf(":")+1, f.length);

   if (h == 1){ fh = h + " Hour "; }
   else if (h > 1){ fh = h + " Hours "; }
     
   if (m == 1) {fh = fh + m + " minute"; }
   else if ( m > 1) {fh = fh + m + " minutes"; }

   return fh;
}

function isValidDateRange(sd, ed){
  var comp = new Array();
  comp[0] = compareDate(sd, ed);
  comp[1] = compareDate(sd, DEPARTURE_DATE);
  comp[2] = compareDate(sd, RETURN_DATE);
  comp[3] = compareDate(ed, RETURN_DATE);
    
  if (comp[0]  == 2 || comp[0] == 0 || comp[1] == 1 || comp[2] == 0 || comp[2] == 2 || comp[3] == 2)  { return false; }
    else { return true; }
}

function isValidDate(dateStr) {
if (dateStr == "") { return true; }
  var sep = "/";
  var slash1 = dateStr.indexOf(sep);
      
  var dateMonth = dateStr.substring(0, slash1);
  var dateMonthAndYear = dateStr.substring(slash1 + 1, dateStr.length);
  var slash2 = dateMonthAndYear.indexOf(sep);
      
  var dateDay = dateMonthAndYear.substring(0, slash2);
  var dateYear = dateMonthAndYear.substring(slash2 + 1, dateMonthAndYear.length);
        
  var numMonth = 0;
  for (var x = 0; x < dateMonth.length; x++) {
    digit = dateMonth.substring(x, x + 1);
    numMonth *= 10;
    numMonth += parseInt(digit);
  }

  if ((numMonth <= 0) || (numMonth > 12)) { return false; }

  var numDay = 0;
  for (var x=0; x<dateDay.length; x++) {
    digit = dateDay.substring(x, x+1);
    numDay *= 10;
    numDay += parseInt(digit);
  }

  if ((numDay <= 0) || (numDay > 31)) { return false; }
        
  // February can't be greater than 29 (leap year calculation comes later)
  if ((numMonth == 2) && (numDay > 29)) { return false; }

  // check for months with only 30 days
  if ((numMonth == 4) || (numMonth == 6) || (numMonth == 9) || (numMonth == 11)) { 
    if (numDay > 30) { return false; } 
  }

  
  // convert the text year to a number
  var numYear = 0;
  for (var x = 0; x < dateYear.length; x++) {
    digit = dateYear.substring(x, x+1)
    numYear *= 10;
    numYear += parseInt(digit);
  }

  // if 2-digit year, use 50 as a pivot date
  if (numYear < 50) { numYear = numYear + 2000; }
  if (numYear < 100) { numYear = numYear + 1900; }
  if ((numYear <= 0) || (numYear > 9999)) { return false; }

  // check for leap year if the month and day is Feb 29
  if ((numMonth == 2) && (numDay == 29)) {
    var div4 = numYear % 4;
    var div100 = numYear % 100;
    var div400 = numYear % 400;
    // if not divisible by 4, then not a leap year so Feb 29 is invalid
    if (div4 != 0) { return false; }
    // at this point, year is divisible by 4. So if year is divisible by
    // 100 and not 400, then it's not a leap year so Feb 29 is invalid
    if ((div100 == 0) && (div400 != 0)) { return false }
  }
  // date is valid
  return true;
}

function stripCharacter(value,charToStrip) {

	if ( value == null || value.length == 0 ) {return value;}

	var newValue = "";
	
	for (var i = 0; i<value.length;i++ ) {
		if (value.charAt(i) != charToStrip) {
			newValue += value.charAt(i);
		}
	}
	
	return newValue;
}

function formatMoney( v ){
  v = stripCharacter(v+"",',');
  if (isNaN(v)){ return ""; }
  else{
      var ism = false;
        if (v < 0) { ism = true; v = v * -100; }
        else { v = v * 100;}

    v = new String(Math.round(v));

    if (v.indexOf(".") != -1) { v = v.substr(0, v.indexOf(".")); }
      if (v < 10){ v = "0.0" + v};

      if (v < 100) { v = "0." + v.substring(v.length-2, v.length); }
      else { v = v.substring(0,v.length - 2) + "." + v.substring(v.length-2, v.length); }
    
    var re = new RegExp(/^\d+\.\d{2}$/); // 0.00
    var re1 = new RegExp(/^\d+\.\d$/); // 0.0
    var re2 = new RegExp(/^\d+$/); // 0

    if (re.test(v)){ v = v; }
    else if (re1.test(v)){ v = v + "0"; }
    else if (re2.test(v)){ v = v + ".00"; }

    return (ism)? "-" + v : v;
  }
}

function PHFormatMoney( v ){
    v = formatMoney(v);
    return pComma(v);
}

function pComma(v){
   var isneg = (v < 0) ? true : false;
   v = new String(Math.abs(v));
   v = formatMoney(v);

   if (v.length - v.indexOf(".") == 2){ v += "0"; }
  if (v.length > 6) { v = v.substring(0, ( v.length - 6)) + "," + v.substr(v.length - 6, v.length); }
  if (v.length > 10) { v = v.substring(0, ( v.length - 10)) + "," + v.substr(v.length - 10, v.length); }
   
  return (isneg)? "-" + v : v;
}
/*
The function in date_utilities should be used instead of this one.
function strToDate(sdate) {
  if (sdate+"" == "undefined" || isEmpty(sdate+"")) { return null; }

  var sdate = new String(sdate);
  var datesplit = sdate.split("/");
  var m = Number(datesplit[0]) - 1;
  var d = datesplit[1];
  var y = "20" + datesplit[2];

  return (new Date(y, m, d));
}
*/
function compareDate(fd, sd){
   if (fd < sd){ return 1; }
   else if (fd > sd){ return 2; }
   else { return 0; }
}

function getRadioValue(elm){
  if (isNaN(elm.length)){
    if (elm.checked) { return elm.value; }
  }
  else{
    for(var i = 0; i < elm.length; i++){
      if (elm[i].checked) { return elm[i].value; }
    }
  }
   return "";
}

function setRadioValue(elm, v){
  if (isNaN(elm.length)){
    if (elm.value == v) { elm.checked = true; }
  }
  else{
    for(var i = 0; i < elm.length; i++){
      if (elm[i].value == v) { elm[i].checked = true; }
    }
  }
}

function unCheckRadioValue(elm){
  if (isNaN(elm.length)){ elm.checked = false;}
  else{
    for(var i = 0; i < elm.length; i++){ elm[i].checked = false; }
  }
}

function setSelectByValue(elm,v){
  for (var i = 0; i < elm.options.length; i++){
    if (elm.options[i].value == v){ elm.options[i].selected = true; }
  }
}
/*function setSelectByValue(elm,v){
	//*********
	//TO REMOVE AUTOCOMPLETE REPLACE:
	//for (var i = 0; i < elm.options.length; i++){
	//	if (elm.options[i].value == v){ elm.options[i].selected = true; }
	//}
	//*********
	
	//if (document.myForm.elements[FN_DEPARTURECITY].value == v){
	//	var ListAuto = this.oAutoComp;
	//	ListAuto.itemSelectEvent = true;
	//}
}*/



function getSelectedRadio(elm){
  if (isNaN(elm.length)){ return elm; }
  else{
    for(var i = 0; i < elm.length; i++){ 
         if (elm[i].checked) { return elm[i]; }
      }
  }
}

function selectAll(box){
  for(var i = 0; i < box.options.length; i++) { box.options[i].selected = true; }
}

function deselectAll(box){
  for(var i = 0; i < box.options.length; i++) { box.options[i].selected = false; }
}

function isDate(ob) { return (ob == null || isNaN(ob))? false : true; }
function isNull(ob){ return (ob == null)? true : false; }
function isEmpty(v){ return (v.length == 0) ? true : false; }
function getSelectValue(elm){ return elm.options[elm.selectedIndex].value; }
function isZipCode(zc){
  zc = new String(zc);
  if (zc+"" == "undefined") { return false; }
  return (zc.match(/^(\d{5})(|-\d{4})$/) != null);
}

function isEmail(email){
  if (new String(email) == "undefined") { return false; }

  var reg = /^[A-Za-z0-9_\-]+([.][A-Za-z0-9_\-]+)*[@][A-Za-z0-9_\-]+([.][A-Za-z0-9_\-]+)+$/;
  
  if (reg.test(email)) { return true; }
  return false;
}

function validNumberField(obj){
  if (isNaN(obj.value)) { obj.value = ""; }
}
function filter(pattern, list){

   var codePattern = "code__.__";
   var match = new Array();
   var nomatch = new Array();

   if (!list.bak){
      list.bak = new Array();
      for (var n = 0; n < list.length; n++){ list.bak[list.bak.length] = new Option(list[n].text, list[n].value); }
   }
	

   for (n = 0; n < list.bak.length; n++){
      if(pattern.length > 0 && list.bak[n].value.toLowerCase().indexOf(codePattern + pattern.toLowerCase())!= -1){ match[match.length] = list.bak[n]; }
   }

   for (n = 0; n < list.bak.length; n++){
      if (pattern.length == 0){ nomatch[nomatch.length] = list.bak[n]; }
      else{
         if(list.bak[n].text.toLowerCase().indexOf(pattern.toLowerCase())!= -1){ 
            if (list.bak[n].value.toLowerCase().indexOf(codePattern + pattern.toLowerCase()) == -1 ){ match[match.length] = list.bak[n]; }
         }
         else if (list.bak[n].value != ""){ nomatch[nomatch.length] = list.bak[n]; }
      }
   }

   clearOptionList(list);
   
   for (n = 0; n < match.length; n++){ list[n] = match[n]; }
   
   var matchLength = match.length;
  if (match.length > 0){ list[matchLength] = new Option("",""); matchLength++; }
  try{
      for (n = 0; n < nomatch.length; n++){ list[n + matchLength] = nomatch[n]; }
   }
   catch(e){}


   if (match.length > 0){ list.options[0].selected = true; }
   else { list.selectedIndex = -1;}
}

function ifEnterPress() {
  if (window.event && window.event.keyCode == 13) {
  	document.myForm.departureFilter.blur();
  	depFilter(); 
  }
}

function MoreDestContinue() {
  /*if (PARTNER == "TravelAgent" && !confirm(MSG_COMMISSION_CONFIRM)) {
    return false;
  }*/
  
  if (IS_TRAVEL_AGENCY && !confirm(MSG_COMMISSION_CONFIRM)) {
    return false;
  }
  
}

// Javascript Basic Hashtable
/**
 * USAGE : 
 *
 * //declare an instance
 * var items = new Hashtable();
 *
 * //add values to the hashtable
 * items.put("key1", "value1");
 * items.put("key2", "value2");
 * items.put("key3", "value3");
 *
 * //get an item from the hastable
 * alert(items.get("key2"));
 * 
 * N.B.: The Hashtable is also in function.js
 */

Hashtable.prototype.hash = null;
Hashtable.prototype.keys = null;
Hashtable.prototype.location = null;

function Hashtable(){
	this.hash = new Array();
	this.keys = new Array();

	this.location = 0;
}

Hashtable.prototype.get = function (key){
	return this.hash[key];
}

Hashtable.prototype.put = function (key, value){
	if (value == null){ return null; }
	if (this.hash[key] == null){ this.keys[this.keys.length] = key; }
	this.hash[key] = value;
}

Hashtable.prototype.moveFirst = function (){
	try {
		this.location = -1;
	} catch(e) {}
}

Hashtable.prototype.next = function (){
	if (++this.location < this.keys.length)
		return true;
	else
		return false;
}

Hashtable.prototype.getValue = function (){
	try {
		return this.hash[this.keys[this.location]];
	} catch(e) {
		return null;
	}
}

Hashtable.prototype.getKey = function (){
	try {
		return this.keys[this.location];
	} catch(e) {
		return null;
	}
}

function alternateChangeCurentFlights(action,position){
	var f = document.myForm;
	f.elements[FN_ACTION].value = action;
	f.submit();
}

function alternateChFlights(action,position){
	var f = document.myForm;
	document.myForm.elements[FN_ACTION].value = action;
	selFlight(parseInt(position));
}

function alternateCurFlights(action){
	var f = document.myForm;
	document.myForm.action = action;
	f.submit();
}