// JavaScript Document
window.onload = initialize;
function huh(){
  disPlayDeprDate();
  resizeIframe();
}

function initialize() { //initialise the screen
  // initialize the DHTML History
  // framework
  if (dhtmlHistory.isFirstLoad()) {
    updateDepartDate();
    disPlayDeprDate();
    resizeIframe();
    dhtmlHistory.initialize();
  } else {
    resizeIframe();
    window.status = "OK";
    updateDepartDate();
    disPlayDeprDate();
    if(document.booking.area.options[historyStorage.get("areaIndex")] != null)
    document.booking.area.options[historyStorage.get("areaIndex")].selected = true;

  }

  // subscribe to DHTML history change
  // events
  //dhtmlHistory.addListener(historyChange);

  //document.booking.area.value = historyStorage.get("locations"));

  //alert(historyStorage.get("locations"));
    //alert("help!!!!!!!!");


  //alert("Area indx " + historyStorage.get("areaIndex"));



  //FillLocations(document.booking.area,"booking");

//Do FillLocations and thereafter the hotels
   var url = "searchAction.do?method=fillLocations";

  url = url + getFormAsString("booking");

      //Do the Ajax call
    if (window.XMLHttpRequest) { // Non-IE browsers
      req = new XMLHttpRequest();
      req.onreadystatechange = processNext;
      try {
      	req.open("GET", url, true); //was get
      } catch (e) {
        alert("Ajax: Problem Communicating with Server\n"+e);
      }
      req.send(null);
    } else if (window.ActiveXObject) { // IE

      req = new ActiveXObject("Microsoft.XMLHTTP");
      if (req) {
        req.onreadystatechange = processNext;
        req.open("GET", url, true);
        req.send();
      }
    }




  //alert("!s");
  //alert("Location " +historyStorage.get("locIndex"));

  //historyStorage.get("areaIndex")






  //dhtmlHistory.add("areaIndex", 0);
  //dhtmlHistory.add("locIndex", 0);
  //historyStorage.put("locIndex",0);
  //alert("OKs");



}

function processNext() {
  var resTex
  var result

    if (req.readyState == 4) { // Complete
      if (req.status == 200) { // OK response

        FillDropDown();
        var indx = historyStorage.get("locIndex");
    if (indx == null) {
    indx = 0;
    }

        document.booking.location.options[indx].selected = true;

        FillHotels(document.booking.location,"booking");

   var url = "searchAction.do?method=fillHotels";

  url = url + getFormAsString("booking");


      } else {
        DisplayInformation();
      }
    }

  }

function processNext2() {
  var resTex
  var result

    if (req.readyState == 4) { // Complete
      if (req.status == 200) { // OK response

        FillDropDown();
      } else {
        DisplayInformation();
      }
    }
  }



function submitHistory()
{
   window.status = "Please wait while we retreive your search criteria...";
   dhtmlHistory.add("locIndex", document.booking.location.selectedIndex);
   dhtmlHistory.add("areaIndex", document.booking.area.selectedIndex);
   //alert(document.booking.location.selectedIndex+ document.booking.area.selectedIndex);

}



function disPlayDeprDate()
{

	var abc = "sss";
	var day = document.booking.arrivalDay.value;
	var month = document.booking.arrivalMonth.value;
	var year = document.booking.arrivalYear.value;
	var numNights = document.booking.nights.value;

	var mth = "";
	var deptDate = new Date();
        var dept = document.getElementById("dept");

    month = month-1;

	if(month == 0)
	{
		mth="Jan";
	}
	else if(month == 1)
	{
		mth="Feb" ;
	}
	else if(month == 2 )
	{
		mth="Mar";
	}
		else if(month == 3 )
	{
			mth="Apr";
	}
		else if( month == 4)
	{
			mth="May";
	}
		else if(month == 5 )
	{
			mth="Jun";
	}
		else if(month == 6 )
	{
			mth="Jul";
	}
		else if(month == 7 )
	{
			mth="Aug";
	}
		else if(month == 8 )
	{
			mth="Sept";
	}
		else if(month == 9 )
	{
			mth="Oct";
	}
		else if(month == 10 )
	{
			mth="Nov";
	}
	else if(month == 11 )
	{
		mth="Dec";
	}

var	monthName =	new	Array("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sept","Oct","Nov","Dec") //
var total = 0 ;
total = parseInt(day) +parseInt( numNights );
deptDate.setFullYear(year,month,total)
dept.innerHTML = "Depart on  " + deptDate.getDate() + " " + monthName [deptDate.getMonth()] + " " +  deptDate.getFullYear() ;
month = month + 1;
var daysInMonth = DaysArray(12);


if ((month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]) {
		dept.innerHTML = "Please enter a valid date";
}


checkArrivalDate();
checkDepartureDate();
}

function checkArrivalDate()
{
        var dept = document.getElementById("dept")
	var day = document.booking.arrivalDay.value;
	var mth = document.booking.arrivalMonth.value-1;
	var year = document.booking.arrivalYear.value;

	var deptDate = new Date();
	var currentDay = deptDate.getDate();
	var currentMonth = deptDate.getMonth();
	var currentYear = deptDate.getFullYear();
	if(year<currentYear)
	{
		dept.innerHTML = "Arrival date is in the past";
                document.booking.subbut.disabled = true;
		return false;
	}
	else if ((year==currentYear)&&(mth<currentMonth))
	{
		dept.innerHTML ="Arrival date is in the past";
                document.booking.subbut.disabled = true;
		return false;
	}
	else if ((year==currentYear)&&(mth==currentMonth)&&(day<currentDay))
	{
		dept.innerHTML = "Arrival date is in the past";
                document.booking.subbut.disabled = true;
		return false;
	}
	else {
          document.booking.subbut.disabled = false;
          return true;
        }

}

function checkDepartureDate()
{
        var dept = document.getElementById("dept")
	var day = document.getElementById("departDay").value;
	var mth = (document.getElementById("departMonth").value);
	var year = document.getElementById("departYear").value;

	var deptDate = new Date();
	var currentDay = deptDate.getDate();
	var currentMonth = deptDate.getMonth();
	var currentYear = deptDate.getFullYear();

	if(year<currentYear)
	{
		dept.innerHTML = "Departure date is in the past";
                document.booking.subbut.disabled = true;
		return false;
	}
	else if ((year==currentYear)&&(mth<currentMonth))
	{
		dept.innerHTML ="Departure date is in the past";
                document.booking.subbut.disabled = true;
		return false;
	}
	else if ((year==currentYear)&&(mth==currentMonth)&&(day<currentDay))
	{
		dept.innerHTML = "Departure date is in the past";
                document.booking.subbut.disabled = true;
		return false;
	}
	else {
          document.booking.subbut.disabled = false;
          return true;
        }

}

function daysInFebruary (year){
	// February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}

function DaysArray(n) {
	for (var i = 1; i <= n; i++) {
		this[i] = 31
		if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
		if (i==2) {this[i] = 29}
   }
   return this
}

function CheckAdults() {
  var rooms = document.booking.rooms.value;
  var adults = document.booking.adults.value;

  if (rooms > adults) {
	  //alert("There must be at least one adult in every room that you book!");
    document.booking.adults.value = document.booking.rooms.value;

  }

}

function FillDropDown() {
//  var responseTextStr = this.req.responseText;
//  alert(this.req.responseText)
//
//  // code for IE
//  if (window.ActiveXObject)
//  {
//  var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
//  xmlDoc.async="false";
//  xmlDoc.loadXML(responseTextStr);
//  }
//// code for Mozilla, Firefox, Opera, etc.
//else
//  {
//  var parser = new DOMParser();
//  var xmlDoc = parser.parseFromString(responseTextStr,"text/xml");
//  }
//
  var xmlDoc = this.req.responseXML.documentElement;
  var xSel = xmlDoc.getElementsByTagName('selectElement')[0];
  var strFName = xSel.childNodes[0].firstChild.nodeValue;
  var strEName = xSel.childNodes[1].firstChild.nodeValue;
  var objDLL = document.forms[strFName].elements[strEName];
  objDLL.options.length = 0;

  var xRows = xmlDoc.getElementsByTagName('entry');
  for (i=0;i<xRows.length;i++) {
    var theText = xRows[i].childNodes[0].firstChild.nodeValue;
    var theValue = xRows[i].childNodes[1].firstChild.nodeValue;
    var option = new Option(theText, theValue);
    try {
      objDLL.add(option,null);
    } catch (e) {
      objDLL.add(option,-1);
    }
  }

}


function FillLocations(oElem,oTarget) {

  //var strValue = oElem.options[oElem.selectedIndex].value;
  var url = "searchAction.do?method=fillLocations";;
  //url = url + "&"+ escape("area") + "=" + escape(strValue);

  retrieveURL(url, "booking");


   //*dhtmlHistory.add("areaIndex", oElem.selectedIndex);

    var url = "searchAction.do?method=fillLocations";

  url = url + getFormAsString("booking");

      //Do the Ajax call
    if (window.XMLHttpRequest) { // Non-IE browsers
      req = new XMLHttpRequest();
      req.onreadystatechange = processNext;
      try {
      	req.open("GET", url, true); //was get
      } catch (e) {
        alert("Ajax: Problem Communicating with Server\n"+e);
      }
      req.send(null);
    } else if (window.ActiveXObject) { // IE

      req = new ActiveXObject("Microsoft.XMLHTTP");
      if (req) {
        req.onreadystatechange = processNext;
        req.open("GET", url, true);
        req.send();
      }
    }
}


function FillHotels(oElem,oTarget) {

 // var strValue = oElem.options[oElem.selectedIndex].value;

  var url = "searchAction.do?method=fillHotels";
  //url = url + "&"+ escape("area") + "=" + escape(strValue);
  retrieveURL(url, "booking");

  //*dhtmlHistory.add("locIndex", oElem.selectedIndex);
}

function DisplayInformation() {
  var url = "searchAction.do?method=ajaxError";
  retrieveURL(url, "booking");
}

function restoreXMLChars(request) {
    if (request != null) {
     for(var i = 0; i < request.length; i++) {
      request = request.replace("&amp;", "&");
      request = request.replace("&apos;", "'");
      request = request.replace("&gt;", ">");
      request = request.replace("&lt;", "<");
      request = request.replace("&quot;", "\"");
     }
    }
    return request;
 }

 function replaceXMLChars(request) {
        if (request != null) {
            request = request.replace("&", "&amp;");
            request = request.replace("'", "&apos;");
            request = request.replace(">", "&gt;");
            request = request.replace("<", "&lt;");
            request = request.replace("\"", "&quot;");
        }
        return request;
  }


function retrieveURL(url, form) {

    url = url + getFormAsString(form);
      //Do the Ajax call
    if (window.XMLHttpRequest) { // Non-IE browsers
      req = new XMLHttpRequest();
      req.onreadystatechange = processStateChange;
      try {
      	req.open("GET", url, true); //was get
      } catch (e) {
        alert("Ajax: Problem Communicating with Server\n"+e);
      }
      req.send(null);
    } else if (window.ActiveXObject) { // IE

      req = new ActiveXObject("Microsoft.XMLHTTP");
      if (req) {
        req.onreadystatechange = processStateChange;
        req.open("GET", url, true);
        req.send();
      }
    }
  }

function retrieveURLS(url) {

      //Do the Ajax call
  try  {    // Firefox, Opera 8.0+, Safari
    req = new XMLHttpRequest();
  } catch (e) {     // Internet Explorer
    try {
      req = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
      try {
        req = new ActiveXObject("Microsoft.XMLHTTP");
      } catch (e) {
        alert("Your browser does not support AJAX!");
        return false;
      }
    }
  }

  if (req) {
    req.onreadystatechange = processStateChange;
    req.open("GET", url, true);
    req.send(null);
  }

}

function processStateChange() {
  var resTex
  var result
    if (req.readyState == 4) { // Complete
      if (req.status == 200) { // OK response

        FillDropDown();
      } else {
        DisplayInformation();
      }
    }
  }

function getFormAsString(formName){

 	//Setup the return String
 	returnString ="";

  	//Get the form values
 	formElements=document.forms[formName].elements;

 	//loop through the array , building up the url
 	//in the form /strutsaction.do&name=value

 	for ( var i=formElements.length-1; i>=0; --i ){
 		//we escape (encode) each value
 		returnString=returnString+"&"+escape(formElements[i].name)+"="+escape(formElements[i].value);
 	}

 	//return the values
        //alert("Form as string:\n" + returnString);
 	return returnString;
 }

function removeBooking(booking) {
 alert(booking);
}
function removeIL(booking) {
//alert(booking);
  if (confirm("Do you want to remove this intinerary line? " +booking)) {
     var url = "cancelBookingAction.do?method=post&parameter=" + booking;
      retrieveURLS(url);
      window.location.reload();
  }

}

function removeSecureIL(booking) {
//alert(booking);
  if (confirm("Do you want to remove this intinerary line? " +booking)) {
     var url = "cancelBookingActionSecure.do?method=post&parameter=" + booking;
      retrieveURLS(url);
      window.location.reload();
  }

}

// Copyright 1999 - 2002 by Ray Stott, Pop-up Windows Script ver 2.0
// OK to use if this copyright is included
// Script is available at http://www.crays.com/jsc

var popWin = null    // use this when referring to pop-up window
var winCount = 0
var winName = "popWin"
function openPopWin(winURL, winWidth, winHeight, winFeatures, winLeft, winTop){
  var d_winLeft = 20  // default, pixels from screen left to window left
  var d_winTop = 20   // default, pixels from screen top to window top
  winName = "popWin" + winCount++ //unique name for each pop-up window
  closePopWin()           // close any previously opened pop-up window
  if (openPopWin.arguments.length >= 4)  // any additional features?
    winFeatures = "," + winFeatures
  else
    winFeatures = ""
  if (openPopWin.arguments.length == 6)  // location specified
    winFeatures += getLocation(winWidth, winHeight, winLeft, winTop)
  else
    winFeatures += getLocation(winWidth, winHeight, d_winLeft, d_winTop)
  popWin = window.open(winURL, winName, "width=" + winWidth
           + ",height=" + winHeight + winFeatures)
  }
function closePopWin(){    // close pop-up window if it is open
  if (navigator.appName != "Microsoft Internet Explorer"
      || parseInt(navigator.appVersion) >=4) //do not close if early IE
    if(popWin != null) if(!popWin.closed) popWin.close()
  }
function getLocation(winWidth, winHeight, winLeft, winTop){
  return ""
  }

function resizeIframe() {
	// Must launched on the body onload event handler for IE
	// Use document.documentElement if you are in Compat mode
	i = parent.document.getElementById(window.name);
	iHeight = document.body.scrollHeight;
	i.style.height = iHeight + 55 + "px";
}

function enforcechar(what,limit){
  if (what.value.length>=limit)
  return false
}


function getCCYear(monthDropdownID,yearDropdownID) {
  var yearDropdown = document.getElementById(yearDropdownID);
  var monthDropdown = document.getElementById(monthDropdownID);
  var date = new Date();
  var month = date.getMonth();
  var year = date.getYear();

  for(var i = 0; i < monthDropdown.options.length; i++) {
    var option = monthDropdown.options[i];
    if(option.value == month)
      monthDropdown.selectedIndex = (i+2);
  }

  for(var i = 0; i < yearDropdown.options.length; i++) {
    var option = yearDropdown.options[i];
    if(option.text == year)
      yearDropdown.selectedIndex = i;
  }
}

function getSelectedArrivalDate(){
  var day = document.getElementById("arriveDay").value;
  var month = document.getElementById("arriveMonth").value;
  var year = document.getElementById("arriveYear").value;

  var dateString = day+"/"+month+"/"+year
  var date = getDateFromString(dateString);
  return date;
}

function getSelectedDepartDate(){
  var day = document.getElementById("departDay").value;
  var month = document.getElementById("departMonth").value;
  var year = document.getElementById("departYear").value;

  var dateString = day+"/"+month+"/"+year
  var date = getDateFromString(dateString);
 return date;

}

function updateNoOfNights() {
	var arrive = getSelectedArrivalDate();
	var depart =  getSelectedDepartDate();

	var nights = document.getElementById("nights");
	var noOfNights = daysBetween(arrive, depart);

	nights.value = noOfNights;
}

function updateDepartDate() {

  var noOfNights = document.getElementById("nights").value;
  var departDaySelect = document.getElementById("departDay");
  var departMonthSelect = document.getElementById("departMonth");
  var departYearSelect = document.getElementById("departYear");

  var arrive = getSelectedArrivalDate();
  var date1 = new Date(arrive.getTime() + noOfNights * 1000 * 60 * 60 * 24);
  var newDate = getStringFromDate(date1);

  departDaySelect.selectedIndex = (getDayString(date1)-1);
  departMonthSelect.selectedIndex = (getMonthString(date1)-1);
  departYearSelect.selectedIndex = (getYearString(date1)-2008);
}

function loadSearch() {
  updateDepartDate();
  disPlayDeprDate();
  resizeIframe();
}

function daysBetween(date1, date2) {
    var ONE_DAY = 1000 * 60 * 60 * 24;

    var date1_ms = date1.getTime();
    var date2_ms = date2.getTime();

    var difference_ms = Math.abs(date1_ms - date2_ms);

    if(date2_ms <= date1_ms)
    	return 1;
    else
      return Math.round(difference_ms/ONE_DAY);
}

/**
Convert a string with the patter 'dd/MM/yyyy' to a JavaScript Date object.
*/
function getDateFromString(dateString) {
  var dateVal;
  var dArray;
  var d, m, y;

  try {
    dArray = splitDateString(dateString);
    if (dArray) {

          d = parseInt(dArray[0], 10);
          m = parseInt(dArray[1], 10) - 1;
          y = parseInt(dArray[2], 10);

      dateVal = new Date(y, m, d);
    } else if (dateString) {
      dateVal = new Date(dateString);
    } else {
      dateVal = new Date();
    }
  } catch(e) {
    dateVal = new Date();
  }

  return dateVal;
}

function getStringFromDate(dateVal) {
  var dayString = "00" + dateVal.getDate();
  var monthString = "00" + (dateVal.getMonth()+1);
  var dateSeparator = "/";
  dayString = dayString.substring(dayString.length - 2);
  monthString = monthString.substring(monthString.length - 2);

  return dayString + dateSeparator + monthString + dateSeparator + dateVal.getFullYear();

}

function getDayString(dateVal) {
   var dayString = "00" + dateVal.getDate();
   dayString = dayString.substring(dayString.length - 2);
   return dayString;
}

function getMonthString(dateVal) {
   var monthString = "00" + (dateVal.getMonth()+1);
   monthString = monthString.substring(monthString.length - 2);
   return monthString;
}

function getYearString(dateVal) {
  return dateVal.getFullYear();
}

/**
Try to split a date string into an array of elements, using common date separators.
If the date is split, an array is returned; otherwise, we just return false.
*/
function splitDateString(dateString)
{
  var dArray;
  if (dateString.indexOf("/") >= 0)
    dArray = dateString.split("/");
  else if (dateString.indexOf(".") >= 0)
    dArray = dateString.split(".");
  else if (dateString.indexOf("-") >= 0)
    dArray = dateString.split("-");
  else if (dateString.indexOf("\\") >= 0)
    dArray = dateString.split("\\");
  else
    dArray = false;

  return dArray;
}

function validateSearch() {
  if(!checknumber(document.getElementById("nights"), " number of nights.", false)) {
    return false;
  }
  return disableButton('subbut');

  return true;
}

function disableButton(buttonID) {
  var isAvailable = checkHotels();

  if(isAvailable) {
    var b = document.getElementById(buttonID);
    b.disabled = true;
    b.value = 'Submitting';
  }

  return isAvailable;
  }

function checknumber(input, fieldname, mandatory){
 var x=input.value
 var anum=/(^\d+$)|(^\d+\.\d+$)/
 if (anum.test(x))
  testresult=true
 else{
  if(input.value != 0 | mandatory) {
  alert("Please input a valid " + fieldname)
  testresult=false
  } else testresult = true;
 }
 return (testresult)
}

  function resizeIframe() {
    // Must launched on the body onload event handler for IE
    // Use document.documentElement if you are in Compat mode
//    var i = parent.document.getElementById(window.name);
//    var iHeight = document.body.scrollHeight;
//    i.style.height = iHeight + 55 + "px";
   }

//-->



