/*Set Global variables*/
  var nbsp = 160;		// non-breaking space char
  var node_text = 3;	// DOM text node-type
  var emptyString = /^\s*$/ ; //regular expression for an empty string
  var global_valfield;	// retain valfield for timer thread
  var alertstr = ""; //holds list of alert messages

/*setfocus - Delayed focus setting to get around IE bug*/
function setFocusDelayed()
{
	global_valfield.focus();
}
function setfocus(valfield)
{
  /*save valfield in global variable so value retained when routine exits*/
  global_valfield = valfield;
  setTimeout( 'setFocusDelayed()', 50 );
}

/*boxSetFocus - Used in newad to colour brdr and setfocus of input box for mileage entry*/
function boxSetfocus(crntid,nextid,valfield,fieldname,setclass)
{
	var newClass='addBg'; //css class name to be used 
	var fieldnameid = ""; //id of field
	var n=document.getElementById(nextid);
	var c=document.getElementById(crntid);
	var fld = c.value;  // value of current field
	var nextfld = n.value;  // value of next field
	var numexp =  /^[0-9]$/;  //regular expression to find numbers and no other chars
  // save valfield in global variable so value retained when routine exits
  global_valfield = valfield;
  if(!numexp.test(fld)){c.value=''; return false; } //clear the current value field unless it contains a number
  // loop over field ids to clear background color
			for(var i=1; i<7; i++){
			var fieldnameid = fieldname + i; //adds the value of i to end of fieldname for each run thru loop 
			var p=document.getElementById(fieldnameid);
			p.className = setclass; //set the css class properties to the class passed to this program
			//if(trim(p.value) ==''){p.value = 'N';} //if field value is empty, set it to 'N'
			}
  if(!numexp.test(nextfld)){n.value='';} //clear the next value field unless it contains a number
  n.className = newClass;  // set the CSS class to adjust appearance of next box
  setTimeout( 'setFocusDelayed()', 50 );
}

/*msg -Display warnTxt/errorTxt message in HTML element*/
function msg(fld,     // id of element to display message in
             msgtype, // class to give element ("warnTxt" or "errorTxt")
             message) // string to display
{
  /* setting an empty string can give problems if later set to a 
  non-empty string, so ensure a space present. (For Mozilla and Opera one could 
  simply use a space, but IE demands something more, like a non-breaking space.)*/
  var dispmessage;
  if (emptyString.test(message)) dispmessage = String.fromCharCode(nbsp); 
  else  
    dispmessage = message;
  var elem = document.getElementById(fld);
  elem.firstChild.nodeValue = dispmessage;  // replaces old text with message text
  elem.className = msgtype;   // set the CSS class to adjust appearance of message
}

/*trim -Trim leading/trailing whitespace off string*/
function trim(str)
{
  return str.replace(/^\s+|\s+$/g, '');
}

//removes all spaces from anywhere in a string
function removeSpaces(string) {
	var tstring = "";
	string = '' + string;
	splitstring = string.split(" ");
	for(i = 0; i < splitstring.length; i++)
	tstring += splitstring[i];
	return tstring;
}
//General purpose - check first half of postcode is entered correctly
//Option - infofield should contain id tag where message is to be displayed
function valpcode1 (pcode,infofield) 
{
	var textfield = pcode;
	var pcodeRegxp = /^([A-Za-z]{1,2}[0-9]{1,2})/;

	if (!pcodeRegxp.test(textfield)) {
	//msg (infofield, "errorTxt", "");
return false;
	 }
	//msg (infofield, "", ""); //this clears the errorTxt message if all ok
	 return true;
}
//General purpose - check second half of postcode is entered correctly
//Option - infofield should contain id tag where message is to be displayed
function valpcode2 (pcode,infofield) 
{
	var textfield = pcode;
	var pcodeRegxp = /^([0-9]{1,1}[A-Za-z]{2,2})/;

	if (!pcodeRegxp.test(textfield)) {
	//msg (infofield, "errorTxt", "");
return false;
	 }
	 //msg (infofield, "", ""); //this clears the errorTxt message if all ok
	 return true;
}
//Search form - check partial postcode is entered
function valpcode (valfield)   // true if required
{
	var infofield = "jfPcode";
	var textfield = document.adform.fPcode.value;
	var pcodeRegxp = /^([A-Za-z]{1,2}[0-9]{1,2})/;

	if (!pcodeRegxp.test(textfield)) {
	msg (infofield, "errorTxt", "");
  	setfocus(valfield);
	alertstr += "- Enter a valid first half postcode i.e. SE10 or NW1.\n\n";
/*	alert("Enter a valid first half postcode i.e. SE10 or NW1");*/    
return false;
	 }
/*	textfield = removeSpaces(textfield);
	if(textfield =="" || textfield.toLowerCase()=="postcode" || textfield.length < 2  || textfield.length > 4 )
            {
	msg (infofield, "errorTxt", "");
  	setfocus(valfield);
	alert("Enter a first half postcode i.e. SE10 or NW1");
    return false;
     } */
	 msg (infofield, "", ""); //this clears the errorTxt message if all ok
	 return true;
}
//check that a make has been entered
function valmake(valfield,infofield)
{
	var info = infofield;
	var textfield = removeSpaces(valfield.value);

	if(textfield == "" || textfield.toLowerCase()== 'make' || textfield.length < 2)  {
	msg (info, "errorTxt floatLeft10", "Select a MAKE");
	
  	setfocus(valfield);
	alertstr += "- Select a MAKE first.\n\n";
/*	alert("Select a MAKE first.");*/    
return false;
			}
 msg (info, "", ""); //this clears the errorTxt message if all ok
 return true;
}			
//check that a model has been entered
function valmodel(valfield,infofield)
{
	var info = infofield;
	var textfield = removeSpaces(valfield.value);

	if(textfield == "" || textfield.toLowerCase()== 'select' || textfield.length < 2)  {
	msg (info, "errorTxt floatLeft10", "Select a MODEL");
	
  	setfocus(valfield);
	//alertstr += "- Select a MODEL first.\n\n";
	/*alert("Select a Model first.");  */ 
return false;
			}
 msg (info, "", ""); //this clears the errorTxt message if all ok
 return true;
}			
/******start - checkform******/
/*check form for errors. Errors are marked by a caution gif image and red input field - used by registration*/
function checkform(formName)
		{
		// Test if DOM is available and there is an element called required
			if(!document.getElementById || !document.createTextNode){return;}
			if(!document.getElementById('required')){return;}
		// Define error messages and split the required fields
			var errorID='errorBox'; //class of element to display error
			var errorClass='errorBg'
			var errorMsg='Please enter or change the fields marked with a ';
		// Select the right dir to get the image. dirlvl2 is set in the calling page	
			if(document.getElementById('dirlvl2')){
			var errorImg='../../vault/image/icon/alert.gif';//path to stored image
			}
			else{
			var errorImg='../vault/image/icon/alert.gif';//path to stored image
			}
			var errorAlt='Error';
			var errorTitle='This field has an error!';
			var reqfields=document.getElementById('required').value.split(',');
			var errorDisp=document.getElementById('displayError');
		// Cleanup old mess
			// if there is an old errormessage field, delete it
			if(document.getElementById(errorID))
			{
				var em=document.getElementById(errorID);
				em.parentNode.removeChild(em);
			}
			// remove old images and classes from the required fields
			for(var i=0;i<reqfields.length;i++)
			{
				var f=document.getElementById(reqfields[i]);
				if(!f){continue;}
				if(f.previousSibling && /img/i.test(f.previousSibling.nodeName))
				{
					f.parentNode.removeChild(f.previousSibling);
				}
				//f.className=''; //set default class for element, after error has cleared
				
				/*if(f.id == 'fPcode1'){f.className='';}
				if(f.id == 'fNameTitle') {f.className='formShortSelect';}*/ //set default class for element, after error has cleared
				switch(f.id)
				{				
					case 'fNameTitle':
					f.className='formShortSelect'; //set default class for element, after error has cleared
					break;
					case 'fBirthDay':
					f.className='formShortSelect'; //set default class for element, after error has cleared
					break;
					case 'fBirthMonth':
					f.className='formStandardSelect'; //set default class for element, after error has cleared
					break;
					case 'fBirthYear':
					f.className='formShortSelect'; //set default class for element, after error has cleared
					break;
					case 'fPcode1':
					f.className='formVShortInput'; //set default class for element, after error has cleared
					break;
					case 'fPcode2':
					f.className='formVShortInput'; //set default class for element, after error has cleared
					break;
					case 'fPrice':
					f.className='formShortInput'; //set default class for element, after error has cleared
					break;
					default:
					f.className='formMedSelect'; //set default class for element, after error has cleared
				}
			}
		// loop over required fields
			for(var i=0;i<reqfields.length;i++)
			{
		// check if required field is there
				var f=document.getElementById(reqfields[i]);
				if(!f){continue;}
		// test if the required field has an error, 
		// according to its type
				switch(f.type.toLowerCase())
				{
					case 'text':
						if(trim(f.value)=='' && f.id!='fEmail'){cf_adderr(f)}
						/*clear errorTxt messages if condition met*/
							else {msg ('jfEmail', "errorTxt", "");}
		// email is a special field and needs checking//
						if(f.id=='fEmail' && !cf_isEmailAddr(f.value)){
							msg ('jfEmail', "errorTxt", "Enter a valid Email");
							cf_adderr(f)}
						/*if(f.id=='fEmail2' && !EmailCompare(f,'jfEmail2'))
						{
		//remove alert symbol if exists. The first image created every time EmailCompare() returns false is not automatically cleared by the code a few lines above, so part of that code is repeated here//
							if(f.previousSibling && /img/i.test(f.previousSibling.nodeName))
							{
							f.parentNode.removeChild(f.previousSibling);
							}
						cf_adderr(f)}//pass element id contained in (f) to the function cf_adderr() to display a warning image  */	
			/*telephone number needs checking*/		
						if(f.id=='fTel1' && !validateTelnr(f,'jfTel1'))
						{
		/*remove alert symbol if exists. The first image created every time validateTelnr() returns false is not automatically cleared by the code a few lines above, so part of that code is repeated here*/
							if(f.previousSibling && /img/i.test(f.previousSibling.nodeName))
							{
							f.parentNode.removeChild(f.previousSibling);
							}
						cf_adderr(f)}//pass element id contained in (f) to the function cf_adderr() to display a warning image  

					//check first part of postcode
					if(f.id=='fPcode1' && !valpcode1(f.value,'jfPcode')){
					msg ('jfPcode', "errorTxt", "First half of postcode invalid.");
							//remove alert symbol if exists.//
							if(f.previousSibling && /img/i.test(f.previousSibling.nodeName))
							{
							f.parentNode.removeChild(f.previousSibling);
							}
 					cf_adderr(f)}
					/*clear errorTxt messages if condition met*/
					if(f.id=='fPcode1' && valpcode1(f.value,'jfPcode')== true)
					{msg ('jfPcode', "errorTxt", "");}
									
					/*check second part of postcode*/
					if(f.id=='fPcode2' && !valpcode2(f.value,'jfPcode')){
					msg ('jfPcode', "errorTxt", "Postcode invalid - example format: [ SE10 ]  [ 2QP ]");
							/*remove alert symbol if exists*/
							if(f.previousSibling && /img/i.test(f.previousSibling.nodeName))
							{
							f.parentNode.removeChild(f.previousSibling);
							}
 					cf_adderr(f)}
					/*check Price is a number*/	
						if(f.id=='fPrice' && !allowNumber(f,'jfPrice'))
						{
		/*remove alert symbol if exists.*/
							if(f.previousSibling && /img/i.test(f.previousSibling.nodeName))
							{
							f.parentNode.removeChild(f.previousSibling);
							}
						cf_adderr(f)}//pass element id contained in (f) to the function cf_adderr() to display a warning image  
					break;
					case 'textarea':
						if(trim(f.value)==''){cf_adderr(f)}							
					break;
					case 'password':
					if(f.id=='fPword0' && !charlength(f,'jfPword0','6','14','true')){cf_adderr(f)}//used in pw change form 
					if(f.id=='fPword1' && !charlength(f,'jfPword1','6','14','true')){cf_adderr(f)}
						//if(trim(f.value)==''|| trim(f.value).length < 6 || trim(f.value).length > 14){cf_adderr(f)}
						//compare both passwords
					if(f.id=='fPword2' && !PwordCompare(f,'jfPword2'))
						{
		/*remove alert symbol if exists*/
							if(f.previousSibling && /img/i.test(f.previousSibling.nodeName))
							{
							f.parentNode.removeChild(f.previousSibling);
							}
						cf_adderr(f)}//pass element id contained in (f) to the function cf_adderr() to display a warning image
					break;
					case 'checkbox':
						if(!f.checked){cf_adderr(f)}							
					break;
					case 'select-one':
						//if(!f.selectedIndex && f.selectedIndex==0){cf_adderr(f)}
					/*Special case - check select list for fModel only. This allows the fModel select element to display an error only when the valmodel check fails and not when the general check fails in the 'else' part of the 'if' clase below. This way we can have a selected index of '0' as long as it does not have the value 'SELECT'*/
					if(f.id=='fModel'){
					//check Model is valid
					if(f.id=='fModel' && !valmodel(document.adform.fModel,'jfModel')){
							//remove alert symbol if exists.//
							if(f.previousSibling && /img/i.test(f.previousSibling.nodeName))
							{ 
							f.parentNode.removeChild(f.previousSibling);
							}
 					cf_adderr(f)}
					}
					else {//general check to check select list is selected for any other select element
						if(!f.selectedIndex && f.selectedIndex==0){cf_adderr(f)}
					}
					//check Make is valid
					if(f.id=='fMake' && !valmake(document.adform.fMake, 'jfMake')){
							//remove alert symbol if exists.//
							if(f.previousSibling && /img/i.test(f.previousSibling.nodeName))
							{
							f.parentNode.removeChild(f.previousSibling);
							}
 					cf_adderr(f)}
					break;
				}
			}
			return !document.getElementById(errorID);

			/* Tool methods */
			function cf_adderr(o)
			{
				// create image, add to and colourise the error fields
				var errorIndicator=document.createElement('img');
				errorIndicator.alt=errorAlt;
				errorIndicator.src=errorImg;
				errorIndicator.title=errorTitle;
				o.className=errorClass;
				o.parentNode.insertBefore(errorIndicator,o);
			// Check if there is no error message
				if(!document.getElementById(errorID))
				{
				// create errormessage and insert before submit button
					var em=document.createElement('div');
					em.id=errorID;
					var newp=document.createElement('p');
					newp.appendChild(document.createTextNode(errorMsg))
					// clone and insert the error image
					newp.appendChild(errorIndicator.cloneNode(true));
					em.appendChild(newp);
					// find the image submit button 
/*NOT IN USE see ***ALTERNATIVE*** below.	for(var i=0;i<of.getElementsByTagName('input').length;i++)
					{
						if(/image/i.test(of.getElementsByTagName('input')[i].type))
						{
							var sb=of.getElementsByTagName('input')[i];
							break;
						}
					}   */
				/******ALTERNATIVE*******/	
					if(errorDisp)//special hidden field in form to receive JS error message-used instead of the above greyed out code//
					{
						errorDisp.parentNode.insertBefore(em,errorDisp);
					}	
				/***********************/	
				} 
			}
			function cf_isEmailAddr(str) 
			{
			    return str.match(/^[\w-]+(\.[\w-]+)*@([\w-]+\.)+[a-zA-Z]{2,7}$/);
			}
		}
/*******END - checkform*******/
	
/*confirm delete box*/
function delconfirm()
{
	check = confirm('Are you sure you want to delete this?\nWarning: This action cannot be undone.');
	if (check == true) {
return true;
} 
else { 
return false;
}
}
/*confirm going back when in upload picsave pages*/
function bckconfirm()
{
	check = confirm('You can go back but adding photos on the previous page will delete all photos from here.\nDo you want continue?');
	if (check == true) {
return true;
} 
else { 
return false;
}
}
/*compare two emails*/
function EmailCompare (valfield, infofield, required)   // true if required
			{
 			var theForm
			theForm = document.adform
			if (theForm.fEmail.value != theForm.fEmail2.value) {
			msg (infofield, "errorTxt", "The re-entered Email did not match the first Email!");
  			//setfocus(valfield);
   			 return false;
			}
			msg (infofield, "errorTxt", "");
			return true;
			}	
			
/*compare two passwords*/
function PwordCompare (valfield, infofield, required)   // true if required
			{
 			var theForm
			theForm = document.Register
			if (theForm.fPword1.value != theForm.fPword2.value) {
			msg (infofield, "errorTxt", "The re-entered Password did not match the first Password!");
  			//setfocus(valfield);
   			 return false;
			}
			msg (infofield, "errorTxt", "");
			return true;
			}				
/*checks that a password or text input field contains a specified minimun and maximum number of
characters, returns false if condition not met.*/
function charlength (valfield,   // element to be validated
                         infofield,  // id of element to receive info/errorTxt msg
                         minchars, maxchars, // range to be checked
						 rettrue)   //If this is set to "No" then "return true" wont be returned
{
  var fld = trim(valfield.value);  // value of field with whitespace trimmed off
  var numdigits = 0;
  var minc = minchars;
  var maxc = maxchars;
  for (var j=0; j<fld.length; j++)
    if (fld.charAt(j)!='') numdigits++;

  if (numdigits<minc) {
    msg (infofield, "errorTxt", "You have " + numdigits + " characters - enter at least " + minc);
    //setfocus(valfield);
    return false;
  }
  if (numdigits>maxc){
    msg (infofield, "errorTxt", "You have " + numdigits + " characters - enter no more than " + maxc);
  return false;
  }
  msg (infofield, "errorTxt", "");
  if(rettrue == 'true')
  return true; //When called by form only, this is disabled so as not to conflict with checkform function
}

/* Validate telephone number, some validation ignored if tel is optional
// Returns true if so (and also if could not be executed because of old browser)
// Permits spaces*/
function validateTelnr  (valfield,   // element to be validated
                         infofield,  // id of element to receive info/errorTxt msg
                         required)   // if tel no is not mandatory set this to 'optional'
{
  var opt = 'optional';
  var tfld = trim(valfield.value);  // value of field with whitespace trimmed off
  var telnr =  /^[0-9 ]+[0-9]$/;  //regular expression to find numbers and spaces and no other chars
  
    var numdigits = 0;
  	for (var j=0; j<tfld.length; j++)
    if (tfld.charAt(j)>='0' && tfld.charAt(j)<='9') numdigits++;

  if (required == opt && tfld !=''){
  if (!telnr.test(tfld)) {
    msg (infofield, "errorTxt", "Not a valid telephone no. (enter numbers or leave blank)");
    return false;}
	}
  
  if (required != opt){ //start optional - skip some checks if tel is optional
  if (!telnr.test(tfld)) {
    msg (infofield, "errorTxt", "Not a valid telephone no. (only enter numbers)");
    //setfocus(valfield);
    return false;
  }
  if (numdigits<6) {
    msg (infofield, "errorTxt", "You entered " + numdigits + " digits - its too short");
    //setfocus(valfield);
    return false;
  }
  }//end optional
  if (numdigits>15){
    msg (infofield, "errorTxt", numdigits + " digits - you entered too many digits");
	 return false;}
  else { 
    if (numdigits<10 && tfld !='')
      msg (infofield, "warnTxt", "You entered " + numdigits + " digits - check area code / optional");
    else
      msg (infofield, "warnTxt", "");
  }
  return true;
}
/*allows only a number to be entered*/
function allowNumber(valfield,infofield)
{
	var fld = valfield.value;
	var numexp =  /^[0-9]+[0-9]$/;  //regular expression to find numbers and spaces and no other chars
  // save valfield in global variable so value retained when routine exits
  if(!numexp.test(fld)){
  // loop over field ids to clear background color
    msg (infofield, "errorTxt", "Digits only. No spaces or commas.");
	return false; }
	else {
	msg (infofield, "errorTxt", "");
	return true;
	}
}

/*Character Counter*/
function textCounter(field, countfield, maxlimit) {
	if (field.value.length > maxlimit) {
		field.value = field.value.substring(0, maxlimit);
	} else {
		countfield.value = maxlimit - field.value.length;
	}
}
