var DDSPEED = 10;
var DDTIMER = 15;

function privacy() {
	window.open( "http://www.theloansite.co.uk/privacy.htm", "myWindow", "status = 1, height = 300, width = 500, resizable = 0" )
}
function roll(img_name, img_src) {
	document.getElementById(img_name).src = img_src;
}

function showstuff(boxid){ document.getElementById(boxid).style.display="block"; }
function hidestuff(boxid){ document.getElementById(boxid).style.display="none"; }

//main function to handle the mouse events //
function ddMenu(id,d){
  var h = document.getElementById(id + '-ddheader');
  var c = document.getElementById(id + '-ddcontent');
  clearInterval(c.timer);
  if(d == 1){
	c.style.display = 'inline';  
    //clearTimeout(h.timer);
    //if(c.maxh && c.maxh <= c.offsetHeight){return}
    //else if(!c.maxh){
    //  c.style.display = 'block';
    //  c.style.height = 'auto';
    //  c.maxh = c.offsetHeight;
    //  c.style.height = '0px';
    //}
    //c.timer = setInterval(function(){ddSlide(c,1)},DDTIMER);
  }else{
	  c.style.display = 'none';
	  //h.timer = setTimeout(function(){ddCollapse(c)},50);
  }
}

// collapse the menu //
function ddCollapse(c){
  c.timer = setInterval(function(){ddSlide(c,-1)},DDTIMER);
}

// cancel the collapse if a user rolls over the dropdown //
function cancelHide(id){
  var h = document.getElementById(id + '-ddheader');
  var c = document.getElementById(id + '-ddcontent');
  c.style.display = 'inline';
  //clearTimeout(h.timer);
  //clearInterval(c.timer);
  //if(c.offsetHeight < c.maxh){
	//  c.timer = setInterval(function(){ddSlide(c,1)},DDTIMER);
  //}
}

// incrementally expand/contract the dropdown and change the opacity //
function ddSlide(c,d){
  var currh = c.offsetHeight;
  var dist;
  if(d == 1){
    dist = (Math.round((c.maxh - currh) / DDSPEED));
  }else{
    dist = (Math.round(currh / DDSPEED));
  }
  if(dist <= 1 && d == 1){
    dist = 1;
  }
  c.style.height = currh + (dist * d) + 'px';
  c.style.opacity = currh / c.maxh;
  c.style.filter = 'alpha(opacity=' + (currh * 100 / c.maxh) + ')';
  if((currh < 2 && d != 1) || (currh > (c.maxh - 2) && d == 1)){
    clearInterval(c.timer);
  }
}

function validate_form(the_form) {
	var reason = "";

	  reason += validate_required(the_form.Loan_Type);
	  reason += validate_required(the_form.loan_amount);
	  reason += validate_required(the_form.loan_purpose);
	  reason += validate_required(the_form.loan_period);

	  reason += validate_required(the_form.forename);
	  reason += validate_required(the_form.surname);
	  reason += validate_required(the_form.Date_of_Birth_Day);
	  reason += validate_required(the_form.Date_of_Birth_Month);
	  reason += validate_required(the_form.Date_of_Birth_Year);
	  reason += validate_required(the_form.address1);
	  reason += validate_required(the_form.postcode);
	  reason += validate_email(the_form.email);
	  reason += validate_phone(the_form.telephone);
	  reason += validate_phone(the_form.mobile);
	      
	  reason += validate_required(the_form.Employment);
	  reason += validate_required(the_form.Income);
	  reason += validate_required(the_form.Credit_Rating);
	  reason += validate_required(the_form.Marital);
	  
	  //reason += validate_required(the_form.OwnHome);
	  //reason += validate_required(the_form.Property);
	  //reason += validate_required(the_form.mortgage_outstanding);
	  //reason += validate_required(the_form.Homeowner_Type);
	  

	  if (reason != "") {
	    alert("Some fields need correction:\n" + reason);
	    return false;
	  }

	  return true;
}

function validate_required(field) {
    var error = "";
 
    if (field.value.length == 0 || field.value == "Please Select") {
        field.style.background = 'Yellow'; 
        error = "The required field has not been filled in.\n"
    } else {
        field.style.background = 'White';
    }
    return error;  
}

function trim(s)
{
  return s.replace(/^\s+|\s+$/, '');
}

function validate_email(field) {
    var error="";
    var tfield = trim(field.value);                        // value of field with whitespace trimmed off
    var emailFilter = /^[^@]+@[^@.]+\.[^@]*\w\w$/ ;
    var illegalChars= /[\(\)\<\>\,\;\:\\\"\[\]]/ ;
   
    if (field.value == "") {
        field.style.background = 'Yellow';
        error = "You didn't enter an email address.\n";
    } else if (!emailFilter.test(tfield)) {              //test email for illegal characters
        field.style.background = 'Yellow';
        error = "Please enter a valid email address.\n";
    } else if (field.value.match(illegalChars)) {
        field.style.background = 'Yellow';
        error = "The email address contains illegal characters.\n";
    } else {
        field.style.background = 'White';
    }
    return error;
}

function validate_phone(field) {
    var error = "";
    var stripped = field.value.replace(/[\(\)\.\-\ ]/g, '');    

   if (field.value == "") {
        error = "You didn't enter a phone number.\n";
        field.style.background = 'Yellow';
    } else if (isNaN(parseInt(stripped))) {
        error = "The phone number contains illegal characters.\n";
        field.style.background = 'Yellow';
    } else if ((stripped.length != 10) && (stripped.length != 11)) {
        error = "The phone number is the wrong length. Make sure you included an area code.\n";
        field.style.background = 'Yellow';
    } else {
        field.style.background = 'White';
    }
    return error;
}

function validate_phone2 (telephoneNumber) {

  // Convert into a string and check that we were provided with something
  var telnum = telephoneNumber + " ";
  if (telnum.length == 1)  {
     telNumberErrorNo = 1;
     return false
  }
  telnum.length = telnum.length - 1;
  
  // Don't allow country codes to be included (assumes a leading "+")
  var exp = /^(\+)[\s]*(.*)$/;
  if (exp.test(telnum) == true) {
     telNumberErrorNo = 2;
     return false;
  }
  
  // Remove spaces from the telephone number to help validation
  while (telnum.indexOf(" ")!= -1)  {
    telnum = telnum.slice (0,telnum.indexOf(" ")) + telnum.slice (telnum.indexOf(" ")+1)
  }
  
  // Remove hyphens from the telephone number to help validation
  while (telnum.indexOf("-")!= -1)  {
    telnum = telnum.slice (0,telnum.indexOf("-")) + telnum.slice (telnum.indexOf("-")+1)
  }  
  
  // Now check that all the characters are digits
  exp = /^[0-9]{10,11}$/
  if (exp.test(telnum) != true) {
     telNumberErrorNo = 3;
     return false;
  }
  
  // Now check that the first digit is 0
  exp = /^0[0-9]{9,10}$/
  if (exp.test(telnum) != true) {
     telNumberErrorNo = 4;
     return false;
  }
  
  // Finally check that the telephone number is appropriate.
  exp = /^(01|02|03|05|070|071|072|073|074|075|07624|077|078|079)[0-9]+$/;
  if (exp.test(telnum) != true) {
     telNumberErrorNo = 5;
     return false;
  }
  
  // Telephone number seems to be valid - return the stripped telehone number  
  return telnum;
}
var telNumberErrorNo = 0;
var telNumberErrors = new Array ();
telNumberErrors[0] = "Valid UK telephone number";
telNumberErrors[1] = "Telephone number not provided";
telNumberErrors[2] = "UK telephone number without the country code, please";
telNumberErrors[3] = "UK telephone numbers should contain 10 or 11 digits";
telNumberErrors[4] = "The telephone number should start with a 0";
telNumberErrors[5] = "The telephone number is either invalid or inappropriate";


/*==============================================================================

Postcode Validation

------------------------------------------------------------------------------*/

function validate_postcode (toCheck) {

  // Permitted letters depend upon their position in the postcode.
  var alpha1 = "[abcdefghijklmnoprstuwyz]";                       // Character 1
  var alpha2 = "[abcdefghklmnopqrstuvwxy]";                       // Character 2
  var alpha3 = "[abcdefghjkstuw]";                                // Character 3
  var alpha4 = "[abehmnprvwxy]";                                  // Character 4
  var alpha5 = "[abdefghjlnpqrstuwxyz]";                          // Character 5
  
  // Array holds the regular expressions for the valid postcodes
  var pcexp = new Array ();

  // Expression for postcodes: AN NAA, ANN NAA, AAN NAA, and AANN NAA
  pcexp.push (new RegExp ("^(" + alpha1 + "{1}" + alpha2 + "?[0-9]{1,2})(\\s*)([0-9]{1}" + alpha5 + "{2})$","i"));
  
  // Expression for postcodes: ANA NAA
  pcexp.push (new RegExp ("^(" + alpha1 + "{1}[0-9]{1}" + alpha3 + "{1})(\\s*)([0-9]{1}" + alpha5 + "{2})$","i"));

  // Expression for postcodes: AANA  NAA
  pcexp.push (new RegExp ("^(" + alpha1 + "{1}" + alpha2 + "?[0-9]{1}" + alpha4 +"{1})(\\s*)([0-9]{1}" + alpha5 + "{2})$","i"));
  
  // Exception for the special postcode GIR 0AA
  pcexp.push (/^(GIR)(\s*)(0AA)$/i);
  
  // Standard BFPO numbers
  pcexp.push (/^(bfpo)(\s*)([0-9]{1,4})$/i);
  
  // c/o BFPO numbers
  pcexp.push (/^(bfpo)(\s*)(c\/o\s*[0-9]{1,3})$/i);
  
  // Overseas Territories
  pcexp.push (/^([A-Z]{4})(\s*)(1ZZ)$/i);

  // Load up the string to check
  var postCode = toCheck;

  // Assume we're not going to find a valid postcode
  var valid = false;
  
  // Check the string against the types of post codes
  for ( var i=0; i<pcexp.length; i++) {
    if (pcexp[i].test(postCode)) {
    
      // The post code is valid - split the post code into component parts
      pcexp[i].exec(postCode);
      
      // Copy it back into the original string, converting it to uppercase and
      // inserting a space between the inward and outward codes
      postCode = RegExp.$1.toUpperCase() + " " + RegExp.$3.toUpperCase();
      
      // If it is a BFPO c/o type postcode, tidy up the "c/o" part
      postCode = postCode.replace (/C\/O\s*/,"c/o ");
      
      // Load new postcode back into the form element
      valid = true;
      
      // Remember that we have found that the code is valid and break from loop
      break;
    }
  }
  
  // Return with either the reformatted valid postcode or the original invalid 
  // postcode
  if (valid) {return postCode;} else return false;
}
