var dt = new Date();
var FOLDERNAME = "searchform";
var strReturnAddresses = "";
var aryDepots;
var locations = {}, depots = {};
var aryPickupDepots = [], aryReturnDepots = [];
var aryLocations = [];
var LOADING_TEXT = "Loading....";
var LocType = "Pickup";
var strCountryPickupID;
var isPageLoadDone = false; //Its been set to true once the page is loaded based upon variables and querystring.

//Getting value from querystring.
function getQueryVariable(a) {
  var b = window.location.search.substring(1).split("&"), c;
  for (c = 0; c < b.length; c++) {
    var d = b[c].split("=");
    if (d[0] === a) {
      return d[1].replace(/%20/g, " ");
    }
  }
  return "";
}
HTTPSERVER = (typeof (HTTPSERVER) === "undefined") ? "" : HTTPSERVER;
HTTPSERVER = (HTTPSERVER === "") ? "http://www.vroomvroomvroom.com.au/" : HTTPSERVER;
PICKUP_PROMPT = (typeof (PICKUP_PROMPT) === "undefined") ? "" : PICKUP_PROMPT;
PICKUP_PROMPT = (PICKUP_PROMPT === "") ? "Where are you picking up from?" : PICKUP_PROMPT;
RETURN_PROMPT = (typeof (RETURN_PROMPT) === "undefined") ? "" : RETURN_PROMPT;
RETURN_PROMPT = (RETURN_PROMPT === "") ? "Where are you returning the car?" : RETURN_PROMPT;
LIST_ALL_LOCATIONS_ONFOCUS = (typeof (LIST_ALL_LOCATIONS_ONFOCUS) === "undefined") ? "" : LIST_ALL_LOCATIONS_ONFOCUS;
LIST_ALL_LOCATIONS_ONFOCUS = (LIST_ALL_LOCATIONS_ONFOCUS === "") ? false : LIST_ALL_LOCATIONS_ONFOCUS;
SUGGESTION_MODE = (typeof (SUGGESTION_MODE) === "undefined") ? "" : SUGGESTION_MODE;
SUGGESTION_MODE = (SUGGESTION_MODE === "") ? "OFF" : SUGGESTION_MODE;
THEME = (typeof (THEME) === "undefined") ? "" : THEME;
THEME = (THEME === "") ? getQueryVariable("theme") : THEME;
if (THEME !== "") {
  document.write("<link type=\"text/css\" rel=\"stylesheet\" href=\"" + HTTPSERVER + FOLDERNAME + "/css/" + THEME + ".css\" \/>");
}
MOBILE = (typeof (MOBILE) === "undefined") ? false : MOBILE;

/*Class to store information in a more jSon format than the array.*/
function ClassDepot(a) {
  this.supplierid = a[0];
  this.depotid = a[1];
  this.address = a[2];
  this.city = a[3];
  this.country = a[4];
  this.postcode = a[5];
  this.airport = a[6];
  this.latitude = a[7];
  this.longitude = a[8];
  this.fulladdress = this.address + ", " + this.city + ", " + this.postcode + ", " + this.country;
  this.selected = false;
}
/*
Creating a new date by adding 2 days.
This is done so to set the ReturnDate 2 days after the PickupDate.
*/
function addDays(myDate, days) {
  return new Date(myDate.getTime() + days * 24 * 60 * 60 * 1000);
}
/*PageLoad. Initializing stuff.*/
$(document).ready(function() {
  var _init = $("#_init").val();
  _init = (typeof (_init) === "undefined") ? "false" : _init;

  var defaultPickupDate = new Date();
  defaultPickupDate.setDate(defaultPickupDate.getDate() + 1);
  var defaultReturnDate = new Date();
  defaultReturnDate.setDate(defaultReturnDate.getDate() + 4);
  $.extend($.datepicker, { _checkOffset: function(inst, offset, isFixed) { return offset; } });

  COUNTRYID = (typeof (COUNTRYID) === "undefined") ? "" : COUNTRYID;
  COUNTRYID = (COUNTRYID === "") ? getQueryVariable("countryid") : COUNTRYID;
  COUNTRYID = (COUNTRYID === "") ? "AU" : COUNTRYID;
  PICKUPDATE = (typeof (PICKUPDATE) === "undefined") ? "" : PICKUPDATE;
  PICKUPDATE = (PICKUPDATE === "") ? getQueryVariable("pickupdate") : PICKUPDATE;
  if (PICKUPDATE !== "") {
    dateParts = PICKUPDATE.split("/");
    PICKUPDATE = new Date();
    PICKUPDATE.setFullYear(dateParts[2], parseInt(dateParts[0], 10) - 1, dateParts[1]);
  }
  PICKUPDATE = (PICKUPDATE === "") ? defaultPickupDate : PICKUPDATE;
  RETURNDATE = (typeof (RETURNDATE) === "undefined") ? "" : RETURNDATE;
  RETURNDATE = (RETURNDATE === "") ? getQueryVariable("returndate") : RETURNDATE;
  if (RETURNDATE !== "") {
    dateParts = RETURNDATE.split("/");
    RETURNDATE = new Date();
    RETURNDATE.setFullYear(dateParts[2], parseInt(dateParts[0], 10) - 1, dateParts[1]);
  }
  RETURNDATE = (RETURNDATE === "") ? defaultReturnDate : RETURNDATE;
  PICKUPTIME = (typeof (PICKUPTIME) === "undefined") ? "" : PICKUPTIME;
  PICKUPTIME = (PICKUPTIME === "") ? getQueryVariable("pickuptime") : PICKUPTIME;
  RETURNTIME = (typeof (RETURNTIME) === "undefined") ? "" : RETURNTIME;
  RETURNTIME = (RETURNTIME === "") ? getQueryVariable("returntime") : RETURNTIME;
  PICKUPFROM = typeof PICKUPFROM === "undefined" ? "" : PICKUPFROM;
  PICKUPFROM = (PICKUPFROM === "") ? getQueryVariable("pickupfrom") : PICKUPFROM;
  PICKUPFROMID = (typeof (PICKUPFROMID) === "undefined") ? "" : PICKUPFROMID;
  PICKUPFROMID = (PICKUPFROMID === "") ? getQueryVariable("pickupfromid") : PICKUPFROMID;
  RETURNTO = (typeof RETURNTO === "undefined") ? "" : RETURNTO;
  RETURNTO = (RETURNTO === "") ? getQueryVariable("returnto") : RETURNTO;
  RETURNTOID = (typeof (RETURNTOID) === "undefined") ? "" : RETURNTOID;
  RETURNTOID = (RETURNTOID === "") ? getQueryVariable("returntoid") : RETURNTOID;
  COUNTRY_LIVE_IN = (typeof (COUNTRY_LIVE_IN) === "undefined") ? "" : COUNTRY_LIVE_IN;
  COUNTRY_LIVE_IN = (COUNTRY_LIVE_IN === "") ? getQueryVariable("countrylivein") : COUNTRY_LIVE_IN;
  COUNTRY_LIVE_IN = (COUNTRY_LIVE_IN === "") ? getQueryVariable("ilivein") : COUNTRY_LIVE_IN;
  COUNTRY_LIVE_IN = (COUNTRY_LIVE_IN === "") ? COUNTRYID : COUNTRY_LIVE_IN;
  AGE = (typeof (AGE) === "undefined") ? "" : AGE;
  AGE = (AGE === "") ? getQueryVariable("age") : AGE;
  AFFILIATEID = (typeof (AFFILIATEID) === "undefined") ? "" : AFFILIATEID;
  AFFILIATEID = (AFFILIATEID === "") ? getQueryVariable("affiliateid") : AFFILIATEID;
  AFFILIATEID = (AFFILIATEID === "") ? getQueryVariable("a") : AFFILIATEID;
  IS_AFFILIATE = getQueryVariable("isaffiliate");
  IS_AFFILIATE = (IS_AFFILIATE === "") ? false : true;
  LOCATION_PROMPT = (typeof (LOCATION_PROMPT) === "undefined") ? "" : LOCATION_PROMPT;
  LOCATION_PROMPT = (LOCATION_PROMPT === "") ? "Click here for {0} locations" : LOCATION_PROMPT;
  SHOW_SUPPLIER_BOX = (typeof (SHOW_SUPPLIER_BOX) === "undefined") ? false : SHOW_SUPPLIER_BOX;

  AGE !== "" && $("#ageList").val(AGE);
  PICKUPTIME !== "" && $("#pickupTime").val(PICKUPTIME);
  RETURNTIME !== "" && $("#returnTime").val(RETURNTIME);

  /* Setup of datepicker. */
  $("#txtPickupDate").datepicker({
    closeText: "Close",
    dateFormat: "dd-M-yy",
    altFormat: "m-d-yy",
    minDate: 0,
    numberOfMonths: 1,
    showOn: "both",
    buttonImage: HTTPSERVER + FOLDERNAME + "/images/calendar.png",
    buttonImageOnly: true,
    buttonText: "",
    showButtonPanel: true,
    showOtherMonths: true,
    selectOtherMonths: true,
    showAnim: "",
    onSelect: function(selectedDate) {
      if ($("#txtReturnDate").datepicker('getDate') < $("#txtPickupDate").datepicker('getDate')) {
        $("#txtReturnDate").datepicker("setDate", addDays($("#txtPickupDate").datepicker('getDate'), 2));
      }
      $("#txtReturnDate").datepicker("option", { minDate: $("#txtPickupDate").datepicker('getDate') });
    },
    beforeShow: function(input, inst) {
      inst.dpDiv.removeClass("dpReturn").addClass("dpPickup");
    }
  });

  $("#txtReturnDate").datepicker({
    closeText: "Close",
    dateFormat: "dd-M-yy",
    altFormat: "m-d-yy",
    minDate: 0,
    numberOfMonths: 1,
    showOn: "both",
    buttonImage: HTTPSERVER + FOLDERNAME + "/images/calendar.png",
    buttonImageOnly: true,
    buttonText: "",
    showButtonPanel: true,
    showOtherMonths: true,
    selectOtherMonths: true,
    showAnim: "",
    beforeShow: function(input, inst) {
      inst.dpDiv.addClass("dpReturn").removeClass("dpPickup");
    }
  });
  if (_init === "true") {
    PICKUPDATE = $("#txtPickupDate").datepicker('getDate');
    RETURNDATE = $("#txtReturnDate").datepicker('getDate');
    PICKUPFROM = $("#_myInputPickupId").val();
    PICKUPFROMID = $("#myInputPickupId").val();
    RETURNTO = $("#_myInputReturnId").val();
    RETURNTOID = $("#myInputReturnId").val();
    COUNTRYID = $("#_countryID").val();
  } else {
    $("#countryListLiveIn").val(COUNTRY_LIVE_IN);
    $("#_countryLiveIn").val(COUNTRY_LIVE_IN);
  }

  enableAutocomplete('Pickup');
  enableAutocomplete('Return');
  
  if (COUNTRYID !== "") {
    $("#countryListPickup").val(COUNTRYID).trigger("change");
  }

  $("#txtPickupDate").datepicker("option", "altField", "#_pickupDate").datepicker("setDate", PICKUPDATE);
  $("#txtReturnDate").datepicker("option", "altField", "#_returnDate").datepicker("setDate", RETURNDATE);
  $("#txtReturnDate").datepicker("option", "minDate", $("#txtPickupDate").datepicker('getDate'));

  $("#_init").val("true");
});

//Hide the link to customise depots
function HideDepotAddressesLink(a) {
  $("#divToggle" + a + "Addresses").hide();
}

/*Setting PICKUPFROM, if PICKUPFROMID already set*/
function setLocationName() {
  var a = 0, c;
  for (c = 0; c < aryLocations.length; c++) {
    if (aryLocations[c][3] === PICKUPFROMID) {//Pickup
      if ($("#_myInputPickupId").val() === "") {
        PICKUPFROM = aryLocations[c][0] + ", " + aryLocations[c][2] + (aryLocations[c][1] !== "" ? " (" + aryLocations[c][1] + ")" : "");
        $("#_myInputPickupId").val(PICKUPFROM);
        $("#myInputPickup").nextAll(".ac_close").show();
      } else {
        PICKUPFROM = $("#_myInputPickupId").val();
      }
      a++;
    }
    if (aryLocations[c][3] === RETURNTOID) {//Return
      if ($("#_myInputReturnId").val() === "") {
        RETURNTO = aryLocations[c][0] + ", " + aryLocations[c][2] + (aryLocations[c][1] !== "" ? " (" + aryLocations[c][1] + ")" : "");
        $("#_myInputReturnId").val(PICKUPFROM);
        $("#myInputReturn").nextAll(".ac_close").show();
      } else {
        RETURNTO = $("#_myInputReturnId").val();
      }
      a++;
    }
    //Break from look if both PICKUPFROM & RETURNTO are set.
    if (a === 2) { break; }
  }
}

/*Setting PICKUPFROMID, if PICKUPFROM already set*/
function setLocationID() {
  var a = 0, b = "", c;
  for (c = 0; c < aryLocations.length; c++) {
    b = aryLocations[c][0] + ", " + aryLocations[c][2] + (aryLocations[c][1] !== "" ? " (" + aryLocations[c][1] + ")" : "");
    if (b === PICKUPFROM) {//Pickup
      PICKUPFROMID = aryLocations[c][3];
      a++;
    }
    if (b === RETURNTO) {//Return
      RETURNTOID = aryLocations[c][3];
      a++;
    }
    //Break from look if both PICKUPFROM & RETURNTO are set.
    if (a === 2) { break; }
  }
}

var DEPOTS_PICKUP = [], // [['AV',4596],['BG',5261],['EC',21388],['HZ',4911],['TH',12908]],
DEPOTS_RETURN = []; // [['AV',4596],['BG',5261],['EC',21388],['HZ',4911],['TH',12908]];
/*Getting selected depot value from hiddend field OR Querystring, otherwise blank*/
function getDepotValue(a) {
  var e = $("#_depots").val();
  var b = e.split("&"), c;
  if (e !== "") {
    for (c = 0; c < b.length; c++) {
      var d = b[c].split("=");
      if (d[0] === a) {
        return d[1].replace(/%20/g, " ");
      }
    }
    return "";
  } else {
    var f = getQueryVariable("depots");
    f = f.substring(f.indexOf(a) + 3, f.indexOf("]", f.indexOf(a)));
    return f;
  }
}

/* Setting up DEPOTS_PICKUP & DEPOTS_RETURN array from hidden field or Querystring
DEPOTS_PICKUP & DEPOTS_RETURN is equivalent to depots in hidden field or querystring i.e depots selected by user. */
function setDepotsFromFieldOrQueryString(a) {
  var temp = [];
  var b = eval("ary" + a + "Depots"), c, d = eval("DEPOTS_" + a.toUpperCase());
  for (c = 0; c < b.length; c++) {
    if ($.inArray(b[c].supplierid, temp) === -1) {//Didn't get registered yet.
      var e = getDepotValue(b[c].supplierid);
      if (e !== '') {
        temp.push(b[c].supplierid);
        d.push([b[c].supplierid, e.split("|")[a === "Pickup" ? 0 : 1]]);
      }
    }
  }
}

/* Setting aryPickupDepots & aryReturnDepots array item to true if it was selected by User because it contains all the depots for a location */
function SetDepotChoices(c) {
  var a, b = eval("DEPOTS_" + c.toUpperCase()), d, e = eval("ary" + c + "Depots");
  for (a = 0; a < b.length; a++) {
    for (d = 0; d < e.length; d++) {
      if (e[d].supplierid === b[a][0]) {
        e[d].selected = (e[d].depotid === b[a][1]);
      }
    }
  }
}
/*
Checking equality of PICKUP and RETURN by comparing:
1. Location
2. Depots
Can't directly return bool value based upon checkbox because when we click modify button than a fresh request it executed.
So, controls doesn't retain their values. 
*/
function CheckPickupAndReturnEquality() {
  if (PICKUPFROMID === RETURNTOID && DEPOTS_PICKUP.length == DEPOTS_RETURN.length) {
    for (var i = 0, len = DEPOTS_PICKUP.length; i < len; i++) {
      if (DEPOTS_PICKUP[i][1] !== DEPOTS_RETURN[i][1])
        return false;
    }
    return true;
  } else {
    return false;
  }
}

//Show/Hide ReturnTo textbox.
function ToggleReturn() {
  var divReturn = $("#divReturn");
  divReturn.toggle();
  if (divReturn.is(":visible")) {
    $("#divCheckSamePickup").hide();
  } else {
    if (PICKUPFROM === RETURNTO) {
      $("#myInputReturn").val("");
      $("#myInputReturnId").val("");
      $("#_myInputReturnId").val("");
    }
  }
}

// dynamically load any javascript file.
function getScript(filename) {
  var script = document.createElement('script');
  script.setAttribute("type", "text/javascript");
  script.setAttribute("src", filename);
  if (typeof script !== "undefined") {
    document.getElementsByTagName("head")[0].appendChild(script);
  }
}

function AutoCompleteSelect(a, ui, IsImplicit) {
  HideDepotAddressesLink(a);
  $("#myInput" + a).val(ui.item[0] + (ui.item[2] == "" ? "" : (", " + ui.item[2])) + (ui.item[1] === "" ? "" : " (" + ui.item[1] + ")")).nextAll(".ac_close").show();
  $("#myInput" + a + "Id").val(ui.item[3]);
  $("#_myInput" + a + "Id").val(ui.item[0] + (ui.item[2] == "" ? "" : (", " + ui.item[2])) + (ui.item[1] === "" ? "" : " (" + ui.item[1] + ")"));
  //Setting ReturnTo stuff as same to PickupFrom, if it is hidden.
  if ($("#divReturn").css("display") === "none") {
    $("#myInputReturnId").val(ui.item[3]);
    $("#_myInputReturnId").val(ui.item[0] + ", " + ui.item[2] + (ui.item[1] === "" ? "" : " (" + ui.item[1] + ")"));
  }
  if (SHOW_SUPPLIER_BOX) {
    BuildSearchBox(ui.item[3]);
  } else if (IsImplicit) {
    if (!IS_AFFILIATE) {
      //$.getScript(HTTPSERVER + "vroomtools/depotJS.aspx?format=Array&action=" + a + "&locationid=" + ui.item[3], function() {
      $.getScript(HTTPSERVER + "book/tools/depotJS.ashx?format=Array&action=" + a + "&locationid=" + ui.item[3], function() {
        DepotsAreLoaded(a);
        var $html = ADVANCED_MODE === "MAP" ? aryDepots.length + (aryDepots.length === 1 ? " company operates" : " companies operate") + " at this depot. <a href='#map' onclick='ShowModalMap(\"" + a + "\", \"" + escape(ui.item[0]) + "\");'>map</a>" : "<a href='#depot' onclick='ShowAddresses(\"" + a + "\", \"" + escape(ui.item[0]) + "\");'>Choose from " + aryDepots.length + " address " + (aryDepots.length === 1 ? "option" : "options");
        $("#divToggle" + a + "Addresses").show().html($html);
      });
    }
  }
}

/*
Configuring the setting when focus function was called implicitly by the control.
*/
function focusInit(a) {
  var PROMPT = a === "Pickup" ? PICKUP_PROMPT : RETURN_PROMPT;
  var from_to = a === "Pickup" ? PICKUPFROM : RETURNTO;

  if ($("#myInput" + a).val() === LOCATION_PROMPT.format(from_to)) {
    $("#myInput" + a).val(from_to);
  }
  var searchterm = $("#myInput" + a).val() === PROMPT ? "" : $("#myInput" + a).val();

  if (from_to === "") {
    if ($("#myInput" + a).val() === PROMPT) {
      $("#myInput" + a).val("");
    }
    if ($("#_myInput" + a + "Id").val() !== searchterm || searchterm === "") {
      $("#myInput" + a).val(searchterm).autocomplete("search", searchterm);
    }
  } else {
    if (SUGGESTION_MODE === "AUTOCOMPLETE") {
      if ($("#myInput" + a).val() !== PROMPT) {
        $("#myInput" + a).nextAll(".ac_close").show();
      }
      if ($("#_myInput" + a + "Id").val() !== searchterm || searchterm === "") {
        $("#myInput" + a).val(searchterm).autocomplete("search", searchterm);
      }
    } else {
      $("myInput" + a).val("");
    }
  }
}

/*
Setting textbox value based upon scenario.
*/
function onBlur(a, isImplicit) {
  var i = $("#myInput" + a),
    from_to = a === "Pickup" ? PICKUPFROM : RETURNTO,
    s;
  if (i.val() === "") {
    if (a === "Pickup") {
      s = PICKUP_PROMPT;
    } else {
      s = RETURN_PROMPT;
    }
    i.val(s).nextAll(".ac_close").hide();
  } else if (i.val() === from_to && $("#_myInput" + a + "Id").val() === "") {
    s = LOCATION_PROMPT.format(from_to);
    i.val(s).nextAll(".ac_close").hide();
  }
  //Used isImplicit parameter to stop recursion while calling blur event.
  if (!isImplicit) { i.blur(); }
}

function pageLoadDone() {
  isPageLoadDone = true;
  $("#_depots").val("");
  $("#_separateDepots").val("")
}

function enableAutocomplete(a) {
  $("#myInput" + a).autocomplete({
    minLength: 0,
    selectFirst: true,
    delay: 10,
    source: function(req, responseFn) {
      if (req.term === "" && LIST_ALL_LOCATIONS_ONFOCUS === false) {
        responseFn([]);
      } else {
        var csub = [],
              csubOther = [],
              needle = req.term.toLowerCase(),
              len = aryLocations.length;
        for (i = 0; i < len; i++) {
          var haystack = (aryLocations[i][0] + ", " + aryLocations[i][2] + (aryLocations[i][1] === "" ? "" : " (" + aryLocations[i][1] + ")")).toLowerCase();
          if (haystack.indexOf(needle) === 0) {
            csub.push(aryLocations[i]);
          } else {
            if (csubOther.length < 15) {
              if (haystack.indexOf(needle) !== -1) {
                csubOther.push(aryLocations[i]);
              }
            }
          }
        }
        $.merge(csub, csubOther);
        responseFn(csub.slice(0, 50));
      }
    },
    select: function(event, ui) {
      if (ui.item[3] > -1) {
        AutoCompleteSelect(a, ui, true);
      } else {
        onBlur(a, false);
      }
      return false;
    }
  })
    .data("autocomplete")._renderItem = function(ul, item) {
      var airport = item[0].indexOf("Airport") !== -1;
      var acClass = (airport === true ? "vvvacairport" : "vvvaccity");
      if (item[3] === -1) {
        item[0] = "<span class='cursordefault'>Type location or airport code now</span>";
        acClass = "vvvactip";
        return $("<li></li>")
          .data("item.autocomplete", item)
          .append("<a><span class='" + acClass + "'>" + item[0] + "</span></a>")
          .appendTo(ul);
      } else {
        $("#myInput" + a).nextAll(".ac_close").show();
        return $("<li></li>")
          .data("item.autocomplete", item)
          .append("<a><span class='" + acClass + "'>" + (item[0] + (item[2] === "" ? "" : ", " + item[2]) + (item[1] === "" ? "" : " (" + item[1] + ")")).replace(new RegExp("(?![^&;]+;)(?!<[^<>]*)(" + $.ui.autocomplete.escapeRegex(this.term).replace(/([\^\$\(\)\[\]\{\}\*\.\+\?\|\\])/gi, "\\$1") + ")(?![^<>]*>)(?![^&;]+;)", "gi"), "<span class='highlight'>$1</span>") + "</span></a>")
          .appendTo(ul);
      }
    };
}
/*
Setting the autoComplete tool for textboxes upon focus.
I chose this event so that tool has the latest data.
AutoComplete cache the data, so that it don't have to get it again.
$.merge(arguments[0], [['', '', '', '-1']]);
*/
function onFocus(a, isImplicit) {
  //Called dynamically by code.
  if (!isImplicit) {
    //Code should only execute if page is loading, so that custom depots can be set
    if (isPageLoadDone == false) {
      var PickupOrReturnID = "";
      //Setting things for appropriate textbox of autoComplete.
      if (a === "Pickup") {
        onBlur("Pickup", false);
        PickupOrReturnID = PICKUPFROMID;
      } else {
        if (RETURNTO !== "") {
          onBlur("Return", false);
          PickupOrReturnID = RETURNTOID;
        }
      }
      /*
      Loading depots from Server, if location is already set during pageLoad:
      1. by default
      2. by querystring
      Also Calling Focus function for RETURN internally, as promised above.
      */
      if (PickupOrReturnID !== "") {
        if (SHOW_SUPPLIER_BOX) {
          PICKUPFROMID != "" && BuildSearchBox(PICKUPFROMID);
          FillLocationTextBoxes();
        } else {
          if (IS_AFFILIATE) {
            FillLocationTextBoxes();
          } else {
            //$.getScript(HTTPSERVER + "vroomtools/depotJS.aspx?format=Array&action=" + a + "&locationid=" + PickupOrReturnID, function() {
            $.getScript(HTTPSERVER + "book/tools/depotJS.ashx?format=Array&action=" + a + "&locationid=" + PickupOrReturnID, function () {
              DepotsAreLoaded(a);
              var $html = ADVANCED_MODE === "MAP" ? aryDepots.length + (aryDepots.length === 1 ? " company operates" : " companies operate") + " at this depot. <a href='#map' onclick='ShowModalMap(\"" + LocType + "\", \"" + escape($("#_myInputPickupId").val()) + "\");'>map</a>" : "<a href='#depot' onclick='ShowAddresses(\"" + LocType + "\", \"" + escape($("#_myInputPickupId").val()) + "\");'>Choose from " + aryDepots.length + " address " + (aryDepots.length === 1 ? "option" : "options");
              $("#divToggle" + LocType + "Addresses").show().html($html);
              setDepotsFromFieldOrQueryString(LocType);
              SetDepotChoices(LocType);
              FillLocationTextBoxes();
            });
          }
        }
      } else {//When depots are not loaded than set PICKUPFROM/RETURNTO.
        if (LocType === "Pickup") {
          PICKUPFROM !== "" && $("#myInput" + a).val(LOCATION_PROMPT.format(PICKUPFROM));
          LocType = "Return";
          onFocus(LocType, false);
        } else {
          RETURNTO !== "" && $("#myInput" + a).val(LOCATION_PROMPT.format(RETURNTO));
          if (PICKUPFROM === RETURNTO) {
            $("#checkSameAsPickup").attr("checked", true);
          } else if (RETURNTO !== "") {
            ToggleReturn();
          }
          pageLoadDone();
        }
      }
    }
  } else {
    focusInit(a);
  }
}

function FillLocationTextBoxes() {
  if (LocType === "Pickup") {
    if (PICKUPFROM !== "") {
      $("#myInputPickupId").val(PICKUPFROMID);
      $("#myInputPickup").val(PICKUPFROM);
    }
    LocType = "Return";
    onFocus(LocType, false);
  } else {//Return called recursively.
    if (RETURNTO !== "") {
      $("#myInputReturnId").val(RETURNTOID);
      $("#myInputReturn").val(RETURNTO);
    }
    if (CheckPickupAndReturnEquality() == false) {//Different
      if ($("#checkSameAsPickup").attr("checked")) {
        $("#checkSameAsPickup").attr("checked", false);
      }
      ToggleReturn();
      //$("#checkSameAsPickup").click(); //Show both Pickup and Return
    }
    pageLoadDone();
  }
}
//Setting the location textboxes with prompt.
function PopulateLocations() {
  $("#myInputPickup").val(PICKUP_PROMPT);
  $("#myInputReturn").val(RETURN_PROMPT);
}

/*Loading the New locations from server*/
var RequestNewLocationsJS = function() {
  HideDepotAddressesLink("Pickup");
  HideDepotAddressesLink("Return");
  //disable the 'same as pickup' checkbox
  $("#checkSameAsPickup").attr("disabled", true);
  SHOW_SUPPLIER_BOX && ResetSearchBox();
  var a = $("#countryListPickup");
  $("#myInputPickup, #myInputReturn").val(LOADING_TEXT).nextAll(".ac_close").hide();
  strCountryPickupID = a.val();
  //Checking if any country is set before getting locations for it.
  if (a.find("option:selected").index() !== 0) {//Valid country
    $("#_countryID").val(strCountryPickupID);
    IS_AFFILIATE = IsCountryAffiliated(strCountryPickupID);
    if (IS_AFFILIATE) {
      aryLocations = [];
      $.ajax({
        url: "/searchform/script/ctlocation.EN.xml",
        dataType: "xml",
        success: function(xml) {
          aryLocations = [];
          var LocationCountry = $(xml).find("Country");
          for (var j = 0, jLen = LocationCountry.length; j < jLen; j++) {
            var $this = jQuery(LocationCountry[j]);
            if ($this.attr("code") == strCountryPickupID) {
              var LocationDetail = $this.children();
              for (i = 0, len = LocationDetail.length; i < len; i++) {
                var locAff = LocationDetail.eq(i);
                var loc = [locAff.attr("Name"),
                    typeof (locAff.attr("AirportCode")) == "undefined" ? "" : locAff.attr("AirportCode"),
                    typeof (locAff.attr("CityName")) == "undefined" ? "" : locAff.attr("CityName"),
                    locAff.attr("Id")];
                aryLocations[i] = [loc[0], loc[1], loc[2], loc[3]];
              }
              break;
            }
          }
          PopulateLocations();
          RunPostLocation();
        }
      });
    } else {
      /*Loading location using jQuery getScript function, which add the response to the document as a script*/
      //$.getScript(HTTPSERVER + "vroomtools/locationJS.aspx?country=" + strCountryPickupID, function() {
      $.getScript(HTTPSERVER + "book/tools/locationJS.ashx?country=" + strCountryPickupID, function() {
        PopulateLocations();
        RunPostLocation();
      });
    }
  } else {
    IS_AFFILIATE = false;
    //Setting it blank so that autocomplete doesn't show any results when country is not valid.
    aryLocations = [];
    PopulateLocations();
  }
};
function RunPostLocation() {
  //enable the 'same as pickup' checkbox
  $("#checkSameAsPickup").attr("disabled", false);
  if (PICKUPFROMID !== "" || RETURNTOID !== "") {
    setLocationName();
  } else {
    setLocationID();
  }
  //It shall call the focus function for RETURNTO internally.
  onFocus("Pickup", false);
}
function IsCountryAffiliated(c) {
  return !(c == "AU" || c == "CA" || c == "FJ" || c == "GB" || c == "MY" || c == "NZ" || c == "US");
}
//Showing the map
function ShowDialog(a) {
  var h = $("#vvvcontainer").height();
  $("#vvvdialog").show().height(h).html(a);
  $(".depotaddresses").height(h - 70);
  $(".depotaddresses").width(465);
  $("#vvvcontainer").hide();
}

/*
Preparing structure of showing depots as a radio button list.
*/
function ShowAddresses(a, name) {
  var b = eval("ary" + a + "Depots");
  var c = "", d = "", e = "", f = 0, g = "", h = "";
  if (a === "Return") {
    h = "R";
  }
  for (i = 0; i < b.length; i++) {
    d = "onClick='OnDepotSelection(\"" + a + '",' + i + ");'";
    if (e !== b[i].supplierid) {
      g = " class=newli";
      if (i + 1 !== b.length) {
        if (b[i + 1].supplierid !== b[i].supplierid) {
          g = " class=sololi";
        }
      } else {
        g = " class=sololi";
      }
    } else {
      g = "";
      f += 1;
    }
    e = (b[i].selected === true ? "checked='true'" : "");
    c += "<li" + g + "><label " + d + "><input id='depot" + i + "' type='radio' " + e + " value='" + i + "' class='" + a + "radio' name='" + b[i].supplierid + h + "' /><span class='supplier" + b[i].supplierid + "16'> <font size='2'>" + b[i].address + ", " + b[i].city + "</font></span></label>";
    if (ADVANCED_MODE === "MAPLINK") {
      c += " <a href='http://maps.google.com/maps?q=" + b[i].fulladdress + "' target=_blank>(map)</a></li>";
    } else {
      c += "</li>";
    }
    e = b[i].supplierid;
  }
  c = f > 0 ? "<b>Select preferred " + a + " addresses in " + unescape(name) + ":</b><div class='depotaddresses'><ul>" + c : "<b>" + a + " addresses in " + unescape(name) + ":</b><div class='depotaddresses'><ul>" + c;
  c += "</ul></div><div class='depotaddressesbutton'><center><input type='button' value='ok' onClick='HideDialog();'></center></div>";
  //Showing the modal if its configured so.
  return (ADVANCED_MODE === "MAP" ? c : ShowDialog(c));
}
function matchSubset(s, sub, option) {
  var i = s.indexOf(sub);
  if (i === -1) { return false; }
  return i === 0 || option;
}

var map;
var markersArray = [];
var lastInfowindow = null;

var google = false,
    mapTimeout = false,
    mapFor, mapDepot;

/*
Change the icon of marker.
Distinquish the selected from unselected for a supplierID.
*/
function changeMarkerIcon(marker) {
  var i;
  for (i = 0; i < markersArray.length; i++) {
    if (markersArray[i].supplierid === marker.supplierid) {
      markersArray[i].setIcon(HTTPSERVER + "images/marker" + marker.supplierid + (markersArray[i].depotid === marker.depotid ? "" : "-off") + ".png");
      markersArray[i].setMap(null);
      markersArray[i].setMap(map);
    }
  }
}

/*
Adding Markers at the map.
Also, configuring the look & event of marker, so that appropriate depot could be selected.
*/
function addMarker(depot, i) {
  var marker = new google.maps.Marker({
    position: new google.maps.LatLng(depot.latitude, depot.longitude),
    map: map,
    title: depot.fulladdress,
    icon: HTTPSERVER + "images/marker" + depot.supplierid + (depot.selected ? "" : "-off") + ".png"
  });
  marker.depotid = depot.depotid;
  marker.supplierid = depot.supplierid;
  var infowindow = new google.maps.InfoWindow({ content: "<strong>" + depot.address + "</strong><br />" + depot.postcode + ", " + depot.city + "<br />" + depot.country + "<span class='info' style='display: none'>" + i + "</span>", disableAutoPan: true });
  google.maps.event.addListener(marker, "click", function() {
    if (lastInfowindow !== null) {//Closing any open Info window.
      lastInfowindow.close();
    }
    infowindow.open(map, marker);
    lastInfowindow = infowindow;

    //Calling the SetDepotChoices function explicitly.
    $("#depot" + $(".info").text()).click();

    //Changing icons of current supplierID.
    changeMarkerIcon(marker);
  });
  markersArray.push(marker);
}

/*Showing the markers at the map*/
function showOverlays() {
  if (markersArray) {
    var bounds = new google.maps.LatLngBounds();
    var i;
    for (i = 0; i < markersArray.length; i++) {
      markersArray[i].setMap(map);
      //FIX: Some depots don't have latitude/longitude been set, which crashes the program/
      if (markersArray[i].position.b !== "" && !isNaN(markersArray[i].position.b) && markersArray[i].position.b !== 0) {
        bounds.extend(new google.maps.LatLng(markersArray[i].position.b, markersArray[i].position.c));
      }
    }
    map.fitBounds(bounds);
  }
}

//Deleting overlays.
function deleteOverlays() {
  if (markersArray) {
    var i;
    for (i = 0; i < markersArray.length; i++) {
      markersArray[i].setMap(null);
    }
    markersArray.length = 0;
  }
}

// Google map load callback.
function OpenMapWhenReady() {
  if (!mapTimeout) { // if Google Map is loaded...
    $("#modalWin").modal({ overlayClose: true }); //Show Modal.

    //Set left hand side information of Modal popup.
    var leftSide = ShowAddresses(mapFor, mapDepot);
    $("#mapLeft").html(leftSide);
    $("#map").width($("#modalWin").width() - $("#mapLeft").outerWidth(true));
    if (map !== null) {
      deleteOverlays();
      lastInfowindow = null;
    }
    var myOptions = { zoom: 13, mapTypeId: google.maps.MapTypeId.ROADMAP };
    map = new google.maps.Map(document.getElementById("map"), myOptions);

    var b = eval("ary" + mapFor + "Depots");
    //Adding Markers at the map.
    var i;
    for (i = 0; i < b.length; i++) {
      addMarker(b[i], i);
    }
    //Showing the markers.
    showOverlays();
  }
}

// Show the Map in modal window.
function ShowModalMap(l, n) {
  mapFor = l; //Is it 'Pickup' or 'Return'
  mapDepot = n; //Name of current Depot.
  setTimeout("checkMapTimeout(0);", 5000); //Call Map timeout alert after specified time.
  /*
  Load goole map script only if its not been even once.
  Call OpenMapWhenReady as a callback, when script is loaded.
  */
  if (!google) {
    getScript('http://maps.google.com/maps/api/js?sensor=false&callback=OpenMapWhenReady');
  } else {
    OpenMapWhenReady();
  }
}

// Checking if google maps is loaded.
function checkMapTimeout(time_elapsed) {
  if (!google) {//Checking google variable associated with Map.
    mapTimeout = true; //Timeout has happened.
    alert("Cannot load Google Maps. Maps are temporarily unavailable. Booooo :-(");
  }
}

//Country Live In Change done.
function CountryLiveInChanged() {
  $("#_countryLiveIn").val($("#countryListLiveIn").val());
}
//Age been changed.
function AgeChanged() {
  $("#_ageList").val($("#ageList").val());
}
//Setting the appropriate depot to true in aryPickupDepots and aryReturnDepots upon click
function OnDepotSelection(a, b) {
  var c = eval("ary" + a + "Depots"), d;
  for (d = 0; d < c.length; d++) {
    if (c[b].supplierid === c[d].supplierid) {
      if (b === d) {
        c[d].selected = true;
        //Changing the Marker icons for current supplierid.
        ADVANCED_MODE === "MAP" && changeMarkerIcon(c[d]);
      } else {
        c[d].selected = false;
      }
    }
  }
}
//Get Return To depot by supperlierID
function GetReturnToDepot(a) {
  var c = aryReturnDepots, l = c.length;
  for (i = 0; i < l; i++) {
    if (c[i].supplierid === a && c[i].selected === true) {
      return c[i];
    }
  }
}
//Constructing a string of prepered depots of user.
function SaveDepotChoices() {
  var a = "", b, c, d = "", e = $("#checkSameAsPickup").attr("checked"), f = aryPickupDepots, l = f.length;
  for (c = 0; c < l; c++) {//Looping through pickup depots
    if (f[c].selected) {//Checking if pickup depot is selected.
      // Getting selected ReturnTo depot of same supplierID as pickup, if checkbox is unchecked.
      b = (e === true ? f[c] : GetReturnToDepot(f[c].supplierid, "Return"));
      if (typeof (b) !== "undefined") {
        if (a !== "") {
          a += ",";
          d += "&";
        }
        a += "[" + f[c].supplierid + "|" + f[c].depotid + "|";
        a += (b !== "" ? b.depotid : f[c].depotid) + "]";

        d += f[c].supplierid + "=" + f[c].depotid + ",";
        d += (b !== "" ? b.depotid : f[c].depotid);
      }
    }
  }
  $("#_depots").val(a);
  $("#_separateDepots").val(d);
}
/*
Hiding based upon mode:
1. Modal for MAP
2. Flipped radio button list selection
*/
function HideDialog() {
  if (ADVANCED_MODE === "MAP") {
    $.modal.close();
  } else {
    $("#vvvdialog").hide();
    $("#vvvcontainer").show();
  }
}
/*
Callback when depots are loaded from server.
Load them to appropriate array, so that it could be used by name.
*/
function DepotsAreLoaded(a) {
  var c = $("#_depots").val(), d = eval("ary" + a + "Depots");
  d.length = 0;
  var g = "", f;
  for (f = 0; f < aryDepots.length; f++) {
    d[f] = new ClassDepot(aryDepots[f]);
    //If page load done than select the first depot for each supplier
    if (isPageLoadDone) {
      d[f].selected = g !== d[f].supplierid;
    } else {//Select depots based upon custom depots (selection done in last page visit)
      if (a === "Pickup") {//Pickup
        d[f].selected = c.indexOf(d[f].depotid) !== -1 ? true : g !== d[f].supplierid;
      } else {//Return
        d[f].selected = c.indexOf("," + d[f].depotid) !== -1 ? true : g !== d[f].supplierid;
      }
    }
    g = d[f].supplierid;
  }
  if ($("#checkSameAsPickup").attr("checked") && a == "Pickup") {
    DepotsAreLoaded('Return');
  }
}

//Generating a unique dateTime, so that request is not been picked upon from cache.
function DateTimeTicks() {
  var a = "", b = new Date();
  a += b.getDate();
  a += b.getMonth() + 1;
  a += b.getFullYear();
  a += b.getHours();
  a += b.getMinutes();
  a += b.getSeconds();
  a += "." + b.getMilliseconds();
  return a;
}

/*
Generating URL based upon country.
Carried from YUI.
*/
function GenerateURL() {
  var a, b = window.location.hostname, c = $("#countryListPickup");
  strCountryPickupID = c.val();
  switch (strCountryPickupID) {
    case "AU":
      if (window.location.hostname === "bargainwheels.com.au" || window.location.hostname === "www.bargainwheels.com.au" || window.location.hostname === "book.bargainwheels.com.au") {
        b = "book.bargainwheels.com.au/book/";
        a = "https://";
      } else {
        b = window.location.hostname === "carhire.com.au" || window.location.hostname === "www.carhire.com.au" ? "carhire.com.au/book/" : "vroomvroomvroom.com.au/book/";
        a = "https://";
      }
      break;
    case "NZ":
      b = "vroomvroomvroom.co.nz/book/";
      a = "https://";
      break;
    case "US": case "CA": case "ZA":
      b = "vroomvroomvroom.com/book/";
      a = "https://";
      break;
    case "CY": case "DE": case "ES": case "FR": case "GB": case "GR": case "HR": case "IE": case "IT": case "MT": case "PT":
      b = "vroomvroomvroom.co.uk/book/";
      a = "https://";
      break;
    default:
      b = "vroomvroomvroom.com.au/book/";
      a = "https://";
      break;
  }

  //The following lines are for testing purposes.  Can be commented out or removed in the Production version
  if (window.location.hostname === "localhost") {
    b = "localhost/book/";
    a = "http://";
  }

  if (window.location.hostname === "vroomtest.com" || window.location.hostname === "www.vroomtest.com") {
    b = "www.vroomtest.com/book/";
    a = "http://";
  }

  PICKUPTIME = $("#pickupTime").val();
  RETURNTIME = $("#returnTime").val();
  pickupId = $("#myInputPickupId").val();
  returnId = $("#myInputReturnId").val();
  var d = $("#ageList").val(), e = $("#countryListLiveIn").val();
  strCountryPickupID = c.val();
  $("#_pickupTime").val(PICKUPTIME);
  $("#_returnTime").val(RETURNTIME);
  SaveDepotChoices();
  if (IS_AFFILIATE) {
    var f = GetLocationByID(pickupId),
      g = GetLocationByID(returnId),
      h = $("#_pickupDate").val().split('-'),
      m = $("#_returnDate").val().split('-'),
      n = PICKUPTIME.split(':'),
      p = RETURNTIME.split(':');
    a = "https://cars.vroomvroomvroom.com/book.htm?clientID=370907&temp=hybrid1&elID=020304475700355944&countryID=" + strCountryPickupID + "&pickupID=" + pickupId + "&returnID=" + returnId + "&pickupName=" + f[0] + "&returnName=" + g[0] + "&pickupDate=" + h[1] + "&pickupMonth=" + (parseInt(h[0]) - 1) + "&pickupYear=" + h[2] + "&returnDate=" + m[1] + "&returnMonth=" + (parseInt(m[0]) - 1) + "&returnYear=" + m[2] + "&pickupHour=" + n[0] + "&pickupMinute=" + n[1] + "&returnHour=" + p[0] + "&returnMinute=" + p[1] + "&age=" + d + "&currencyID=EUR&carGroupID=0&residenceID=AU&CT=AJ&referrer=0:&=undefined#book";
  } else
    a = a + b + "?pickupdate=" + $("#_pickupDate").val().replace("-", "/").replace("-", "/") + "&pickuptime=" + PICKUPTIME + ":00&dropoffdate=" + $("#_returnDate").val().replace("-", "/").replace("-", "/") + "&dropofftime=" + RETURNTIME + ":00&ddlPickUpLocation=" + pickupId + "&ddlDropOffLocation=" + returnId + "&" + $("#_separateDepots").val() + "&age=" + d + "&ddlCountry=" + strCountryPickupID + "&countryfrom=" + e + "&a=" + AFFILIATEID + "&dosearch=true&tick=" + DateTimeTicks();
  return a;
}

function GetLocationByID(id) {
  for (var i = 0; i < aryLocations.length; i++) {
    if (aryLocations[i][3] === id)
      return aryLocations[i];
  }
  return null;
}

//Saving the ReturnTo location, same as PickupFrom.
function SameAsPickup() {
  if (($("#myInputReturn").val() === LOADING_TEXT || $("#myInputReturn").val() === RETURN_PROMPT || $("#myInputReturn").val() === "") && $("#myInputPickup").val() !== PICKUP_PROMPT) {
    //This will set location specific stuff appropriately.
    AutoCompleteSelect('Return', { item: GetLocationByID($("#myInputPickupId").val()) }, false);
    //This will set depot specific stuff appropriately.
    $("#checkSameAsPickup").attr("checked", true);
  }
}

//Validating the form.
function Validate() {
  if ($("#countryListPickup > option:selected").index() === 0) {
    alert("Please select a country, then select your desired pickup and return locations to search.");
    return false;
  }
  if (new Date($("#txtReturnDate").val()) - new Date($("#txtPickupDate").val()) < 0) {
    alert("You must return the car after you pick it up. Please change your dates!");
    return false;
  }
  if ($("#myInputPickupId").val() === "" || $("#myInputPickup").val() === "" || $("#myInputPickup").value === PICKUP_PROMPT || $("myInputPickup").val() === LOADING_TEXT) {
    alert("Please type in a pickup city.");
    return false;
  }
  if ($("#myInputReturnId").val() === "" || $("#myInputReturn").val() === "" || $("#myInputReturn").value === RETURN_PROMPT || $("myInputReturn").val() === LOADING_TEXT) {
    alert('Please type in a return city.');
    return false;
  }
  if ($("#countryListLiveIn").val() === "ZZ") {
    alert('Please select your country of residence.');
    return false;
  }
  return true;
}

//Submit call.
function go() {
  SameAsPickup();
  if (Validate()) {//Validating the form.
    $("#btnSearch").val("Please Wait...");
    top.location = GenerateURL();
  }
}
//Resetting the location textbox.
function EmptySearch(a) {
  $("#myInput" + a).nextAll(".ac_close").hide();
  $("#myInput" + a).val(a === "Pickup" ? PICKUP_PROMPT : RETURN_PROMPT);
  $("#myInput" + a + "Id").val("");
  $("#_myInput" + a + "Id").val("");
  $("#divToggle" + a + "Addresses").hide();

  if ($("#divReturn").css("display") === "none" && a === 'Pickup') {
    EmptySearch('Return');
  }

  $("#_depots").val("");

  if (a === "Pickup") {
    PICKUPFROM = "";
  } else {
    RETURNTO = "";
  }
  SHOW_SUPPLIER_BOX && a === 'Pickup' && ResetSearchBox();
}

$(window).unload(function() {
});

/*
* jQuery UI Autocomplete Select First Extension
*
* Copyright 2010, Scott González (http://scottgonzalez.com)
* Dual licensed under the MIT or GPL Version 2 licenses.
*
* http://github.com/scottgonzalez/jquery-ui-extensions
*/
(function($) {
  $(".ui-autocomplete-input").live("autocompleteopen", function() {
    var autocomplete = $(this).data("autocomplete"),
      menu = autocomplete.menu;
    if (!autocomplete.options.selectFirst) {
      return;
    }
    menu.activate($.Event({ type: "mouseenter" }), menu.element.children().first());
  });
} ($));
String.prototype.format = function() {
  var formatted = this;
  var i;
  for (i = 0; i < arguments.length; i++) {
    var regexp = new RegExp('\\{' + i + '\\}', 'gi');
    formatted = formatted.replace(regexp, arguments[i]);
  }
  return formatted;
};
