var loader=null;
var formPosted=false;
var error=null;
var startup=true;
var oldMode=false;
var globalError=null;
var globalFocus=null;
var gmap=null;
var gds=null;
var capm=null;
var gdr=null;

function quotePrice(v)
{
  var f=document.forms['qf'];
  var url='';
  if (f.elements['email'].value=='' || !validateEmailv2(f.elements['email'].value)) {
    alert('Please enter a valid email address.');
    f.elements['email'].focus();
    return;
  }
  if (f.origin.value=="") {
    alert("Please enter where you will be travelling from to arrive here");
    f.origin.focus();
    return;    
  }
  for (var i=0; i < f.elements.length; i++) {
    url+='&'+f.elements[i].name+'='+f.elements[i].value;
  }
  url='get_price.php?t='+(new Date()).getTime()+'&v='+v+url;
  //document.getElementById('arrow').style.display='block';
  document.getElementById('result').style.display='none';
  document.getElementById('w').innerHTML="Calculating price, please wait...";
  loader.loadInto(url,'result');
}

function closeQuote()
{
  document.getElementById('result').style.display='none'; 
  //window.scrollTo(0,400);   
}
function loaded(a,b,c)
{
  document.getElementById('result').style.display='block';
  
  document.getElementById('w').innerHTML="";
  window.scrollTo(0,0);
}

function initPage()
{
  loader = new RemoteFileLoader('loader'); 
  loader.onload=loaded;
  document.getElementById('result').style.top=document.getElementById('parkingBox').offsetTop+'px';
  
}

function initPage2()
{
  http = new HTMLHttpRequest('http', null);  
  load_vb(true);
}
function validate_book(theForm)
{
  if (formPosted)
    return false;
  if (document.getElementById('q_tab') && document.getElementById('q_tab').style.display=='none') {
    alert('You need to update your quote first by clicking the button in the Your Quote column.');
    return false;    
  }  
  if (theForm.firstname.value=="") {
    alert("Please enter your firstname.");
    theForm.firstname.focus();
    return false;
  }
  if (theForm.lastname.value=="") {
    alert("Please enter your lastname.");
    theForm.lastname.focus();
    return false;
  }
  if (theForm.phone.value=="") {
    alert("Please enter your contact mobile number whilst travelling");
    theForm.phone.focus();
    return false;
  }
  if (theForm.email.value=="" || !validateEmailv2(theForm.email.value)) {
    alert("Please enter a valid email address");
    theForm.email.focus();
    return false;
  }
  if (theForm.homePh.value=="") {
    alert('Please enter your home phone number');
    theForm.homePh.focus();
    return false;
  }
  if (theForm.street.value=="") {
    alert('Please enter your home street address');
    theForm.street.focus();
    return false;
  }
  if (theForm.origin.value=="") {
    alert('Please enter your home town/suburb');
    theForm.origin.focus();
    return false;
  }
  
  if (!theForm.payby[0].checked && !theForm.payby[1].checked && !theForm.payby[2].checked) {
    alert("Please nominate your preferred payment method on drop off");
    return false;
  }
  if (theForm.payby[1].checked && (typeof(theForm.cc_exist)=='undefined' || theForm.cc_exist[1].checked)) {
    if (theForm.c_num_1.value=="" || theForm.c_num_2.value=="" || theForm.c_num_3.value=="" || theForm.c_num_4.value=="") {
      alert("Please enter your credit card number.\nNo payment will be taken until after your booking.");
      theForm.c_num_1.focus();
      return false;    
    }
    if (theForm.c_exp_m.selectedIndex <= 0) {
      alert("Please enter your card expiry month");
      theForm.c_exp_m.focus();
      return false;    
    }
    if (theForm.c_exp_y.selectedIndex <= 0) {
      alert("Please enter your card expiry year");
      theForm.c_exp_y.focus();
      return false;    
    }
  }  
  if (theForm.type.selectedIndex <= 0) {
    alert("Please select your vehicle type");
    theForm.type.focus();
    return false;
  }
  if (theForm.rego.value=="") {
    alert("Please enter your vehicle registration");
    theForm.rego.focus();
    return false;
  }
  if (parseInt(theForm.adults.value) <1) {
    alert('Please nominate the number of adults travelling');
    theForm.adults.focus();
    return false;    
  }
  if (!theForm.carry[0].checked && !theForm.carry[1].checked) {
    alert("Please nominate whether you will have baggage to check in or just carry on.");
    theForm.t_out.focus();
    return false;    
  }
  if (theForm.t_in.checked && !theForm.t_tbain.checked) {
    if (theForm.ff.value=="") {
      alert("Please enter the flight number of your flight departing Cairns");
      theForm.ff.focus();
      return false;
    }
    if (!theForm.fo_day.options[theForm.fo_day.selectedIndex].value) {
      alert('Please enter the day of the flight departure');
      theForm.fo_day.focus();
      return false;    
    }
    if (!theForm.fo_month.options[theForm.fo_month.selectedIndex].value) {
      alert('Please enter the month of the flight departure');
      theForm.fo_month.focus();
      return false;    
    }
    if (!theForm.fo_year.options[theForm.fo_year.selectedIndex].value) {
      alert('Please enter the year of the flight departure');
      theForm.fo_year.focus();
      return false;    
    }
    getFlightDate('fo');
    if (!flightOut) {
      alert('Check the date you have entered for the departure flight.');
      theForm.fo_day.focus();
      return false;    
    }
/*    if (flightOut.getTime() < dateIn.getTime()) {
      alert('Your departure flight is before your vehicle drop off / check in.  Check your drop off date and flight departure date.');
      theForm.fo_day.focus();
      return false;
    }
*/    
    if (theForm.fo_time.selectedIndex <= 0) {
      alert("Please enter the flight departure time.")    
      theForm.fo_time.focus();
      return false;
    }
  }
  if (theForm.t_in.checked && theForm.f_dest && theForm.f_dest.value=="") {
    alert("Please enter the flight destination.");
    theForm.f_dest.focus();
    return false;    
  }
  
  if (theForm.t_out.checked && !theForm.t_tbaout.checked) {
    if (theForm.ft.value=="") {
      alert("Please enter the flight number of your flight arriving Cairns");
      theForm.ft.focus();
      return false;
    }
    if (!theForm.ea_day.options[theForm.ea_day.selectedIndex].value) {
      alert('Please enter the day of the flight arrival');
      theForm.ea_day.focus();
      return false;    
    }
    if (!theForm.ea_month.options[theForm.ea_month.selectedIndex].value) {
      alert('Please enter the month of the flight arrival');
      theForm.fo_month.focus();
      return false;    
    }
    if (!theForm.ea_year.options[theForm.ea_year.selectedIndex].value) {
      alert('Please enter the year of the flight arrival');
      theForm.ea_year.focus();
      return false;    
    }
    getFlightDate('ea');
    if (!flightIn) {
      alert('Check the date you have entered for the arrival flight.');
      theForm.ea_day.focus();
      return false;    
    }
/*    
    if (flightIn.getTime() > dateOut.getTime()) {
      alert('Your arrival flight is after your vehicle pick up / check out date.  Check your pick up date and flight arrival date.');
      theForm.ea_day.focus();
      return false;
    }
    */
    if (theForm.ea_time.selectedIndex <= 0) {
      alert("Please enter the flight arrival time.")    
      theForm.ea_time.focus();
      return false;
    }
  }  
  if (theForm.v && theForm.v.value.length != 1) {
    alert("Please enter the validation code exactly as shown");
    theForm.v.focus();
    return false;
  }
  
  return formPosted=true;
}

function doBooking()
{
  var f=document.getElementById('bf');
  if (f.onsubmit())
    f.submit();
}

function load_vb(u)
{
  var list=['year','month','day','time'];
  var f=document.forms['bf'];
  for (var i=0; i< list.length; i++) {
    if (f.elements['a_'+list[i]])
      f.elements['a_'+list[i]].onchange=function() { changeDate(u); }    ;
    f.elements['d_'+list[i]].onchange=function() { changeDate(u); }    ;
  }  
  for (var i=0; i< list.length-1; i++) {
    if (f.elements['fo_'+list[i]])
      f.elements['fo_'+list[i]].onchange=function() { changeDay('fo'); }    ;
    if (f.elements['ea_'+list[i]])
      f.elements['ea_'+list[i]].onchange=function() { changeDay('ea'); }    ;
  }  
  changeDate(u);
  changeDay('fo');
  changeDay('ea');
  changeTime(f.fo_time);
  changeTime(f.ea_time);
  tg_in(f.t_in);
  tg_out(f.t_out);
}

function getFlightDate(dn)
{
  var h,n,td,y,m,d,yd,md,dd,f,dt=null;
  f=document.forms['bf'];
  yd=f.elements[dn+'_year'];
  md=f.elements[dn+'_month'];
  dd=f.elements[dn+'_day'];
  td=f.elements[dn+'_time'];
  
  y=yd.options[yd.selectedIndex].value;
  d=dd.options[dd.selectedIndex].value;
  m=md.options[md.selectedIndex].value;
  h=parseInt(td.options[td.selectedIndex].value/100);
  n=parseInt(td.options[td.selectedIndex].value%100);
  
  if (y && m && dd && dateValid(y,m,d))
    dt=new Date(y,m-1,d,h,n);
  if (dn=='fo')
    flightOut=dt;
  else
    flightIn=dt;  
}
function changeDay(dn)
{
  var y,m,d,yd,md,dd,f,dt=null;
  f=document.forms['bf'];
  yd=f.elements[dn+'_year'];
  md=f.elements[dn+'_month'];
  dd=f.elements[dn+'_day'];
  
  y=yd.options[yd.selectedIndex].value;
  d=dd.options[dd.selectedIndex].value;
  m=md.options[md.selectedIndex].value;
  if (y && m && dd && dateValid(y,m,d))
    dt=new Date(y,m-1,d);
  document.getElementById(dn+'_dow').innerHTML=dt ? formatDate(dt,'EE') : ''; 
}
function showQuote()
{
  var f=document.forms['bf'];
  var url;
  if (error)
    alert(error);
  else {
    document.getElementById('q_tab').style.display='';  
    // send form values
    url='send_quote.php?di='+formatDate(dateIn,'yyyy-MM-dd HH:mm')+'&do='+formatDate(dateOut,'yyyy-MM-dd HH:mm')+'&email='+f.email.value+'&cost='+f.cost.value+'&ff='+f.ff.value+
            '&ft='+f.ft.value+'&ud='+userDiscount+'&os='+(f.oversized && f.oversized[1].checked ? '1' : '0');
    if (flightOut)
      url+='&fo='+formatDate(flightOut,'yyyy-MM-dd HH:mm');
    if (flightIn)
      url+='&ea='+formatDate(flightIn,'yyyy-MM-dd HH:mm');
    if (f.t_in.checked)
      url+='&t_in';
    if (f.t_out.checked)
      url+='&t_out';
    if (f.fo_dt && (f.fo_dt[0].checked || f.fo_dt[1].checked))
      url+='&fo_dt='+(f.fo_dt[0].checked ? f.fo_dt[0].value : f.fo_dt[1].value); 
    url+='&firstname='+escape(f.firstname.value)+'&lastname='+escape(f.lastname.value)+'&phone='+f.phone.value;     
    http.load(url);  
    if (document.getElementById('cbd'))
      document.getElementById('cbd').style.display='block';
    if (document.getElementById('cbd2'))
      document.getElementById('cbd2').style.display='block';
  }      
}


function changeTime(e)
{
  var t,s='';
  if (!e)
    return;
  if (e.options[e.selectedIndex].value.length) {
    t=parseInt(e.options[e.selectedIndex].value);    
    if (t < 700)
      s='early morning';
    else if (t < 1200)
      s='morning';
    else if (t < 1800)
      s='afternoon';
   else
     s='evening';   
      
  }    
  document.getElementById(e.name+'_').innerHTML=s;
  
}

function changeDate(u)
{
  var sd=null,ed=null,e,d,m,y,h,n,ex,efc;
  var f=document.forms['bf'];
  
  changeTime(f.a_time);
  changeTime(f.d_time);
    
   
  f.cost.value='';
  if (f.days)
    f.days.value='';
    
  if (efc=document.getElementById('efc'))
    efc.style.display='none';
     
  error=null;
  
  e=document.getElementById('bf_di');
  // build date....
  if (typeof(b_sd) != 'undefined') 
    sd=b_sd;
  else {  
    y=f.a_year.options[f.a_year.selectedIndex].value;
    d=f.a_day.options[f.a_day.selectedIndex].value;
    m=f.a_month.options[f.a_month.selectedIndex].value;
    h=parseInt(f.a_time.options[f.a_time.selectedIndex].value/100);
    n=parseInt(f.a_time.options[f.a_time.selectedIndex].value%100);
    //h=f.a_hour.options[f.a_hour.selectedIndex].value;
    //n=f.a_min.options[f.a_min.selectedIndex].value;
    if (dateValid(y,m,d)) 
      sd=new Date(y,m-1,d,h,n);
    else
      error='Invalid vehicle drop off date.  Check your date';  
  }

  y=f.d_year.options[f.d_year.selectedIndex].value;
  d=f.d_day.options[f.d_day.selectedIndex].value;
  m=f.d_month.options[f.d_month.selectedIndex].value;
//  h=f.d_hour.options[f.d_hour.selectedIndex].value;
//  n=f.d_min.options[f.d_min.selectedIndex].value;
    h=parseInt(f.d_time.options[f.d_time.selectedIndex].value/100);
    n=parseInt(f.d_time.options[f.d_time.selectedIndex].value%100);

  if (dateValid(y,m,d)) 
    ed=new Date(y,m-1,d,h,n);
  else
    error='Invalid vehicle pick up date.  Check your date';  
  
  if (document.getElementById('bf_di'))
    document.getElementById('bf_di').innerHTML=sd ? formatDate(sd,'EE') : 'Check date';
  document.getElementById('bf_do').innerHTML=ed ? formatDate(ed,'EE') : 'Check date';
  
  if (sd && ed) {
      document.getElementById('bf_co').innerHTML='';
    // calc diff in dates
    if (typeof(b_sd)=='undefined' && sd.getTime()-now.getTime() < 3600000) {
      document.getElementById('bf_co').innerHTML=(error='Your date in must be at least an hour in advance. To book sooner please contact our office.');
      return;  
    }
    y=(ed.getTime()-sd.getTime())/1000;        // total seconds
    if (y < 0) 
      document.getElementById('bf_co').innerHTML=(error='Your date out is before your date in - check dates');
    else {  
      // arrival date early flight cross check
      if (efc && ed.getHours() < 7) {
        efc.innerHTML='This means boarding a flight <em>'+formatDate(new Date(ed.getTime()-86400000),'EE d NNN')+"</em> and arriving the following day <em>"+
                    formatDate(ed,'EE d NNN')+"</em>.<br/><br/>If you are actually departing on the <em>"+formatDate(ed,'EE d NNN')+"</em> please change pickup date.";    
        efc.style.display='block';    
      }
      d=parseInt(y/86400);        // full days
      h=parseInt((y-d*86400)/3600);   // full hours
      n=parseInt(y%3600)/60;
      // charge $1/hr up to 7 hrs
      if (h > 0 || n > 0) {
        if (h >= 7 || (h==6 && n >0))
          ex=7;
        else
          ex=h+(n > 0 ? 1 : 0);        
      }
      else
        ex=0;
      //m=(d+((h > 8 || h==8 && n > 0) ? 1 : 0))*7;
      m=d*7+ex;
      if (m < MIN_CHARGE)
        m=MIN_CHARGE;
      // check discount
      if (userDiscount > 0)
        m=parseInt(m*(100.0-userDiscount))/100.0;
      document.getElementById('bf_co').innerHTML=d+' days '+h+' hours '+n+' minutes = $'+m;
      if (f.days)
        f.days.value=d;
      if (u)
        f.cost.value=m;
    }  
  }
  dateIn=sd;
  dateOut=ed;
}

function validate_edit(theForm)
{
  if (formPosted)
    return false;
  else if (error) {
    alert(error);
    return false;
  }  
  else    
    return validate_book(theForm);      
}

function togglePay(f)
{
  var s=f.payby[1].checked ? '' : 'none';
  for (var i=0; i <=3 ; i++)
    document.getElementById('bf_c_'+i).style.display=s;        
}

function startQuote()
{
  var f=document.forms['bqf'];
  if (f.email.value=="" || !validateEmailv2(f.email.value)) {
    alert("Please enter a valid email address.");
    f.email.focus();
    return;    
  }
  f.submit();
}

function tg_in(c)
{
  var e,s=c.checked;
  document.getElementById('tin_1').style.display=c.checked ? '' : 'none';
  c=c.form.t_tbain;
  for (i=2; i <= 5; i++) 
    if (e=document.getElementById('tin_'+i))
      e.style.display=s & !c.checked ? '' : 'none';
}

function tg_ink(c)
{
  var e;
  for (i=2; i <= 4; i++) 
    if (e=document.getElementById('tin_'+i))
      e.style.display=!c.checked ? '' : 'none';
}

function tg_outk(c)
{
  var e;
  for (i=2; i <= 4; i++) 
    if (e=document.getElementById('tout_'+i))
      e.style.display=!c.checked ? '' : 'none';
}

function tg_out(c)
{
  var e,s=c.checked;
  document.getElementById('tout_1').style.display=c.checked ? '' : 'none';
  c=c.form.t_tbaout;
  for (i=2; i <= 4; i++) 
    if (e=document.getElementById('tout_'+i))
      e.style.display=s & !c.checked ? '' : 'none';
}

/* new form */
function tg_vin(c)
{
  if (!c)
    return;
  document.getElementById('fd_k_r1').style.display=c.checked ? '' : 'none';
  document.getElementById('fd_k_r2').style.display=c.checked ? '' : 'none';
  
  document.getElementById('fd_in_t').style.display=(c.checked && c.form.t_tbain[0].checked) ? '' : 'none';
  document.getElementById('v_in_t').style.display=(!c.checked || c.form.t_tbain[0].checked || c.form.t_tbain[1].checked) ? '' : 'none';
  checkDividers();
}

function tg_vout(c)
{
  document.getElementById('fa_k_r1').style.display=c.checked ? '' : 'none';
  document.getElementById('fa_k_r2').style.display=c.checked ? '' : 'none';
  
  document.getElementById('fa_out_t').style.display=(c.checked && c.form.t_tbaout[0].checked) ? '' : 'none';
  document.getElementById('v_out_t').style.display=(!c.checked || c.form.t_tbaout[1].checked) ? '' : 'none';
  checkDividers();
}

function tg_fdk(on)
{
  document.getElementById('fd_in_t').style.display=on ? '' : 'none';
  document.getElementById('v_in_t').style.display='';
  checkDividers();
}

function tg_fak(on)
{
  document.getElementById('fa_out_t').style.display=on ? '' : 'none';
  document.getElementById('v_out_t').style.display=!on ? '' : 'none';
  checkDividers();
}




function getFlightDate2(pr)
{
  var f=document.forms['bf'];
  var y,m,d,yd,md,dd,h,n,t,dt=null;
  yd=f.elements[pr+'_year'];
  md=f.elements[pr+'_month'];
  dd=f.elements[pr+'_day'];

  if (pr=='ea') {
    f.d_day.selectedIndex=f.ea_day.selectedIndex;    
    f.d_month.selectedIndex=f.ea_month.selectedIndex;    
    f.d_year.selectedIndex=f.ea_year.selectedIndex;    
    f.d_time.selectedIndex=f.ea_time.selectedIndex;    
  }  
  y=yd.options[yd.selectedIndex].value;
  d=dd.options[dd.selectedIndex].value;
  m=md.options[md.selectedIndex].value;
  t=getFlightTime(f.elements[pr+'_time']);
  h=parseInt(t/100);
  n=parseInt(t%100);
  if (y && m && d && dateValid(y,m,d))
    return new Date(y,m-1,d,h,n,0,0);
  else
    return null;  
}

function spu_d(b,adj)
{
  var f=b.form;
  if (dt=getFlightDate2('ea')) {
    // we want to take an 1.25 hours off
    dt.setTime(dt.getTime()+adj*60*1000);
    set_lb_val(f.d_day,dt.getDate()); 
    set_lb_val(f.d_month,dt.getMonth()+1); 
    set_lb_val(f.d_year,dt.getFullYear()%100); 
    set_lb_val(f.d_time,dt.getHours().toString()+(dt.getMinutes() < 10 ? '0' : '')+dt.getMinutes().toString());
    changeDate(true);
  }
  else
    alert('Check your flight date/time is valid');
}



// NEW FUNCTIONS

function load_vb2(u)
{
  var list=['year','month','day','time'];
  var f=document.forms['bf'];
  if (!f)
    return;
  var dates=['a','fo','ea','d'];
  var e;
  for (var i=0; i< list.length; i++) 
    for (var j=0; j < dates.length; j++) 
      if (e=f.elements[dates[j]+'_'+list[i]]) {
        if (list[i]=='time') {
          e.onchange=function() { timeChangedCB(this); };
        }  
        else  
          e.onchange=function() { dateChangedCB(this); };
        e.onchange();
      }    

  tg_vin(f.t_in);
  tg_vout(f.t_out);
  if (f.oversized) {
    f.oversized[0].onclick=function() { doCosting(f,false); };    
    f.oversized[1].onclick=function() { doCosting(f,false); };    
  }
  if (typeof(f.undercover) != 'undefined') {
    f.undercover[0].onclick=function() { doCosting(f,false); };    
    f.undercover[1].onclick=function() { doCosting(f,false); };    
  }
  if ((f.elements['i'] && f.elements['i'].value) || f.__qb.value=="1" || onerror) {
    // edit booking
    document.getElementById('cbd2').style.display='block'; 
    document.getElementById('cbd').style.display='block'; 
    doCosting(f,true);
    if (document.getElementById('v_out_t_n') && (f.v_out_dr[0].checked || f.v_out_dr[1].checked)) {
        unconf(f.v_out_dr[1].checked ? 1 : 0);
    }
    checkDividers();    
  }
  startup=false;
}



// date changed callback - just set the DOW
function dateChangedCB(e)
{
  // first lets check the date and set day of week
  var y,m,d,yd,md,dd,f,dt=null;
  var prefix=e.name.substring(0,e.name.indexOf('_'));
  
  f=document.forms['bf'];
  yd=f.elements[prefix+'_year'];
  md=f.elements[prefix+'_month'];
  dd=f.elements[prefix+'_day'];
  
  y=yd.options[yd.selectedIndex].value;
  d=dd.options[dd.selectedIndex].value;
  m=md.options[md.selectedIndex].value;
  if (y && m && dd && dateValid(y,m,d))
    dt=new Date(y,m-1,d);
  document.getElementById(prefix+'_dow').innerHTML=dt ? formatDate(dt,'EE') : 'check date above'; 
  
  if (prefix=='ea' && document.getElementById('v_out_t').style.display=='none') {
    // copy to our pickup 
    f.d_day.selectedIndex=f.ea_day.selectedIndex;    
    f.d_month.selectedIndex=f.ea_month.selectedIndex;    
    f.d_year.selectedIndex=f.ea_year.selectedIndex;   
    dateChangedCB(f.d_day); 
  }  
  else if (!startup && prefix=='fo' && (e.form.fo_dt[0].checked || e.form.fo_dt[1].checked)) 
    changeTerminal();
  
  // next if it is a date which affects our quote, we need to hide our quote section if not already or if edit booking auto update quote
  if ((prefix=='a' || prefix=='ea' || prefix=='d')) {
    if ((f.i && f.i.value) || f.__qb.value=="1")       
      doCosting(f,true);
  }  
  if (prefix=='d')
    checkEarlyFlight(f); 
    
  checkAlerts();   
}

function checkEarlyFlight(f)
{
  var t=9999,ed,e=f.d_time,efc=document.getElementById('efc');
  if (efc && e.options[e.selectedIndex].value.length) {
    t=parseInt(e.options[e.selectedIndex].value);
    ed=getDateTime('d');
  }      
  if (ed && t < 700) {  
    efc.innerHTML='This means boarding a flight <em>'+formatDate(new Date(ed.getTime()-86400000),'EE d NNN')+"</em> and arriving the following morning <em>"+
                    formatDate(ed,'EE d NNN')+"</em>.<br/><br/>If you are actually departing on the <em>"+formatDate(ed,'EE d NNN')+"</em> please change above date.";    
    efc.style.display='block';    
  }
  else
    efc.style.display='none'; 
      
}
// time changed callback - set the time of day ref - moring, late night etc
function timeChangedCB(e)
{
  var efc,t,s='',ed;
  if (!e)
    return;
  if (e.options[e.selectedIndex].value.length) {
    t=parseInt(e.options[e.selectedIndex].value);    
    if (t < 700)
      s='early morning';
    else if (t < 1200)
      s='morning';
    else if (t < 1800)
      s='afternoon';
   else
     s='evening';   
   s+=' - '+formatTime(e.options[e.selectedIndex].value);   
  }    
  document.getElementById(e.name+'_').innerHTML=s;
  if (e.name=='ea_time' && document.getElementById('v_out_t').style.display=='none') {
    // copy to our pickup 
    e.form.d_time.selectedIndex=e.form.ea_time.selectedIndex;    
    timeChangedCB(e.form.d_time); 
  }  
  else if (!startup && e.name=='fo_time' && (e.form.fo_dt[0].checked || e.form.fo_dt[1].checked)) {
    changeTerminal();
  }  
  // finally check if we need to alert to our special conditions
  if (s.length && (e.name=='ea_time' || e.name=='d_time') && (t > valet_closed_from || t < valet_closed_to)) {
    document.getElementById('pu_alert').style.display='block';    
  }
  else if ((e.name=='ea_time' || e.name=='d_time') && document.getElementById('pu_alert').style.display != 'none')
    document.getElementById('pu_alert').style.display='none';  
  if ((e.form.i && e.form.i.value) || e.form.__qb.value=="1")  
      doCosting(e.form,true);
  if (e.name=='ea_time' || e.name=='d_time')
    checkEarlyFlight(e.form);
  checkAlerts(); 
  checkDividers(); 
}
                                                           
function changeTerminal()
{
  var adj,dt,f=document.forms['bf'];
  if (dt=getDateTime('fo')) {
    // we want to take an 1.25 hours off                                                       
    adj=f.fo_dt[1].checked ? 135 : 75;
    dt.setTime(dt.getTime()-adj*60*1000);
    // check if this is earlier than our time and change if so....
    dateIn=getDateTime('a');
    if (!dateIn || dateIn.getTime() != dt.getTime() || (dateIn.getTime() > dt.getTime() || dt.getTime()-dateIn.getTime() > 6*60*60*1000)) {
      set_lb_val(f.a_day,dt.getDate()); 
      set_lb_val(f.a_month,dt.getMonth()+1); 
      set_lb_val(f.a_year,dt.getFullYear()); 
      set_lb_val(f.a_time,dt.getHours().toString()+(dt.getMinutes() < 10 ? '0' : '')+dt.getMinutes().toString());
      dateChangedCB(f.a_day);
      timeChangedCB(f.a_time);                             
      if (document.getElementById('drop-suggest') && document.getElementById('drop-suggest').style.display != 'block')
        document.getElementById('drop-suggest').style.display='block';
    }  
  }
}

function showQuote2(next)
{
  var f=document.forms['bf'];
  var now=new Date();
  var msg='';
  error=null;
  if (preventBooking) {
    error=document.getElementById('alert').innerHTML;
    alert(error.replace(/<br>/gi,"\r\n"));   
    return;    
  }
  // departure details.....
  if (f.email.value=="" || !validateEmailv2(f.email.value)) {
    alert("Please enter a valid email address");
    f.email.focus();
    return;
  }
  if (f.t_in.checked) {
    if (!f.t_tbain[0].checked && !f.t_tbain[1].checked) {
      alert('Please advise whether you know your departure flight details or not.');
      return;
    } 
    if (f.t_tbain[0].checked) {
      if (!(flightOut=getDateTime('fo'))) {
        alert('Check your flight departure date/time is correct.  Date not entered or invalid.');
        f.fo_day.focus(); 
        return;   
      }
      if (f.fo_time.selectedIndex <=0) {
        alert('Please enter your flight departure time of day');
        f.fo_time.focus();
        return;
      }
      if (flightOut.getTime() < now.getTime()+60*60*1000) {
        alert("Your departure flight must be at least an hour from now.\nTo book at this late stage contact our office on 4053 5171 or operations on 0488 535 171.");
        f.fo_day.focus();
        return;
      }
      if (!f.fo_dt[0].checked && !f.fo_dt[1].checked) {
        alert("Please nominate the terminal the flight departs from - domestic or international.\nNote some domestic flights leave from the international terminal.");
        return;    
      }
    } 
  }    
  if (!(dateIn=getDateTime('a'))) {
    alert("Check your vehicle in drop off date/time.  Date not entered or invalid.");
    
    return;
  }
  if (f.a_time.selectedIndex <=0) {
    alert('Please enter your drop off time of day');
    f.a_time.focus();
    return;
  }
  
  if (dateIn.getTime() < now.getTime()+60*60*1000) {
    alert("Your drop off date must be at least an hour from now.\nTo book at this late stage contact our office on 4053 5171 or operations on 0488 535 171.");
    f.a_day.focus();
    return;    
  }
  if (flightOut && dateIn.getTime() > flightOut.getTime()-30*60*1000) {
    //alert('Your flight can not be any earlier than 30 minutes after your drop off.  Check your flight time and vehicle drop off time.');
    //f.a_day.focus();
    //return;    
  }
  
  // arrival details.....
  if (f.t_out.checked) {
    if (!f.t_tbaout[0].checked && !f.t_tbaout[1].checked) {
      alert('Please advise whether you know your arrival flight details or not.');
      return;
    } 
    if (f.t_tbaout[0].checked) {
      if (!(flightIn=getDateTime('ea'))) {
        alert('Check your flight arrival date/time.  Date not entered or invalid'); 
        f.ea_day.focus();
        return;   
      }
      if (f.ea_time.selectedIndex <=0) {
        alert('Please enter your flight arrival time of day');
        f.ea_time.focus();
        return;
      }
      
      dateOut=flightIn;
      if (flightIn.getTime() < now.getTime()) {
        alert('Your flight arrival date can not be in the past');
        return;
      }
    } 
  }    
  if (document.getElementById('v_out_t').style.display != 'none') {
    if (!(dateOut=getDateTime('d'))) {
      alert("Check your vehicle pick up date/time.  Date not entered or invalid");
      f.d_day.focus();
      return;
    }  
    if (f.d_time.selectedIndex <=0) {
      alert('Please enter your pickup time of day');
      f.d_time.focus();
      return;
    }
  }
  
  if (dateOut.getTime() < dateIn.getTime()) {
    alert("Your pickup date can not be prior to your drop off date.  Check your dates are correct.");
    return;    
  }
  if (document.getElementById('pu_alert').style.display=='block' && !f.pu_alert.checked) {
    alert('Please read the conditions relating to your pickup (in the red box), and acknowledge by ticking the box at the bottom of the conditions.');
    f.pu_alert.focus();
    return;
  }
  if (f.oversized && !f.oversized[0].checked && !f.oversized[1].checked) {
    alert("Please select your vehicle category/size.\nStandard - Most cars and 4wd's\nOversized - Any vehicle wider/longer than standard 4wd wagon'");
    return;    
  }
  doCosting(f,false);
  showQuote();
  checkDividers(); 
  if (next) {
    window.scrollTo(0,790);
    //f.homePh.focus();  
  }  
}


function doCosting(f,calc)
{
    // calc diff in dates
    var d,h,n,y,ex,m,ind,outd,f,rate;
    error='';
    f.days.value='';
    f.cost.value='';
    if (calc) {
      dateIn=typeof(b_sd)=='undefined' ? getDateTime('a') : b_sd;
      // check for unknown option
      if (!document.getElementById('v_out_t_n') || f.t_tbaout[0].checked || f.v_out_dr[0].checked)
        dateOut=getDateTime('d');    
      else
        dateOut=null;  
    }
    if (!dateIn ||!dateOut) {
      if (!dateIn)
        error='Your drop off date is invalid.  Check date and time.';
      else if (!document.getElementById('q_untab') || document.getElementById('q_untab').style.display=='none')    
        error='Your pickup date is invalid.  Check date and time.';
      document.getElementById('avail').style.display='none';
      return;
    }  
    if (typeof(b_sd)=='undefined' && dateIn.getTime()-now.getTime() < 3600000) {
      document.getElementById('bf_co').innerHTML=(error='Your drop off time must be at least an hour from now');
      document.getElementById('avail').style.display='none';
      return;  
    }
    y=(dateOut.getTime()-dateIn.getTime())/1000;        // total seconds

    if (y < 0) { 
      document.getElementById('bf_co').innerHTML=(error='Your date out is before your date in - check dates');
      document.getElementById('avail').style.display='none';
    }  
    else {  
      outd=new Date(dateOut.getYear(),dateOut.getMonth(),dateOut.getDate(),0,0,1);
      ind=new Date(dateIn.getYear(),dateIn.getMonth(),dateIn.getDate(),0,0,0);
      d=parseInt((outd.getTime()-ind.getTime())/86400000)+1;
      f=document.forms['bf'];
      m=calcRate(dateIn,d,f.oversized[1].checked,typeof(f.undercover)=='undefined' ? 0 : f.undercover[0].checked);
      // check discount
      if (userDiscount > 0)
        m=parseInt(m*(100.0-userDiscount))/100.0;
      //document.getElementById('bf_co').innerHTML=d+' days '+h+' hours '+n+' minutes = $'+m;
      if (f.days)
        f.days.value=d;
      f.cost.value=formatCurrency(m);
      document.getElementById('bf_co').innerHTML='';
      document.getElementById('avail').style.display='block';
    }  

}

function formatTime(t)
{
  var tm;
  for (var i=0; i < t.length; i++)
    if (t.substring(i,1) != '0') {
      tm=parseInt(t.substring(i,t.length)); 
      break;
    }    
  return (tm < 100 ? 12 : parseInt(tm/100)-(tm >= 1300 ? 12 : 0))+":"+(tm%100 < 10 ? '0' : '')+(tm%100)+(tm < 1200 ? 'am' : 'pm');   
}

function validate_edit2(theForm)
{
  if (formPosted)
    return false;
  else if (error) {
    alert(error);
    return false;
  }  
  else    
    return validate_book2(theForm);      
}
function validate_book2(theForm)
{
  var e;
  if (formPosted)
    return false;
  if (preventBooking) {
    error=document.getElementById('alert').innerHTML;
    alert(error.replace(/<br>/gi,"\r\n"));   
    return false;    
  }
    
    if ((!document.getElementById('q_untab') || document.getElementById('q_untab').style.display=='none') && !(dateOut=getDateTime('d'))) {
      alert("Check your flight/pickup date and time.");
      theForm.t_out.focus();
      return false;    
    }
    if (dateOut) {
      if (dateOut.getTime() < now.getTime()) {
        alert("Check your flight/pick up date and time as it appears to be prior to now.");
        theForm.t_out.focus();
        return false;    
      }
    if (theForm.days.value=='') {
      alert('Unable to calculate your parking cost.  Check dates and times entered in Step 2.');
      theForm.t_in.focus();
      return false;    
    }
    }  
  if (document.getElementById('pu_alert').style.display=='block' && !theForm.pu_alert.checked) {
    alert('Please read the conditions relating to your pickup (in the red box), and acknowledge by ticking the box at the bottom of the conditions.');
    theForm.pu_alert.focus();
    return false;
  }
  
  if (theForm.firstname.value=="") {
    alert("Please enter your firstname.");
    theForm.firstname.focus();
    return false;
  }
  if (theForm.lastname.value=="") {
    alert("Please enter your lastname.");
    theForm.lastname.focus();
    return false;
  }
  if (theForm.phone.value=="") {
    alert("Please enter your contact mobile number whilst travelling");
    theForm.phone.focus();
    return false;
  }
  if (theForm.email.value=="" || !validateEmailv2(theForm.email.value)) {
    alert("Please enter a valid email address");
    theForm.email.focus();
    return false;
  }
  if (theForm.homePh.value=="") {
    alert('Please enter your home phone number');
    theForm.homePh.focus();
    return false;
  }
  if (theForm.street.value=="") {
    alert('Please enter your home street address');
    theForm.street.focus();
    return false;
  }
  if (theForm.origin.value=="") {
    alert('Please enter your home town/suburb');
    theForm.origin.focus();
    return false;
  }
  
  if (!theForm.payby[0].checked && !theForm.payby[1].checked && !theForm.payby[2].checked) {
    alert("Please nominate your preferred payment method on drop off");
    return false;
  }
  if (theForm.payby[1].checked && (typeof(theForm.cc_exist)=='undefined' || theForm.cc_exist[1].checked)) {
    if (theForm.c_num_1.value=="" || theForm.c_num_2.value=="" || theForm.c_num_3.value=="" || theForm.c_num_4.value=="") {
      alert("Please enter your credit card number.\nNo payment will be taken until after your booking.");
      theForm.c_num_1.focus();
      return false;    
    }
    if (theForm.c_exp_m.selectedIndex <= 0) {
      alert("Please enter your card expiry month");
      theForm.c_exp_m.focus();
      return false;    
    }
    if (theForm.c_exp_y.selectedIndex <= 0) {
      alert("Please enter your card expiry year");
      theForm.c_exp_y.focus();
      return false;    
    }
  }  
  if (theForm.type.selectedIndex <= 0) {
    alert("Please select your vehicle type");
    theForm.type.focus();
    return false;
  }
  if (theForm.rego.value=="") {
    alert("Please enter your vehicle registration");
    theForm.rego.focus();
    return false;
  }
  if (parseInt(theForm.adults.value) <1) {
    alert('Please nominate the number of adults travelling');
    theForm.adults.focus();
    return false;    
  }
/*  
  if (parseInt(theForm.infants.value) >0 && !theForm.infOpt[0].checked && !theForm.infOpt[1].checked) {
    alert("When travelling with infants you must select how to be transported to the airport.\n\nOption 1 - Drop family to airport and then bring your car to our yard.\nOption 2 - We drive your car to/from airport\n\nSelect either option by clicking the option next to the number of infants.") ;
    theForm.infants.focus();
    return false;
  }
  */
  if (!theForm.carry[0].checked && !theForm.carry[1].checked) {
    alert("Please nominate whether you will have baggage to check in or just carry on.");
    theForm.carry[0].focus();
    return false;    
  }
  if (theForm.t_in && theForm.t_in.checked && theForm.f_dest && theForm.f_dest.value=="") {
    alert("Please enter the flight destination.");
    theForm.f_dest.focus();
    return false;    
  }
  if (theForm.terms && !theForm.terms.checked) {
    alert('Please acknowledge you have read the terms and conditions by ticking the box at the bottom of this page.');
    return false;    
  }
 
 if ((e=document.getElementById('t_remember')) && e.style.display=='block') {
   if (theForm.r_pwd.value != theForm.r_pwd2.value) {
     alert('Your password and re-enter password do not match.  Enter your desired password in to both boxes exactly the same.')    ;
     theForm.r_pwd2.focus();
     return false;
   }
 }
  return formPosted=true;
}

function checkDividers()
{
  var max=0,e,l;
  for (var i=1; i<=3; i++)
    if ((e=document.getElementById('col'+i)) && e.offsetHeight > max)
      max=e.offsetHeight;
  for (var i=1; i<=2; i++)
    if ((e=document.getElementById('coldiv'+i)) && e.offsetHeight != max)
      e.style.height=max+'px';
      
  // cbd div
  if (document.getElementById('cbd').style.display != 'none') {
    max=0;
    for (var i=4; i<=5; i++)
      if ((e=document.getElementById('col'+i)) && e.offsetHeight > max)
        max=e.offsetHeight;
      if ((e=document.getElementById('coldiv3')) && e.offsetHeight != max)
        e.style.height=max+'px';
  }    
  // cbd2 div
  if (document.getElementById('cbd2').style.display != 'none') {
    max=0;
    for (var i=6; i<=7; i++)
      if ((e=document.getElementById('col'+i)) && e.offsetHeight > max)
        max=e.offsetHeight;
      if ((e=document.getElementById('coldiv4')) && e.offsetHeight != max)
        e.style.height=max+'px';
  }    
}

function email_changed()
{
  var em=document.forms['bf'].elements['email'];
  if (em.value != lastEM && em.value != '' && validateEmailv2(em.value)) {
    http.callback=email_cb;
    lastEM=em.value;
    http.load('_ruinf?e='+em.value);        
  }  
}

/* new ajax functions qf8 */
function disableBrowser(greyed)
{
  var s=new Element('div',{id: 'shadow'});
  s.style.top=0;
  s.style.left=0;
  s.style.position='absolute';
  s.style.zIndex=1000;
  var b=$(document.body);    /* ie6 requires!! */
  s.style.width=b.getWidth()+'px';
  s.style.height=b.getHeight()+'px';
  if (greyed) {
    s.style.backgroundColor='#000';
    s.setOpacity(0.6);
  }
  document.body.appendChild(s);
  return s;    
}

function createPopup(title,html,greyed,outsideClose)
{
  var d;
  if (!(d=$('shadow'))) 
    d=disableBrowser(greyed);
  // create popup window
  var p=new Element('div',{'class' : 'popup'});
  p.update('<h5>'+title+'<a title="close" href="javascript:void(0)">x close window</a></h5><div class="inner">'+html+'<p align="center"><input type="button" value="close window" title="close" /></p></div>');
  document.body.appendChild(p);
  p.style.top=parseInt((document.viewport.getHeight()-p.getHeight())/2)+document.viewport.getScrollOffsets().top+'px';
  p.style.left=parseInt((document.viewport.getWidth()-p.getWidth())/2)+document.viewport.getScrollOffsets().left+'px';
  if (outsideClose)
    d.onclick=function() { document.body.removeChild(d); document.body.removeChild(p); };
  var l=p.select("[title=close]");
  for (var i=0; i < l.length; i++)
    l[i].onclick=function() { document.body.removeChild(d); document.body.removeChild(p); };
  return p;
}



function validate_edit3(theForm)
{
  if (formPosted)
    return false;
  return validate_book3(theForm);      
}
function validate_book3(theForm)
{
  var e;
  if (formPosted)
    return false;
  resetError(); 
  dateIn=dateOut=null;
   
  // first section
  if (theForm.email.value=="" || !validateEmailv2(theForm.email.value)) {
    setError("Please enter a valid email address",theForm.email);
  }
  if (theForm.firstname.value=="") {
    setError("Please enter your firstname.",theForm.firstname);
  }
  if (theForm.lastname.value=="") {
    setError("Please enter your lastname.",theForm.lastname);
  }
  if (theForm.phone.value=="") {
    setError("Please enter your contact mobile number whilst travelling",theForm.phone);
  }
  
  // step 2 - drop off
  if (theForm.t_in) {
    if (theForm.t_in.checked) {
      if (!theForm.t_tbain[0].checked && !theForm.t_tbain[1].checked)
        setError('Please indicate whether you know your departing flight details',theForm.t_tbain[0]);    
      else if (theForm.t_tbain[0].checked) {
        if (!getDateTime('fo'))
          setError('Enter a valid date and time for your flight departing Cairns',theForm.fo_day);
      }
    }  
    if (!theForm.t_in.checked || theForm.t_tbain[0].checked || theForm.t_tbain[0].checked) {
      if (!(dateIn=getDateTime('a')))  
        setError('Enter a valid date and time for your vehicle drop off',theForm.a_day);
      if (theForm.f_dest.value=='')
        setError('Please indicate where you are travelling to.',theForm.f_dest);   
    }    
  } 
  // step 2 - pickup
  if (theForm.t_out.checked) {
      if (!theForm.t_tbaout[0].checked && !theForm.t_tbaout[1].checked)
        setError('Please indicate whether you know your arriving flight details',theForm.t_tbaout[0]);    
      else if (theForm.t_tbaout[0].checked) {
        if (!(dateOut=getDateTime('ea')))
          setError('Enter a valid date and time for your flight arriving Cairns',theForm.ea_day);
      }
      else if (!theForm.v_out_dr[0].checked && !theForm.v_out_dr[1].checked) {
        setError('Please indicate whether you know your approximate return date',theForm.v_out_dr[0]);    
      }
      else if (theForm.v_out_dr[0].checked && !(dateOut=getDateTime('d'))) {
        setError('Please indicate your approximate pickup date and time',theForm.d_day);    
      }  
  }
  else {
    if (!theForm.v_out_dr[0].checked && !theForm.v_out_dr[1].checked) {
      setError('Please indicate whether you know your approximate return date',theForm.v_out_dr[0]);    
    }
    else if (theForm.v_out_dr[0].checked && !(dateOut=getDateTime('d'))) {
      setError('Please indicate your approximate pickup date and time',theForm.d_day);    
    }  
  }
  if (dateIn && dateIn.getTime()-now.getTime() < 3600000) {
    setError('Vehicle drop off date and time must be at least 1hr from now',theForm.a_day);        
  }
  if (typeof(b_sd) != 'undefined')
    dateIn=b_sd;
  if (dateOut && dateOut.getTime() < dateIn.getTime())
    setError('Your pickup date/time seems to preceed your drop-off date/time');
  
    
  if (document.getElementById('pu_alert').style.display=='block' && !theForm.pu_alert.checked) {
    setError('Please read the conditions relating to your pickup (in the red box), and acknowledge by ticking the box at the bottom of the conditions.',theForm.pu_alert);
  }
  if (!theForm.carry[0].checked && !theForm.carry[1].checked) {
    setError("Please nominate whether you will have baggage to check in or just carry on.",theForm.carry[0]);
  }
  
  // step 2 - vehicle category
  if (!theForm.oversized[0].checked && !theForm.oversized[1].checked)
    setError('Nominate your vehicle category - standard or oversized');
  
  // step 3 
  if (theForm.homePh.value=="") {
    setError('Please enter your home phone number',theForm.homePh);
  }
  if (theForm.street.value=="") {
    setError('Please enter your home street address',theForm.street);
  }
  if (theForm.origin.value=="") {
    setError('Please enter your home town/suburb',theForm.origin);
  }
 if ((e=document.getElementById('t_remember')) && e.style.display=='block') {
   if (theForm.r_pwd.value != theForm.r_pwd2.value) {
     setError('Your password and re-enter password do not match.  Enter your desired password in to both boxes exactly the same.',theForm.r_pwd2);
   }
 }

  // step 3 
  if (theForm.type.selectedIndex <= 0) {
    setError("Please select your vehicle type",theForm.type);
  }
  if (theForm.rego.value=="") {
    setError("Please enter your vehicle registration",theForm.rego);
  }
  if (parseInt(theForm.adults.value) <1) {
    setError('Please nominate the number of adults travelling',theForm.adults);
  }

  // step 4
  if (!theForm.payby[0].checked && !theForm.payby[1].checked && !theForm.payby[2].checked) {
    setError("Please nominate your preferred payment method on drop off");
  }
  if (theForm.payby[1].checked && (typeof(theForm.cc_exist)=='undefined' || theForm.cc_exist[1].checked)) {
    if (theForm.c_num_1.value=="" || theForm.c_num_2.value=="" || theForm.c_num_3.value=="" || theForm.c_num_4.value=="") {
      setError("Please enter your credit card number.\nNo payment will be taken until after your booking.",theForm.c_num_1);
    }
    if (theForm.c_exp_m.selectedIndex <= 0) {
      setError("Please enter your card expiry month",theForm.c_exp_m);
    }
    if (theForm.c_exp_y.selectedIndex <= 0) {
      setError("Please enter your card expiry year",theForm.c_exp_y);
    }
  }  

  if (theForm.terms && !theForm.terms.checked) {
    setError('Please acknowledge you have read the terms and conditions by ticking the box at the bottom of this page.');
  }
 
 if (globalError) {
   showError('Cairns Airport Parking - Unable to submit booking');    
   return false;
 }
   
  return formPosted=true;
}



function retrieve_details_cb2(response)
{
  var e;
  document.body.removeChild($('loading'));
  //document.body.removeChild($('shadow'));
  if (e=document.getElementById('bf_c_4')) 
    getParent(e,'table').deleteRow(e.rowIndex);
  
  if (response.status != 200) {
    // do error....
    createPopup('Cairns Airport Parking - Network Error','There was a communication problem trying to retrieve your details.<br />The Internet connection may have timed out or some other network error has occurred.<br /><br />Please try again.  If the problem persists continue your booking without using your password, or use the help button located at the bottom of the form.',true,false);    
  }    
  else {
    document.body.removeChild($('shadow')); // disable now incase something breaks, popup will recreate...
    var f=document.forms['bf'];
    var result=response.responseJSON;
    if (!result || result.error) {
      createPopup('Cairns Airport Parking - Unable to verify your account','We were unable to verify your account details.<br /><br />Either your email address or your password (or both) have been entered incorrectly.<br /><br />Close this window and check your email address is correct and retype your password and try again.<br /><br />If the problem persists you can use the Forgot My Password button to reset your password.',true,false);    
      return;  
    }  
    previousVehicles=result.PreviousVehicles;  
    f.firstname.value=result.BookingFirstname;
    f.lastname.value=result.BookingSurname;
    f.phone.value=result.BookingPhone;  
    f.homePh.value=result.HomePhone;
    f.company.value=result.BookingCompanyName;
    f.street.value=result.StreetOrigin;
    f.origin.value=result.Origin;
    selectByValue(f.state,result.StateOrigin);
    f.f_dest.value=result.FlightDestination;
    selectByValue(f.type,result.VehicleType);
    f.make.value=result.VehicleMake;
    f.rego.value=result.VehicleRego;
    f.adults.value=result.Adults;
    f.children.value=result.Children ? result.Children : '';
    f.infants.value=result.Infants ? result.Infants : '';
    f.payby[parseInt(result.PaymentMethod)-1].checked=true;
    f.tax.checked=result.TaxInvoice=="1";
    f.__cid.value=result.ContactID;
    togglePayment(f);
    if (e=document.getElementById('t_remember')) {
        e.style.display='none';  
    }
    // insert credit card details.....
    if (result.PaymentMethod=="2" && result.CardNumber.length) {
      // insert a row for the option....
      var tr=document.getElementById('bf_c_1');
      tr.style.display='none';
      document.getElementById('bf_c_0').style.display='';
      document.getElementById('bf_c_2').style.display='none';
      document.getElementById('bf_c_3').style.display='none';
      var table=getParent(tr,'table');
      tr=table.insertRow(tr.rowIndex);
      tr.id='bf_c_4';
      var td=tr.insertCell(0);    
      td.colSpan=2;
      td.innerHTML='<input onclick="togglePayment(this.form)" type="radio" value="'+result.BookingID+'" name="cc_exist" checked="checked" /> Use previous card '+result.CardNumber+' Exp: '+result.CardExpiry
                    +'<br /><input onclick="togglePayment(this.form)" type="radio" name="cc_exist" value="" />Enter new card details';
    }
    // open up form
    fillVehicles(f);
    document.getElementById('cbd').style.display='block';
    document.getElementById('cbd2').style.display='block';
    //alert('Booking details retrieved.  Please continue to quote.');  
  }
}

function resetError()
{
  globalError='';
  globalFocus=null;    
}

function setError(error,focus)
{
  globalError+='<li>'+error+'</li>';
  if (focus && !globalFocus)
    globalFocus=focus;    
}

function showError(title,prefix)
{
  createPopup(title ? title : 'Cairns Airport Parking - Notice',(prefix ? prefix : 'Unable to process your request. Please correct the following - <ul>')+globalError+'</ul>',true,false);      
}

function retrieveDetails2(e)
{
  var f=e.form;
  var d=disableBrowser(true);
  if (f.email.value=='' || f.r_p_pwd.value=='')  
    return createPopup('More Information Required','Please enter both your email address and password nominated when you created your booking.<br /><br />',true,false);
  

  var s=new Element('div',{id: 'loading'});
  s.style.textAlign='center';
  s.style.top=parseInt((document.viewport.getHeight()-120)/2)+document.viewport.getScrollOffsets().top+'px';
  s.style.left=0;
  s.style.backgroundColor='#eee';
  s.style.position='absolute';
  s.style.zIndex=1000;
  s.style.width=document.viewport.getWidth()+'px';
  s.style.height='120px';
  s.update('<h2>Please wait, retrieving your details...<br /><br /><img src="images/loading.gif" />');
  document.body.appendChild(s);
  new Ajax.Request('_ajax.retrieve-details.html',{
      parameters: {email: f.email.value, password: hex_md5(f.r_p_pwd.value) },
      onComplete: retrieve_details_cb2
  });
}

function showNotice(msg)
{
  return createPopup('Cairns Airport Parking - Notice',msg,true,false);    
}

function forgotPwd2(ib)
{
  if (ib.form.email.value=='' || !validateEmailv2(ib.form.email.value)) 
    return showNotice('Your email address has not been entered or is invalid.<br /><br />Enter your full email address in to the email box and then click the forgot password button.');
  new Ajax.Request('_ajax.forgot-pwd.html',{
      parameters: {email: ib.form.email.value },
      onComplete: function(response) {
        if (response.status != 200)    
          createPopup('Cairns Airport Parking - Network Error','There was a communication problem trying to retrieve your details.<br />The Internet connection may have timed out or some other network error has occurred.<br /><br />Please try again.  If the problem persists continue your booking without using your password, or use the help button located at the bottom of the form.',true,false);    
        else
          createPopup('Cairns Airport Parking - Forgot Password',response.responseText,true,false);  
      }
  });
}

function email_cb2(response)
{
  var f=document.forms['bf'];
  if (response.status==200 && response.responseJSON) {
    userDiscount=parseInt(response.responseJSON.userDiscount);
      if ((e=document.getElementById('wom')) && parseInt(response.responseJSON.existingClient) > 0) {
        e.style.display='none';
        f.found.selectedIndex=-1;    
      }
      else if (e)
        e.style.display='block';
      if ((e=document.getElementById('t_remember')) && parseInt(response.responseJSON.hasPassword) > 0)
        e.style.display='none';
      else if (e)
        e.style.display='block';  
      checkDividers();  
      lastEM=response.responseJSON.email;
      doCosting(document.forms['bf'],false);
    }
}

function email_changed2()
{
  var em=document.forms['bf'].elements['email'];
  if (em.value != lastEM && em.value != '' && validateEmailv2(em.value)) {
    new Ajax.Request('_ajax.check-email.html',{
        parameters: {email: em.value},
        method: 'get',
        onComplete: email_cb2
    });
  }  
      
}

function initPage4()
{
  if (!document.forms['bf'])
    return;
  load_vb2(true);
  var y=new Date;
  y.setTime(y.getTime()-86400000);
  poCalendar=new CalendarPopup("poCalendar_");
  poCalendar.addDisabledDates(null,formatDate(y,"yyyy-MM-dd"));
  poCalendar.setReturnFunction("setCalendarDates");
  poCalendar.setCssPrefix("poCal_");
  var supernote = new SuperNote('helpnote', {});
  document.forms['bf'].elements['email'].onblur=email_changed2;
}

/* end new functions */

function initPage3()
{
  if (!document.forms['bf'])
    return;
  http = new HTMLHttpRequest('http', null);  
  load_vb2(true);
  var y=new Date;
  y.setTime(y.getTime()-86400000);
  poCalendar=new CalendarPopup("poCalendar_");
  poCalendar.addDisabledDates(null,formatDate(y,"yyyy-MM-dd"));
  poCalendar.setReturnFunction("setCalendarDates");
  poCalendar.setCssPrefix("poCal_");
  var supernote = new SuperNote('helpnote', {});
  document.forms['bf'].elements['email'].onblur=email_changed;
}


function initQuotePage()
{
  var y=new Date;
  y.setTime(y.getTime()-86400000);
  poCalendar=new CalendarPopup("poCalendar_");
  poCalendar.addDisabledDates(null,formatDate(y,"yyyy-MM-dd"));
  poCalendar.setReturnFunction("setCalendarDates_quote");
  poCalendar.setCssPrefix("poCal_");
  var f=document.forms['bf'];
  for (var i=0; i < f.elements.length; i++)
    if (!f.elements[i].readonly)
      f.elements[i].onchange=function() { quotePageCost(); };
  quotePageCost();    
}



function setCalendarDates_quote(y,m,d)
{
  var f=document.forms['bf'];
  set_lb_val(f.elements[calendarMode+'_year'],y);
  f.elements[calendarMode+'_day'].selectedIndex=d;
  f.elements[calendarMode+'_month'].selectedIndex=m;
  quotePageCost();
}

function finalBook()
{
  document.getElementById('cbd2').style.display='block'; 
  window.scrollTo(0,870);
  document.forms['bf'].notes.focus(); 
  checkDividers();  
}

function togglePayment(f)
{
  var s=f.payby[1].checked ? '' : 'none';
  if (document.getElementById('bf_c_4'))    
    document.getElementById('bf_c_4').style.display=s;
  // check if the use previous option is around
  if (s=='' && typeof(f.cc_exist) != 'undefined' && f.cc_exist[0].checked)
    s='none';
  document.getElementById('bf_c_0').style.display=f.payby[1].checked ? '' : 'none';  
  for (var i=1; i <=3 ; i++)
    document.getElementById('bf_c_'+i).style.display=s;
  checkDividers();          
}

function support()
{
  // need to get all the details in all the fields emailed....should post it rather than get incase notes are large, need to create hidden form and iframe then...
  var frame,f,saveAction,saveSubmit;
  f=document.forms['bf'];
  f.setAttribute('action','p_support_rq.php');
  f.setAttribute('onsubmit','');
  f.submit();
}

/*
function support_x()
{
  // need to get all the details in all the fields emailed....should post it rather than get incase notes are large, need to create hidden form and iframe then...
  var frame,f,saveAction,saveSubmit;
  f=document.forms['bf'];
  var iframeID='support_frame_tmp';
  if (!(frame=document.getElementById(iframeID))) {
    frame=document.createElement('iframe');    
    frame.setAttribute('name',iframeID);
    frame.setAttribute('id',iframeID);
    frame.style.visibility = 'hidden';
    frame.style.position = 'absolute';
    frame.style.width = frame.style.height = frame.borderWidth = '0px';
    frame = document.getElementsByTagName('body')[0].appendChild(frame); 
  }
  if (window.frames && window.frames[iframeID]) iframe = window.frames[iframeID];
  iframe.name = iframeID;    
  // redirect our form temporarily and disable validation
  saveAction=f.getAttribute('action');
  f.setAttribute('action','p_support_rq.php');
  f.setAttribute('target',iframeID);  
  saveSubmit=f.getAttribute('onsubmit') ;
  f.setAttribute('onsubmit','');
  f.submit();
  alert('Details have been sent to support.  Someone will contact you shortly.');
  f.setAttribute('action',saveAction);
  f.setAttribute('target','');
  f.setAttribute('onsubmit',saveSubmit);
}
*/

function s_close()
{
  document.getElementById('support_frame_tmp').style.display='none';    
}
function support_x(id)
{
  // need to get all the details in all the fields emailed....should post it rather than get incase notes are large, need to create hidden form and iframe then...
  var frame,f,saveAction,saveSubmit,e=document.getElementById(id);
  f=document.forms['bf'];
  var now=new Date();
  f.__sbtz.value=now.toString();
  var frame=document.getElementById('support_frame_tmp');
  // redirect our form temporarily and disable validation
  saveAction=f.getAttribute('action');
  f.setAttribute('action','p_support_rq.php');
  f.setAttribute('target','support_frame_tmp');  
  frame.style.left=e.offsetLeft+20+'px';
  frame.style.top=e.offsetTop-140+'px';
  frame.style.display='block';
  saveSubmit=f.getAttribute('onsubmit') ;
  f.setAttribute('onsubmit','');
  f.submit();
  f.setAttribute('action',saveAction);
  f.setAttribute('target','');
  f.setAttribute('onsubmit',saveSubmit);
}
function validate_enquiry(theForm)
{
  if (formPosted)
    return false;
  if (theForm.name.value.length < 1) {
    alert('Please enter your name');
    theForm.name.focus();
    return false;    
  }  
  if (theForm.email.value.length < 3 && theForm.phone.value.length <1) {
    alert('Please enter an email address or phone number so we can contact you');
    theForm.email.focus();
    return false;    
  }
  if (theForm.message.value.length < 3) {
    alert('Please enter your enquiry');
    theForm.message.focus();
    return false;    
  }  
  if (theForm.v.value.length != 1) {
    alert('Please enter the single anti-span letter or number exactly as shown.')    ;
    theForm.v.focus();
    return false;
  }
  return formPosted=true;
}

function validate_testimonial(theForm)
{
  if (formPosted)
    return false;
  if (theForm.name.value.length < 1) {
    alert('Please enter your name');
    theForm.name.focus();
    return false;    
  }  
  if (theForm.email.value.length < 3) {
    alert('Please enter an email address');
    theForm.email.focus();
    return false;    
  }
  if (theForm.message.value.length < 3) {
    alert('Please enter your feedback/testimonial');
    theForm.message.focus();
    return false;    
  }  
  if (theForm.v.value.length != 1) {
    alert('Please enter the single anti-span letter or number exactly as shown.')    ;
    theForm.v.focus();
    return false;
  }
  return formPosted=true;
}


function infantWarning(e,on)
{
  document.getElementById('infantW').style.display=on ? 'block' : 'none';
}


function checkAlerts()
{
  var din,dout,d,a;
  preventBooking=false;
  if (typeof(alerts)=='undefined' || !alerts)
    return;
  din=(d=getDateTime('a')) ? d.getTime() : 0;
  dout=(d=getDateTime('d')) ? d.getTime() : 0;
  a=document.getElementById('alert');
  
  for (var i=0; i < alerts.length; i++)
    for (var j=0; j < alerts[i].dates.length; j++)
      if ((alerts[i].dates[j].type==0 && din >= Date.parse(alerts[i].dates[j].from) && din < Date.parse(alerts[i].dates[j].to)) ||
          (alerts[i].dates[j].type==1 && dout >= Date.parse(alerts[i].dates[j].from) && dout < Date.parse(alerts[i].dates[j].to))) {
        preventBooking=parseInt(alerts[i].prevent);
        // show message
        a.innerHTML=alerts[i].message.replace(/\r\n/g,'<br>');
        a.style.display='block';
        if (preventBooking) {
          document.getElementById('col3').style.display='none'; 
          a.className='prevent';       
        }  
        else {
          document.getElementById('col3').style.display='block'; 
          a.className='';       
            
        }
        return;                                                    
      }  

  a.style.display='none';
  document.getElementById('col3').style.display='block';        
}

function showTerms()
{
  // need to get all the details in all the fields emailed....should post it rather than get incase notes are large, need to create hidden form and iframe then...
  var frame,f,saveAction,saveSubmit;
  f=document.forms['bf'];
  var frame=document.getElementById('support_frame_tmp');
  // redirect our form temporarily and disable validation
  saveAction=f.getAttribute('action');
  f.setAttribute('action','p_terms.php');
  f.setAttribute('target','support_frame_tmp');  
  saveSubmit=f.getAttribute('onsubmit') ;
  f.setAttribute('onsubmit','');
  f.submit();
  f.setAttribute('action',saveAction);
  f.setAttribute('target','');
  f.setAttribute('onsubmit',saveSubmit);
  window.open('terms.php','','width=800,height=600,scrollbars=1');

}

function viewTerms()
{
  window.open('terms.php','','width=800,height=600,scrollbars=1');
}

function toggleRemember(cb)
{
  document.getElementById('t_remember').style.display=cb.checked ? 'block' : 'none';    
  checkDividers();
}

function selectByValue(sb,v)
{
  for (var i=0; i < sb.options.length; i++) 
    if (sb.options[i].value==v) {
      sb.selectedIndex=i;
      break;    
    }   
}
function email_cb(dom,txt,uri)
{
  http.callback=null;
  var div=dom.document ? dom.document.getElementById('result') : dom.getElementById('result');
  var result=null;
  var f=document.forms['bf'];
  if (div) {
    eval('result='+div.innerHTML+';');
    if (result) {
      userDiscount=parseInt(result.userDiscount);
      if ((e=document.getElementById('wom')) && parseInt(result.existingClient) > 0) {
        e.style.display='none';
        f.found.selectedIndex=-1;    
      }
      else if (e)
        e.style.display='block';
      if ((e=document.getElementById('t_remember')) && parseInt(result.hasPassword) > 0)
        e.style.display='none';
      else if (e)
        e.style.display='block';  
      checkDividers();  
      lastEM=result.email;
      doCosting(document.forms['bf'],false);
    }
  }  
}

function prevVehicle(s)
{
  var v;
  if (s.selectedIndex > 0) {
    v=previousVehicles[s.selectedIndex-1];
    selectByValue(s.form.type,s.VehicleType);
    s.form.make.value=v.VehicleMake;
    s.form.rego.value=v.VehicleRego;
  } 
  else {
    s.form.make.value='';
    s.form.rego.value='';    
  }   
}

function fillVehicles(f)
{
  
  f.prevV.options.length=0;
  if (previousVehicles && previousVehicles.length > 1) {
    f.prevV.options[0]=new Option('- new vehicle -','');      
    for (var i=0; i < previousVehicles.length; i++)
      f.prevV.options[i+1]=new Option(previousVehicles[i].VehicleRego,'');
    f.prevV.selectedIndex=1;
    document.getElementById('prev-v').style.display='';
  }
  else
    document.getElementById('prev-v').style.display='none';      
}
function details_cb(dom,txt,uri)
{
  http.callback=null;
  var div=dom.document ? dom.document.getElementById('result') : dom.getElementById('result');
  var result=null;
  var f=document.forms['bf'];
  var e;
  f.rdbtn.value="Retrieve Details";
  if (div) {
    eval('result='+div.innerHTML+';');
    if (result) {
      previousVehicles=result.PreviousVehicles;  
      f.firstname.value=result.BookingFirstname;
      f.lastname.value=result.BookingSurname;
      f.phone.value=result.BookingPhone;  
      f.homePh.value=result.HomePhone;
      f.company.value=result.BookingCompanyName;
      f.street.value=result.StreetOrigin;
      f.origin.value=result.Origin;
      selectByValue(f.state,result.StateOrigin);
      f.f_dest.value=result.FlightDestination;
      selectByValue(f.type,result.VehicleType);
      f.make.value=result.VehicleMake;
      f.rego.value=result.VehicleRego;
      f.adults.value=result.Adults;
      f.children.value=result.Children ? result.Children : '';
      f.infants.value=result.Infants ? result.Infants : '';
      f.payby[parseInt(result.PaymentMethod)-1].checked=true;
      f.tax.checked=result.TaxInvoice=="1";
      f.__cid.value=result.ContactID;
      togglePayment(f);
      if (e=document.getElementById('t_remember')) {
        e.style.display='none';  
      }
      // insert credit card details.....
      if (result.PaymentMethod=="2" && result.CardNumber.length) {
        // insert a row for the option....
        var tr=document.getElementById('bf_c_1');
        tr.style.display='none';
        document.getElementById('bf_c_0').style.display='';
        document.getElementById('bf_c_2').style.display='none';
        document.getElementById('bf_c_3').style.display='none';
        var table=getParent(tr,'table');
        tr=table.insertRow(tr.rowIndex);
        tr.id='bf_c_4';
        var td=tr.insertCell(0);    
        td.colSpan=2;
        td.innerHTML='<input onclick="togglePayment(this.form)" type="radio" value="'+result.BookingID+'" name="cc_exist" checked="checked" /> Use previous card '+result.CardNumber+' Exp: '+result.CardExpiry
                    +'<br /><input onclick="togglePayment(this.form)" type="radio" name="cc_exist" value="" />Enter new card details';
      }
      // open up form
      fillVehicles(f);
      document.getElementById('cbd').style.display='block';
      document.getElementById('cbd2').style.display='block';
      alert('Booking details retrieved.  Please continue to quote.');  
    }
  }
  if (!result)
    alert("Unable to retrieve previous details.  Check your email address and password are correct and try again.")  ;
}

function retrieveDetails(ib)
{
  if (ib.form.r_p_pwd.value=='') {
    alert('Please enter your password');
    ib.form.r_p_pwd.focus();
    return;    
  }
  http.callback=details_cb;
  var e;
  if (e=document.getElementById('bf_c_4')) 
    getParent(e,'table').deleteRow(e.rowIndex);
  ib.value="Please wait...";
  http.load('_rdetails?e='+ib.form.email.value+'&p='+hex_md5(ib.form.r_p_pwd.value));        
}

function getParent(e,tag)
{
  var p=e.parentNode;
  while (p && p.tagName.toLowerCase() != tag.toLowerCase())
    p=p.parentNode;
  return p;        
}

function forgot_cb(dom,text,uri)
{
  http.callback=null;
  var div=dom.document ? dom.document.getElementById('result') : dom.getElementById('result');
  if (div)
    alert(div.innerHTML);
  else
    alert('There was a problem retrieving your password.');  

}
function forgotPwd(ib)
{
  http.callback=forgot_cb; 
  http.load('_forgotpw?e='+document.forms['bf'].email.value);   
}

function travellingWC(wc)
{
  document.getElementById('t_twc').style.display=wc.checked ? 'block' : 'none';    
  checkDividers();
  
}

function quotePageCost()
{
  var outd=getDateTime('pu');
  var ind=getDateTime('do');
  f=document.forms['bf'];
  if (outd && ind && outd.getTime() > ind.getTime()) {
      d=parseInt((outd.getTime()-ind.getTime()+3600000)/86400000)+1;
      f.days.value=d+' calendar days';
      f.cost.value='$'+calcRate(ind,d,f.oversized[1].checked,typeof(f.undercover)=='undefined' ? 0 : f.undercover[1].checked);
  } 
  else {
    f.cost.value='';
    f.days.value='';    
  } 
}

function unconf(un)
{
  document.getElementById('v_out_t_n').style.display=un ? 'none' : '';    
  document.getElementById('q_tab').style.display=un ? 'none' : '';    
  document.getElementById('q_untab').style.display=un ? '' : 'none';    
  doCosting(document.forms['bf'],true);
}

function nextTestimonial()
{
  new Ajax.Updater('tm-r','_ajax.testimonial.html');    
}

function initTestimonials()
{
  nextTestimonial();
  window.setInterval('nextTestimonial()',20000);    
}

function initCMap()
{
  gmap = new google.maps.Map(document.getElementById("cmap"),{
                    mapTypeId: google.maps.MapTypeId.ROADMAP,
                    mapTypeControl:true,
                    navigationControl: true,
                    scrollwhell:false,
                    streetViewControl:true,
                    zoom:17,
                    center:capm=new google.maps.LatLng(-16.89816,145.75780)
                });
  new google.maps.Marker({
          draggable:false,
          map: gmap,
          position: capm
  });                  
 
  gds=new google.maps.DirectionsService;
  gdr=new google.maps.DirectionsRenderer;     
}

function get_dir(o)
{
  gds.route({
        destination: capm,
        origin:o+',Australia',
        travelMode:google.maps.DirectionsTravelMode.DRIVING
      },
      function(result,status) {
        switch (status) {
          case google.maps.DirectionsStatus.NOT_FOUND:
            createPopup('Cairns Airport Parking','Unable to locate your address.<br /><br />Be sure you have entered both the street and suburb correctly.<br /><br />Alternatively try a main road nearby or drop the street number.',true,true);    
            break;
          case google.maps.DirectionsStatus.ZERO_RESULTS:
            createPopup('Cairns Airport Parking','Unable to find a route between your address and Cairns Airport Parking.<br /><br />Try using a main road nearby as your address.',true,true);    
            break;
          case google.maps.DirectionsStatus.OK:  
            gdr.setMap(null);
            gdr.setPanel(null);
            gdr.setMap(gmap);
            gdr.setPanel(document.getElementById('map-directions'));
            gdr.setDirections(result);
            break;
          default:
            createPopup('Cairns Airport Parking','There was a problem processing your request.<br /><br />The server may be busy or other network error may have occurred.<br /><br />Try again soon.',true,true);    
            break;
        }      
      }
  );    
}
