//--------------------------------------------------
//  IMAGE ROLLOVERS
//--------------------------------------------------

if(typeof(tamar_rollover_warnings) == 'undefined') {
  tamar_rollover_warnings = false;
}

tamar_rollovers = new Array();

function tamar_rollover(obj, onSrc, offSrc) {

  //if the objects already in the array, leave it
  for (var i=0; i<tamar_rollovers.length; i++) {
    if (obj == tamar_rollovers[i].obj) return
  }

  //assign image object to this object and create image objects
  this.obj     = obj;
  this.off     = new Image();
  this.off.src = offSrc || obj.src;
  this.on      = new Image();
 
  //see if an onSrc image was supplied
  if (onSrc) {
    //it was so set the mouseover image source the supplied one
    this.on.src = onSrc;
    
    //see if the on and off images supplied are the same. If they are fail. We only need to check here
    //as if an onSrc wasn't supplied we know they should take the form _on/_off
    if (this.off.src == this.on.src) {
      this.error_msg('image with tamar_rollover has the same mouseover/mouseout image');
      return;
    }
  } else {
    //a mouseover image was not supplied, so we're going to work it out
    //the original image should have the format imagename_off.ext
    //the new image will have the format imagename_on.ext
    
    //onSrc = /(\w*)_off\.(\w\w\w\w?)$/.exec(this.off.src)
    
    if (this.off.src.indexOf('_off') > -1) {
      //transforms the _off filename to be an _on filename
      newString = this.off.src.replace(/_off/i,"_on");
      this.on.src = newString;
    } else {
      //the image didn't follow the pattern imagename_off.ext
      this.error_msg('image with tamar_rollover failed to load a correct filename.\n(file should be called [name]_off.gif)');
      return;
    }
  }
  
  //check the mouseover images filesize to see if it has been loaded properly
  /*
  if (this.on.fileSize <= 0) {
    this.error_msg('image with tamar_rollover failed to load mouseover (on) image. '+this.on.src+' could not be found');
    return;
  }
  */
  if ((this.on.width != this.off.width || this.on.height != this.off.height) && tamar_rollover_warnings) {
    this.error_msg('warning: image with tamar_rollover, dimensions of rollover images don\'t match');
  }

  //assign this object (tamar_rollover) to variable so we can assign it in functions below
  var thisObject  = this;
  
  //create handlers for image that change the image
  obj.onmouseover = function() { obj.src = thisObject.on.src  }
  obj.onmouseout  = function() { obj.src = thisObject.off.src }
  
  //push this object into the rollovers array
  tamar_rollovers[tamar_rollovers.length] = this;
}

tamar_rollover.prototype.error_msg = function(message) {
  alert(message);
  this.obj.style.border = '3px solid #ff3333';
}


//--------------------------------------------------
//  END IMAGE ROLLOVERS
//--------------------------------------------------


//--------------------------------------------------
//  NAV
//--------------------------------------------------
    var imageRoot = "/images/nav/";

    tab_1_off = new Image();
    tab_1_off.src = imageRoot + "tab_1_off.gif";
    tab_1_on = new Image();
    tab_1_on.src = imageRoot + "tab_1_on.gif";
    
    tab_2_off = new Image();
    tab_2_off.src = imageRoot + "tab_2_off.gif";
    tab_2_on = new Image();
    tab_2_on.src = imageRoot + "tab_2_on.gif";
    
    tab_3_off = new Image();
    tab_3_off.src = imageRoot + "tab_3_off.gif";
    tab_3_on = new Image();
    tab_3_on.src = imageRoot + "tab_3_on.gif";
    
    tab_4_off = new Image();
    tab_4_off.src = imageRoot + "tab_4_off.gif";
    tab_4_on = new Image();
    tab_4_on.src = imageRoot + "tab_4_on.gif";
    
    tab_5_off = new Image();
    tab_5_off.src = imageRoot + "tab_5_off.gif";
    tab_5_on = new Image();
    tab_5_on.src = imageRoot + "tab_5_on.gif";
    
    tab_6_off = new Image();
    tab_6_off.src = imageRoot + "tab_6_off.gif";
    tab_6_on = new Image();
    tab_6_on.src = imageRoot + "tab_6_on.gif";
    

function startup(whichNav) {
    //This is required to reset the nav when the back buttong has been pressed
    //Without this two div and two rollovers will be present
    for (var d=1; d<7; d++){
      var thisSubnav = document.getElementById('subNav_'+d);
      if(thisSubnav == null) {return;}
      thisSubnav.style.visibility = 'hidden';
      imageObject = eval("tab_" + d + "_off");
      document.images["tab_" + d].src = imageObject.src;
    }
    //The display the correct rollover and div for the page.
    showDiv(whichNav,1); //show a div on page load (and init with a fresh value of 1)
}


function showDiv(id,fresh) {
//alert(tab_1_on)
  if (fresh==1) {
    prevId = 1;
  }
  if (typeof(prevId) != "undefined") {
    if (prevId != id && prevId){
      document.getElementById('subNav_'+prevId).style.visibility = 'hidden';
    }
    document.getElementById('subNav_'+id).style.visibility = 'visible';
    
    
    //highlight the new tab
    imageObject = eval("tab_" + id + "_on");
    document.images["tab_" + id].src = imageObject.src;
    
    //lowlight the previous tab if it exists
    if (prevId != id && prevId){
      imageObjectOff = eval("tab_" + prevId + "_off");
      document.images["tab_" + prevId].src = imageObjectOff.src;
    }
    prevId = id
  }

}



//--------------------------------------------------
//  END NAV
//--------------------------------------------------


//--------------------------------------------------
//  PHONE ME
//--------------------------------------------------

function popup(url, aname, theheight, thewidth, scrollers) {
  //var aname = 'popup' ;
  var winX = 0;
  var winY = 0;
  var winnX =  (screen.width-thewidth)/2;
  var winnY = (screen.height-theheight)/2;
  str_WinParams = 'top=' + winnY+',left=' + winnX +',toolbar=no,location=no,status=no,menubar=no,scrollbars=no,resizable=no,width='+thewidth+',height='+theheight;
  thewindowobject = window.open(url,aname, str_WinParams);
  if (window.focus) thewindowobject.focus()
}

//--------------------------------------------------
//  END PHONE ME
//--------------------------------------------------


//--------------------------------------------------
//  FORM SUBMIT
//--------------------------------------------------

function submitForm(which){

    //alert(document.getElementById('search'))

    if (document.layers){
            //NS 4
            formObject=document.forms[which];
            //alert(formObject)
          }                
          else if (document.all){      
              //IE 4
              formObject=document.forms[which];
              //alert(formObject)
          }
          else if (document.getElementById){
              //Standards Mode
              formObject = document.getElementById(which);
              //alert(divObject)
          }

          formObject.submit()

}

//--------------------------------------------------
//  END FORM SUBMIT
//--------------------------------------------------



//--------------------------------------------------
//  CLAIMS FORM CHECK
//--------------------------------------------------

function checkClaimsForm() {

  theForm = document.forms['main'];

  if (theForm.policyholder_name.value == '') {
  
    alert("Please fill in the policy holder's name");
    return false;
      
  }
  
  else if (theForm.policy_number.value == '') {
  
    alert("Please fill in the policy number");
    return false;
      
  }
  
  else if (theForm.name.value == '') {
  
    alert("Please fill in your name");
    return false;
  
  }
  
  else if (theForm.message.value == '') {
  
    alert("Please enter your message");
    return false;
  
  }
  
  else {
    
    return true;
  
  }

}

//--------------------------------------------------
// END CLAIMS FORM CHECK
//--------------------------------------------------



// --------------------------------------------------------------------------
// COST RUNNING CALC
// --------------------------------------------------------------------------

function strRound( number, places ) {
    if ( number < 1 ) {
        result = "0" + Math.round( number * Math.pow(10, places) );
    }
    else {
        result = "" + Math.round( number * Math.pow(10, places) );
    }

    var dp = result.length - places;
    result = result.substring(0, dp) + "." + 
             result.substring(dp, result.length);
        
    if ( number < 0 ) {
        result = "-" + result;
    }

    return result;
}


function commaFormat(num , sep) 
{ 
    var n = '' + num;
    var numl  = n.length;
    var i = n.indexOf('.');
    var fract = '';

    if (i > -1){
        numl -= n.length-i;
        fract = n.substring(i);
    }
    if (numl > 3){
        var s, dl = numl%3;
        var str = (dl > 0) ? n.substring(0,dl):'';
        var max = Math.floor(numl/3);
        for (i=0 ; i < max ; i++){
            s = n.substring(dl+i*3,dl+i*3+3);
            str += (dl==0 && i==0) ? s : sep+s;
        }
        return str+fract;
    }else return n;
}


function calcCarCost() {
 
  var loan      = document.forms['car_calculator'].loan.value;
  var insurance = document.forms['car_calculator'].insurance.value;
  var car       = document.forms['car_calculator'].car.value;
  var engine    = document.forms['car_calculator'].engine.value;
  var mileage   = document.forms['car_calculator'].mileage.value;
  var tax       = document.forms['car_calculator'].tax.value;

  var error = '';

  if (loan == '')      error += '* Loan field is empty\n';
  if (insurance == '') error += '* Insurance field is empty\n';
  if (car == '')       error += '* Please select a car\n';
  if (engine == '')    error += '* Please select an engine\n';
  if (mileage == '')   error += '* Please select a mileage\n';
  if (tax == '')       error += '* Please select a tax\n';

  if (error != '') alert (error);
  else {
  // ----------------  Constant values -----------------------
        var cover_figure    = 3.14;
    var tax_figure      = [60.50,110.00,90.75,165.00];
    var pence_per_mile  = [0.0795,0.0875,0.1115,0.1300,0.1500];
    var service_figures = [16.00,18.50,24.00,30.00,38.00];
  // ---------------------------------------------------------
    
    var which_tax    = (Number(engine) < 2 ? 0 : 2) + Number(tax);
    var tax_months   = Number(tax) == 0 ? 6.00 : 12.00;
    var pence        = pence_per_mile[Number(engine)];
    var figure       = service_figures[Number(engine)];
    var fig_per_mile = parseFloat(mileage) + 1.00;
    
    var m_tax        = tax_figure[which_tax] / tax_months;
    var m_insurance  = parseFloat(insurance) / 12;
    var m_petrol     = pence  * fig_per_mile * 5000.00 / 12;
    var m_service    = figure * fig_per_mile;
    
    var m_total      = parseFloat(loan) + m_tax + m_insurance + cover_figure + m_petrol + m_service;
    
    document.getElementById('m_loan').innerHTML      = '&pound;' + commaFormat(strRound(loan, 2), ",");
      document.getElementById('m_tax').innerHTML       = '&pound;' + commaFormat(strRound(m_tax, 2), ",");
    document.getElementById('m_insurance').innerHTML = '&pound;' + commaFormat(strRound(m_insurance, 2), ",");
    document.getElementById('m_cover').innerHTML     = '&pound;' + commaFormat(strRound(cover_figure, 2), ",");
    document.getElementById('m_petrol').innerHTML    = '&pound;' + commaFormat(strRound(m_petrol, 2), ",");
    document.getElementById('m_service').innerHTML   = '&pound;' + commaFormat(strRound(m_service, 2), ",");

      document.getElementById('m_total').innerHTML     = '&pound;' + commaFormat(strRound(m_total, 2), ",");
  }

}
// --------------------------------------------------------------------------
// END COST RUNNING CALC
// --------------------------------------------------------------------------


function matchheight(id1,id2,offset) { /* matches the heights of element with id1 and element with id2, with the offset of offset between 1 and 2 */
    if (document.getElementById(id1) && document.getElementById(id2)) { /* Only if both elements actually exist */
        var elem1 = document.getElementById(id1);
        var elem2 = document.getElementById(id2);
        if ((elem1.offsetHeight + offset) > elem2.offsetHeight) elem2.style.height = (elem1.offsetHeight + offset) + "px";
        else if (elem2.offsetHeight > (elem1.offsetHeight + offset)) elem1.style.height = (elem2.offsetHeight - offset) + "px";
    }
    return false;
}


function mortgageFormCheck() {
  var error = 0;
  var myForm = document.forms.mortgage_email;
  
  // If forename isn't there display error
  if(!myForm.forename.value) {
    document.getElementById('err_forename').className = 'red';
    error = 1;
  } else document.getElementById('err_forename').className = 'hidden';
  // If surname isn't there display error
  if(!myForm.surname.value) {
    document.getElementById('err_surname').className = 'red';
    error = 1;
  } else document.getElementById('err_surname').className = 'hidden';
  // If date of birth has en error display an error
  if(!myForm.dob_d.value.match(/^\d\d$/) || !myForm.dob_m.value.match(/^\d\d$/) || !myForm.dob_y.value.match(/^\d\d\d\d$/)) {
    document.getElementById('err_dob').className = 'red';
    error = 1;
  } else document.getElementById('err_dob').className = 'hidden';
  // If daytime telephone number has en error display error
  if(!myForm.day_tel.value.match(/^[\d+()\s]+$/)) {
    document.getElementById('err_day_tel').className = 'red';
    error = 1;
  } else document.getElementById('err_day_tel').className = 'hidden';
  // If daytime telephone number has en error display error
  if(!myForm.eve_tel.value.match(/^[\d+()\s]+$/)) {
    document.getElementById('err_eve_tel').className = 'red';
    error = 1;
  } else document.getElementById('err_eve_tel').className = 'hidden';
  // If daytime telephone number has en error display error
  if(!myForm.mob_tel.value.match(/^[\d+()\s]+$/)) {
    document.getElementById('err_mob_tel').className = 'red';
    error = 1;
  } else document.getElementById('err_mob_tel').className = 'hidden';
  // If email there but wrong format there display error
  if(myForm.email.value && !myForm.email.value.match(/^[^\s^@]+@[^\s^@]+$/)) {
    document.getElementById('err_email').className = 'red';
    error = 1;
  } else document.getElementById('err_email').className = 'hidden';
  
  if(error) return false;
  else return true;
}

//--------------------------------------------------
//  STYLE SHEET SWAPPER
//--------------------------------------------------

function formInputStyleSwapper(formName) {
    var funForm = document.forms[formName];
    
    for(var i=0; i<funForm.length; i++) {
        if(funForm[i].hasAttribute('type') && funForm[i].getAttribute('type') == 'text') {
            funForm[i].addEventListener('focus',styleSwapOn,true);
            funForm[i].addEventListener('blur',styleSwapOff,true);
        }
    }
    
    return false;
}

function styleSwapOn() {
    this.className ='inputBodyFocus';
}

function styleSwapOff() {
    this.className ='inputBody';
}

//--------------------------------------------------
//  END STYLE SHEET SWAPPER
//--------------------------------------------------

//--------------------------------------------------
//  MORTGAGE REPAYMENT CALC
//--------------------------------------------------


function makeFloat(theFloat){

      var optionalRateFix = theFloat
      optionalRateFix = Math.round(optionalRateFix*100).toString();
      theNewNumber = optionalRateFix.substring(0,optionalRateFix.length-2) +'.'+ optionalRateFix.substring(optionalRateFix.length-2,optionalRateFix.length);
      return theNewNumber
}

function mortgageRepayCalc() {
    if (document.forms.repay_calc.mortgage_amount.value =="" || document.forms.repay_calc.interest.value == "" || document.forms.repay_calc.years.value == "" || document.forms.repay_calc.months.value == ""){
      alert('Please complete all fields.')
    } else {
      var mortgage_amount = parseFloat(Number(document.forms.repay_calc.mortgage_amount.value.replace(/(,)/g, "")));
      var interest = parseFloat(Number(document.forms.repay_calc.interest.value.replace(/(,)/g, "")));

      var years = parseFloat(Number(document.forms.repay_calc.years.value));
      var repay_months = parseFloat(Number(document.forms.repay_calc.months.value));
      

      var rate = interest / 1200;
      var months = years * 12;
      months = months + repay_months;

      var divider = Math.pow((1 + rate), months);

      monthly_payments = (rate + (rate / (divider -1))) * mortgage_amount;


      // inflation as interest
      interest = 2.5;

      var rate = interest / 1200;
      var months = years * 12;
      months = months + repay_months;

      var divider = Math.pow((1 + rate), months);

      monthly_payments_interest = (rate + (rate / (divider -1))) * mortgage_amount;

      if (monthly_payments < 1) {
        return;
      } 

      if (document.getElementById){
        document.getElementById('monthValue').innerHTML = '&pound;' + makeFloat(monthly_payments)//.toFixed(2);
        document.getElementById('monthInterestValue').innerHTML = '&pound;' + makeFloat(monthly_payments_interest)//.toFixed(2);
      }
    }
}
