function getCheckedValue(radioObj) {
	if(!radioObj)
		return "";
	var radioLength = radioObj.length;
	if(radioLength == undefined)
		if(radioObj.checked)
			return radioObj.value;
		else
			return "";
	for(var i = 0; i < radioLength; i++) {
		if(radioObj[i].checked) {
			return radioObj[i].value;
		}
	}
	return "";
}
function setCheckedValue(radioObj, newValue) {
	if(!radioObj)
		return;
	var radioLength = radioObj.length;
	if(radioLength == undefined) {
		radioObj.checked = (radioObj.value == newValue.toString());
		return;
	}
	for(var i = 0; i < radioLength; i++) {
		radioObj[i].checked = false;
		if(radioObj[i].value == newValue.toString()) {
			radioObj[i].checked = true;
		}
	}
}
// =============================================================================================================
// Function: getCookie( name )
// =============================================================================================================
//
// This function reads the named cookie from the user's computer
function getCookie(name){
  var cname = name + "=";               			// e.g. 'PolyflorUserDetails='
  var dc = document.cookie;             			// get all defined cookies
  
  // Check cookie(s) are loaded from the user's computer  
  if (dc.length > 0) {
      // Search for the cookie - beginning with the specified name
    begin = dc.indexOf(cname);     
	// Check the required cookie name was found  
	    if (begin != -1) { 
	    		// Extract the text between the initial cookie name and the terminating ';' ( or end of string )
		      begin += cname.length;       
		      end = dc.indexOf(";", begin);
		      if (end == -1) end = dc.length;
		      // return the cookie
	           return unescape(dc.substring(begin, end));
  		  } 
	  }
  return null;
}	// end function - getCookie
// = = = = = = TRIM LEFT = = = = = = //
function leftTrim(sString) 
{
while (sString.substring(0,1) == ' ')
{
sString = sString.substring(1, sString.length);
}
return sString;
}
// = = = = = = TRIM LEFT = = = = = = //
// = = = = = = TRIM RIGHT  = = = = = = //
function rightTrim(sString) 
{
while (sString.substring(sString.length-1, sString.length) == ' ')
{
sString = sString.substring(0,sString.length-1);
}
return sString;
}
// = = = = = = TRIM RIGHT  = = = = = = //
// Set the expires date for any cookies stored on the user's PC
var expiration = new Date( 2099, 11, 31, 12, 0, 0 );
// =============================================================================================================
// Function: loadURLSpecifiedManuals( f )
// =============================================================================================================
//
function loadURLSpecifiedManuals(  ) {
	if ( FullManualName != "" ) {
	
	if(checkRow("BrochureTable", FullManualName) == false)
{
return false;
}
else
{
 		//AddTableRow( "Brochure" , FullManualName ) ;		//Add a row to the HTML order table 
		AddTableRow( "Brochure" , FullManualName ,"BrochureTable") ;
		setAllCookies();
}
	
	} // end if
} // end function loadURLSpecifiedManuals
// =============================================================================================================
// Function: GetManualAlias() 
// =============================================================================================================
//
// This function returns the alias for a POLYFLOR manual/brochure, given its full name
// e.g. "Corporate Brochure" returns "Corporate"
function GetManualAlias( fullname ) {
	// Get comma separated list of POLYFLOR manuals/brochures ... cunningly put in a <SPAN> on this document!
	if(document.all){
     var sAllManuals = document.getElementById( "MANUALS" ).innerText
	} else{
    var sAllManuals = document.getElementById( "MANUALS" ).textContent
	}
	
	var sManualAlias = "";
	var s;
	var n1;
	var n2;
	// Split the string so that the array contains individual manual names and aliases e.g. Corporate Brochure | Corporate
	var a = sAllManuals.split( "," );
	
	// Step through the array - checking for the specified product code
	
	var sSearch = fullname + "|";
	for ( var i=0 ; i<a.length ; i++ ) {
		// Find a match for the full manual name plus separator |  e.g. Corporate Brochure|
		if ( a[i].indexOf( sSearch ) != -1 ) {	
			s = a[i];
			n1 = s.indexOf( "|" ) + 1;
			n2 = s.length;	
			// Extract the manual alias e.g. Corporate		
			sManualAlias = a[i].substring( n1 , n2 );
			return sManualAlias;
		} // end if
	
	}  // end for
	// If no match found return an empty string
	
	return "";
	
} // end function
function OnChangeSelectManual( s ) {
	var manual = s.options[ s.selectedIndex ].text ;
	var n = document.forms[0].elements.length;
//	alert( "Brochure=" + manual );
	for ( var i=0 ; i<n; i++ ) {
// 		alert( "Form=" + document.forms[0].elements[i].name );
 	}
	window.document.forms[0].SEItem.value = manual;
}
function OnChangeSelectDescription( s ) {
	var description = s.options[ s.selectedIndex ].text ;
//	alert( "Description=" + description );
	oElement = document.getElementById( "SESelectShadecard" );
//	alert( oElement.value );
	window.document.forms[0].elements["Description01"].innerHTML = manual;
}
// =============================================================================================================
// Function: savePolyflorCorporateUserDetails( f )
// =============================================================================================================
//
// This function writes a cookie to the user's computer.
// The cookie is named 'PolyflorCorporateUserDetails' and contains the user's name, address, telephone number etc
//
// When the user next uses the 'Sample Express' form - their details are retrieved from the cookie and used to
// populate the document fields automatically - saving the user form having to re-enter their details
function savePolyflorCorporateUserDetails( f ) {
var saveFields;
// var SelectedSector=f.sector.options[f.sector.selectedIndex].text;  	
// Build a string containing all the field values - to be saved on the user's PC as a cookie
    
saveFields = f.name_first.value+"~";				//   0 - First Name:
saveFields += f.name_last.value+"~";			//   1 - Last Name:
saveFields += f.addr1.value+"~";					//   2 - Address (1)
saveFields += f.addr2.value+"~";					//   3 -      "         (2)
saveFields += f.town.value+"~";					//   4 - Town
saveFields += f.StateOrProvince.value+"~";	//   5 - State or Province:
saveFields += f.pcode.value+"~";					//   6 - Post / ZIP Code:
saveFields += f.country.selectedIndex+"~";	//   7 - Country:
saveFields += f.tel.value+"~";						//   8 - Telephone:
saveFields += f.email.value+"~";					//   9 - Email:
// Store value of Title radio button that is selected e.g. Mrs
     
  	for ( i=0; i<f.title.length; i++) 							// 11 - Title:
	{
		if(f.title[i].checked==true) {saveFields += f.title[i].value+"~" }
  	}
saveFields += f.job_title.selectedIndex+"~";	//   12 - Sector: -index of selected keyword
saveFields += f.company.value+"~";			//   13 - Company:
saveFields += f.fax.value+"~";					//   14 - Fax:
saveFields += f.sector.selectedIndex+"~";	//   15 - Sector: -index of selected keyword
saveFields += f.IndustrySectorOther.value+"~";					//   16 - Specify sector: - used if 	sector is          'Other please specify'
saveFields += f.jobtitleother.value+"~";			//   17 - Job title:
saveFields += getCheckedValue(document.forms[0].elements['enquiryTyp'])+"~";		//   18 - Enquiry Type:
// Set the cookie - to store user's selections on their computer
setCookie('PolyflorUserDetails', saveFields, expiration );
  	
}
// =============================================================================================================
// Function: loadPolyflorCorporateUserDetails( f )
// =============================================================================================================
//
// This function reads a cookie from the user's computer.
// The cookie is named 'PolyflorCorporateUserDetails' and contains the user's name, address, telephone number etc
//
// The cookie's contents are used to populate the document fields automatically - saving the user form having to re-enter their details
function loadPolyflorCorporateUserDetails (f) {
    
	t = getCookie('PolyflorUserDetails');
	
	//alert( 'Cookie=' + t );
	
	if (!t=='') {
		t2 = t.split('~');
		f.name_first.value = t2[0];			//    0 - First Name:
		f.name_last.value = t2[1];			//    1 - Last Name:
		f.addr1.value = t2[2];					//    2 - Address (1)
		f.addr2.value = t2[3];					//    3 - Address (2)
		f.town.value = t2[4];						//    4 - Town
		f.StateOrProvince.value=t2[5];	     //    5 - State / Province
		f.pcode.value = t2[6];					//    6 - Post / ZIP code
		f.country.selectedIndex = t2[7];	     //    7 - Country ( index of selected keyword )
		f.tel.value = t2[8];						//    8 - Telephone:
		f.email.value = t2[9];					//    9 - Email:
		
		
		for ( i=0; i<f.title.length; i++) 			//  10 - Radio button with stored value is checked
		{
			if(f.title[i].value==t2[10]) { f.title[i].checked=true; }
		}
		f.job_title.selectedIndex = t2[11];				//    11 - Email:
		f.company.value = t2[12];				//    12 - Company:
		f.fax.value = t2[13];						//    13 - Fax:
		f.sector.selectedIndex = t2[14];	     //    14 - Sector ( index of selected keyword )
		f.IndustrySectorOther.value = t2[15];			//    15 - Specify sector: - has a value if user selected Sector 'Other please specify'
		f.jobtitleother.value = t2[16];				//    16
		if(t2[17] == undefined || t2[17] == ""){}
		else{
			setCheckedValue(document.forms[0].elements['enquiryTyp'],t2[17]);
			if(t2[17] == "Commercial"){document.getElementById('compAsterix').style.visibility = 'visible';}
		}
		// OK - fields are now loaded with values from the cookie - Now decide what is to be displayed
		
		// If the user selected industry sector 'Other please specify' then display the 'Other Industry Sector' field and its title
		
		var SelectedSector = f.sector.options[f.sector.selectedIndex].text;
		if (SelectedSector == "Other - please specify")
		{
			document.getElementById("IDIndustrySectorOtherTitle").style.display="block";
			document.getElementById("IDIndustrySectorOther").style.display="block";
		}
		var SelectedJob_Title = f.job_title.options[f.job_title.selectedIndex].text;
		if (SelectedJob_Title == "Other - please specify")
		{
			document.getElementById("IDJobTitle").style.display="block";
			document.getElementById("IDJobTitleOther").style.display="block";
		}
		
	}
} // end function loadPolyflorCorporateUserDetails
function updateCheckboxes(fld,box) {
	// which checkbox field element has been clicked?
	chkd=0;
	while (chkd<fld.length&&fld[chkd].value!=box.value) {
		chkd++;
	}
	if (!(fld[0].checked)&&checkboxCount(fld)==fld.length-1) {
		// all checkboxes set, so check first box
		fld[0].checked=true;
	} else if (chkd>0) {
		// clear first checkbox if one of the other boxes is clicked
		fld[0].checked=false;
	}
	
	// has first checkbox has been set?	
	if(fld[0].checked&&chkd==0) {
		// check all other boxes
		for ( i=1; i<fld.length; i++) {
			fld[i].checked=true;
		}
	}
}
// =============================================================================================================
// Function: validate ( f )
// =============================================================================================================
//
// This function validates all the required fields on the form
// If one or more fields fail validation, an error message is displayed in a message box and the user is returned to the form to correct the error(s)
//
// If all required fields pass validation, the user's details are saved on the user's computer, for possible later use when re-visiting the web site
// and the form is submitted.
//
// Note - the $$Return field on this form contains a re-direction URL which re-opens this form with a URL argument &Confirm=Y&
//
// The following are the required fields that are validated:-
//		[0]		name_first
//		[1]		name_last
//		[2]		addr1
//		[3]		addr2
//		[4]		town
//		[5]		StateOrProvince
//		[6]		pcode
//		[7]		country
function validate(f) {
	if (f.submitted.value=='y') 
	{
  	alert ('You have already sent this request form.');
  	return false;
  	}
	var msg;
	// var SelectedSector=f.sector.options[f.sector.selectedIndex].text;
//	var SelectedMediaChannel=f.MediaChannels.options[f.MediaChannels.selectedIndex].text;	
	var err = "";
	
	// Validate required fields
	
	if(f.name_first.value.length<3) { err+='- Please enter your first name.\n' }						// Validate - First Name
	if(f.name_last.value.length<3) { err+='- Please enter your last name.\n' }						// Validate - Last Name:
	if(f.addr1.value.length<4) { err+='- Please enter your address.\n' }								// Validate - Address: first line of address
	if(f.town.value.length<4) { err+='- Please enter your town/city.\n' }								// Validate - Town:
	if(f.StateOrProvince.value.length<4) { err+='- Please enter your state or province.\n' }	// Validate - State or Province
	if(f.pcode.value.length<4) { err+='- Please enter your post code.\n' }							// Validate - Post Code / ZIP Code
	if(f.email.value.length<4) { err+='- Please enter your email address.\n' }						// Validate - Email address
	if(f.tel.value.length<4) { err+='- Please enter your telephone number.\n' }
	// Validate - Country
	if(f.country[f.country.selectedIndex].value=='0' || f.country[f.country.selectedIndex].value=='-') {err+='- Please select your country.\n' }	
		
	//check that enquiry type is checked
	var enquiryTypeSelection = getCheckedValue(document.forms[0].elements['enquiryTyp'])
	if(enquiryTypeSelection == ""){err+='- Please select your enquiry type.\n'}
	//If it's commercial then ask for the Company Name
	if(enquiryTypeSelection == "Commercial"){
	if(f.company.value == "") { err+='- Please enter a company name.\n' }
	}
	//Job Title
	var SelectedJobTitle = f.job_title.options[f.job_title.selectedIndex].text;	
	if(f.sector[f.job_title.selectedIndex].value=='0') { err+='- Please select your Job Title.\n' }
	// If user has selected 'Other - please specify' then ensure they enter an job title:
	if (SelectedJobTitle == "Other - please specify" && f.jobtitleother.value.length<3) {err +='- Please specify your Job Title.\n'}		
	//Sector
	var SelectedSector=f.sector.options[f.sector.selectedIndex].text;	
	if(f.sector[f.sector.selectedIndex].value=='0' || f.sector[f.sector.selectedIndex].value=='-') { err+='- Please select your Sector.\n' }
	//
	// If user has selected 'Other - please specify' then ensure they enter an actual industry sector:
	if (SelectedSector=="Other - please specify" && f.IndustrySectorOther.value.length<3) {err +='- Please enter your Sector.\n'}		
	// If one or more field values do NOT pass validation - report the error(s) and do not submit the form
	
	if(f.TextEntered.value == "") { err+='- Spam Checker text.\n' }
	if ( err.length > 0 ) {
	
	// Build an error message
	
	msg = "Your form is not complete for the following reasons.\n";
 	msg += "Please correct these error(s) and send your form again.\n";
  	msg += "_______________________________________\n\n";
  	msg += err;
  	
  	// Display the error message to the user
  	
  	alert(msg);
  	
  	// Do NOT submit the form as the user has not completed some of the required fields
  	
  	return false;
  	}
  	  	
	// OK - If we get here then the required fields passed validation - so continue
	// save the user details field values as a cookie on the user's PC - as they passed validation
	
	savePolyflorCorporateUserDetails( f )
	
	// Check that the online order table does contain at least one selection! If the user forgot to select anything exit now
	
	//var oTable = document.all.DGVTABLE;
	//var nRow = oTable.rows.length;
	
	//if ( nRow <= 1 ) {
	//	alert( "Remember to add the brochure(s), shadecard(s), product sample(s), accessories you would like to order to the order form!" );
	//	return false;
	//}
	
  	// Set a flag to indicate the form has been submitted
  	
  	f.submitted.value='y'
  	
  	// Get all the user's selections from the table - and put into the standard request fields
  	
  	//ProcessTable(); /* Removed as we now do this before going to the user info page*/
	//remove cookie
	//var expiration = new Date( 1954, 11, 31, 12, 0, 0 );
	//setCookie('SampleRequestCookie', '', expiration, "/" );  	
	//setCookie('Brochures', '', expiration, "/" );  
  	
	// Submit the form to save the Lotus Notes document
  	
  	f.submit();
  
}
function popUpWin(url,name,param) {
        var newWindow = window.open(url,name,param);
}
// Check strV for the presence of any of the characters listed in chars
function charChk(strV,chars) {
  var res=false;
  for ( i=0; i<chars.length; i++) {
    for ( c=0; c<strV.length; c++) {
      if(strV.charAt(c)==chars.charAt(i)) { res=true; }
   }
  }
  return (res);
}
// Count the number of char characters in strVal
function countChar(s,c) {
  var charCount=0;
  for ( i=0; i<s.length; i++) {
    if (s.charAt(i)==c) {charCount++};
  }
  return charCount;
}
// Return how many checkboxes in field fd are set
function checkboxCount(fd) {
	counter=0
	for ( i=0; i<fd.length; i++) {
		if(fd[i].checked) { counter++ }
	}
	return counter;
}
// Check form fm for presence of field fd, returns true/false
function findField(fm,fd) {
  var found=false;
  for ( i=0; i<fm.elements.length; i++) {
    if (fm.elements[i].name==fd) {return true};
  }
  return false;
}
addLoadEvent(function (){
if(document.all){
if(document.all && document.forms[0].submittedhidden.value !="Y"){
//document.getElementsByTagName('fieldset')[2].style.visibility = "hidden"; 
}
else{
//document.getElementsByTagName('fieldset')[1].style.visibility = "hidden"; 
}
}
// Read user's details, name, address, telephone no. etc from cookie 'PolyflorUserDetails' on the user's computer
if(document.getElementById('name_first')){
loadPolyflorCorporateUserDetails (document.forms[0]);
}
//If successful delete cookie (added because of spam checker code removing cookie when not a valid submission, forcing user to add back in shade selections)
if(successDeleteCookie=="Y"){
	//remove cookie
	var expiration = new Date( 1954, 11, 31, 12, 0, 0 );
	setCookie('SampleRequestCookie', '', expiration, "/" );  	
	setCookie('Brochures', '', expiration, "/" );  
}
// Add any manuals specified in the URL argument e.g. &Manual=Technical& to the online order
//loadURLSpecifiedManuals();
 });



