/* Code for the Search Form */
//Yahoo namespace used for the YUI!calendar
YAHOO.namespace("vroom.calendar");

/** global variables **/
//string variables
var strMonth, strURL, strPageName, strCountryID, strHost, strProtocol, pickupLoc, returnLoc, pickupTxt, returnTxt, affiliateID;
//dates
var dates, date, year, month, day;
//textbox fields
var txtPickupDate, txtReturnDate;
//dropdown lists
var countryList, pickupList, returnList, pickupHour, pickupMins,
    countryList2, returnHour, returnMins, ageList;
//hidden fields
var _init, _returnHour, _returnMins, _pickupHour, _pickupMins, _returnDateObj, _pickupDateObj,
    _pickupIndex, _returnIndex, _pickupDate, _returnDate, _ageListID, _countryID, _countryID2,
    _hidSDay, _hidSMonth, _hidSYear, _hidEDay, _hidEMonth, _hidEYear;
//serviceProxy location
var proxyDir;

var body, btnSearch;

var newWin = false;
var bDowntown = (location.href.indexOf("City")>-1);

function DateTimeTicks () {
  var strReturn = "";
  var datenow = new Date();

  strReturn += datenow.getDate();
  strReturn += datenow.getMonth() + 1;
  strReturn += datenow.getFullYear();
  strReturn += datenow.getHours();
  strReturn += datenow.getMinutes();
  strReturn += datenow.getSeconds();
  strReturn += "." + datenow.getMilliseconds();
  
  return strReturn;
}

function pickupSelect(type,args,obj) {
	dates = args[0]; 
	date = dates[0];
	year = date[0], month = date[1], day = date[2];
  
	strMonth = getMonth(month);
	
	txtPickupDate = YAHOO.util.Dom.get("pickupDate");
	_pickupDate = YAHOO.util.Dom.get("_pickupDate");
	_hidSDay = YAHOO.util.Dom.get("hidSDay");
	_hidSMonth = YAHOO.util.Dom.get("hidSMonth");
	_hidSYear = YAHOO.util.Dom.get("hidSYear");
	
	var dateTest = new Date();
	dateTest.setDate(day); dateTest.setMonth(month-1); dateTest.setFullYear(year);
	
  txtPickupDate.value = day + '-' + strMonth + '-' + year;
	_pickupDate.value = month + '/' + day + '/' + year;  //US date for the search form paramater
  _pickupDateObj.value = date;
  _hidSDay.value = day;
  _hidSMonth.value = month;
  _hidSYear.value = year;

  if(YAHOO.vroom.calendar.returncal.getSelectedDates() != "") {
    if(YAHOO.widget.DateMath.before(YAHOO.vroom.calendar.returncal.getSelectedDates()[0], YAHOO.vroom.calendar.pickupcal.getSelectedDates()[0])) {
	    YAHOO.vroom.calendar.returncal.select(YAHOO.widget.DateMath.add(YAHOO.vroom.calendar.pickupcal.getSelectedDates()[0], YAHOO.widget.DateMath.DAY, 3));
      YAHOO.vroom.calendar.returncal.cfg.setProperty("pagedate", YAHOO.util.Dom.get("hidEMonth").value + "/" + YAHOO.util.Dom.get("hidEYear").value);
      YAHOO.vroom.calendar.returncal.render();
    }
  }

	YAHOO.vroom.calendar.pickupcal.hide();
}

function setPickupDate() {
  date = new Date(YAHOO.vroom.calendar.pickupcal.getSelectedDates()[0]);
  
  alert(date);
}

function returnSelect(type,args,obj) {
	dates = args[0]; 
	date = dates[0];
	year = date[0], month = date[1], day = date[2];
  
	strMonth = getMonth(month);
  
	txtReturnDate = YAHOO.util.Dom.get("returnDate");
	_returnDate = YAHOO.util.Dom.get("_returnDate");
	_hidEDay = YAHOO.util.Dom.get("hidEDay");
	_hidEMonth = YAHOO.util.Dom.get("hidEMonth");
	_hidEYear = YAHOO.util.Dom.get("hidEYear");

  txtReturnDate.value = day + '-' + strMonth + '-' + year;
	_returnDate.value = month + '/' + day + '/' + year;  //US date for the search form paramater
  _returnDateObj.value = date;
  _hidEDay.value = day;
  _hidEMonth.value = month;
  _hidEYear.value = year;
	YAHOO.vroom.calendar.returncal.hide();
}

function getMonth(month) {
  strMonth;
  switch (month) {
  case 1:
    strMonth = "Jan";
    break;
  case 2:
    strMonth = "Feb";
    break;
  case 3:
    strMonth = "Mar";
    break;
  case 4:
    strMonth = "Apr";
    break;
  case 5:
    strMonth = "May";
    break;
  case 6:
    strMonth = "Jun";
    break;
  case 7:
    strMonth = "Jul";
    break;
  case 8:
    strMonth = "Aug";
    break;
  case 9:
    strMonth = "Sep";
    break;
  case 10:
    strMonth = "Oct";
    break;
  case 11:
    strMonth = "Nov";
    break;
  case 12:
    strMonth = "Dec";
    break;
  }
  return strMonth;
}

function init() {
  YAHOO.util.Dom.setStyle('Loading', 'display', 'none');
  _init = YAHOO.util.Dom.get('_init');
	txtPickupDate = YAHOO.util.Dom.get("pickupDate");
	_pickupDate = YAHOO.util.Dom.get("_pickupDate");
	txtReturnDate = YAHOO.util.Dom.get("returnDate");
	_returnDate = YAHOO.util.Dom.get("_returnDate");
	_countryID = YAHOO.util.Dom.get("_countryID");
	_pickupIndex = YAHOO.util.Dom.get("_pickupIndex");
	_returnIndex = YAHOO.util.Dom.get("_returnIndex");
  countryList = YAHOO.util.Dom.get('countryList');
  _pickupDateObj = YAHOO.util.Dom.get("_pickupDateObj");
  _returnDateObj = YAHOO.util.Dom.get("_returnDateObj");
  _pickupHour = YAHOO.util.Dom.get("_pickupHour");
  _pickupMins = YAHOO.util.Dom.get("_pickupMins");
  _returnHour = YAHOO.util.Dom.get("_returnHour");
  _returnMins = YAHOO.util.Dom.get("_returnMins");
  _countryID2 = YAHOO.util.Dom.get("_countryID2");
  _ageListID = YAHOO.util.Dom.get("_ageListID");

  if((window.location.hostname.match("vroom.co")) || 
     (window.location.hostname.match("carhire.co")) ||
     (window.location.hostname.match("vroomtest.com"))) {
	  YAHOO.widget.Calendar.IMG_ROOT = "/SearchForm/gfx/";
  } else {
	  YAHOO.widget.Calendar.IMG_ROOT = (window.location.href.toLowerCase().indexOf("https")===0?"https://www.vroomvroomvroom.com/gfx/":"http://www.vroomvroomvroom.com/gfx/");
  }

  YAHOO.vroom.calendar.pickupcal = new YAHOO.widget.Calendar("pickupcal","pickupcalContainer", { title:"Pickup date:", close:true } );
	YAHOO.vroom.calendar.pickupcal.selectEvent.subscribe(pickupSelect, YAHOO.vroom.calendar.pickupcal, true);
  YAHOO.util.Event.addListener("pickupcalimg", "click", YAHOO.vroom.calendar.pickupcal.show, YAHOO.vroom.calendar.pickupcal, true);
  YAHOO.util.Event.addListener("pickupDate", "click", YAHOO.vroom.calendar.pickupcal.show, YAHOO.vroom.calendar.pickupcal, true);

  YAHOO.vroom.calendar.returncal = new YAHOO.widget.Calendar("returncal","returncalContainer", { title:"Return date:", close:true } );
	YAHOO.vroom.calendar.returncal.selectEvent.subscribe(returnSelect, YAHOO.vroom.calendar.returncal, true);
  YAHOO.util.Event.addListener("returncalimg", "click", YAHOO.vroom.calendar.returncal.show, YAHOO.vroom.calendar.returncal, true);
  YAHOO.util.Event.addListener("returnDate", "click", YAHOO.vroom.calendar.returncal.show, YAHOO.vroom.calendar.returncal, true);

  //body = YAHOO.util.Dom.get("body");
  //btnSearch = YAHOO.util.Dom.get("btnSearch");
  //YAHOO.util.Event.addListener(document.body, "click", YAHOO.vroom.calendar.pickupcal.hide, btnSearch, true);

  if(_init.value == "true") {
    if (_pickupDateObj.value == null || _pickupDateObj.value == "") {
  	  YAHOO.vroom.calendar.pickupcal.select(YAHOO.widget.DateMath.add(new Date(), YAHOO.widget.DateMath.DAY, 1));
    } else {
      YAHOO.vroom.calendar.pickupcal.select(new Date(_pickupDateObj.value));
    }

    if (_returnDateObj.value == null || _returnDateObj.value == "") {
    	YAHOO.vroom.calendar.returncal.select(YAHOO.widget.DateMath.add(new Date(), YAHOO.widget.DateMath.DAY, 5));
    } else {
  	  YAHOO.vroom.calendar.returncal.select(new Date(_returnDateObj.value));
  	}
  } else {
  	YAHOO.vroom.calendar.pickupcal.select(YAHOO.widget.DateMath.add(new Date(), YAHOO.widget.DateMath.DAY, 1));
    YAHOO.vroom.calendar.returncal.select(YAHOO.widget.DateMath.add(new Date(), YAHOO.widget.DateMath.DAY, 5));
  }
  
  YAHOO.vroom.calendar.pickupcal.render();
  YAHOO.vroom.calendar.returncal.render();

  if(countryList.selectedIndex > 0) {
    makeRequest();
  }

  //testing colour customisation
  YAHOO.util.Dom.setStyle('Loading', 'display', 'none');

  _init.value = "true";
}
// End - Calendar fucntions

// Begin - Dynamic drop down population
var handleSuccess = function(o) {
	if(o.responseText != undefined) {
	  //populate the two dropdown lists here
	  var depotArray = o.responseText.split("|");
    pickupList = YAHOO.util.Dom.get('pickupList');
    returnList = YAHOO.util.Dom.get('returnList');

    pickupList.length = (depotArray.length-3)/2;
    pickupList.selectedIndex = -1;
    returnList.length = ((depotArray.length-3)/2) + 1;
    returnList.selectedIndex = -1;
    var i;
    returnList[0].text = "Same as Pickup Location";
    returnList[0].value = "SAME";

    for(i=1; i<((depotArray.length-1)/2); i++) {
      pickupList[i-1].text = depotArray[(i*2)+1];
      pickupList[i-1].value = depotArray[(i*2)];
      returnList[i].text = depotArray[(i*2)+1];
      returnList[i].value = depotArray[(i*2)];
      if(depotArray[1] == depotArray[(i*2)+1]) {
        pickupList.selectedIndex = i-1;
        //pickupChange();
        returnList.selectedIndex = 0;
        //returnChange();
      }
    }
    if(_pickupIndex.value != "") {
      pickupList.selectedIndex = _pickupIndex.value;
    } else if(pickupLoc != "") {
      if(setSelectedCity(pickupList,pickupLoc)==false){
        setSelectedCity(pickupList,pickupLoc + " Airport")
      }
    }
/*
    if(_returnIndex.value != "") {
      returnList.selectedIndex = _returnIndex.value;
    } else if(returnLoc != "") {
      if(setSelectedCity(returnList,returnLoc)==false){
        setSelectedCity(returnList,returnLoc + " Airport")
      }
    }
*/
	}
}

function setSelectedCity(selectObject, text) {
  for(i = 0; i < selectObject.length; i++) {
    if(selectObject[i].text == text) {
      if(selectObject[i+1].text == text + " Airport" && bDowntown==false){
        selectObject.selectedIndex = i+1;
        return true;
      }
      else{
        selectObject.selectedIndex = i;
        return true;
      }
    }
  }
  return false;
}

var handleFailure = function(o){
	if(o.responseText !== undefined){
	  //div.innerHTML = "<li>Transaction id: " + o.tId + "</li>";
		//div.innerHTML += "<li>HTTP status: " + o.status + "</li>";
		//div.innerHTML += "<li>Status code message: " + o.statusText + "</li>";
		//div.innerHTML += "<li>HTTP headers: <ul>" + o.getAllResponseHeaders + "</ul></li>";
		//div.innerHTML += "<li>Server response: " + o.responseText + "</li>";
		//div.innerHTML += "<li>Argument object: Object ( [foo] => " + o.argument.foo + " [bar] => " + o.argument.bar +" )</li>";
	}
}

var callback = {
  success:handleSuccess,
  failure:handleFailure,
  argument: { foo:"foo", bar:"bar" }
};

function makeRequest() {
  //clear the pickup and return drop downs
  pickupList = YAHOO.util.Dom.get('pickupList');
  returnList = YAHOO.util.Dom.get('returnList');

  strCountryID = countryList[countryList.selectedIndex].value;
  var sUrl = proxyDir + "serviceProxy.asp?country=" + strCountryID;
  
  /*
  for (x = pickupList.length; x >= 0; x--) {
    pickupList[x] = null;
    returnList[x] = null;
  }
  */
  
  if(YAHOO.util.Dom.get('countryList').selectedIndex == 0) {
    //do nothing
  } else {
    pickupList[0] = new Option("Loading...","Loading...");
    returnList[0] = new Option("Loading...","Loading...");
    pickupList.selectedIndex = 0;
    returnList.selectedIndex = 0;
    
    //need to get the countryID from the country drop down
    countryList = YAHOO.util.Dom.get('countryList');
    if(strCountryID.value == "" || strCountryID == "Select Country") {
      alert("Please choose a country from the list.")
    } else {
      _countryID.value = strCountryID;
      var postData = "country=" + strCountryID;
      var request = YAHOO.util.Connect.asyncRequest('GET', sUrl, callback);
    }
  }
}
// End - Dynamic drop down population

function sameAsPickup() {
  pickupList = YAHOO.util.Dom.get('pickupList');
  returnList = YAHOO.util.Dom.get('returnList');
  returnList.selectedIndex = pickupList.selectedIndex+1;
  _returnIndex.value = returnList.selectedIndex;
}

//to store the selected index of the pickup location
function pickupChange() {
  pickupList = YAHOO.util.Dom.get('pickupList');
  _pickupIndex.value = pickupList.selectedIndex;
}

//to store the selected index of the return location
function returnChange() {
  returnList = YAHOO.util.Dom.get('returnList');
  _returnIndex.value = returnList.selectedIndex;
}

function generateURL() {
  //used to generate the URL for the vehicle search
  //typical search URL
  //http://www.vroomvroomvroom.com.au/book/default.aspx?pickupdate=2/4/2007&pickuptime=09:00:00&dropoffdate=2/7/2007&dropofftime=18:00:00&ddlPickUpLocation=1817&ddlDropOffLocation=1817&age=25&countryfrom=AU&dosearch=true#results
  //required paramaters for the query string: pickupdate, pickuptime, dropoffdate, dropofftime,
  //                                          ddlPickUpLocation=1817, ddlDropOffLocation=1817, age,
  //                                          countryfrom, dosearch=true#results
  strHost = window.location.hostname;
  
  if(strHost.match("vroomtest.com")) {
    strPageName = "default3.aspx"
  } else if (strHost.match("vroomvroomvroom.com.au")) {
    strPageName = "default3.aspx"
  } else {
    strPageName = "default.aspx"
  }
  //check if the page is hosted on a vroom site, if not, default to the AU site
  //can use the country selected in the country drop down list to redirect to the appropriate site
  countryList = YAHOO.util.Dom.get('countryList');
  strCountryID = countryList[countryList.selectedIndex].value;
  
  switch (strCountryID) {
    case "AU":
      if(strHost.match("vroomtest.com")) {
        strHost = "www.vroomtest.com";
		    strProtocol = "http://";
      } else if(strHost.match("carhire.com.au")) {
        strHost = "carhire.com.au";
		    strProtocol = "https://";
      } else {
        strHost = "vroomvroomvroom.com.au";
		    strProtocol = "https://";
      }
      break;
    case "NZ":
      strHost = "www.vroomvroomvroom.co.nz";
	    strProtocol = "https://";
      break;
    case "US":
    case "CA":
    case "ZA":
      strHost = "vroomvroomvroom.com";
	  strProtocol = "https://";
      break;
    case "CY":
    case "DE":
    case "ES":
    case "FR":
    case "GB":
    case "GR":
    case "HR":
    case "IE":
    case "IT":
    case "MT":
    case "PT":
      strHost = "vroomvroomvroom.co.uk";
	  strProtocol = "https://";
      break;
    default:
      strHost = "vroomvroomvroom.com.au";
	  strProtocol = "https://";
      break;
  }
  
  //for testing on vroomtest only
  //strHost = "www.vroomtest.com";

  var pickupDate = YAHOO.util.Dom.get('_pickupDate').value;
  var returnDate = YAHOO.util.Dom.get('_returnDate').value;
  pickupHour = YAHOO.util.Dom.get('pickupHour')[YAHOO.util.Dom.get('pickupHour').selectedIndex].value;
  pickupMins = YAHOO.util.Dom.get('pickupMins')[YAHOO.util.Dom.get('pickupMins').selectedIndex].value;
  returnHour = YAHOO.util.Dom.get('returnHour')[YAHOO.util.Dom.get('returnHour').selectedIndex].value;
  returnMins = YAHOO.util.Dom.get('returnMins')[YAHOO.util.Dom.get('returnMins').selectedIndex].value;
  pickupLoc = YAHOO.util.Dom.get('pickupList')[YAHOO.util.Dom.get('pickupList').selectedIndex].value;
  pickupTxt = YAHOO.util.Dom.get('pickupList')[YAHOO.util.Dom.get('pickupList').selectedIndex].text;
  //if = "SAME", send the same details we just got for pickup
  returnLoc = YAHOO.util.Dom.get('returnList')[YAHOO.util.Dom.get('returnList').selectedIndex].value;
  //returnTxt = YAHOO.util.Dom.get('returnList')[YAHOO.util.Dom.get('returnList').selectedIndex].text;
  if(returnLoc == "SAME") {
    returnLoc = pickupLoc;
    returnTxt = pickupTxt;
  } else {
    returnTxt = YAHOO.util.Dom.get('returnList')[YAHOO.util.Dom.get('returnList').selectedIndex].text;
  }
  var age = YAHOO.util.Dom.get('ageList')[YAHOO.util.Dom.get('ageList').selectedIndex].value;
  var country = YAHOO.util.Dom.get('countryList2')[YAHOO.util.Dom.get('countryList2').selectedIndex].value;
  countryList = YAHOO.util.Dom.get('countryList');
  strCountryID = countryList[countryList.selectedIndex].value;
  countryList = YAHOO.util.Dom.get('countryList');
  strCountryID = countryList[countryList.selectedIndex].value;

  strURL = strProtocol + strHost + "/book/" + strPageName + "?pickupdate=" + pickupDate + "&pickuptime=" + pickupHour + ":" + pickupMins + ":00" +
        "&dropoffdate=" + returnDate + "&dropofftime=" + returnHour + ":" + returnMins + ":00" + "&ddlPickUpLocation=" + pickupLoc + 
        "&ddlDropOffLocation=" + returnLoc + "&age=" + age + "&ddlCountry=" + strCountryID + "&countryfrom=" + country + "&dosearch=true" + "&tick=" + DateTimeTicks();

  if (typeof affiliateID != 'undefined') {
    if(affiliateID != "") {
    strURL = strURL + "&affiliate=" + affiliateID;
    }
  }
}

function go() {
  if(YAHOO.util.Dom.get('countryList').selectedIndex == 0) {
    alert("Please select a country, then select your desired pickup and return locations to search.");
  } else if(YAHOO.widget.DateMath.before(YAHOO.vroom.calendar.returncal.getSelectedDates()[0], YAHOO.vroom.calendar.pickupcal.getSelectedDates()[0])) {
    alert("Invalid Return Date.  Must be on or after the Pickup Date.");
  } else {
    YAHOO.util.Dom.get('btnSearch').value = "Please Wait...";
    if(window.location.hostname.match("vroomtest.com") || (window.location.hostname.match("vroomvroomvroom.com.au"))) {
      YAHOO.util.Dom.get('divWaitMsg').innerHTML = YAHOO.util.Dom.get('divPleaseWait').innerHTML
  	  YAHOO.util.Dom.get('divPleaseWait').height="80px";
      YAHOO.util.Dom.setStyle('divWaitMsg', 'display', '');
      YAHOO.util.Dom.setStyle('divPleaseWait', 'display', '');
    }
    generateURL();
    window.location = strURL;
  }
}

function customise(age,countryID2) {
  countryList = YAHOO.util.Dom.get("countryList");
  pickupList = YAHOO.util.Dom.get("pickupHour");
  pickupMins = YAHOO.util.Dom.get("pickupMins");
  returnList = YAHOO.util.Dom.get("returnHour");
  returnMins = YAHOO.util.Dom.get("returnMins");
  countryList2 = YAHOO.util.Dom.get("countryList2");
  ageList = YAHOO.util.Dom.get("ageList");
  _init = YAHOO.util.Dom.get('_init');

  countryID = (countryID == null) ? "" : countryID;
  pickupFrom = (pickupFrom == null) ? "" : pickupFrom;
  returnTo = (returnTo == null) ? "" : returnTo;
  pickupDate = (pickupDate == null || pickupDate == "") ? (YAHOO.widget.DateMath.add(new Date(), YAHOO.widget.DateMath.DAY, 1)) : pickupDate;
  returnDate = (returnDate == null || returnDate == "") ? (YAHOO.widget.DateMath.add(new Date(), YAHOO.widget.DateMath.DAY, 5)) : returnDate;
  pickupHour = (pickupHour == null) ? "" : pickupHour;
  pickupMins = (pickupMins == null) ? "" : pickupMins;
  returnHour = (returnHour == null) ? "" : returnHour;
  returnMins = (returnMins == null) ? "" : returnMins;
  countryID2 = (countryID2 == null) ? "" : countryID2;
  age = (age == null) ? "" : age;
  proxyDir = (proxyDir == null) ? "/book/" : proxyDir;
  bDowntown = (bDowntown == null) ? "false" : bDowntown;
  affiliateID = (affiliateID == null) ? "" : affiliateID;

  pickupLoc = pickupFrom;
  returnLoc = returnTo;
  
  if(_init.value != "true") {
    YAHOO.util.Dom.get('_pickupDateObj').value = pickupDate;
    YAHOO.util.Dom.get('_returnDateObj').value = returnDate;
    YAHOO.util.Dom.get('_countryID').value = countryID;
    YAHOO.util.Dom.get('_pickupDate').value = pickupDate;
    YAHOO.util.Dom.get('_returnDate').value = returnDate;
    YAHOO.util.Dom.get('_pickupHour').value = pickupHour;
    YAHOO.util.Dom.get('_pickupMins').value = pickupMins;
    YAHOO.util.Dom.get('_returnHour').value = returnHour;
    YAHOO.util.Dom.get('_returnMins').value = returnMins;
    YAHOO.util.Dom.get('_countryID2').value = countryID2;
    YAHOO.util.Dom.get('_ageListID').value = age;

    if(countryID != "") {
      setSelectedText(countryList, countryID);
      setSelectedText(countryList2, countryID);
    }
    if(pickupHour != "") {
      setSelectedValue(pickupList, pickupHour);
    }
    if(pickupMins != "") {
      setSelectedText(pickupMins, pickupMins);
    }
    if(returnHour != "") {
      setSelectedValue(returnList, returnHour);
    }
    if(returnMins != "") {
      setSelectedText(returnMins, returnMins);
    }
    if(countryID2 != "") {
      setSelectedText(countryList2, countryID2);
    }
    if(age != "") {
      setSelectedValue(ageList, age);
    }
  }
  _init.value = "true";
}

function setSelectedValue(selectObject, value) {
  for(i = 0; i < selectObject.length; i++) {
    if(selectObject[i].value == value) {
      selectObject.selectedIndex = i;
    }
  }
}

function setSelectedText(selectObject, text) {
  for(i = 0; i < selectObject.length; i++) {
    if(selectObject[i].text == text) {
      selectObject.selectedIndex = i;
    }
  }
}

customise(null,null);
init();
