// Drop Downs

// A fix to access .net controls from external JS files
jQuery.expr[':'].asp = function(elem, i, match) {
  return (elem.id && elem.id.match(match[3] + "$"));
};


function GetSelectedItem(field) {
  len = field.length;
  i = 0;
  chosen = "none";

  for (i = 0; i < len; i++) {
    if (field[i].selected) {
      chosen = field[i].value;
    }
  }
  return chosen;
} 

function SetSelectedItem(field,value){
  len = field.length;
  i = 0;

  for (i = 0; i < len; i++) {
    if (field[i].value == value) {
      field[i].selected = true;
    }
  }
  return true;
} 

function SetSelectedText(field,value) {
  len = field.length;
  i = 0;

  for (i = 0; i < len; i++) {
    if (field[i].text == value) {
      field[i].selected = true;
    }
  }
  return true;
}

/*
function SupplierChange(supplierID) {
  if(supplierID == "ALL") {
    window.location.href="/book/";
  } else {
    window.location.href="/book/?supplier=" + supplierID;
  }
}
*/

//############## Special Vroom Functions #################
function readmorewindow() {
   window.open("","popup","width=780,height=480,left=30,top=30, toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=yes,resizable=yes,copyhistory=0,");
}

function smswindow() {
   window.open("","popup","width=380,height=285,left=30,top=30, toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=yes,resizable=yes,copyhistory=0,");
}

function insurancemorewindow() {
   window.open("","popup","width=600,height=400,left=30,top=30, toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=yes,resizable=yes,copyhistory=0,");
}

function vehiclemorewindow() {
   window.open("","popup","width=580,height=270,left=30,top=30, toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=yes,resizable=yes,copyhistory=0,");
}
function depotmorewindow(depotid) {
   window.open("/book/depot.aspx?depotid="+depotid,"popup","width=800,height=600,left=30,top=30, toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=yes,resizable=yes,copyhistory=0,");
}

function mapwindow() {
   window.open("","popup","width=417,height=320,left=30,top=30, toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=yes,resizable=yes,copyhistory=0,");
}
// Confirmations
function confirm_booking_cancel() {
  var bReturn = false;
  if(confirm("WARNING\nAre you sure you wish to cancel this booking?")) {
    if (Page_ClientValidate() === true) {
      bReturn = true;
    } else {
      bReturn = false;
    }
  } else {
    bReturn = false;
  }
  return bReturn;
}

function confirm_booking_modify(url) {
  if(confirm("WARNING\nAny modifications may change the original quoted price.\nAre you sure you wish to modify your booking?")) {
    window.location.href=url;
  }
}

// LAYERS AND DIVS
//function SetContent(layerName,content){
//  eval(layerRef+'["'+layerName+'"].innerHTML="' + content + '"');
//}

function getObjStyle(name) {
  if (document.getElementById) {
    return document.getElementById(name).style;
  } else if (document.all) {
    return document.all[name].style;
  } else if (document.layers) {
    return document.layers[name];
  } else {
    return false;
  }
}

function getObj(name) {
  if (document.getElementById) {
    return document.getElementById(name);
  } else if (document.all) {
    return document.all[name];
  } else if (document.layers) {
    return document.layers[name];
  } else {
    return false;
  }
}

function HideLayer(layerName) {
  //getObjStyle(layerName).visibility = "hidden";
  getObjStyle(layerName).display = 'none';
}

function ShowLayer(layerName) {
  //getObjStyle(layerName).visibility = "inherit";
  getObjStyle(layerName).display = '';
}

function ChangeImage(imageID, imgURL) {
  getObj(imageID).src = imgURL;
}

//Cookie Helpers
function SetCookie(name, value, expires, path, domain, secure) {
 var curCookie = name + "=" + escape(value) +
  ((expires) ? "; expires=" + expires.toGMTString() : "") +
  ((path) ? "; path=" + path : "") +
  ((domain) ? "; domain=" + domain : "") +
  ((secure) ? "; secure" : "");
 document.cookie = curCookie;
}

function GetCookie(name) {
  var dc = document.cookie;
  var prefix = name + "=";
  var begin = dc.indexOf("; " + prefix);
  if (begin == -1) {
    begin = dc.indexOf(prefix);
    if (begin != 0) return null;
  } else
    begin += 2;
  var end = document.cookie.indexOf(";", begin);
  if (end == -1)
    end = dc.length;
  return unescape(dc.substring(begin + prefix.length, end));
}

function registerCookie(name,value) {
 var now = new Date();
 now.setTime(now.getTime() + 60 * 24 * 60 * 60 * 1000);
 var d = document.domain;
 d = d.replace('www.','');
 d = d.replace('secure.','');
 SetCookie(name,value,now,"/",d);
}

function getCookieVal (offset) {
   var endstr = document.cookie.indexOf (";", offset);
   if (endstr == -1) {
     endstr = document.cookie.length;
   }
   return unescape(document.cookie.substring(offset, endstr));
}

function SetDropoffLocation() {
  var strPickupLocation = GetSelectedItem(document.frmRateSearch.ddlPickUpLocation);
  var strDropoffLocation = GetSelectedItem(document.frmRateSearch.ddlDropOffLocation);
  if(strDropoffLocation==='SAME' || strDropoffLocation==='') {
    SetSelectedItem(document.frmRateSearch.ddlDropOffLocation,strPickupLocation);
  }
}

// Standard Dreamweaver routines 
function validateForm() { //v3.0
// put fields you want to validate here
// R= "Required"
// RisEmail = "Email required"
// R!=goober = "Cannot be the word 'goober'."
// RisNum = "Must be a number"
// RinRange10:20 = "Must be number between 10 and 20"
  var i,p,q,nm,test,num,min,max,errors='',args=validateForm.arguments;
  for (i=0; i<(args.length-2); i+=3) {
    test=args[i+2];
    val=getObj(args[i]);
    if (val) {
      nm=args[i+1];
      if(nm==='') {
        nm=val.name;
      }
      if ((val=val.value)!=="") {
        if (test.indexOf('isEmail')!=-1) {
          p=val.indexOf('@');
          if (p<1 || p==(val.length-1)) {
            errors+='- '+nm+' must contain an e-mail address.\n';
          }
        } else if (test!='R') {
          num = parseFloat(val);
          if (val!=''+num) {
            errors+='- '+nm+' must contain a number.\n';
          }
          if (test.indexOf('inRange') != -1) {
            p=test.indexOf(':');
            min=test.substring(8,p);
            max=test.substring(p+1);
            if (num<min || max<num) {
              errors+='- '+nm+' must contain a number between '+min+' and '+max+'.\n';
            }
          }
        }
      } else if (test.charAt(0) == 'R') {
        errors += '- '+nm+' is required.\n';
      }
    }
  }
  if (errors) {
    alert('The following error(s) occurred:\n'+errors);
  }
  document.returnValue = (errors === '');
}

function validateBooking() { //v3.0
// put fields you want to validate here
// R= "Required"
  var i,p,q,nm,test,num,min,max,errors='',args=validateBooking.arguments;
  for (i=0; i<(args.length-2); i+=3) {
    test=args[i+2];
    val=getObj(args[i]);
    if (val) {
      nm=args[i+1];
      if(nm==='') {
        nm=val.name;
      }
      if ((val=val.value)!=="") {
      } else if (test.charAt(0) == 'R') {
        errors += '- '+nm+' is required.\n';
      }
    }
  }
  if (errors) {
    var message;
    message = 'You have not entered a flight number.\n\n';
    message += 'Booking a vehicle at an airport without including\n';
    message += 'your flight number may delay collecting your rental car.\n\n';
    message += 'Are you sure you want to continue?';
    return window.confirm (message);
  }
  return (errors === '');
}

function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr;
  for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) {
    x.src=x.oSrc;
  }
}

function MM_preloadImages() { //v3.0
  var d=document;
  if(d.images) {
    if(!d.MM_p) {
      d.MM_p=[];
    }
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments;
    for(i=0; i<a.length; i++) {
      if (a[i].indexOf("#")!==0) {
        d.MM_p[j]=new Image();
        d.MM_p[j++].src=a[i];
      }
    }
  }
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;
  if(!d) {
    d=document;
  }
  if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);
  }
  if(!(x=d[n])&&d.all) {
    x=d.all[n];
  }
  for (i=0;!x&&i<d.forms.length;i++) { x=d.forms[i][n]; }
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) { x=MM_findObj(n,d.layers[i].document); }
  if(!x && d.getElementById) { x=d.getElementById(n); }
  return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments;
  document.MM_sr=[];
  for(i=0;i<(a.length-2);i+=3) {
    if ((x=MM_findObj(a[i]))!==null) {
      document.MM_sr[j++]=x;
      if(!x.oSrc) {
        x.oSrc=x.src;
      }
      x.src=a[i+2];
    }
  }
}

/* DATE FUNCTIONS - BASIC CALENDAR 3RD PARTY */        
//BDPDropoffDate
//BDPPickupDate
function updateEndDate(sender) {
  //basicDatePicker.setSelectedDate(sender.getSelectedDate().addDays(7),"BDPDropoffDate");
  var startDate, endDate;
  startDate = sender.getSelectedDate();
  endDate = basicDatePicker.getSelectedDate("BDPDropoffDate");
  if(endDate < startDate) {
    basicDatePicker.setSelectedDate(sender.getSelectedDate().addDays(7),"BDPDropoffDate");
  }
}
        
/*// AJAX SEARCH CODE //
var bProcessing  = false;
var previousReturn = 0;
var previousPickup = 0;

function callback_test_pickup(res) {
  bProcessing = false;
  document.getElementById("locationoptionsPickup").innerHTML = res.value;

  if(document.getElementById("pickuplocation").value.length != previousPickup) {
    RefreshPickupPossibilities()
  }
}
    
function callback_test_return(res) {
  bProcessing = false;
  document.getElementById("locationoptionsReturn").innerHTML = res.value;

  if(document.getElementById("returnlocation").value.length != previousReturn) {
    RefreshReturnPossibilities()
  }
}

function RefreshPickupPossibilities() {
  //if (depotmode = 'depotid') {
  //alert(depotmode);
  //alert(bProcessing);
  //}
  if(document.getElementById("pickuplocation").value.length>2 & bProcessing == false) {
    bProcessing = true;
    previousPickup = document.getElementById("pickuplocation").value.length;

    if(document.getElementById("depotmode").value == 'depotid') {
      ClassAJAX.SetPickupPossibilities(
        document.getElementById("pickuplocation").value, "Pickup", "Depot", 
        callback_test_pickup);
    } else {
      ClassAJAX.SetPickupPossibilities(
        document.getElementById("pickuplocation").value, "Pickup", "Location", 
        callback_test_pickup);
    }
  }
}
    
function RefreshReturnPossibilities() {
  if(document.getElementById("returnlocation").value.length>2 & bProcessing == false) {
    bProcessing = true;
    previousReturn = document.getElementById("returnlocation").value.length;

    if(document.getElementById("depotmode").value == 'depotid') {
      ClassAJAX.SetPickupPossibilities(
        document.getElementById("returnlocation").value, "Return", "Depot", 
        callback_test_return);
    } else {
      ClassAJAX.SetPickupPossibilities(
        document.getElementById("returnlocation").value, "Return", "Location", 
        callback_test_return);
    }
  }
}

//Set location Pickup
function SLP(locationname, code) {
  document.getElementById("pickuplocation").value = locationname;
  //getObj("locationoptions").style.visibility="hidden";
  getObj("locationoptionsPickup").innerHTML="";
  document.frmRateSearch.pickuplocation.focus();
  document.getElementById("pickuplocationhidden").value = code;
  document.getElementById("lblError").innerHTML = "";
}  

//Set location Return
function SLR(locationname, code) {
  document.getElementById("returnlocation").value = locationname;
  //getObj("locationoptions").style.visibility="hidden";
  getObj("locationoptionsReturn").innerHTML="";
  document.frmRateSearch.returnlocation.focus();
  document.getElementById("returnlocationhidden").value = code;
}*/

function RemoveOnClick() {
  if (document.frmRateSearch.returnlocation.value == 'SAME AS PICKUP') {
    document.frmRateSearch.returnlocation.value = "";
  }
}
    
function RemoveErrorOnClick() {
  document.getElementById("lblError").innerHTML = "";
}        
  
/* Double Click Trap function - to reduce multiple bookings from double-clicking the Make Booking button */
/* may be used on the search page also to stop double submission of the search form */
var trapDelay = 5;  //change this if you want to stop the user clicking for a longer (or shorter) period of time (in seconds)
var trapTime = 0;   //do not change
var counter = 0;    //do not change
var trapClick = false;   //do not change
var tDate;

function DoubleClickTrap() {
  counter++;
  if(counter > 1 ) {
    trapClick = true;
  } else {
    tDate = new Date();
    trapTime = tDate.valueOf();
  }

  if(trapClick) {
    tDate = new Date();
    var localTrapTime = tDate.valueOf();
    if((localTrapTime - trapTime) > (trapDelay * 1000)) {
      trapTime = 0;
      trapClick = false;
      counter = 0;
    }
  }
  return !trapClick;
}
/* End Double Click Trap function */

// SEARCH FORM
function SubmitSearch() {
  var bReturn = DoubleClickTrap();

  if(bReturn) {
    //bReturn = validateForm('ddlPickUpLocation','Pickup Location','R');
    //ShowLayer("divPleaseWait");
    document.frmRateSearch.btnSendRequest.value = "Please Wait...";
    //getObj("divPleaseWait").innerHTML = getObj("divTip").innerHTML;
  } else {
    trapTime = 0;
    trapClick = false;
    counter = 0;
  }
  return bReturn;
}

// SEARCH FORM
function SubmitSearchWait() {
  var bReturn = DoubleClickTrap();

  if(bReturn) {
  	//bReturn = validateForm('ddlPickUpLocation','Pickup Location','R');
    ShowLayer("divPleaseWait");
    document.frmRateSearch.btnSendRequest.value = "Please Wait...";
    getObj("divPleaseWait").innerHTML = getObj("divTip").innerHTML;
  } else {
    trapTime = 0;
    trapClick = false;
    counter = 0;
  }
  return bReturn;
}

function BookValidation(airport) {
  var bReturn = false;
  if(DoubleClickTrap()) {
    if(airport=="True") {
      bReturn = validateBooking('txtAirNumber','Flight Number','R');
      if(!bReturn) {
        trapTime = 0;
        trapClick = false;
        counter = 0;
      }
    }
  }
  return bReturn;
}

// BOOKING FORM
/* Click Trap Version
function MakeBooking() {
  var bReturn = false;
  if (typeof(Page_ClientValidate) == 'function') {
    if (Page_ClientValidate() === true) {
      bReturn = DoubleClickTrap();
      if(bReturn) {
        //Change the text of the "Make Booking" button
        getObj("btnSubmit").value = "Please Wait...";
      } else {
        trapTime = 0;
        trapClick = false;
        counter = 0;
      }
    } else {
      //form is not valid
      alert('The form is not completed.\n\nPlease check the red messages and complete the missing fields.');
    }
  }
  return bReturn;
}
*/

var bookingCountDownInterval=20;
var bookingCountDownTime=countDownInterval+1;
var bookingCounter = 0;

function BookingCountDown() {
  bookingCountDownTime--;
  if (bookingCountDownTime <=0) {
    bookingCountDownTime=0;
    clearTimeout(bookingCounter);
    getObj("bookingtimer").innerHTML = '<h2>We are stuck at a red light. Come on, go green!</h2><h3>Please <a href="javascript:window.location.reload();">click here</a> to reload the page to try the booking again.</h3>';
  } else {
    getObj("bookingtimer").innerHTML = '<h2>Please wait while we make the booking</h2><h3>Maximum wait time: '+countDownTime+' seconds</h3>';
    bookingCounter=window.setTimeout(function() { BookingCountDown(); }, 1000);
  }
}

function MakeBooking() {
  if (typeof(Page_ClientValidate) == 'function') {
    if (Page_ClientValidate() === true) {
      getObj("btnSubmit").value = "Please Wait....";
      getObj("btnSubmit").disabled = true;
      getObj("frmBooking").submit();
      return false;
    } else {
      //form is not valid
      alert('The form is not completed.\n\nPlease check the red messages and complete the missing fields.');
      return false;
    }
  }
}

function DeleteCookie( name, path, domain ) {
  if(GetCookie(name)) {
    document.cookie = name + "=" +
      ((path) ? "; path=" + path : "") +
      ((domain) ? "; domain=" + domain : "") +
      "; expires=Thu, 01-Jan-70 00:00:01 GMT";
  }
}

/* Function to test if cookies are enabled */
function CookieCheck() {
  SetCookie( "foo", "bar" );
  if(GetCookie("foo")) {
    DeleteCookie("foo");
    return true;
  } else {
    return false;
  }
}
/* End function */

function RemoveSpaces(txbField) {
  var fieldInput = txbField.value;
  var originalFieldArray = fieldInput.split(" ");
  var result = originalFieldArray.join("");

  if (fieldInput!=="") {
    $(":asp(txbField)").value = result;
  } else {
    $(":asp(txbField)").value = '';
  }
}

function CopyText(txtFrom, txtTo) {
  document.getElementById(txtTo).value = document.getElementById(txtFrom).value;
}

function EmailCheck() {
  if(document.getElementById("chkEmail").checked) {
    CopyText("txbEmail", "txbPayPalEmail");
    //document.getElementById("txbEmail2").disabled = true;
  } else {
    document.getElementById("txbPayPalEmail").value = "";
    //document.getElementById("txbEmail2").disabled = false;
    document.getElementById("txbPayPalEmail").focus();
  }
}

function AddressCheck() {
  if(document.getElementById("chkAddress").checked) {
    CopyText("txbAddress", "txbPaymentAddress");
    //document.getElementById("txbAddress2").disabled = true;
  } else {
    document.getElementById("txbPaymentAddress").value = "";
    //document.getElementById("txbAddress2").disabled = false;
    document.getElementById("txbPaymentAddress").focus();
  }
}

function Trim(str) {
  return str.replace(/^\s+|\s+$/g, '');
}

function CodeNumber() {
  var newwin;
  newwin = window.open("/book/CodeNumber.html","popup","width=450,height=300,left=30,top=30, toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=yes,resizable=yes,copyhistory=0,");
  return false;
}

function NoFlightNumber() {
  var newwin;
  newwin = window.open("/book/NoFlightNumber.html","popup","width=450,height=300,left=30,top=30, toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=yes,resizable=yes,copyhistory=0,");
   //setTimeout('newwin.focus();',500);
   
  document.frmBooking.txtAirCode.value = '--'; 
  document.frmBooking.txtAirNumber.value = '--'; 
  document.frmBooking.ddlAirName.value = '__'; 
  //document.frmBooking.txtAirNumber.readOnly = true;
  if (typeof(Page_ClientValidate) == 'function') { Page_ClientValidate(); }
  //document.frmBooking.regexAirCode.display = 'none';
  //document.frmBooking.Requireddomvalidator6.value = '';
  //document.frmBooking.Regexdomvalidator6.value = '';
  //document.frmBooking.Requireddomvalidator7.value = '';
  return false; 
}

/**
 * New functions to help use the dynamic population
 * of the location drop down lists 
 */

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 handleSuccess = function(o) {
  if(o.responseText!==undefined) {
    //populate the two dropdown lists here
    var depotArray = o.responseText.split("|");
    pickupList = YAHOO.util.Dom.get('ddlPickUpLocation');
    returnList = YAHOO.util.Dom.get('ddlDropOffLocation');

    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[0] == depotArray[(i*2)]) {
        pickupList.selectedIndex = i-1;
      }
    }
    var customLocation = YAHOO.util.Dom.get('lblPickup').innerHTML;
    if ((customLocation!=='') && (customLocation!==pickupList.selectedText)) {
      setSelectedCity(pickupList, customLocation);
    }
    returnList.selectedIndex = 0;
  }
};

var handleFailure = function(o) {
//should do something with the failure here
  //if(o.responseText !== undefined){
  //}
};

var callback = {
  success:handleSuccess,
  failure:handleFailure,
  argument: { foo:"foo", bar:"bar" }
};

function makeRequest() {
  //clear the pickup and return drop downs
  var depotMode = YAHOO.util.Dom.get('depotmode').value;
  var pickupList = YAHOO.util.Dom.get('ddlPickUpLocation');
  var returnList = YAHOO.util.Dom.get('ddlDropOffLocation');
  var countryList = YAHOO.util.Dom.get('ddlCountry');
  var strSupplierID = "";

  var strCountryID = countryList[countryList.selectedIndex].value;

  var sUrl;

  if(depotMode=="depotid") {
    supplierList = YAHOO.util.Dom.get('ddlSupplier');
    strSupplierID = supplierList[supplierList.selectedIndex].value;
  }

  if(strSupplierID==="") {
    sUrl = "/book/DepotList.aspx?country=" + strCountryID;
 } else {
    if(YAHOO.util.Dom.get('ddlSupplier').value == "ALL") {
      var url = window.location;
      window.location = url.replace(/\?.*$/, "");      //window.location = window.location.protocol + '//' + window.location.host + window.location.pathname;
      return false;
    } else {
      YAHOO.util.Dom.get('imgSupplier').src = "/book/images/logo-" + strSupplierID + "-75.gif";
      sUrl = "/book/DepotList.aspx?country=" + strCountryID + "&supplier=" + strSupplierID;
    }
  }

  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
  if(strCountryID==="" || strCountryID==="Select Country") {
    alert("Please choose a country from the list.");
  } else {
    var request = YAHOO.util.Connect.asyncRequest('GET', sUrl, callback);
  }
}

function DateToISOString(theDate) {
  /**
   * Takes a valid javascript Date object and outputs the date
   * in ISO Date Format (yyyy-MM-dd)
   */
  var dy = theDate.getFullYear();
  var dm = theDate.getMonth() + 1;
  var dd = theDate.getDate();
  if ( dy < 1970 ) { dy = dy + 100; }
  var ys = dy;
  var ms = dm;
  var ds = dd;
  if ( ms.length == 1 ) { ms = "0" + ms; }
  if ( ds.length == 1 ) { ds = "0" + ds; }
  return (ys + "-" + ms + "-" + ds);
}


function InitialiseEdit(strEditLink){
  //Shows edit button if logged in
  if(GetCookie("isadmin")=="true") {
    document.write("<span class='editbutton'><a href='" + strEditLink + "'><img src='/book/images/edit_button.gif' border='0' /></a></span>");
  }
}

//Scripts for the CountDown Timer
var countDownInterval = 20;
var countDownTime = countDownInterval + 1;
var countContinue = true;

function countDown() {
  if (countContinue) {
    countDownTime--;
    if (countDownTime <= 0) {
      countDownTime = 0;
      clearTimeout(counter);
      getObj("timer").innerHTML = '<h2>We are stuck at a red light. Come on, go green!</h2><h3>Please <a href="javascript:window.location.reload();">click here</a> to repeat the search.</h3>';
      getObj("waitImage").innerHTML = '';
    } else {
      getObj("timer").innerHTML = '<h2>Maximum wait time: ' + countDownTime + ' seconds</h2>';
      counter = window.setTimeout(function() { countDown(); }, 1000);
    }
  }
}

function startit() {
  if (document.all||document.getElementById) {
    getObj("waitImage").innerHTML = '<img src="/book/images/ajax-loader.gif" /><br />';
    countDown();
  } else {
    window.onload=countDown();
  }
}
//End CountDown Timer

//Start Bookmark
function bookmark(url,title){
  if ((navigator.appName == "Microsoft Internet Explorer") && (parseInt(navigator.appVersion) >= 4)) {
  window.external.AddFavorite(url,title);
  } else if (navigator.appName == "Netscape") {
    window.sidebar.addPanel(title,url,"");
  } else {
    alert("Press CTRL-D (Netscape) or CTRL-T (Opera) to bookmark");
  }
}

function is_valid_email(email) {
  if (email != "") {

    // build the regex filter
    var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;

    // test the email
    if (filter.test(email)) {
      return true;

    } else {
      return false;
    }
  } else {
    return false;
  }
}

function checkValidation(control) {
    if(control.value=='') {
        alert('Required fields cannot be left blank, please fill them.');
        control.focus();
        return false;
    }
    else {
      return true;
    }
}

// This function returns the .Net equivalent ticks value for a Date
function getDateTicks(date) {
 
   this.day = date.getDate();
   this.month = date.getMonth() + 1;
   this.year = date.getFullYear();
   this.hour = date.getHours();
   this.minute = date.getMinutes();
   this.second = date.getSeconds();
   this.ms = date.getMilliseconds();
   
   this.monthToDays = function(year, month)
   {
      var add = 0;
      var result = 0;
      if((year % 4 == 0) && ((year % 100  != 0) || ((year % 100 == 0) && (year % 400 == 0)))) add++;
         
      switch(month)
      {
         case 0: return 0;
         case 1: result = 31; break;
         case 2: result = 59; break;
         case 3: result = 90; break;
         case 4: result = 120; break;
         case 5: result = 151; break;
         case 6: result = 181; break;
         case 7: result = 212; break;
         case 8: result = 243; break;
         case 9: result = 273; break;
         case 10: result = 304; break;
         case 11: result = 334; break;
         case 12: result = 365; break;
      }
      if(month > 1) result += add;
      return result;      
   }

   this.dateToTicks = function(year, month, day)
   {
      var a = parseInt((year - 1) * 365);
      var b = parseInt((year - 1) / 4);
      var c = parseInt((year - 1) / 100);
      var d = parseInt((a + b) - c);
      var e = parseInt((year - 1) / 400);
      var f = parseInt(d + e);
      var monthDays = this.monthToDays(year, month - 1);
      var g = parseInt((f + monthDays) + day);
      var h = parseInt(g - 1);
      return h * 864000000000;
   }

   this.timeToTicks = function(hour, minute, second)
   {
      return (((hour * 3600) + minute * 60) + second) * 10000000;
   }   
   
   //document.writeln('<br />' +this.dateToTicks(this.year, this.month, this.day) + this.timeToTicks(this.hour, this.minute, this.second) + (this.ms * 10000));
   var ticks = this.dateToTicks(this.year, this.month, this.day) + this.timeToTicks(this.hour, this.minute, this.second) + (this.ms * 10000);
   return ticks;
   //document.writeln('<br />JS ticks: ' +numb);
   
}

function getQueryVariable(variable) {
  var query = window.location.search.substring(1);
  var vars = query.split("&");
  for (var i=0;i<vars.length;i++) {
    var pair = vars[i].split("=");
    if (pair[0] == variable) {
      return pair[1];
    }
  } 
  return "null";
}

function toggle(div) {
  var div = document.getElementById(div);
  
  if (div.style.display == 'none') {
    div.style.display = 'block';
  }
  else {
    div.style.display = 'none';
  }
}


//End Bookmark

//Redirect OR Show Window popup for Agent Information.
function GoDirect(AgentWebsite, AgentID, AgentName, AgentAddress, ContactEmail, ContactPhone) {
	if (AgentWebsite == '')
		alert("Please use the following details:\n\nName:\t" + AgentName + "\nAddress:\t" + AgentAddress + "\nEmail:\t" + ContactEmail + "\nPhone:\t" + ContactPhone);
	else
		window.location.href = "/book/redirect.aspx?agentID=" + AgentID;
}


function theRotator() {
    //Set the opacity of all images to 0
    $('div.rotator div').css({ opacity: 0.0 });

    //Get the first image and display it (gets set to full opacity)
    $('div.rotator div:first').css({ opacity: 1.0 });

    //Call the rotator function to run the slideshow, 6000 = change to next image after 6 seconds

    setInterval('rotate()', 7000);

}

function rotate() {
    //Get the first image
    var current = ($('div.rotator div.show') ? $('div.rotator div.show') : $('div.rotator div:first'));

    if (current.length == 0) current = $('div.rotator div:first');

    //Get next image, when it reaches the end, rotate it back to the first image
    var next = ((current.next().length) ? ((current.next().hasClass('show')) ? $('div.rotator div:first') : current.next()) : $('div.rotator div:first'));

    //Un-comment the 3 lines below to get the images in random order

    var sibs = current.siblings();
    var rndNum = Math.floor(Math.random() * sibs.length);
    var next = $(sibs[rndNum]);


    //Set the fade in effect for the next image, the show class has higher z-index
    next.css({ opacity: 0.0 })
	.addClass('show')
	.animate({ opacity: 1.0 }, 2000);

    //Hide the current image
    current.animate({ opacity: 0.0 }, 2000)
	.removeClass('show');

};

$(document).ready(function () {
  //set the referral cookie if it has not yet been saved
  if ((GetCookie("vroomref") == null) || (GetCookie("vroomref") == "")) {
    registerCookie("vroomref", document.referrer);
  }

  if ($('div.rotator').length) {
    //Load the slideshow
    theRotator();
    $('div.rotator').fadeIn(1000);
    $('div.rotator ul li').fadeIn(1000); // tweek for IE
  }
});

