
var objCountryList;

// FIX MIMETYPES/DOCUMENT HEADERS FOR GECKO
// By Vladdy from CodingForums.com
function fixXmlMimeType(filename) {
  oxmlhttp = null;
  try {
    oxmlhttp = new XMLHttpRequest();
    oxmlhttp.overrideMimeType("text/xml");
  } catch(e) {
    try {
      oxmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
    } catch(e) {
      return null;
    }
  }

  if (!oxmlhttp) return null;

  try {
    oxmlhttp.open("GET", filename, false);
    oxmlhttp.send(null);
  } catch(e) {
    return null;
  }

  return oxmlhttp.responseXML;
}

function updateCityList(countryId) {
  var filename = "/utils/country_destinations.php?l=" + l + "&country_id=" + countryId;
  if (moz) {
    objCountryList = document.implementation.createDocument("", "", null);
    objCountryList.async = false;
    objCountryList = fixXmlMimeType(filename);
    getcitylist();
  } else if (ie) {
    objCountryList = new ActiveXObject("Microsoft.XMLDOM");
    objCountryList.async = false;
    objCountryList.onreadystatechange = function () {if (objCountryList.readyState == 4) getcitylist()};
    objCountryList.load(filename);
  }
}

function preselectCountry(country_id) {
  updateCityList(country_id);
  toggleSubmitButton(document.getElementById("search_form"));
}

function preselectCity(city_id) {
  updateCityList(document.getElementById("country").value);

  var city = document.getElementById("city");
  var oplen = city.options.length;
  for (var i = 0; i <= oplen; i++) {
    var option = city.options[i];
    if (option.value == city_id) {
      city.selectedIndex = i;
      break;
    }
  }

  getdistrictlist();
  toggleSubmitButton(document.getElementById("search_form"));
}



// -----------------------------------------------------------------------



/*
// Found at http://www.sitepoint.com/print/xml-javascript-mozilla
var xmlDoc;
function importXML(file) {
  var xmlDoc;
  var moz = (typeof document.implementation != 'undefined') &&
            (typeof document.implementation.createDocument != 'undefined');
  var ie = (typeof window.ActiveXObject != 'undefined');

  if (moz) {
    xmlDoc = document.implementation.createDocument("", "", null);
    xmlDoc.async = false;
    xmlDoc.onload = readXML;
  } else if (ie) {
    xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
    xmlDoc.async = false;
    while(xmlDoc.readyState != 4) {};
  }
  xmlDoc.load(file);
}
*/



function removecitylist() {
  var city = document.getElementById("city");
  var oplen = city.options.length;

  for (var i = 0; i <= oplen; i++) {
    var option = city.options[i];
    city.remove(option);
  }
}

function removedistrictlist() {
  var district = document.getElementById("district");
  var oplen = district.options.length;

  for (var i = 0; i <= oplen; i++) {
    var option = district.options[i];
    district.remove(option);
  }
}

//==================================================================================//
// This function is called if the browser is Mozilla Firefox
// Load city and district list according to the country or city selected
//==================================================================================//
function getCityListMozilla(bPopulateCity) {
  var objCountryListData = objCountryList.getElementsByTagName("A"); // <Data>
  var iTotalCountryCityCount = objCountryListData.length;
  var bAdded = false;
  var strAddCityName = "";
  var iCounter = 0;
  var objCityList;
  var ccode;
  var iCode;
  var iCodeName;
  var strText="";

  //==================================================================================//
  // bPopulateCity = true  ==> Called for populating city list
  // bPopulateCity = false ==> Called for populating area list
  //==================================================================================//
  if (bPopulateCity) {
    objCityList = document.getElementById("city");
    ccode = document.getElementById("country").value;
    iCode = 1;
    iCodeValue = 5;
    iCodeName = 7;
    strText = selectCityMsg;
  } else {
    removedistrictlist();
    objCityList = document.getElementById("district");
    ccode = document.getElementById("city").value;
    iCode = 5;
    iCodeValue = 9;
    iCodeName = 11;
    strText = selectAreaMsg;
  }

  var objCountryListChildNodes;
  for (var i = 0; i < iTotalCountryCityCount; i++) {
    objCountryListChildNodes = objCountryList.getElementsByTagName("A")[i].childNodes; // Data

    var iCountryCode = objCountryListChildNodes[iCode].firstChild.nodeValue;
    var strCityName = "";
    try {
      strCityName = objCountryListChildNodes[iCodeName].firstChild.nodeValue;
    } catch (e) {}

    strCityName = removeNewLineAndSpaces(strCityName);

    if (ccode == iCountryCode && strAddCityName != strCityName && strCityName != "") {
      if (!bAdded) {
        objCityList.length = objCityList.length + 1;
        objCityList.options[iCounter].value = 0;
        objCityList.options[iCounter].text = strText;
        bAdded = true;
        iCounter++;
      }

      strAddCityName = strCityName;
      var iCityCode = objCountryListChildNodes[iCodeValue].firstChild.nodeValue;
      objCityList.length = objCityList.length + 1;
      objCityList.options[iCounter].value = iCityCode;
      objCityList.options[iCounter].text = strAddCityName;
      iCounter++;
    }
  }
}

function getcitylist() {
  removecitylist();
  removedistrictlist();

  if (window.ActiveXObject) {
    var city = document.getElementById("city");
    var ccode = document.getElementById("country").value;
    var objcitylist;

    objcitylist = objCountryList.selectNodes("//A"); // Data

    var bAdded = false;

    var cityname = "";
    var option = "";

      for (var i = 0; i < objcitylist.length; i++) {
      if (ccode == objcitylist.item(i).selectSingleNode("B").text && // COUNTRY_CODE
          cityname != objcitylist.item(i).selectSingleNode("E").text) { // CITY_NAME

        if (!bAdded) {
          var optionSelect = new Option(selectCityMsg, 0);
          city.add(optionSelect);
          bAdded = true;
        }

        cityname = objcitylist.item(i).selectSingleNode("E").text; // CITY_NAME
        var option = new Option(cityname, objcitylist.item(i).selectSingleNode("D").text); // CITY_CODE
        city.add(option);
      }
    }
  } else {
    getCityListMozilla(true);
  }
}


function getdistrictlist() {

  if (window.ActiveXObject) {
    var district = document.getElementById("district");
    removedistrictlist();
    var ccode = document.getElementById("country").value;
    var ctcode = document.getElementById("city").value;

    var objdistrictlist;
    objdistrictlist = objCountryList.selectNodes("//A"); // Data

    var districtname = "";
    var bAdded = false;

    for (var i = 0; i < objdistrictlist.length; i++) {
      if (ccode == objdistrictlist.item(i).selectSingleNode("B").text && // COUNTRY_CODE
          ctcode == objdistrictlist.item(i).selectSingleNode("D").text && // CITY_CODE
          districtname != objdistrictlist.item(i).selectSingleNode("G").text) { // DISTRICT_NAME

        if (!bAdded) {
          var optionSelect = new Option(selectOptionalMsg, 0);
          district.add(optionSelect);
          bAdded = true;
        }

        districtname = objdistrictlist.item(i).selectSingleNode("G").text; // DISTRICT_NAME
        var option = new Option(districtname, objdistrictlist.item(i).selectSingleNode("F").text); // DISTRICT_CODE
        district.add(option);
      }
    }
  } else {
    getCityListMozilla(false);
  }
}

//==================================================================================//
// Remove white space and new line character from a string
//==================================================================================//
function removeNewLineAndSpaces(strText) {
  // Removing white spaces from the left
  while (strText.charAt(0) == ' ' || strText.charAt(0) == '\n')
       strText = strText.substring(1, strText.length);
  return strText;
}



//==================================================================================//
// Calendar utilities
//==================================================================================//

function dateToJulianDate(d, m, y) {
  if (m < 3) {y--; m += 12;}
  with (Math) {
    var ig = floor(y / 100.0);
    return floor(y * 365.25) + floor(30.6001 * (m + 1.0)) + d - 694023.0 - ig + floor(ig / 4.0) + 2415020.0;
  }
}

function julianDateToDate(jd) {
  var n, c, np, yp, npp, mp, d, m, y;

  with (Math) {
    n = jd - 1721119;
    c = floor((n - 0.2) / 36524.25);
    np = n + c - floor(c / 4);
    yp = floor((np - 0.2) / 365.25);
    npp = np - floor(365.25 * yp);
    mp = floor((npp - 0.5) / 30.6001);

    d = floor(npp - 30.6001 * mp + 0.5);
    if (mp <= 9 ) {m = mp + 3; y = yp;} else {m = mp - 9; y = yp + 1;}

    return y + "-" + (m <= 9 ? "0" : "") + m + "-" + (d <= 9 ? "0" : "") + d;
  }
}

//alert(dateToJulianDate(9, 12, 2006));
//alert(julianDateToDate(dateToJulianDate(31, 12, 2006) + 1));

var arrivalMonth, arrivalDay, arrivalYear,
    departureMonth, departureDay, departureYear,
    numberOfNights;

function resetDates(f) {
  arrivalMonth = parseInt(f.am.value, 10);
  arrivalDay = parseInt(f.ad.value, 10);
  arrivalYear = parseInt(f.yr.value, 10);

    departureMonth = parseInt(f.dm.value, 10);
  departureDay = parseInt(f.dd.value, 10);
  departureYear = parseInt(f.dyr.value, 10);

  numberOfNights = parseInt(f.txt_num_nights.value, 10);;

  //alert(arrivalMonth + "-" + arrivalDay + "-" + arrivalYear);
  //alert(departureMonth + "-" + departureDay + "-" + departureYear);
}

function refreshDates(f, arrivalChanged, msgInvalidDate) {
  var selectedArrivalMonth, selectedArrivalDay, selectedArrivalYear,
        selectedDepartureMonth, selectedDepartureDay, selectedDepartureYear;

  selectedArrivalMonth = parseInt(f.am.value, 10);
  selectedArrivalDay = parseInt(f.ad.value, 10);
  selectedArrivalYear = parseInt(f.yr.value, 10);

    selectedDepartureMonth = parseInt(f.dm.value, 10);
  selectedDepartureDay = parseInt(f.dd.value, 10);
  selectedDepartureYear = parseInt(f.dyr.value, 10);

  if (arrivalChanged) {
    if (!checkDate(selectedArrivalDay, selectedArrivalMonth, selectedArrivalYear)) {
      alert(msgInvalidDate);
      revertToDates(f, arrivalMonth, arrivalDay, arrivalYear, departureMonth, departureDay, departureYear);
      return;
    }

    setNewDepartureDate(f, selectedArrivalDay, selectedArrivalMonth, selectedArrivalYear, parseInt(f.txt_num_nights.value, 10));
    resetDates(f);

  } else {
    if (!checkDate(selectedDepartureDay, selectedDepartureMonth, selectedDepartureYear)) {
      alert(msgInvalidDate);
      revertToDates(f, arrivalMonth, arrivalDay, arrivalYear, departureMonth, departureDay, departureYear);
      return;
    }

    //alert("refreshDates: " + selectedDepartureDay + "-" + selectedDepartureMonth + "-" + selectedDepartureYear + " --- " + arrivalDay + "-" + arrivalMonth + "-" + arrivalYear);
    //alert(dateToJulianDate(selectedDepartureDay, selectedDepartureMonth, selectedDepartureYear) - dateToJulianDate(arrivalDay, arrivalMonth, arrivalYear));
    if ((dateToJulianDate(selectedDepartureDay, selectedDepartureMonth, selectedDepartureYear) - dateToJulianDate(arrivalDay, arrivalMonth, arrivalYear)) <= 0) {
      alert(msgInvalidDate);
      revertToDates(f, arrivalMonth, arrivalDay, arrivalYear, departureMonth, departureDay, departureYear);
      return;
    }

    revertToDates(f, selectedArrivalMonth, selectedArrivalDay, selectedArrivalYear, selectedDepartureMonth, selectedDepartureDay, selectedDepartureYear);
    resetDates(f);
  }
}

function revertToDates(f, arrivalMonth, arrivalDay, arrivalYear, departureMonth, departureDay, departureYear) {
  chooseSelectListOption(f.am, arrivalMonth);
  chooseSelectListOption(f.ad, arrivalDay);
  chooseSelectListOption(f.yr, arrivalYear);

    chooseSelectListOption(f.dm, departureMonth);
  chooseSelectListOption(f.dd, departureDay);
  chooseSelectListOption(f.dyr, departureYear);

  //alert("revertToDates: " + departureDay + "-" + departureMonth + "-" + departureYear + " --- " + arrivalDay + "-" + arrivalMonth + "-" + arrivalYear);
  f.txt_num_nights.value = dateToJulianDate(departureDay, departureMonth, departureYear) - dateToJulianDate(arrivalDay, arrivalMonth, arrivalYear);
}

function setNewDepartureDate(f, arrivalDay, arrivalMonth, arrivalYear, nights) {
  var departureJulianDate = dateToJulianDate(arrivalDay, arrivalMonth, arrivalYear) + nights;

  var n, c, np, yp, npp, mp, d, m, y;
  with (Math) {
    n = departureJulianDate - 1721119;
    c = floor((n - 0.2) / 36524.25);
    np = n + c - floor(c / 4);
    yp = floor((np - 0.2) / 365.25);
    npp = np - floor(365.25 * yp);
    mp = floor((npp - 0.5) / 30.6001);

    d = floor(npp - 30.6001 * mp + 0.5);
    if (mp <= 9 ) {m = mp + 3; y = yp;} else {m = mp - 9; y = yp + 1;}

    chooseSelectListOption(f.dm, m);
    chooseSelectListOption(f.dd, d);
    chooseSelectListOption(f.dyr, y);
  }
}


function chooseSelectListOption(sel, val) {
  var oplen = sel.options.length;
  for (var i = 0; i <= oplen; i++) if (sel.options[i].value == val) {sel.selectedIndex = i; break;}
}


function checkDate(d, m, y) {
  return d <= getDaysInMonth(m, y);
}

function isLeapYear(yrStr) {
  var leapYear = false;
  var year = parseInt(yrStr, 10);

  // every fourth year is a leap year
  if (year % 4 == 0) {
    leapYear = true;

    // unless it's a multiple of 100
    if (year % 100 == 0) {
      leapYear = false;

      // unless it's a multiple of 400
      if (year % 400 == 0) {
        leapYear = true;
      }
    }
  }

  return leapYear;
}


function getDaysInMonth(m, y) {
  var maxDays = 31;
  if (m == 2) {
    maxDays = 28 + (isLeapYear(y) ? 1 : 0);
  } else if (m == 4 || m == 6 || m == 9 || m == 11) {
    maxDays = 30;
  }

  return maxDays;
}

