var gds=null;
var gdr=null;
var dropoffClosed=false;

function validate_enquiry(f)
{
  if (f.name.value=='') {
    alert('Please enter your name');
    f.name.focus();
    return false;
  }  
  if (f.phone.value=='' && f.email.value=='') {
    alert('Please enter your phone or email');
    f.phone.focus();
    return false;
  }  
  if (f.email.value.length && !validateEmailv2(f.email.value)) {
    alert('Please enter a valid email');
    f.email.focus();
    return false;
  }  
  if (f.v.value=='') {
    alert('Please enter the anti-spam code as shown');
    f.v.focus();
    return false;
  }  

  return true;    
}

function pickupDisplay(f)
{
  if (f.t_out.checked) {
    $('fa_k_r1').style.display=f.v_out_dr[0].checked ? '' : 'none';  
    $('fa_k_r2').style.display=f.v_out_dr[0].checked ? '' : 'none';  
    $('q_untab').style.display=f.v_out_dr[1].checked ? '' : 'none';
    $('q_tab').style.display=f.v_out_dr[1].checked ? 'none' : '';
    $('fa_out_t').style.display=(f.v_out_dr[0].checked && f.t_tbaout[0].checked) ? '' : 'none';
    $('v_out_t_n').style.display=(f.v_out_dr[0].checked && f.t_tbaout[1].checked) ? '' : 'none';
  }  
  else {  // no valet
    $('fa_k_r1').style.display='none';  
    $('fa_k_r2').style.display='none';  
    $('fa_out_t').style.display='none';
    $('v_out_t_n').style.display=f.v_out_dr[0].checked ? '' : 'none';
    $('q_untab').style.display=f.v_out_dr[1].checked ? '' : 'none';
    $('q_tab').style.display=f.v_out_dr[1].checked ? 'none' : '';
  }
  // pickup time style - will be hidden by parent table anyway
  $('pu_time').style.display=f.pu_time_k[0].checked ? '' : 'none';
  checkDividers();
}

function returnTimeUnknown(f)                                     
{
  // hide pu alert in case they have been changing things around
  if (f.pu_time_k[1].checked)
    set_lb_val(f.d_time,'1200');        // set to midday
  else {
    f.d_time.selectedIndex=0;  
    $('d_time_').innerHTML='';
  }  
  $('pu_alert').style.display='none';
  $('efc').style.display='none';
  pickupDisplay(f); 
  doCosting(f,true);    
}



function initCallbacks()
{
  var list=['year','month','day','time'];
  var f=document.forms['bf'];
  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);
  pickupDisplay(f);
  if (f.category) 
    f.category.onchange=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
    $('cbd2').style.display='block'; 
    $('cbd').style.display='block';
    if (f.d_time.selectedIndex)
      timeChangedCB(f.d_time);  // in case of late night pickup
    else  
      doCosting(f,true);
    checkDividers();    
  }
  //ajx call backs
  if (f.elements['rdbtn']) {
    f.elements['rdbtn'].onclick=function() { retrieveDetails2(this); };
    f.elements['fpbtn'].onclick=function() { forgotPwd2(this); };
  }
  if (typeof(b_sd)=='undefined') {
    f.elements['t_in'].onclick=function() { tg_vin(this); };
    f.elements['t_tbain'][0].onclick=function() { tg_fdk(1); };
    f.elements['t_tbain'][1].onclick=function() { tg_fdk(0); };

    f.elements['fo_dt'][0].onclick=changeTerminal;
    f.elements['fo_dt'][1].onclick=changeTerminal;
  }
  
  f.elements['t_out'].onclick=function() { pickupDisplay(this.form); };
  
  f.elements['t_tbaout'][0].onclick=function() { pickupDisplay(this.form); };
  f.elements['t_tbaout'][1].onclick=function() {pickupDisplay(this.form); };

  f.elements['v_out_dr'][0].onclick=function() { pickupDisplay(this.form); if (maxSpace) doCosting(f,true); };
  f.elements['v_out_dr'][1].onclick=function() { pickupDisplay(this.form); if (maxSpace) doCosting(f,true); };

  f.elements['pu_time_k'][0].onclick=function() { returnTimeUnknown(this.form); };
  f.elements['pu_time_k'][1].onclick=function() { returnTimeUnknown(this.form); };
  
  f.elements['twc'].onclick=function() { travellingWC(this); };

  for (var i=0; i <= 3; i++)
    f.elements['payby'][i].onclick=function() { togglePayment(this.form); };

  f.elements['prevV'].onchange=function() { prevVehicle(this) };
  
  startup=false;
}
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,get_lb_val(f.category),typeof(f.undercover)=='undefined' ? 0 : f.undercover[1].checked);
  } 
  else {
    f.cost.value='';
    f.days.value='';    
  } 
}
function initQuotePage()
{
  var y=new Date;
  y.setTime(y.getTime()-86400000);

  calendarCtl=init_calendar_view(document.forms['bf'],setCalendarDates_quote);
  var f=document.forms['bf'];
  for (var i=0; i < f.elements.length; i++)
    if (!f.elements[i].readonly)
      f.elements[i].onchange=quotePageCost;
  quotePageCost();    
}

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

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'];
  if (f) {
    var frame=$('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 tg_fdk(on)
{
  $('fd_in_t').style.display=on ? '' : 'none';
  $('v_in_t').style.display='';
  checkDividers();
}



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

 
function checkEarlyFlight(f)
{
  var t=9999,ed,e=f.d_time,efc=$('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'; 
      
}

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=$('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) {
          $('col3').style.display='none'; 
          a.className='prevent';       
        }  
        else {
          $('col3').style.display='block'; 
          a.className='';       
            
        }
        return;                                                    
      }  

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

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());
      timeChangedCB(f.a_time);                             
      dateChangedCB(f.a_day);
      if ($('drop-suggest') && $('drop-suggest').style.display != 'block')
        $('drop-suggest').style.display='block';
    }  
  }
}

/* ajax functions & callbacks */
function retrieve_details_cb2(response)
{
  var e;
  document.body.removeChild($('loading'));
  //document.body.removeChild($('shadow'));
  if (e=$('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);    
    sendNotice('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.');    
  }    
  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',result.error ? result.error : '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);    
      sendNotice(result.error ? result.error : '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.');    
      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=$('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=$('bf_c_1');
      tr.style.display='none';
      $('bf_c_0').style.display='';
      $('bf_c_2').style.display='none';
      $('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';
    }
    fillVehicles(f);
  }
}
function email_cb2(response)
{
  var f=document.forms['bf'];
  if (response.status==200 && response.responseJSON) {
    userDiscount=parseInt(response.responseJSON.userDiscount);
      if ((e=$('wom')) && parseInt(response.responseJSON.existingClient) > 0) {
        e.style.display='none';
        f.found.selectedIndex=-1;    
      }
      else if (e)
        e.style.display='block';
      if ((e=$('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 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_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 retrieveDetails2(e)
{
  var f=e.form;
  if (f.email.value=='') { 
    sendNotice('Please enter the email address you used for your previous booking.<br /><br />');
    return createPopup('Email Address Required','Please enter the email address you used for your previous booking.<br /><br />',true,false);
  }
  if (!validateEmailv2(f.email.value)) { 
    sendNotice('The email address you entered appears to be invalid. Check you have entered a full email address correctly without any spaces and try again.<br /><br />');
    return createPopup('Check Email Address','The email address you entered appears to be invalid. Check you have entered a full email address correctly without any spaces and try again.<br /><br />',true,false);
  }
  if (f.r_p_pwd.value=='') { 
    sendNotice('Please enter your booking passowrd.  Note the password is case sensitive so must be entered exactly as you did when you set the password.<br /><br />');
    return createPopup('Email Address Required','Please enter your booking password.  Note the password is case sensitive so must be entered exactly as you did when you set the password.<br /><br />',true,false);
  }
  
  pleaseWait();
  
  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 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;
    $('prev-v').style.display='';
  }
  else
    $('prev-v').style.display='none';      
}

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 doBooking()
{
  var f=document.getElementById('bf');
  if (f.onsubmit())
    f.submit();
}

function togglePayment(f)
{
  var s=f.payby[1].checked ? '' : 'none';
  if ($('bf_c_4'))    
    $('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';
  $('bf_c_0').style.display=f.payby[1].checked ? '' : 'none';  
  for (var i=1; i <=3 ; i++)
    $('bf_c_'+i).style.display=s;
  checkDividers();   
  updateCostSummary(f);       
}



function initBookingPage()
{
  if (!document.forms['bf'])
    return;
  initCallbacks(true);
  var y=new Date;
  y.setTime(y.getTime()-86400000);
  calendarCtl=init_calendar_view(document.forms['bf'],setCalendarDates);
  var supernote = new SuperNote('helpnote', {});
  document.forms['bf'].elements['email'].onblur=email_changed2;
}

function setCalendarDates(f,y,m,d)
{
  set_lb_val(f.elements[calendarMode+'_year'],y);
  f.elements[calendarMode+'_day'].selectedIndex=d;
  f.elements[calendarMode+'_month'].selectedIndex=m;
  dateChangedCB(f.elements[calendarMode+'_day']);
}

// 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);
  $(prefix+'_dow').innerHTML=dt ? formatDate(dt,'EE') : 'check date above'; 
  
  if (prefix=='d' /*&& $('v_out_t_n').style.display=='none'*/) {
    // copy to our pickup 
    f.ea_day.selectedIndex=f.d_day.selectedIndex;    
    f.ea_month.selectedIndex=f.d_month.selectedIndex;    
    f.ea_year.selectedIndex=f.d_year.selectedIndex;   
    //dateChangedCB(f.d_day); 
  }  
  else if (prefix=='ea' /*&& $('v_out_t_n').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();   
}

// 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);   
  }    
  $(e.name+'_').innerHTML=s;
  if (e.name=='d_time')
    e.form.ea_time.selectedIndex=e.form.d_time.selectedIndex;    
  else if (e.name=='ea_time' /*&& $('v_out_t_n').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)) {
    $('pu_alert').style.display='block';    
  }
  else if ((e.name=='ea_time' || e.name=='d_time') && $('pu_alert').style.display != 'none')
    $('pu_alert').style.display='none';  
  if (e.name=='a_time' && dropoff_closed_from)
    if (e.selectedIndex > 0 && (t >= dropoff_closed_from || t < dropoff_closed_to)) {
      // can't proceed
      if ($('do_alert').style.display != 'block')
        sendNotice('Trying to dropoff outside hours');
      $('do_alert').style.display='block';
      $('complete-booking').style.display='none';
      $('q_tab').style.display='none';
      dropoffClosed=true;  
    }
    else {
      $('do_alert').style.display='none';   
      dropoffClosed=false; 
      // let docosting re-issue availability check with should fix any hidden elements if changing back to normal time
    }
  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 tg_vin(c)
{
  if (!c)
    return;
  $('fd_k_r1').style.display=c.checked ? '' : 'none';
  $('fd_k_r2').style.display=c.checked ? '' : 'none';
  
  $('fd_in_t').style.display=(c.checked && c.form.t_tbain[0].checked) ? '' : 'none';
  $('v_in_t').style.display=(!c.checked || c.form.t_tbain[0].checked || c.form.t_tbain[1].checked) ? '' : 'none';
  checkDividers();
}

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

function checkAvailability(dateIn,dateOut)
{
  if (dropoffClosed)
    return;
  $('q_tab').style.display='none';
  $('avail-ch').style.display='block';
  
  new Ajax.Request('_ajax.availability.html',{
      parameters: {i:formatDate(dateIn,'yyyy-MM-dd'),o:dateOut ? formatDate(dateOut,'yyyy-MM-dd') : null },
      onComplete: function(response) {
        $('avail-ch').style.display='none';
        if (response.status != 200) {    
          createPopup('Cairns Airport Parking - Network Error','There was a communication problem trying to check availability.<br />The Internet connection may have timed out or some other network error has occurred.<br /><br />Please try again.  If the problem persists please contact us on 07 4053 5171',true,false);    
          sendNotice('There was a communication problem trying to check availability.<br />The Internet connection may have timed out or some other network error has occurred.<br /><br />Please try again.  If the problem persists please contact us on 07 4053 5171');    
        }    
        else {
          $('complete-booking').style.display=!response.responseJSON.available ? 'none' : 'block';
          $('q_tab').style.display=!response.responseJSON.available || !dateOut  ? 'none' : 'block';
          $('pa-full').style.display=!response.responseJSON.available ? 'block' : 'none';
          $('avail').style.display=!response.responseJSON.available || !dateOut ? 'none' : 'block';
          if (!response.responseJSON.available) {
            createPopup('Cairns Airport Parking - Car Park Full','The car park is full during the period you have nominated.');
            sendNotice('Car Park Full - '+response.responseJSON.reason);
          }
        } 
        checkDividers(); 
      }
  });
}

function doCosting(f,calc)
{
    if (__newCosting) {
      doCosting2(f,calc);
      return;    
    }
    // calc diff in dates
    var d,h,n,y,ex,m,ind,outd,f,rate;
    error='';
    f.days.value='';
    f.cost.value='';
    f.total.value='';
    if (maxSpace) {
      $('pa-full').style.display='none';
      $('avail').style.display='none';
    }
    $('aad_1').style.display='none';
    $('aad_2').style.display='none';
    
    if (calc) {
      dateIn=typeof(b_sd)=='undefined' ? getDateTime('a') : b_sd;
      // check for unknown option
      if (f.v_out_dr[0].checked) {
        // we can ignore pickup time if our pickup table is displayed and answered no to knowing approx time  
        if ($('v_out_t_n').style.display !=' none' && f.pu_time_k[1].checked) {
          if (dateOut=getDateTime('d',true)) // no time - will be midnight    
            dateOut.setTime(dateOut.getTime()+12*3600*1000);  // add 12 hrs to make midday  
        }
        else
          dateOut=getDateTime('d');    
      }    
      else
        dateOut=null;  
    }
    if (!dateIn ||!dateOut) {
      if (!dateIn)
        error='Your drop off date is invalid.  Check date and time.';
      else if ($('q_untab').style.display=='none')    
        error='Your pickup date is invalid.  Check date and time.';
      if (maxSpace > 0 && dateIn && $('q_untab').style.display != 'none')
        checkAvailability(dateIn,null);
      else  
        $('avail').style.display='none';
      updateCostSummary(f);
      return;
    }  
    if (typeof(b_sd)=='undefined' && dateIn.getTime() < now.getTime()) {
      $('bf_co').innerHTML=(error='Your vehicle drop off can not be in the past');
      $('avail').style.display='none';
      updateCostSummary(f);
      return;  
    }
    y=(dateOut.getTime()-dateIn.getTime())/1000;        // total seconds

    if (y < 0) { 
      $('bf_co').innerHTML=(error='Your date out is before your date in - check dates');
      $('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,get_lb_val(f.category),typeof(f.undercover)=='undefined' ? 0 : f.undercover[0].checked,$('pu_alert').style.display=='block' && !noah);
      if ($('pu_alert').style.display=='block' && lateDiscount > 0.01) {
        $('aad_1').style.display='';
        $('aad_2').style.display='';
        f.base.value=formatCurrency(m+lateDiscount);
      }  
      f.__lds.value=formatCurrency(lateDiscount);
      // check discount
      if (userDiscount > 0) {
        f.total.value=formatCurrency(m);
        f.discount.value=userDiscount+'%';
        $('dpc_1').style.display='';
        $('dpc_2').style.display='';
        m=parseInt(m*(100.0-userDiscount))/100.0;
      }  
      else {
        $('dpc_1').style.display='none';
        $('dpc_2').style.display='none';
      }
      if (f.days)
        f.days.value=d;
      f.cost.value=formatCurrency(m);
      $('bf_co').innerHTML='';  
      if (maxSpace > 0)
        checkAvailability(dateIn,dateOut);
      else  
        $('avail').style.display='block';
    }  
    updateCostSummary(f);
}

function doCosting2(f,calc)
{
    // calc diff in dates
    var d,h,n,y,ex,m,ind,outd,f,rate,category;
    error='';
    f.days.value='';
    f.cost.value='';
    f.total.value='';
    if (maxSpace) {
      $('pa-full').style.display='none';
      $('avail').style.display='none';
    }
    $('aad_1').style.display='none';
    $('aad_2').style.display='none';
    
    category=get_lb_val(f.category);
    if (calc) {
      dateIn=typeof(b_sd)=='undefined' ? getDateTime('a') : b_sd;
      // check for unknown option
      if (f.v_out_dr[0].checked) {
        // we can ignore pickup time if our pickup table is displayed and answered no to knowing approx time  
        if ($('v_out_t_n').style.display !=' none' && f.pu_time_k[1].checked) {
          if (dateOut=getDateTime('d',true)) // no time - will be midnight    
            dateOut.setTime(dateOut.getTime()+12*3600*1000);  // add 12 hrs to make midday  
        }
        else
          dateOut=getDateTime('d');    
      }    
      else
        dateOut=null;  
    }
    if (!dateIn ||!dateOut) {
      if (!dateIn)
        error='Your drop off date is invalid.  Check date and time.';
      else if ($('q_untab').style.display=='none')    
        error='Your pickup date is invalid.  Check date and time.';
      if (maxSpace > 0 && dateIn && $('q_untab').style.display != 'none')
        checkAvailability2(dateIn,null,category,f.email.value);
      else  
        $('avail').style.display='none';
      updateCostSummary(f);
      return;
    }  
    if (typeof(b_sd)=='undefined' && dateIn.getTime() < now.getTime()) {
      $('bf_co').innerHTML=(error='Your vehicle drop off can not be in the past');
      $('avail').style.display='none';
      updateCostSummary(f);
      return;  
    }
    y=(dateOut.getTime()-dateIn.getTime())/1000;        // total seconds

    if (y < 0) { 
      $('bf_co').innerHTML=(error='Your date out is before your date in - check dates');
      $('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,get_lb_val(f.category),typeof(f.undercover)=='undefined' ? 0 : f.undercover[0].checked,$('pu_alert').style.display=='block' && !noah);
      if ($('pu_alert').style.display=='block' && lateDiscount > 0.01) {
        $('aad_1').style.display='';
        $('aad_2').style.display='';
        f.base.value=formatCurrency(m+lateDiscount);
      }  
      f.__lds.value=formatCurrency(lateDiscount);
      // check discount
      if (userDiscount > 0) {
        f.total.value=formatCurrency(m);
        f.discount.value=userDiscount+'%';
        $('dpc_1').style.display='';
        $('dpc_2').style.display='';
        m=parseInt(m*(100.0-userDiscount))/100.0;
      }  
      else {
        $('dpc_1').style.display='none';
        $('dpc_2').style.display='none';
      }
      if (f.days)
        f.days.value=d;
      f.cost.value=formatCurrency(m);
      $('bf_co').innerHTML='';  
      if (maxSpace > 0)
        checkAvailability2(dateIn,dateOut,category,f.email.value);
      else  
        $('avail').style.display='block';
    }  
    updateCostSummary(f);
}

function updateCostSummary(f)
{
  var html='';
  var total=0.0;
  f.__ccf.value='0';
  if (!f.payby[0].checked && !f.payby[1].checked && !f.payby[2].checked && !f.payby[3].checked) {
    $('cost_parking').innerHTML='- select payment method above -';
    return;    
  }
  var q=$('q_untab');
  if ($('q_untab').style.display != 'none') {
    html='Cost can not be calculated until return date known';
    if (f.payby[1].checked)
      html+='<br/><strong>'+formatCurrency(cardProcessingFee)+' processing fees applies to credit card payments</strong>';    
    else if (f.payby[3].checked)
      html+='<br/><strong>'+formatCurrency(eftposProcessingFee)+' processing fees applies to eftpos payments</strong>';    
  } 
  else if (f.cost.value=='') {
    html='Check your dates above.';    
  }  
  else if (f.cost.value==0) {
    html='$0.00';    
  } 
  else if (!f.payby[1].checked && !f.payby[3].checked) {
    html='<strong>'+f.cost.value+' including GST</strong>';
  }
  else {    
    html='<table cellpadding="0" cellspacing="4"><tr><th>Fee for parking</th><td>'+f.cost.value+'</td><td>&nbsp;</td></tr>';
    total=parseFloat(f.cost.value.substring(1));
      html+='<tr><th>'+(f.payby[1].checked ? 'Credit card' : 'Eftpos')+' processing fee</th><td>'+formatCurrency(f.payby[1].checked ? cardProcessingFee : eftposProcessingFee)+'</td><td>&nbsp;</td></tr>';    
      total+=f.payby[1].checked ? cardProcessingFee : eftposProcessingFee;
      html+='<tr class="t"><th>Total due on return</th><td>'+formatCurrency(total)+'</td><td>including GST</td></tr>';    
    html+='</table>';
    f.__ccf.value=f.payby[1].checked ? cardProcessingFee : eftposProcessingFee;
  }
  $('cost_parking').innerHTML=html;
}

function validate_booking(theForm)
{
  var e;
  if (formPosted)
    return false;
  resetError(); 
  dateIn=dateOut=null;
  if ($('alert') && preventBooking) {
    showNotice($('alert').innerHTML);
    sendNotice($('alert').innerHTML);
    return false;    
  }
  // first section
  if (theForm.email.value=="") {
    setError("Please enter an email address.  If you don't have an email address you can use your_phone_number@cairnsparking.com eg.0488535171@cairnsparking.com.  Be sure not to include spaces.",'email');
  }
  else if (!validateEmailv2(theForm.email.value)) {
    setError("The email address you entered <span style=\"font-size:16px;color:#ff0000\">"+theForm.email.value+"</span> doesn't appear to be a valid email address. Check your email address and try again.",'email');
  }
  if (theForm.firstname.value=="") {
    setError("Please enter your firstname.",'firstname');
  }
  if (theForm.lastname.value=="") {
    setError("Please enter your lastname.",'lastname');
  }
  if (theForm.phone.value=="") {
    setError("Please enter your contact mobile number whilst travelling",'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','tbain');    
      else if (theForm.t_tbain[0].checked) {
        if (!getDateTime('fo'))
          setError('Enter a valid date and time for your flight departing Cairns','flightout');
      }
    }  
    if (!theForm.t_in.checked || theForm.t_tbain[0].checked || theForm.t_tbain[1].checked) {
      if (!(dateIn=getDateTime('a')))  
        setError('Enter a valid date and time for your vehicle drop off','dropoff');
      if (theForm.f_dest.value=='')
        setError('Please indicate where you are travelling to.','dest');   
    }    
  } 
  // step 2 - pickup
  if (theForm.t_out.checked) {
    if (!theForm.v_out_dr[0].checked && !theForm.v_out_dr[1].checked) {
      setError('Please indicate whether you know your approximate return date','approxin');    
    }
    else if (theForm.v_out_dr[0].checked) {
      if (!theForm.t_tbaout[0].checked && !theForm.t_tbaout[1].checked)
        setError('Please indicate whether you know your arriving flight details','tbaout');    
      else if (theForm.t_tbaout[0].checked && !(dateOut=getDateTime('ea')))
        setError('Please enter a valid date and time for your arrival flight','flightin');
      else 
        if (theForm.t_tbaout[1].checked) {    
          if (!theForm.pu_time_k[0].checked && !(dateOut=getDateTime('d',true)))        // if ticked nothing yet or ticked unknown check date at least
            setError('Please enter a valid date for your approximate pickup','pickup');  
          if (!theForm.pu_time_k[0].checked && !theForm.pu_time_k[1].checked)
            setError('Please indicate whether you know your approximate return time','pickuptime');  
          else if (theForm.pu_time_k[0].checked && !(dateOut=getDateTime('d')))   // recheck with time now
            setError('Please enter a valid date and time for your approximate pickup','pickup');  
        }      
      }
  }
  else {  // no valet
      if (!theForm.v_out_dr[0].checked && !theForm.v_out_dr[1].checked) {
        setError('Please indicate whether you know your approximate return date','approxin');    
      }
      else if (theForm.v_out_dr[0].checked && !(dateOut=getDateTime('d'))) 
        setError('Please enter a valid date and time for your approximate pickup','dropoff')  
  }
  
  if (dateIn) {
    var t=new Date();
    now.setTime(now.getTime()+t.getTime()-startBooking.getTime());
    startBooking.setTime(t.getTime());
    if (dateIn.getTime() < now.getTime())  
      setError('Vehicle drop off date and time can not be in the past. Check your drop off date and time.  You have entered '+formatDate(dateIn,'dd-MMM @ h:mma'),'dropoff');        
  }
  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 ($('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.",'baggage');
  }
  
  // step 2 - vehicle category
  if (theForm.category.selectedIndex <= 0)
    setError('Nominate your vehicle category - standard, oversized or motorcycle','category');
  
  // step 3 
  if (theForm.homePh.value=="") {
    setError('Please enter your home phone number','homeph');
  }
  if (theForm.street.value=="") {
    setError('Please enter your home street address','street');
  }
  if (theForm.origin.value=="") {
    setError('Please enter your home town/suburb','origin');
  }
 if ((e=$('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.','password');
   }
 }

  // step 3 
  if (theForm.type.selectedIndex <= 0) {
    setError("Please select your vehicle type",'type');
  }
  if (theForm.rego.value=="") {
    setError("Please enter your vehicle registration",'rego');
  }
  if (theForm.adults.value=='' || parseInt(theForm.adults.value) <1) {
    setError('Please nominate the number of adults travelling','adults');
  }
  if (theForm.infants.value.length && parseInt(theForm.infants.value) > 0 && !theForm.infantSeat[0].checked && !theForm.infantSeat[1].checked)
    setError("If travelling with infants specify whether you require rear or forward facing capsule",'infantseat');
    
  // step 4
  if (!theForm.payby[0].checked && !theForm.payby[1].checked && !theForm.payby[2].checked && !theForm.payby[3].checked) {
    setError("Please nominate your preferred payment method on drop off",'method');
  }
  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.",'cardno');
    }
    if (theForm.c_exp_m.selectedIndex <= 0) {
      setError("Please enter your card expiry month",'cardexp');
    }
    if (theForm.c_exp_y.selectedIndex <= 0) {
      setError("Please enter your card expiry year",'cardexp');
    }
  }                                                                    

  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.','terms');
  }
 
 if (globalError) {
   showError('Cairns Airport Parking - Unable to submit booking');
   setLabels(theForm);
   sendNotice('<ul>'+globalError+'</ul>');
   return false;
 }
  return formPosted=true;
}

function sendNotice(msg)
{
   $('bf').__msg.value=msg;
   new Ajax.Request('_ajax.email-notice.html',{
      parameters: $('bf').serialize()
   });    
   $('bf').__msg.value='';
    
}

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;
        }      
      }
  );    
}

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

/* support functions */
function s_close()
{
  $('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=$(id);
  f=document.forms['bf'];
  var now=new Date();
  f.__sbtz.value=now.toString();
  var frame=$('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 checkAvailability2(dateIn,dateOut,cat,email)
{
  if (dropoffClosed)
    return;
  $('q_tab').style.display='none';
  $('avail-ch').style.display='block';

  new Ajax.Request('_ajax.availability2.html',{
      parameters: {
          i:formatDate(dateIn,'yyyy-MM-dd HH:mm'),
          o:dateOut ? formatDate(dateOut,'yyyy-MM-dd HH:mm') : null,
          c:cat,
          e:email  
      },
      onComplete: function(response) {
        $('avail-ch').style.display='none';
        if (response.status != 200) {    
          createPopup('Cairns Airport Parking - Network Error','There was a communication problem trying to check availability.<br />The Internet connection may have timed out or some other network error has occurred.<br /><br />Please try again.  If the problem persists please contact us on 07 4053 5171',true,false);    
          sendNotice('There was a communication problem trying to check availability.<br />The Internet connection may have timed out or some other network error has occurred.<br /><br />Please try again.  If the problem persists please contact us on 07 4053 5171');    
        }    
        else {
          $('complete-booking').style.display=!response.responseJSON.available ? 'none' : 'block';
          $('q_tab').style.display=!response.responseJSON.available || !dateOut  ? 'none' : 'block';
          $('pa-full').style.display=!response.responseJSON.available ? 'block' : 'none';
          $('avail').style.display=!response.responseJSON.available || !dateOut ? 'none' : 'block';
          if (!response.responseJSON.available) {
            createPopup('Cairns Airport Parking - Car Park Full','The car park is full during the period you have nominated.');
            sendNotice('Car Park Full - '+response.responseJSON.reason);
          }
        } 
        checkDividers(); 
      }
  });
}





/*
SUPERNOTE v1.0beta (c) 2005-2006 Angus Turnbull, http://www.twinhelix.com
Altering this notice or redistributing this file is prohibited.
*/
if(typeof addEvent!='function'){var addEvent=function(o,t,f,l){var d='addEventListener',n='on'+t,rO=o,rT=t,rF=f,rL=l;if(o[d]&&!l)return o[d](t,f,false);if(!o._evts)o._evts={};if(!o._evts[t]){o._evts[t]=o[n]?{b:o[n]}:{};o[n]=new Function('e','var r=true,o=this,a=o._evts["'+t+'"],i;for(i in a){o._f=a[i];r=o._f(e||window.event)!=false&&r;o._f=null}return r');if(t!='unload')addEvent(window,'unload',function(){removeEvent(rO,rT,rF,rL)})}if(!f._i)f._i=addEvent._i++;o._evts[t][f._i]=f};addEvent._i=1;var removeEvent=function(o,t,f,l){var d='removeEventListener';if(o[d]&&!l)return o[d](t,f,false);if(o._evts&&o._evts[t]&&f._i)delete o._evts[t][f._i]}}function cancelEvent(e,c){e.returnValue=false;if(e.preventDefault)e.preventDefault();if(c){e.cancelBubble=true;if(e.stopPropagation)e.stopPropagation()}};function SuperNote(myName,config){var defaults={myName:myName,allowNesting:false,cssProp:'visibility',cssVis:'inherit',cssHid:'hidden',IESelectBoxFix:true,showDelay:0,hideDelay:500,animInSpeed:0.1,animOutSpeed:0.1,animations:[],mouseX:0,mouseY:0,notes:{},rootElm:null,onshow:null,onhide:null};for(var p in defaults)this[p]=(typeof config[p]=='undefined')?defaults[p]:config[p];var obj=this;addEvent(document,'mouseover',function(evt){obj.mouseHandler(evt,1)});addEvent(document,'click',function(evt){obj.mouseHandler(evt,2)});addEvent(document,'mousemove',function(evt){obj.mouseTrack(evt)});addEvent(document,'mouseout',function(evt){obj.mouseHandler(evt,0)});this.instance=SuperNote.instances.length;SuperNote.instances[this.instance]=this}SuperNote.instances=[];SuperNote.prototype.bTypes={};SuperNote.prototype.pTypes={};SuperNote.prototype.pTypes.mouseoffset=function(obj,noteID,nextVis,nextAnim){with(obj){var note=notes[noteID];if(nextVis&&!note.animating&&!note.visible){note.ref.style.left=checkWinX(mouseX,note)+'px';note.ref.style.top=checkWinY(mouseY,note)+'px'}}};SuperNote.prototype.pTypes.mousetrack=function(obj,noteID,nextVis,nextAnim){with(obj){var note=notes[noteID];if(nextVis&&!note.animating&&!note.visible){var posString='with('+myName+'){var note=notes["'+noteID+'"];note.ref.style.left=checkWinX(mouseX,note)+"px";note.ref.style.top=checkWinY(mouseY,note)+"px"}';eval(posString);obj.IEFrameFix(noteID,1);if(!note.trackTimer)note.trackTimer=setInterval(posString,50)}else if(!nextVis&&!nextAnim){clearInterval(note.trackTimer);note.trackTimer=null}}};SuperNote.prototype.pTypes.triggeroffset=function(obj,noteID,nextVis,nextAnim){with(obj){var note=notes[noteID];if(nextVis&&!note.animating&&!note.visible){var x=0,y=0,elm=note.trigRef;while(elm){x+=elm.offsetLeft;y+=elm.offsetTop;elm=elm.offsetParent}note.ref.style.left=checkWinX(x,note)+'px';note.ref.style.top=checkWinY(y,note)+'px'}}};SuperNote.prototype.bTypes.pinned=function(obj,noteID,nextVis){with(obj){return(!nextVis)?false:true}};SuperNote.prototype.docBody=function(){return document[(document.compatMode&&document.compatMode.indexOf('CSS')>-1)?'documentElement':'body']};SuperNote.prototype.getWinW=function(){return this.docBody().clientWidth||window.innerWidth||0};SuperNote.prototype.getWinH=function(){return this.docBody().clientHeight||window.innerHeight||0};SuperNote.prototype.getScrX=function(){return this.docBody().scrollLeft||window.scrollX||0};SuperNote.prototype.getScrY=function(){return this.docBody().scrollTop||window.scrollY||0};SuperNote.prototype.checkWinX=function(newX,note){with(this){return Math.max(getScrX(),Math.min(newX,getScrX()+getWinW()-note.ref.offsetWidth-8))}};SuperNote.prototype.checkWinY=function(newY,note){with(this){return Math.max(getScrY(),Math.min(newY,getScrY()+getWinH()-note.ref.offsetHeight-8))}};SuperNote.prototype.mouseTrack=function(evt){with(this){mouseX=evt.pageX||evt.clientX+getScrX()||0;mouseY=evt.pageY||evt.clientY+getScrY()||0}};SuperNote.prototype.mouseHandler=function(evt,show){with(this){if(!document.documentElement)return true;var srcElm=evt.target||evt.srcElement,trigRE=new RegExp(myName+'-(hover|click)-([a-z0-9]+)','i'),targRE=new RegExp(myName+'-(note)-([a-z0-9]+)','i'),trigFind=1,foundNotes={};if(srcElm.nodeType!=1)srcElm=srcElm.parentNode;var elm=srcElm;while(elm&&elm!=rootElm){if(targRE.test(elm.id)||(trigFind&&trigRE.test(elm.className))){if(!allowNesting)trigFind=0;var click=RegExp.$1=='click'?1:0,noteID=RegExp.$2,ref=document.getElementById(myName+'-note-'+noteID),trigRef=trigRE.test(elm.className)?elm:null;if(ref){if(!notes[noteID]){notes[noteID]={click:click,ref:ref,trigRef:null,visible:0,animating:0,timer:null};ref._sn_obj=this;ref._sn_id=noteID}var note=notes[noteID];if(!note.click||(trigRef!=srcElm))foundNotes[noteID]=true;if(!note.click||(show==2)){if(trigRef)notes[noteID].trigRef=notes[noteID].ref._sn_trig=elm;display(noteID,show);if(note.click&&(srcElm==trigRef))cancelEvent(evt)}}}if(elm._sn_trig){trigFind=1;elm=elm._sn_trig}else{elm=elm.parentNode}}if(show==2)for(var n in notes){if(notes[n].click&&notes[n].visible&&!foundNotes[n])display(n,0)}}};SuperNote.prototype.display=function(noteID,show){with(this){with(notes[noteID]){clearTimeout(timer);if(!animating||(show?!visible:visible)){var tmt=animating?1:(show?showDelay||1:hideDelay||1);timer=setTimeout('SuperNote.instances['+instance+'].setVis("'+noteID+'",'+show+',false)',tmt)}}}};SuperNote.prototype.checkType=function(noteID,nextVis,nextAnim){with(this){var note=notes[noteID],bType,pType;if((/snp-([a-z]+)/).test(note.ref.className))pType=RegExp.$1;if((/snb-([a-z]+)/).test(note.ref.className))bType=RegExp.$1;if(nextAnim&&bType&&bTypes[bType]&&(bTypes[bType](this,noteID,nextVis)==false))return false;if(pType&&pTypes[pType])pTypes[pType](this,noteID,nextVis,nextAnim);return true}};SuperNote.prototype.setVis=function(noteID,show,now){with(this){var note=notes[noteID];if(note&&checkType(noteID,show,1)||now){note.visible=show;note.animating=1;animate(noteID,show,now)}}};SuperNote.prototype.animate=function(noteID,show,now){with(this){var note=notes[noteID];if(!note.animTimer)note.animTimer=0;if(!note.animC)note.animC=0;with(note){clearTimeout(animTimer);var speed=(animations.length&&!now)?(show?animInSpeed:animOutSpeed):1;if(show&&!animC){if(onshow)this.onshow(noteID);IEFrameFix(noteID,1);ref.style[cssProp]=cssVis}animC=Math.max(0,Math.min(1,animC+speed*(show?1:-1)));if(document.getElementById&&speed<1)for(var a=0;a<animations.length;a++)animations[a](ref,animC);if(!show&&!animC){if(onhide)this.onhide(noteID);IEFrameFix(noteID,0);ref.style[cssProp]=cssHid}if(animC!=parseInt(animC)){animTimer=setTimeout(myName+'.animate("'+noteID+'",'+show+')',50)}else{checkType(noteID,animC?1:0,0);note.animating=0}}}};SuperNote.prototype.IEFrameFix=function(noteID,show){with(this){if(!window.createPopup||!IESelectBoxFix)return;var note=notes[noteID],ifr=note.iframe;if(!ifr){ifr=notes[noteID].iframe=document.createElement('iframe');ifr.style.filter='progid:DXImageTransform.Microsoft.Alpha(opacity=0)';ifr.style.position='absolute';ifr.style.borderWidth='0';note.ref.parentNode.insertBefore(ifr,note.ref.parentNode.firstChild)}if(show){ifr.style.left=note.ref.offsetLeft+'px';ifr.style.top=note.ref.offsetTop+'px';ifr.style.width=note.ref.offsetWidth+'px';ifr.style.height=note.ref.offsetHeight+'px';ifr.style.visibility='inherit'}else{ifr.style.visibility='hidden'}}};
