

//
// common borro form validation functions
//

function openwindow(url)
{
 window.open(url,"borropopup","scrollbars=yes,menubar=1,resizable=1,width=600,height=600");
}

var digits = "0123456789";

// non-digit characters which are allowed in phone numbers
var phoneNumberDelimiters = "()- ";

// characters which are allowed in international phone numbers
// (a leading + is OK)
var validWorldPhoneChars = phoneNumberDelimiters + "+";

// Minimum no of digits in an international phone no.
var minDigitsInUkPhoneNumber = 11;
var maxDigitsInUkPhoneNumber = 11;

var minDigitsInInternationalPhoneNumber = 12;

function isInteger(s)
{   var i;
    for (i = 0; i < s.length; i++)
    {   
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}

function isNumber(value) {
	
	if (isNaN(value) || (value == '') ) {		
		return false;
	}
	else{
		return true;
	}
}

function stripCharsInBag(s, bag)
{   var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++)
    {   
        // Check that current character isn't whitespace.
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function checkInternationalPhone(strPhone){
  s=stripCharsInBag(strPhone,validWorldPhoneChars);
 
  return (isInteger(s) && s.length >= minDigitsInInternationalPhoneNumber);
}

function checkUkPhone(strPhone){
  s=stripCharsInBag(strPhone,phoneNumberDelimiters);
 
  return (isInteger(s) && s.length >= minDigitsInUkPhoneNumber && s.length <= maxDigitsInUkPhoneNumber && s.charAt(0)=="0");
}

function checkConfirmPhone(strPhone, strConfirmPhone){
  
  return strPhone == strConfirmPhone;
  
}

  function isEmptyElem(elem) {
        if(elem==null){
          return true;
        }
	    return isEmpty(elem.value);
  }
	  
  function isEmpty(aTextField) {
  
	     if ((aTextField==null) || (aTextField=="")) {
	        return true;
	     } else { 
	       return false; 
	     }
   }

  function cleanEntry(entry) {
	entry = removeChar(entry, '$');
       entry = removeChar(entry, '£');
	entry = removeCommas(entry);
	return entry;
  }
  
  	  function removeChar(entry, character) {
  	  	// Remove any leading characters
  	  	while ( entry.charAt(0) == character )
  	  		entry = entry.substring(1, entry.length);
  	  	// Remove any trailing characters
  	  	while ( entry.charAt(entry.length-1) == character )
  	  		entry = entry.substring(0, entry.length-1);
  	  
  	  	return entry;
  	  }
  	  
  	  
  	  function removeCommas(number) {
  	  	// Remove the commas from a number
  	  	number = number.toString();
  	  	index = 0;
  	  	while(index < number.length) {
  	  		if (number.charAt(index) == ','){
  	  			number = number.substring(0, index) + number.substring(index+1, number.length);
  	  		}
  	  
  	  		index++;
  	  	}
  	  	return number;
	  }
	  
function pwrdCheck(password) {
		/*function to calculate "strength" of a password
		* expects password, returns strength
		*/
		//calculate strength out of length
		
	
		var strength = 0;
		var length = password.length;
		if (length > 16) {
			strength = 18;
			} else {
			if (length > 7) {
				strength = 12
				} else {
				if (length > 5) {
					strength = 6;
					} else {
					if (length > 0) {
						strength = 3;
						} else {

						return 0; //no password means no strength, :-)
					}
				}
			}
		}
		//Now consider the letters
		if (password.match(/[a-z]/i)) {
			strength += 5; //at least one letter, 5 points
		} //no letter, no points
		
		//Now check for numbers
		count = password.match(/[0-9]/g);
		if (count) {
			strength += 5; //at least one number, 5 points
			if (count > 2) {
				strength += 2; //three or more numbers, 2 extra points;
			}
		} //no number, no points
		
		//Now check for special characters
		count = password.match(/[!,@,#,$,%,^,*,?,_,~,-]/g)
		if (count) {
			strength += 5; //at least one special characters, 5 points
			if (count > 1) {
				strength += 2; //two or more special characters, 2 extra points
			}
		} //no special characters, no points
		
		return strength;
	}
	
	

//Check valid email
function checkEmail(email){
	
	pattern_text = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	  
	if(pattern_text.test(email.value)){
		
		return true;
	}else{
		
		return false;
	}
}


function checkCharactersOcurrences(min_number, str){
	var counter = 0;
	var pattern_text = /^[a-zA-Z]+$/;
	var fieldvalue = str.value;		
	for (var i=0; i<fieldvalue.length; i++){
	
		if(pattern_text.test(fieldvalue.charAt(i))){
		counter += 1;
		}
	}
	if(counter < min_number){
		return false;
	}else {
		return true;
	}
}	

function atLeastOneCharacter(str){
	var counter = 0;
	var pattern_text = /^[a-zA-Z]+$/;
	var fieldvalue = str.value;		
	for (var i=0; i<fieldvalue.length; i++){
	
		if(pattern_text.test(fieldvalue.charAt(i))){
		counter += 1;
		}
	}
	if(counter < 1){
		return false;
	}else {
		return true;
	}
}	


/*==============================================================================

Application:   Postcode Utility Function
              
  
Parameters:    toCheck - postcodeto be checked. 

This function checks the value of the parameter for a valid postcode format. The 
space between the inward part and the outward part is optional, although is 
inserted if not there as it is part of the official postcode.

If the postcode is found to be in a valid format, the function returns the 
postcode properly formatted (in capitals with the outward code and the inward
code separated by a space. If the postcode is deemed to be incorrect a value of 
false is returned.
  
Example call:
  
  if (checkPostCode (myPostCode)) {
    alert ("Postcode has a valid format")
  } 
  else {alert ("Postcode has invalid format")};
                    
------------------------------------------------------------------------------*/

function checkPostCode (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.value;

  // 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;
}

function formatAmount(num) {
	
	var formatNum = num.replace(",", "");
	
	var index = formatNum.lastIndexOf(".");
	if (index > -1) {
		var numParts = formatNum.split(".");
		formatNum = numParts[0];
	}
	
	return formatNum;
	
}

function formatAmounts() {

	var loanamount = document.getElementById("loanamount");
	var propertyvalue = document.getElementById("propertyvalue");
	var mortgagevalue = document.getElementById("mortgagevalue");
	
	n_loanamount = formatAmount(loanamount.value);
	n_propertyvalue = formatAmount(propertyvalue.value);
	n_mortgagevalue = formatAmount(mortgagevalue.value);
	
	loanamount.value = n_loanamount;
	propertyvalue.value = n_propertyvalue;
	mortgagevalue.value = n_mortgagevalue;
	
}

function validateLongterm() {

	var loanamount = document.getElementById("loanamount");
	var homeowner = document.getElementById("homeowner");
	var propertyvalue = document.getElementById("propertyvalue");
	var mortgagevalue = document.getElementById("mortgagevalue");
	
	//alert("document.applyform.homeowner.length: "  + document.applyform.homeowner.length);
	
	var homeowner_value = "";
	
	// Radio Button Validation
	for (i=0;i<document.applyform.homeowner.length;i++)
	{
	      if (document.applyform.homeowner[i].checked)
	      {
	             var homeowner_value = document.applyform.homeowner[i].value;
	      }
	} 
	                  
	//alert("homeowner_value: "  + homeowner_value);

	if(loanamount.value == ""){
 
         alert("Please enter a required loan amount.");
         loanamount.focus();
         isValid = false;
         
     } else if(isNumber(loanamount.value)==false){

        alert("Please ensure your required loan amount is a valid number.");
        loanamount.focus();
        isValid = false;
        
     } else if(homeowner_value == ""){

        alert("Please specify whether or not you are a homeowner.");
        homeowner.focus();
        isValid = false;
        
    } else if((homeowner_value == "home_yes") && propertyvalue.value == ""){

        alert("Please enter a property value.");
        propertyvalue.focus();
        isValid = false;
    
    } else if((homeowner_value == "home_yes") && isNumber(propertyvalue.value)==false){

        alert("Please ensure your property value is a valid number.");
        propertyvalue.focus();
        isValid = false;
        
     } else if((homeowner_value == "home_yes") && mortgagevalue.value == ""){

        alert("Please enter a outstanding mortgage value.");
        mortgagevalue.focus();
        isValid = false;
    
    } else if((homeowner_value == "home_yes") && isNumber(mortgagevalue.value)==false){

        alert("Please ensure your outstanding mortgage value is a valid number.");
        mortgagevalue.focus();
        isValid = false;
        
     }
     
     //alert("isValid: " + isValid);
     
     //isValid = false;
	     
     return isValid;
}

function validateAsset() {

	var secondhandvalue = document.getElementById("secondhandvalue");
	var description_area = document.getElementById("description_area");
	var type = document.getElementById("type");
	var make = document.getElementById("make");
	
	var secondhandvalue1 = document.getElementById("secondhandvalue1");
	var description1 = document.getElementById("description1");
	var type1 = document.getElementById("type1");
		
	if(type.value== "" && type1.value == "") {

    	alert("Please enter an Item Type.");
      	type.focus(); 
      	isValid = false;

	} else if(type.value == "Watch" && make.value == ""){
  		   
   		alert("Please enter a Make.");
   		make.focus(); 
      	isValid = false;  
   
   	} else if((description_area.value == "Enter brief description..." || description_area.value == "") && description1.value == "") {
 
         alert("Please enter an Item Description.");
         description_area.value = '';
         description_area.focus();
         isValid = false;
        
      } else if(isEmptyElem(secondhandvalue) && secondhandvalue1.value == ""){
 
         alert("Please enter an Estimated Resale Value.");
         secondhandvalue.focus();
         isValid = false;
         
      } else if(isNumber(secondhandvalue.value)==false && secondhandvalue1.value == ""){
 
         alert("Please ensure the Estimated Resale Value is a number.");
         secondhandvalue.focus();
         isValid = false;
         
      } else if(!(secondhandvalue.value > 0) && secondhandvalue1.value == ""){
 
         alert("Please ensure the Estimated Resale Value which is greater than 0");
         secondhandvalue.focus();
         isValid = false;
     }
	
	return isValid;

}

function validateForm() {

	var phone = document.getElementById("phone");
	var mobile = document.getElementById("mobile");
	var email = document.getElementById("email");
	
	//var title = document.getElementById("title");
	var surname = document.getElementById("surname");
	var firstname = document.getElementById("firstname");
	var address1 = document.getElementById("address1");
	var citytown = document.getElementById("citytown");
	var postcode = document.getElementById("postcode");
	
    var loantype = document.getElementById("loantype");

	isValid = true;
	
	/*if(isEmptyElem(title)){

        alert("Please enter your Title.");
        title.focus();
        isValid = false;
        
	} else*/ if(isEmptyElem(firstname)){
		 
        alert("First name is a mandatory field.");
        firstname.focus();
        isValid = false;
              
    } else if(!atLeastOneCharacter(firstname)){
		 
        alert("Please enter a valid first name.");
        firstname.focus();
        isValid = false;
              
    } else if(isEmptyElem(surname)){
    	 
        alert("Surname is a mandatory field.");
        surname.focus();
        isValid = false;

    } else if(!atLeastOneCharacter(surname)){
		 
        alert("Please enter a valid surname.");
        surname.focus();
        isValid = false;
           
    }  else if (((phone.value==null)||(phone.value==""))&&((mobile.value==null)||(mobile.value=="")||(mobile.value=="00000000"))){

		if (mobile.value=="00000000") {
			alert("Please enter a phone number");
		} else {
			alert("Please enter at least one phone number");
		}
		phone.focus();
		isValid = false;
		
	} else if ((checkUkPhone(phone.value)==false || (checkInternationalPhone(phone.value)==false && checkUkPhone(phone.value))==false) &&
		(checkUkPhone(mobile.value)==false || (checkInternationalPhone(mobile.value)==false && checkUkPhone(mobile.value))==false)){
		alert("Please enter a valid UK phone number.");		
		phone.focus();
		isValid = false;
	
	} else if(isEmptyElem(email)){
        
         alert("Email is a mandatory field.");
         email.focus();
         isValid = false;

    } else if(checkEmail(email) == false){
	
    	alert("Please enter a valid email address.");
        email.focus();
        isValid = false;	
    } else if(isEmptyElem(postcode)){
 
         alert("Postcode is a mandatory field.");
         postcode.focus();
         isValid = false;
 
    } else if(loantype.value != null && loantype.value == ""){
		   		   
		 alert("Please select a loan type.");
		 loantype.focus(); 
	     isValid = false; 
   
   	} else if(checkPostCode(postcode) == false){
    	
    	 alert("Please enter a valid postcode.");
         postcode.focus();
         isValid = false;
    	
    } else  {
    	postcode.value = checkPostCode(postcode);
    	
    	if(isEmptyElem(address1)) {
	    
	       	alert("First line of your address is a mandatory.");
	       	address1.focus();
	       	isValid = false;
       
   		} else if(!checkCharactersOcurrences(3, address1)){
  	
  			alert("Please enter a valid first line of your address.");
      		address1.focus();
      		isValid = false;	
  	
   		} else if(isEmptyElem(citytown)){
  	 
      		alert("City/Town is mandatory.");
      		citytown.focus();
      		isValid = false;
      
   		} else if(!checkCharactersOcurrences(3, citytown)){
 	
	   		alert("Please enter a valid city/town .");
	   		citytown.focus();
	    	isValid = false;	
   		}
   	}   
   	
   	//Validate Loan Type
   	//Default to Asset Loan -> therefore should not affect existing code
   	
   	if (isValid == true) {
	   	if (loantype.value == "debtmanagement" || loantype.value == "longtermloan") {
	   		formatAmounts();
	   		isValid = validateLongterm();
	   	} else {
	   		isValid = validateAsset();
	   	}
	}
    
	return isValid;
 }



 var account_code='INDIV51202';
 var license_code='UZ62-AY75-KP29-EE49';
 var machine_id='';

 function doPostcode () {

	//RW Added
	document.getElementById("selectaddresslabel").style.display = '';
	document.getElementById("manualPostcodeEnter").style.display = '';
	pcaByPostcodeBegin();

 }
 function finishPostcode() {

	//RW Added
	document.getElementById("selectaddresslabel").style.display = 'none';
	document.getElementById("manualPostcodeEnter").style.display = 'none';
	pcaFetchBegin();
	
 } 
 function manualPostcode() {

	document.getElementById("address1").disabled = false;
	document.getElementById("citytown").disabled = false;
	
	document.getElementById("address1").style.backgroundColor  = 'white';
	document.getElementById("citytown").style.backgroundColor  = 'white';

 }
 function pcaByPostcodeBegin()
   {
	  var postcode = document.forms[0]["postcode"].value;
      var scriptTag = document.getElementById("pcaScriptTag");
      var headTag = document.getElementsByTagName("head").item(0);
      var strUrl = "";
      
      document.getElementById("divLoading").style.display = '';
      
      //Build the url
      strUrl  = "https://services.postcodeanywhere.co.uk/inline.aspx?";
      strUrl += "&action=lookup";
      strUrl += "&type=by_postcode";
      strUrl += "&postcode=" + escape(postcode);
      strUrl += "&account_code=" + escape(account_code);
      strUrl += "&license_code=" + escape(license_code);
      strUrl += "&machine_id=" + escape(machine_id);
      strUrl += "&callback=pcaByPostcodeEnd";
      
      //Make the request
      if (scriptTag)
         {
            //The following 2 lines perform the same function and should be interchangeable
            headTag.removeChild(scriptTag);
            //scriptTag.parentNode.removeChild(scriptTag);
         }
      scriptTag = document.createElement("script");
      scriptTag.src = strUrl
      scriptTag.type = "text/javascript";
      scriptTag.id = "pcaScriptTag";
      headTag.appendChild(scriptTag);
      
   }

 	function pcaByPostcodeEnd()
	   {
		  document.getElementById("divLoading").style.display = 'none';
		  
	      //Test for an error
	      if (pcaIsError)
	         {
	            //Show the error message
	            document.getElementById("selectaddress").style.display = 'none';
	            document.getElementById("btnFetch").style.display = 'none';
	            alert(pcaErrorMessage);
	            
	         }
	      else
	         {
	         	
	            //Check if there were any items found
	            if (pcaRecordCount==0)
	               {
	                  document.getElementById("selectaddress").style.display = 'none';
					  document.getElementById("btnFetch").style.display = 'none';
	                  alert("Sorry, no matching items found. Please try another postcode.");
	               }
	            else
	               {
	               	
					  document.forms[0]["selectaddress"].style.display = '';
					  document.forms[0]["btnFetch"].style.display = '';
					  
					  for (i=document.forms[0]["selectaddress"].options.length-1; i>=0; i--) {
						  document.forms[0]["selectaddress"].options[i] = null;
					  }
					  
					  document.forms[0]["selectaddress"].options[0] = new Option("Please Select Address", "");
					  
					  for (i=0; i<pca_id.length; i++) {
	                    document.forms[0]["selectaddress"].options[document.forms[0]["selectaddress"].length] = new Option(pca_description[i], pca_id[i]);
	                  }
	               }
	         }
	   }

 function pcaFetchBegin()
   {
	  var address_id = document.forms[0]["selectaddress"].value;
      var scriptTag = document.getElementById("pcaScriptTag");
      var headTag = document.getElementsByTagName("head").item(0);
      var strUrl = "";

      //Build the url
      strUrl  = "https://services.postcodeanywhere.co.uk/inline.aspx?";
      strUrl += "&action=fetch";
      strUrl += "&id=" + escape(address_id);
      strUrl += "&account_code=" + escape(account_code);
      strUrl += "&license_code=" + escape(license_code);
      strUrl += "&machine_id=" + escape(machine_id);
      strUrl += "&callback=pcaFetchEnd";

      //Make the request
      if (scriptTag)
         {
            //The following 2 lines perform the same function and should be interchangeable
            headTag.removeChild(scriptTag);
            //scriptTag.parentNode.removeChild(scriptTag);
         }
      scriptTag = document.createElement("script");
      scriptTag.src = strUrl
      scriptTag.type = "text/javascript";
      scriptTag.id = "pcaScriptTag";
      headTag.appendChild(scriptTag);
      
      document.forms[0]["selectaddress"].style.display = 'none';
      document.forms[0]["btnFetch"].style.display = 'none';
   }

 function pcaFetchEnd()
   {
      //Test for an error
      if (pcaIsError)
         {
            //Show the error message
            alert(pcaErrorMessage);
         }
      else
         {
            //Check if there were any items found
            if (pcaRecordCount==0)
               {
                  alert("Sorry, no matching items found");
               }
            else
               {
                  if (pca_line2[0] == "" || pca_line2[0] == null)
				  	document.forms[0]["address1"].value = '' + pca_line1[0];
				  else
				  	document.forms[0]["address1"].value = '' + pca_line1[0] + ', ' + pca_line2[0];
				  
				  document.forms[0]["address2"].value = '' + pca_line1[0];
				  document.forms[0]["citytown"].value = '' + pca_post_town[0];
				  document.forms[0]["postcode"].value = '' + pca_postcode[0];
				  
				  var type = document.getElementById("type");
				  type.focus();
               }
         }
   }
   function ShowPopup(hoveritem)
   {
	hp = document.getElementById("hoverpopup");
	
	// Set position of hover-over popup
	hp.style.top = hoveritem.offsetTop + 18;
	hp.style.left = hoveritem.offsetLeft + 20;
	
	// Set popup to visible
	hp.style.visibility = "Visible";
   }
	
   function HidePopup()
   {
	hp = document.getElementById("hoverpopup");
	hp.style.visibility = "Hidden";
   }

   function ClearBox(desc)
   {
    if (desc.value == 'Enter brief description...')
   	{
   		desc.value = '';
   	}
   }
   
   function ClearResaleBox(desc)
   {
    if (desc.value == 'Enter second hand value...')
   	{
   		desc.value = '';
   	}
   	
   }
   
   function ClearLoanAmountBox(desc)
   {
	
	if ((desc.value).lastIndexOf('Loan Amount Required') >= 0)
   	{
   		desc.value = '';
   	}
   	
   }
   
   function ClearPropertyBox(desc)
   {
	
	if ((desc.value).lastIndexOf('Property Value') >= 0)
   	{
   		desc.value = '';
   	}
   	
   }
   
   function ClearMortgageBox(desc)
   {
	
	if ((desc.value).lastIndexOf('Outstanding Mortgage Value') >= 0)
   	{
   		desc.value = '';
   	}
   	
   }
   
   function addAnotherItem()
   {
  
     var counter = document.getElementById("counter");

     if(validateForm())
     {    
        var sval = document.getElementById("secondhandvalue");
        var desc = document.getElementById("description_area");
        var type = document.getElementById("type");
        var make = document.getElementById("make");
   	
    	if(type.value == "Watch") {
    		var makeVar = make.value;
    		
    	} else {
    		var makeVar = '';
    	}
    	
    	make.value = '';
    	
        var sval_next = document.getElementById("secondhandvalue" + counter.value);
        var desc_next = document.getElementById("description" + counter.value);
        var type_next = document.getElementById("type" + counter.value);
        var make_next = document.getElementById("make" + counter.value);

        var cartDiv = document.getElementById("cart" + counter.value);

        sval_next.value = sval.value;
        desc_next.value = desc.value;
        type_next.value = type.value;
        make_next.value = makeVar;

        cartDiv.style.visibility = "Visible";
        //cartDiv.innerHTML = "<p class='cart'><span style='padding-left:11px; padding-top:3px; padding-bottom:2px;'><a style='cursor:pointer;' onclick=\"editItem('" + counter.value + "')\">[Edit]</a>&nbsp;<b>Item " + counter.value + ":</b> " + type.value + " (&pound;" + sval.value + ")</span></p>";
		//<p align='right'><a style='cursor:pointer;' onclick=\"editItem('" + counter.value + "')\">[Edit]</a>
				
		cartDiv.innerHTML = "<li><h5>" + type.value + " &pound;" + sval.value + "</h5><p>" + desc.value + "</p></li>";
		
		//"<p class='cart'><span style='padding-left:11px; padding-top:3px; padding-bottom:2px;'><a style='cursor:pointer;' onclick=\"editItem('" 
		//+ counter.value + "')\">[Edit]</a>&nbsp;<b>Item " 
		//+ counter.value + ":</b> " + type.value + " (&pound;" + sval.value + ")</span></p>"
		
        sval.value = '';
        desc.value = '';
        type.value = '';
              
        counter.value = (counter.value - 0) + 1;
    }

   }
   
  
   
   function saveItem()
   {
   	var count_holder = document.getElementById("countposition");
   	var count = count_holder.value;
   	
   	var sval_hidden = document.getElementById("secondhandvalue" + count);
    var desc_hidden = document.getElementById("description" + count);
    var type_hidden = document.getElementById("type" + count);
    var make_hidden = document.getElementById("make" + count);
    
    var sval = document.getElementById("secondhandvalue");
    var desc = document.getElementById("description_area");
    var type = document.getElementById("type");
    var make = document.getElementById("make");
    
    sval_hidden.value = sval.value;
    desc_hidden.value = desc.value;
    type_hidden.value = type.value;
    make_hidden.value = make.value;
    
    var cartDiv = document.getElementById("cart" + count);

    cartDiv.style.visibility = "Visible";
    cartDiv.innerHTML = "<span style='padding-left:11px; padding-top:3px; padding-bottom:2px;'><a style='cursor:pointer;' onclick=\"editItem('" + count + "')\">[Edit]</a>&nbsp;<b>Item " + count + ":</b> " + type.value + " (&pound;" + sval.value + ")</span>";
		
	sval.value = '';
    desc.value = '';
    type.value = '';
    make.value = '';
    
    var saveButton = document.getElementById("saveitem_wrapper");
    saveButton.style.display = "none";
    //saveButton.style.height = "0px";
    
    var addButton = document.getElementById("addanotheritem_wrapper");
    addButton.style.display = "block";
    //addButton.style.height = "33px";
    
    var enquiryButton = document.getElementById("enquiry_wrapper");
    enquiryButton.style.display = "block";
    //enquiryButton.style.height = "60px";
   	
   	//Reset countposition
   	count_holder.value == '-1';
   }
   
   function editItem(count)
   {
    //Store count, so it can be retrieved on save
    var count_holder = document.getElementById("countposition");
   	count_holder.value = count;
   
   	//count will be 1 -5
   	var sval_hidden = document.getElementById("secondhandvalue" + count);
    var desc_hidden = document.getElementById("description" + count);
    var type_hidden = document.getElementById("type" + count);
    var make_hidden = document.getElementById("make" + count);
    
    var sval = document.getElementById("secondhandvalue");
    var desc = document.getElementById("description_area");
    var type = document.getElementById("type");
    var make = document.getElementById("make");
    
    sval.value = sval_hidden.value;
    desc.value = desc_hidden.value;
    type.value = type_hidden.value;
    make.value = make_hidden.value;
   
   	//Add Item Details back into the box and popup a save button
   	//Disable submit and add buttons until save button is clicked
   	
   	var saveButton = document.getElementById("saveitem_wrapper");
    saveButton.style.display = "block";
    //saveButton.style.height = "60px";
        
    var addButton = document.getElementById("addanotheritem_wrapper");
    addButton.style.display = "none";
    //addButton.style.height = "0px";
    
    var enquiryButton = document.getElementById("enquiry_wrapper");
    enquiryButton.style.display = "none";
    //enquiryButton.style.height = "0px";

   }
   
   onload = function fillCart()
   {
   	   var i = 1;
	   for (i = 1; i < 10; i++)
	   {
	   	var sval = document.getElementById("secondhandvalue" + i);
	    var type = document.getElementById("type" + i);
	   	
	   	var cartDiv = document.getElementById("cart" + i);
	   	//alert("Cart " + i + ": " + sval.value);
	   	
	   	if (sval.value > 0)
	   	{
	   		cartDiv.style.visibility = "Visible";
	   		cartDiv.innerHTML = "<span style='padding-left:11px; padding-top:3px; padding-bottom:2px;'><b>Item " + i + ":</b> " + type.value + " (&pound;" + sval.value + ")</span>";
		}	
	   }
   }
   
   function showWatchMakes(checkedOption){
	   var make = document.getElementById("make");
	   
	   if(checkedOption.value == "Watch"){
	   
		   showdiv('watches-ddl');

	   } else{
		   
		   hidediv('watches-ddl'); 
		   make.value= '';
	   }
   }
   
   function showPropertySelect(checkedOption) {

	   if(checkedOption.checked == false) {
		   hidediv('propertyselectyes'); 
		   hidediv('propertyselectno'); 
	   } else {
		 
		   if(checkedOption.value == "home_yes") {
			   showdiv('propertyselectyes');
		   } else {
			   hidediv('propertyselectyes'); 
		   }
		   
		   if(checkedOption.value == "home_no") {
			   showdiv('propertyselectno');
		   } else {
			   hidediv('propertyselectno'); 
		   }
	   }
   }
   
   
   function showAssetLoan(checkedOption) {

	   if(checkedOption.value == "assetloan" || checkedOption.value == "sellvaluables") {
		   showdiv('assetloan');
		   showdiv('additembutton');
		   
	   } else {
	   
	   	   hidediv('assetloan'); 
	   	   hidediv('additembutton');
		   
	   }
	   
	   
	   if(checkedOption.value == "longtermloan"  || checkedOption.value == "debtmanagement") {
		   showdiv('longtermloan');
		  
		   //On showing this div, decide whether or not to show property div
		   //var homeowner = document.getElementById("homeowner");
    	   //showPropertySelect(homeowner);
	   } else {

		   hidediv('longtermloan'); 
	   }
	   
	   
   }
   
   
   function hidediv(id) {
		//safe function to hide an element with a specified id
		if (document.getElementById) { // DOM3 = IE5, NS6
			document.getElementById(id).style.display = 'none';
		}
		else {
			if (document.layers) { // Netscape 4
				document.id.display = 'none';
			}
			else { // IE 4
				document.all.id.style.display = 'none';
			}
		}
	}

	function showdivnormal(id) {
		//safe function to show an element with a specified id
			  
		if (document.getElementById) { // DOM3 = IE5, NS6
			document.getElementById(id).style.display = 'normal';
		}
	}

	function showdiv(id) {
		//safe function to show an element with a specified id
			  
		if (document.getElementById) { // DOM3 = IE5, NS6
			document.getElementById(id).style.display = '';
		}
		else {
			if (document.layers) { // Netscape 4
				document.id.display = 'block';
			}
			else { // IE 4
				document.all.id.style.display = 'block';
			}
		}
	}
	
// ]]>
