var verifiedMobileNumber = true; //Used to verify the mobilenumber.
var verifiedNumber = "";
var verificationCompleted = true;
var validationResponse = "";

////////////////////////////////JQuery cookie Plugin///////////////////////////////////

jQuery.cookie = function(name, value, options) {
	// //alert('in query cookie');
	if (typeof value != 'undefined') { // name and value given, set cookie
		options = options || {};
		if (value === null) {
			value = '';
			options.expires = -1;
		}
		var expires = '';
		if (options.expires
				&& (typeof options.expires == 'number' || options.expires.toUTCString)) {
			var date;
			if (typeof options.expires == 'number') {
				date = new Date();
				date.setTime(date.getTime()
						+ (options.expires * 24 * 60 * 60 * 1000));
			} else {
				date = options.expires;
			}
			expires = '; expires=' + date.toUTCString(); // use expires
			// attribute,
			// max-age is not
			// supported by IE
		}
		// CAUTION: Needed to parenthesize options.path and options.domain
		// in the following expressions, otherwise they evaluate to undefined
		// in the packed version for some reason...
		var path = options.path ? '; path=' + (options.path) : '';
		var domain = options.domain ? '; domain=' + (options.domain) : '';
		var secure = options.secure ? '; secure' : '';
		document.cookie = [ name, '=', encodeURIComponent(value), expires,
				path, domain, secure ].join('');
	} else { // only name given, get cookie
		var cookieValue = null;
		if (document.cookie && document.cookie != '') {
			var cookies = document.cookie.split(';');
			for ( var i = 0; i < cookies.length; i++) {
				var cookie = jQuery.trim(cookies[i]);
				// Does this cookie string begin with the name we want?
				if (cookie.substring(0, name.length + 1) == (name + '=')) {
					cookieValue = decodeURIComponent(cookie
							.substring(name.length + 1));
					break;
				}
			}
		}
		return cookieValue;
	}
};
////////////////////////////////Offer Ticker///////////////////////////////////
/*
 * Load an array of offers and randomly display an offer.
 * Users will periodically be shown a new random offer. The offer that they
 * see should be consistent across multiple pages, until the next period has
 * expired. 
 * 
 * A session cookie is used to manage the offers displayed. No checks are 
 * made to prevent a user being presented the same random offer during their 
 * session.
 * 
 * For example, if a random offer is being shown every 5 seconds, the 
 * user will see the same offer for the period of 5 seconds, irrespective of 
 * which page they visit. 
 */

// alert('START');

var offerArray = [];
var j = 0;

function initOffers() {
	
	offerArray = new Array();

	// remote call for offers
	// alert('Remote call for offers');
	if(offerArray.length < 1){
		jQuery.getJSON("/loanapplication/feed/json/offers", function(data) {
			// load into array
			// alert('load offer array');
			jQuery.each(data.offers, function(i, offer) {
				offerArray[i] = offer;
			});
			//alert('offers loaded');
			// rotater sets the content
			rotater();
			return false;
		});
	}
}

function getItemURL(item) {
	var baseurl = '/what-we-loan-against/pawn-';
	var url = '';
	if (item.toLowerCase() == 'watch' 
			|| item.toLowerCase() == 'jewellery'
			|| item.toLowerCase() == 'gold' 
			|| item.toLowerCase() == 'ring'
			|| item.toLowerCase() == 'art' 
			|| item.toLowerCase() == 'antique'
			|| item.toLowerCase() == 'gemstones'
			|| item.toLowerCase() == 'car (over 25K)') {
		if(item.toLowerCase() == 'watch'){
			item = 'watches';
		}
		url = baseurl + item;
	}
	return url.toLowerCase();
}

function writeTickerContent(element) {
		
	
	// special cases to build the phrase properly for each type of item
	var englishLanguageArticle = '';
	var watchMake = '';
			
	if (element.item.toLowerCase() == 'watch'
			|| element.item.toLowerCase() == 'car (over 25K)') {
		watchMake = ' (' + element.make + ') ';
		englishLanguageArticle = 'a ';
	}

	if (element.item.toLowerCase() == 'antique')
		englishLanguageArticle = 'an ';
	
	// formatting offer amount if its >= 1000;
	var formattedAmount = element.offerAmount;
	var formattedAmountLength = formattedAmount.length;
	
	if(formattedAmount.length >= 4){
		var rightSideOfComma = formattedAmount.substring(formattedAmountLength - 3);
		var leftSideOfComma = formattedAmount.substring(0, formattedAmountLength - 3);
		formattedAmount = leftSideOfComma + ',' + rightSideOfComma;
	}	
	
	var tickerContent = '<b><span style="font-size:14px; color:#a50b1b;">Recent Offers: </span><span style="font-size:14px; color:#8C8C8C;"> '
			+ '&pound;'
			+ formattedAmount
			+ ' for '
			+ englishLanguageArticle
			+ '<a style=\"font-size:14px; color:#8C8C8C;\" href=\"'
			+ getItemURL(element.item)
			+ '\">'
			+ element.item
			+ watchMake
			+ '</a>'
			+ ' to '
			+ element.title
			+ ' '
			+ element.name
			+ '</span></b>';

	 //alert('tickerContent '+ tickerContent);
	document.getElementById("tickermessage").innerHTML = tickerContent;
}

var index;

function rotater() {
	//alert('rotater called, offerArray = ' + offerArray);
	
	index = Math.floor(Math.random() * (offerArray.length + 1));
	// how often checks if we have to rotate - in seconds
	var howOften = 2; 
	// how often to rotate
	var delayTimeVar = 5 + (Math.floor(Math.random() * 7));
	// time now in secs
	var d = new Date();
	var timeNow = d.getTime() / 1000;

	//alert('index ' + index);
	// alert('.cookie ' + jQuery.cookie("index"));
	if (jQuery.cookie("index") == null) {
		jQuery.cookie("index", index);
		// alert(' cookie index: ' + index);
	} else {
		index = jQuery.cookie("index");
		//alert('***** cookie index: ' + index);
	}

	// alert('Rotator index: '+index +'howOften:'+howOften+'OfferArrayLenght'+offerArray.length + 'j:' + j);
	if (jQuery.cookie("delayTime") == null) {
		//alert('D time null ');

		/* set cookies values for the first time */
		jQuery.cookie("delayTime", delayTimeVar);
		jQuery.cookie("storedTime", timeNow);

		storedTimeVar = 0;

		// alert('no previous cookie value.');

	} else {
		delayTimeVar = jQuery.cookie("delayTime");
		storedTimeVar = jQuery.cookie("storedTime");
		//alert('D time not null: ' + delayTimeVar);
	}

	//alert('delayTimeVar+storedTimeVar '+ (parseInt(delayTimeVar)+parseInt(storedTimeVar)) + ' <= ' + timeNow +' ?' );
	if ((parseInt(delayTimeVar) + parseInt(storedTimeVar)) <= timeNow) {
		//alert('update: offer ');
		jQuery.cookie("storedTime", timeNow);

		// select a new offer
		index = Math.floor(Math.random() * (offerArray.length + 1)); // start
		// the
		// counter
		// at 0
		jQuery.cookie("index", index);
		//alert('index before update ' + index);
		//stored new random delay value
		jQuery.cookie("delayTime", delayTimeVar);
		writeTickerContent(offerArray[index]);

	} else {
		//alert('do not update: inner html');
		writeTickerContent(offerArray[index]);
	}

	//index = Math.floor(Math.random() * (offerArray.length + 1));
	setTimeout("rotater()", howOften * 1000);
}

////////////////////////////////News Ticker ARCHIVED///////////////////////////////////

//
// common borro form validation functions
//

//
// common borro form validation functions
//


//
// common borro form validation functions
//

//
// common borro form validation functions
//

function openwindow(url)
{
	var newwindow;
	newwindow=window.open(url,'name','height=600,width=570,resizable=yes,scrollbars=yes');
	if (window.focus) {newwindow.focus()}
}


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 minDigitsInUSPhoneNumber = 10;
var maxDigitsInUSPhoneNumber = 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 checkUSPhone(phoneElem){
	
	
	  removeAmericanCharacters(phoneElem);  
	  s = phoneElem.value;
	
	  total = (isInteger(s) && s.length >= minDigitsInUSPhoneNumber && s.length <= maxDigitsInUSPhoneNumber);
	
	  return total;
	}


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) {

  // don't validate international postcodes
  var countryCode = getCountryCode();
  if (countryCode != 'GB' && countryCode != 'DEFAULT') {
	  return toCheck.value;
  }

  // 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");
	var channelType = document.getElementById("channelTypeId");
	
	if(type.value== "" && type1.value == "") {

    	alert("Please enter an item type.");
      	type.focus(); 
      	isValid = false;

	} else if((type.value == "Watch" || type.value == "Vehicle") && 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(!channelType || channelType.value != 150) { 
    	  if(isEmptyElem(secondhandvalue) && secondhandvalue1.value == ""){
 
	         alert("Please enter an estimated resale value.");
	         secondhandvalue.focus();
	         isValid = false;
	         
	      } else if(isNumber(secondhandvalue.value)==false && secondhandvalue1.value == ""){
	    	 secondhandvalue.value = secondhandvalue.value.replace(/\u00A3/g, '');
	    	 secondhandvalue.value = secondhandvalue.value.replace(/\u0024/g, '');
	    	 secondhandvalue.value = secondhandvalue.value.replace(/,/g, '');
	    	 // if still bad, complain
	    	 if (!isNumber(secondhandvalue.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 validateBackendIdCheckForm() {

	var licenceDate = document.getElementById("licenceDate");
	var licenceNumber = document.getElementById("licenceNumber");
	var licencePostcode = document.getElementById("licencePostcode");
	
	var passportExpiryDate = document.getElementById("passportExpiryDate");
	var passportLongNumber = document.getElementById("passportLongNumber");
	
	var surname = document.getElementById("surname");
	var firstname = document.getElementById("firstname");

	isValid = true;
	
	if((!isEmptyElem(licenceDate) || !isEmptyElem(licenceNumber) || !isEmptyElem(licencePostcode))
	&& (isEmptyElem(licenceDate) || isEmptyElem(licenceNumber) || isEmptyElem(licencePostcode))) {
		 
		//If any licence field is filled out, they must all be filled out
        alert("Please fill out all licence details.");
        licenceDate.focus();
        isValid = false;
              
    } else if(!isEmptyElem(licenceDate) && !isEmptyElem(licenceNumber) && !isEmptyElem(licencePostcode) && licenceNumber.value.length > 16){
    	
    	//If all licence fields are filled out and the licence number is more than 16 characters.
    	alert("The licence number you have entered is invalid.\n It may not be longer than 16 characters.");
		licenceNumber.focus();
		isValid = false;
    } else if( (!isEmptyElem(passportExpiryDate) || !isEmptyElem(passportLongNumber))
	&& (isEmptyElem(passportExpiryDate) || isEmptyElem(passportLongNumber))
    ) {
		 
        //If any passport field is filled out, they must all be filled out
        alert("Please fill out all passport details.");
        passportExpiryDate.focus();
        isValid = false;
              
    } else if(!isEmptyElem(passportExpiryDate) && !isEmptyElem(passportLongNumber) && passportLongNumber.value.length > 30) {
    	
    	//If all passport fields are filled out and the long passport number is more than 30 characters.
    	alert("The long passport number you have entered is invalid.\n It may not be longer than 30 characters.");
		passportLongNumber
		isValid = false
	
    } else if(isEmptyElem(surname)){
    	 
        alert("Please enter your surname.");
        surname.focus();
        isValid = false;

	} else if(isEmptyElem(firstname)){
    	 
        alert("Please enter your firstname.");
        firstname.focus();
        isValid = false;

	}
	
	return isValid;
	
}

function validateShortForm(formType) {
	
	var phone = document.getElementById("phone");
	var mobile = document.getElementById("mobile");
	var email = document.getElementById("email");
	
	var surname = document.getElementById("surname");
	var firstname = document.getElementById("firstname");
	
	var description_area = document.getElementById("description_area");
	
	var secondhandvalue = document.getElementById("secondhandvalue");
	var type = document.getElementById("type");
	
	//Watches only
	var make = document.getElementById("make");

	var surnameLbl = document.getElementById("surnameLbl");
	if (typeof surnameLbl == 'undefined' || surnameLbl == null) {
		surnameLbl = "surname";
	} else {
		surnameLbl = surnameLbl.innerHTML;
	}
	
	isValid = true;
	
	if(isEmptyElem(firstname)){
		 
        alert("Please enter your first name.");
        firstname.focus();
        isValid = false;
              
    } else if(!atLeastOneCharacter(firstname)){
		 
        alert("Please enter a valid first name.");
        firstname.focus();
        isValid = false;
              
    } else if(isEmptyElem(surname)){
    	 
        alert("Please enter your " + surnameLbl + ".");
        surname.focus();
        isValid = false;

    } else if(!atLeastOneCharacter(surname)){
		 
        alert("Please enter a valid " + surnameLbl + ".");
        surname.focus();
        isValid = false;
           
    }  else if (((checkUkPhone(phone.value)==false)||(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(isEmptyElem(email)){
        
         alert("Please enter an email address.");
         email.focus();
         isValid = false;
     
    } else if(checkEmail(email) == false) {
	
    	alert("Please enter a valid email address.");
        email.focus();
        isValid = false;
    
    } else if(isEmptyElem(description_area) || description_area.value == "Description") {
	
    	alert("Please enter a description.");
        description_area.focus();
        isValid = false;
    } else if(isEmptyElem(make) && formType == "watch") {
	
    	alert("Please enter a watch brand.");
        make.focus();
        isValid = false;	
        
    } else if(isEmptyElem(type) && formType == "gamble") {
	
    	alert("Please enter an item type.");
        type.focus();
        isValid = false;	
        
    } else if(isEmptyElem(secondhandvalue) && formType == "gamble") {
	
    	alert("Please enter an secondhand value.");
        secondhandvalue.focus();
        isValid = false;	
        
    } else if(type.value == "Watch" && make.value == "" && formType == "gamble") {
  		   
   		alert("Please enter a watch make.");
   		make.focus(); 
      	isValid = false;  

     } else if(!(secondhandvalue.value > 0) && formType == "gamble") {
 
         alert("Please ensure the estimated resale value which is greater than 0");
         secondhandvalue.focus();
         isValid = false;
     }
    
    
    
    
    
    return isValid;
	
}

function prependZero(intValueAsString) {

   intValueAsString = "" + intValueAsString;
   if(intValueAsString.length==1){
   	intValueAsString = "0" + intValueAsString
   } 
  return intValueAsString
}

function validateForm() {
	return validateFormWithAddress(true);	
}

function validateFormWithAddress(withAddress) {
	
	//alert("Validate Form");
	
    isValid = true;
	
	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");
    
    var promocode = document.getElementById("promocode");
    
    var homeCountryElem = document.getElementById("homeCountryId");
    if (homeCountryElem != null && isInteger(homeCountryElem.value)) {
    	homeCountryId = homeCountryElem.value;
    } else {
    	homeCountryId = 20;
    }
    
    //alert("Validate Form: Set home id: " + homeCountryId);

	var surnameLbl = document.getElementById("surnameLbl");
	if (typeof surnameLbl == 'undefined' || surnameLbl == null) {
		surnameLbl = "surname";
	} else {
		surnameLbl = surnameLbl.innerHTML;
	}

    //check = checkUSPhone(phone);
    
    //alert("USP: " + check)
    //alert("homeCountryId: " + homeCountryId.value);
	
	if(isEmptyElem(title)){

        alert("Please select your Title.");
        title.focus();
        isValid = false;
        
	} else if(isEmptyElem(firstname)){
		 
        alert("Please enter a first name.");
        firstname.focus();
        isValid = false;
              
    } else if(!atLeastOneCharacter(firstname)){
		 
        alert("Please enter a valid first name.");
        firstname.focus();
        isValid = false;
              
    } else if(isEmptyElem(surname)){
    	 
        alert("Please enter a " + surnameLbl + ".");
        surname.focus();
        isValid = false;

    } else if(!atLeastOneCharacter(surname)){
		
        alert("Please enter a valid " + surnameLbl + ".");
        surname.focus();
        isValid = false;
    
    }  else if (isEmptyElem(phone)&&(homeCountryId!=30)){ //non-US Validation

		alert("Please enter at least a phone number");
		phone.focus();
		isValid = false;    
		
    }  else if (checkUSPhone(phone)==false&&(homeCountryId==30)){ //US Validation
    	    	
		alert("Please enter a valid US phone number");
		phone.focus();
		isValid = false;    
                
    }  else if ((isEmptyElem(phone)&&(isEmptyElem(mobile)||(mobile.value=="00000000")))&&(homeCountryId!=30)){ //UK Validation

		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))&&(homeCountryId!=30)){ //UK Validation
		
		alert("Please enter a valid UK phone number.");		
		phone.focus();
		isValid = false;
	
	} else if(isEmptyElem(email)){
        
         alert("Please enter an email address.");
         email.focus();
         isValid = false;

    } else if(checkEmail(email) == false){
	
    	alert("Please enter a valid email address.");
        email.focus();
        isValid = false;	
    } else if(loantype.value != null && loantype.value == ""){
		   		   
		 alert("Please select a loan type.");
		 loantype.focus(); 
	     isValid = false; 
  
   	} 
	
	if(isValid && withAddress) {
		if(isEmptyElem(postcode)){
			 alert("Please enter a postcode.");
			 postcode.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("Please enter the first line of your address.");
		       	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("Please enter a city/town.");
	      		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
   	
   	//alert("Validation Done");
 	
   	if (isValid == true) {
	   	
	   	//alert("About to Validate Asset");
	   	if (loantype.value == "debtmanagement" || loantype.value == "longtermloan") {
	   		formatAmounts();
	   		isValid = validateLongterm();
	   	} else {
	   	
	   		//alert("In validateAsset");
	   		isValid = validateAsset();
	   	}
	}

	return isValid;
 }


function validateBackendForm () {

	isValid = true;

	// validate time and date
	var dateElem = document.getElementById("applicationDate");
	var dateVal = dateElem.value;
	// regular expression to match required date format 
	var dateRegEx = /^\d{1,2}\/\d{1,2}\/\d{4}$/; 

    var timeElem = document.getElementById("applicationTime");
	var timeVal = timeElem.value;
	// regular expression to match required time format  
	var timeRegEx = /^([0-1][0-9]|[2][0-3])(:([0-5][0-9])){1,2}$/; 

    if(isEmptyElem(dateElem) || (dateRegEx.test(dateVal) != true)){
    
     	alert("Invalid Date: " + dateVal + "\n Please Enter a date in the format DD/MM/YYYY"); 
     	dateElem.focus(); 
    	isValid = false; 
    			
    } else if(isEmptyElem(timeElem) || (timeRegEx.test(timeVal) != true)){
    
     	alert("Invalid Time: " + timeVal + "\n Please Enter a time in the format hh:mm:ss"); 
     	timeElem.focus(); 
    	isValid = false;
    	 		
    } 
    
    
    // validate time and date
	var sourceElem = document.getElementById("source");
	var sourceVal = sourceElem.value;
	var trackingCid = document.getElementById("trackingCid");
	var backendchanneltypeid = document.getElementById("backendchanneltypeid");

    if(isEmptyElem(sourceElem)){
	 
		alert("Please enter a source, we've got to track applications! ");
   		sourceElem.focus();
    	isValid = false;
 	
    } else if (isEmptyElem(backendchanneltypeid)) {
    	
 	   if (isEmptyElem(trackingCid)){
 			alert("Please select a sub channel.");
 			backendchanneltypeid.focus();
 	        isValid = false;
 		}
 	    	
	} else if (sourceVal == "175") {
	
	   if (isEmptyElem(trackingCid)){
			alert("Tracking CID must be entered when source is Perfect Storm.");
	        trackingCid.focus();
	        isValid = false;
		}
	}
	
	return isValid;
}


 var account_code='INDIV51202';
 var license_code='UZ62-AY75-KP29-EE49';
 var machine_id='';
 
 function getCountryCode() {
	var countryCodeFld = document.getElementById("countrycode");
		
	if (typeof countryCodeFld != 'undefined' && countryCodeFld) {
		return countryCodeFld.value;
	}
	//else
	return 'DEFAULT';
 }

 function doPostcode() {
	document.getElementById("manualPostcodeEnter").style.display = '';
	
	var countryCode = getCountryCode();
	// 3rd party lookup
	if (countryCode == 'GB' || countryCode == 'DEFAULT' || countryCode == '') {
		document.getElementById("selectaddresslabel").style.display = '';
		document.getElementById("selectaddress").style.display = '';

		pcaByPostcodeBegin();
	} else {
		document.getElementById("selectstreetlabel").style.display = '';
		document.getElementById("selectaddresslabel").style.display = 'none';
		document.getElementById("selectstreet").style.display = '';
		document.getElementById("selectaddress").style.display = 'none';

		PostcodeAnywhereInternational_Interactive_RetrieveByPostalCode_v2_11Begin(countryCode);
	}

	//disable the manual input fields
	document.getElementById("address1").disabled = true;
	document.getElementById("citytown").disabled = true;
	
	document.getElementById("address1").style.backgroundColor  = 'rgb(224, 224, 224)';
	document.getElementById("citytown").style.backgroundColor  = 'rgb(224, 224, 224)';
	
	if (countryCode == 'US') {
		document.getElementById("state").disabled = true;
		document.getElementById("state").style.backgroundColor  = 'rgb(224, 224, 224)';
	}
 }
 
 function doStreet() {
	document.getElementById("selectstreetlabel").style.display = '';
	document.getElementById("selectaddresslabel").style.display = '';
	document.getElementById("manualPostcodeEnter").style.display = '';
	// 3rd party lookup
	PostcodeAnywhereInternational_Interactive_ListBuildings_v1_12Begin();
	document.getElementById("selectstreet").style.display = '';
	document.getElementById("selectaddress").style.display = '';
 }
 
 function finishPostcode(countryCode) {
	document.getElementById("selectaddresslabel").style.display = 'none';
	document.getElementById("manualPostcodeEnter").style.display = 'none';

	var countryCode = getCountryCode();
	if (countryCode == 'GB' || countryCode == 'DEFAULT') {
		pcaFetchBegin();
	} else {
		document.getElementById("selectstreetlabel").style.display = 'none';
		PostcodeAnywhereInternational_FetchEnd();
	}
 }
 
 function manualPostcode() {
	// enable the manual input fields
	document.getElementById("address1").disabled = false;
	document.getElementById("citytown").disabled = false;
	
	document.getElementById("address1").style.backgroundColor  = 'white';
	document.getElementById("citytown").style.backgroundColor  = 'white';
	
	var countryCode = getCountryCode();
	if (countryCode == 'US') {
		document.getElementById("state").disabled = false;
		document.getElementById("state").style.backgroundColor  = 'white';
	}
	
 }
 
 // supplied js - shouldnt need to edit
 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('INDIV51202');
      strUrl += "&license_code=" + escape('UZ62-AY75-KP29-EE49');
      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);
}

//supplied js - shouldnt need to edit
 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]);
            }
		 }
	 }
}

//supplied js - shouldnt need to edit
 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('INDIV51202');
      strUrl += "&license_code=" + escape('UZ62-AY75-KP29-EE49');
      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';
   }

//supplied js - shouldnt need to edit
 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 = '';
				  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 = '';
   	}else{
   		if(desc.value.indexOf('Enter brief description...') != -1){
   			var auxString = desc.value.replace('Enter brief description...', '');
   			desc.value = auxString;   			
   		}   		
	   }
   }
   
   function ClearShortBox(desc)
    {
	    if (desc.name == 'description')
	   	{
	   		if (desc.value == 'Description') {
	   			desc.value = '';
	   		} else if (desc.value == '') {
	   			desc.value = 'Description';
	   		}
	   	}
	   	if (desc.name == 'surname')
	   	{
	   		if (desc.value == 'Surname') {
	   			desc.value = '';
	   		} else if (desc.value == '') {
	   			desc.value = 'Surname';
	   		}
	   	}
	   	if (desc.name == 'firstname')
	   	{
	   		if (desc.value == 'Firstname') {
	   			desc.value = '';
	   		} else if (desc.value == '') {
	   			desc.value = 'Firstname';
	   		}
	   	}
	   	if (desc.name == 'email')
	   	{
	   		if (desc.value == 'Email') {
	   			desc.value = '';
	   		} else if (desc.value == '') {
	   			desc.value = 'Email';
	   		}
	   	}
	   	if (desc.name == 'phone')
	   	{
	   		if (desc.value == 'Phone') {
	   			desc.value = '';
	   		} else if (desc.value == '') {
	   			desc.value = 'Phone';
	   		}
	   	}
	   	if (desc.name == 'secondhandvalue')
	   	{
	   		if (desc.value == 'Approx. used value (�)') {
	   			desc.value = '';
	   		} else if (desc.value == '') {
	   			desc.value = 'Approx. used value (�)';
	   		}
	   	}

    }
   
   function ClearResaleBox(desc)
   {
    if (desc.value == 'Enter second hand value...')
   	{
   		desc.value = '';
   	}
   	
   }
   
   function ClearELBox(desc)
   {
    if (desc.value == 'Enter Estimated Loan 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 = '';
   	}
   	
   }
   /* 
   window.onload = onLoadFunctionSet;
 
   function onLoadFunctionSet()
   {	var currentPath = window.location.pathname;
	   	initOffers();
	   	if(currentPath == "/" || currentPath == "/start"){
	   		initNews();
	   	}
   		packIssueChange();
   		fillCart();
   }
   
    */
   jQuery(document).ready(function () {
	
	    //initOffers();
  		packIssueChange();
  		fillCart();
	   
   });
  
   function packIssueChange()
   {
  		var packSent = document.getElementById("packIssuedFlag");

		if (packSent != null) {
	
	   		if(packSent.value == "Yes") {
	    		showdiv('packIssued');
				hidediv('noPackIssued'); 
	    		
	    	}
	    	if(packSent.value == "No") {
	    		hidediv('packIssued');
				showdiv('noPackIssued');
	    		
	    	} 
	   }
   } 
   
   function addAnotherItem(isBackendApp) 
   {
  
     var counter = document.getElementById("counter");

     if (validateFormWithAddress(false) && (!isBackendApp || validateManualApp())) 
     {
    	 
        var sval = document.getElementById("secondhandvalue");
        var desc = document.getElementById("description_area");
        var type = document.getElementById("type");
        var make = document.getElementById("make");
        var itemupload = document.getElementById("itemupload");
   	
    	if (type.value == "Watch" || type.value == "Vehicle" ) {
    		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 itemupload_next = document.getElementById("itemupload" + counter.value);

        var cartDiv = document.getElementById("cart" + counter.value);
        
        //Hide file upload box
        //var uai = document.getElementById("upload-art-image");
        //uai.style.visibility = "hidden";

        sval_next.value = sval.value;
        desc_next.value = desc.value;
        type_next.value = type.value;
        make_next.value = makeVar;
        //itemupload_next.value = itemupload.value;

        //can't copy FILE values over
        //hide file upload
        //make visible next item upload
        itemupload_next.style.visibility = "Visible";	
        itemupload.style.visibility = "hidden";
                
        if (counter.value > 1) {
        	curr_count = counter.value - 1;
        	//alert("Getting element: " + "itemupload" + curr_count);
        	var itemupload_current = document.getElementById("itemupload" + curr_count);
        	itemupload_current.style.visibility = "hidden";
        }
        
        itemupload_next.style.height = "auto";	
        itemupload.style.height = "0px";
       
        var symbol = "&pound;";
        homeCountry = document.getElementById("homeCountryId");
        if(homeCountry.value == 30) {
        	symbol = "$";
        }
        
        cartDiv.style.visibility = "Visible";		
		cartDiv.innerHTML = 
		"<div style='margin-top:15px; padding: 5px 20px 5px 20px;' class='bottomPart'>" +
		"<table><tbody><tr><td>Valuable:</td><td style='padding-left:5px'>" + type.value + "</td></tr>" +
		"<tr><td>Est Value:</td><td style='padding-left:5px'>" + symbol + sval.value + "</td></tr>" +
		"<tr><td>Description:</td><td style='padding-left:5px'>" + desc.value + "</td></tr>" +
		"<tr><td>File:</td><td style='padding-left:5px'>" + itemupload.value + "</td></tr>" +
		"</tbody></table><p></p></div>";
		
        sval.value = '';
        desc.value = '';
              
        counter.value = (counter.value - 0) + 1;
     }

   }
   
   function showAddress()
   {
   	
   	document.getElementById("address_area").style.display = '';
   
   }
   
   function addAnotherFriend()
   {
  	
  	var counter = document.getElementById("counter");
    var count = counter.value;
    
    document.getElementById("name").value = "updated";
  	alert('Add Another Friend: ' + counter.value);
  
  	var addContent = '<p>'
	+	'<label for="name' + count + '">To: </label>'
	+	'<input type="text" value="" id="name' + count + '" name="<portlet:namespace />name' + count + '">'
	+	'<label for="email' + count + '">Email:</label>'
	+	'<input name="<portlet:namespace />email' + count + '" type="text" value="" id="email' + count + '">'
	+ '</p>';
	
	var friendDiv = document.getElementById("friends");

    friendDiv.style.visibility = "Visible";	
	friendDiv.innerHTML += addContent;

   }

   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";

   }
   
   function fillCart()
   {
   	var svh = document.getElementById("secondhandvalue");
   
   	if (svh != null) {
   	   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);
	   	
	   	if (sval != null) {
		   	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 setMake(checkedOption) {
	   
	   var type = document.getElementById("type");
	   var make = document.getElementById("make");
	   var carmake = document.getElementById("carmake");
	   var watchmake = document.getElementById("watchmake");
	   
	   //alert("type: " + type.value + ", WM: " + watchmake.value + ", M: " + make.value);
	   
	   if(type.value == "Watch") {
		   make.value = watchmake.value;

	   } else if(type.value == "Vehicle") {
		   make.value = carmake.value;
		   
	   } else {
		   make.value= '';

	   }  
	   
	   //alert("____M: " + make.value);
   }
   
   function showWatchMakes(checkedOption) {
	   
	   //THIS DOES MORE THAN WATCHES
	   //ANY REQUIRED ACTION ON CHANGE ITEM
	   
	   
	   var make = document.getElementById("make");
	   var carmake = document.getElementById("carmake");
	   var watchmake = document.getElementById("watchmake");
	   
	   if(checkedOption.value == "Watch") {
	   
		   showdiv('watches-ddl');
		   hidediv('car-ddl');
	
	   } else if(checkedOption.value == "Vehicle") {
			   
		   showdiv('car-ddl');
		   hidediv('watches-ddl'); 
			   
	   } else {
		   
		   hidediv('watches-ddl'); 
		   hidediv('car-ddl');
		   make.value= '';
	   }  
	   
	   //Upload Div
	   if(checkedOption.value == "Art") {
		   showdiv('upload-art-image');	   
	   } else {
		   hidediv('upload-art-image'); 
	   }  
   }
   
   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
			if (document.getElementById(id)) {
				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';
			}
		}
	}
	
// ]]>
	

//////////////////////////////// Exit Survey ///////////////////////////////////
	
	// to display survey
	/*
	survey = {
		active:1,
		init: function (){
			// check whether to do survey
			if(survey.active == 1 && jQuery.cookie('survey') != null && jQuery.cookie('survey') == 'true') {
				document.getElementById('surveypage').style.display = 'block';
				document.getElementById('surveycontainer').style.display = 'block';
				document.getElementById('surveyreturn').style.display = 'block';
				survey.active = 0;
				jQuery.cookie('survey', 'false', { expires: 30 });
				return "We would like to provide our users with the best service. Would you mind filling out a short survey (3 questions)? \n\nClick CANCEL (STAY) to fill out the quick survey\nClick OK (LEAVE) to exit the page"
			}
			return "";
		}
	}

	// display survey on exit
	if(jQuery.cookie('survey') == 'true'){
		window.onbeforeunload = survey.init;
		document.onclick = function() {window.onbeforeunload = null}
		document.onmouseout = function(){window.onbeforeunload = survey.init;}
	}
	*/
	
	
//////////////////////////////// Notes Submit - encoding % ///////////////////////////////////
	function encodeNote(note) {
							
		if(!isEmptyElem(note)){
			note.value = note.value.replace(/%/g, '%25');
			note.value = note.value.replace(/�/g, '%C2%A3');
		}
		return true;
	}
///////////////////////////////	
	
function checkAll(checkboxCommonName, checked) {
	var checkboxList = document.getElementsByName(checkboxCommonName);
	if (checkboxList != null && checkboxList.length > 0) {
		for (i = 0; i < checkboxList.length; i++) {
			checkboxList[i].checked = checked ;
		}
	}
}

function countChecked(checkboxList) {
	var countCheckedCheckboxes = 0;
	for (i = 0; i < checkboxList.length; i++) {
		if (checkboxList[i].checked) {
			countCheckedCheckboxes++;
		}
	}
	return countCheckedCheckboxes;
}

function removePhoneNumberSpaces(field) {
	field.value = field.value.split(" ").join("");
}
function removeAmericanCharacters(field) {
	removeCharacter(field, " ");
	removeCharacter(field, "+");
	removeCharacter(field, ")");
	removeCharacter(field, "(");
	removeCharacter(field, "-");
}
function removeCharacter(field, character) {
	field.value = field.value.split(character).join("");
}

/////////////////////////// Prevent double application submission ///////////////////////////////////
function preventDoubleSubmit() {
	var progressDialog = document.getElementById("progressDialog");
	progressDialog.style.visibility = "visible";
	document.getElementById("progress_image").style.backgroundImage = "url('https://c218787.ssl.cf3.rackcdn.com/snake.gif')";
}


function showPublications(checkedOption) {
	   
   if(checkedOption.value == 30 || checkedOption.value == 40 ) {
	   showdiv('publications-ddl');
   } else {
	   hidediv('publications-ddl');
   }
}

// to hold the first PostcodeAnywhereInternational response
var streetArray;

/***
 * Returns the streets in a given postal code.
 * Use this to capture addresses on your website or application using an auto-complete input model.
 * http://www.postcodeanywhere.co.uk/support/webservices/PostcodeAnywhereInternational/Interactive/RetrieveByPostalCode/v2.11/default.aspx
 */
function PostcodeAnywhereInternational_Interactive_RetrieveByPostalCode_v2_11Begin(countryCode) {

	var postcode = document.forms[0]["postcode"].value;

	var script = document.createElement("script"),
        head = document.getElementsByTagName("head")[0],
    	url = "http://services.postcodeanywhere.co.uk/PostcodeAnywhereInternational/Interactive/RetrieveByPostalCode/v2.11/json2.ws?";
	
    // Build the query string
    url += "&Key=" + encodeURIComponent('UZ62-AY75-KP29-EE49');
    url += "&Country=" + encodeURIComponent(countryCode);
    url += "&PostalCode=" + encodeURIComponent(postcode);
    url += "&Building=" + encodeURIComponent('');
    url += "&CallbackFunction=PostcodeAnywhereInternational_Interactive_RetrieveByPostalCode_v2_11End";


    script.src = url;

    // Make the request
    script.onload = script.onreadystatechange = function () {
        if (!this.readyState || this.readyState === "loaded" || this.readyState === "complete") {
            script.onload = script.onreadystatechange = null;
            if (head && script.parentNode)
                head.removeChild(script);
        }
    }

    head.insertBefore(script, head.firstChild);
}

/*
 * this method copied from 
 * http://www.postcodeanywhere.co.uk/support/webservices/PostcodeAnywhereInternational/Interactive/RetrieveByPostalCode/v2.1/default.aspx
 * receives PCA response 
 */
function PostcodeAnywhereInternational_Interactive_RetrieveByPostalCode_v2_11End(response) {
	 document.getElementById("divLoading").style.display = 'none';

	 // Test for an error
    if (response.length == 1 && typeof(response[0].Error) != "undefined") {
        // Show the error message
		document.getElementById("selectstreet").style.display = 'none';
		document.getElementById("selectaddress").style.display = 'none';
		document.getElementById("btnFetch").style.display = 'none';
        //alert(response[0].Description);
        alert("Please enter a valid zip code.");
    }
    else {
        // Check if there were any items found
        if (response.length == 0) {
			document.getElementById("selectstreet").style.display = 'none';
			document.getElementById("selectaddress").style.display = 'none';
			document.getElementById("btnFetch").style.display = 'none';
	        alert("Please enter a valid zip code.");
        } else {
            //FYI: The output is an array of key value pairs (e.g. response[0].StreetId), the keys being:
            //StreetId
            //Description
            //Street
            //District
            //City
            //State
            //PostalCode
            //CountryCode
            //Country
            //AdminArea
        	streetArray = response;

        	document.forms[0]["selectstreet"].style.display = '';
        	document.forms[0]["btnFetch"].style.display = '';

        	for (i=document.forms[0]["selectstreet"].options.length-1; i>=0; i--) {
        		document.forms[0]["selectstreet"].options[i] = null;
        	}

        	document.forms[0]["selectstreet"].options[0] = new Option("Please Select Street", "");

        	for (i=0; i<response.length; i++) {
        		document.forms[0]["selectstreet"].options[document.forms[0]["selectstreet"].length] = new Option(response[i].Description, response[i].StreetId);
        	}
        }
    }
}

/*
if you first call http://www.postcodeanywhere.co.uk/support/webservices/PostcodeAnywhereInternational/Interactive/RetrieveByPostalCode/v2.11/default.aspx, 
then pass in the "StreetId" field of the street you wish to use into the "StreetId" parameter of 
http://www.postcodeanywhere.co.uk/support/webservices/PostcodeAnywhereInternational/Interactive/ListBuildings/v1.12/default.aspx
that should sort you fine
*/
function PostcodeAnywhereInternational_Interactive_ListBuildings_v1_12Begin(Key, StreetId) {
	
	var selectedStreetId = document.forms[0]["selectstreet"].value;

    var script = document.createElement("script"),
        head = document.getElementsByTagName("head")[0],
        url = "http://services.postcodeanywhere.co.uk/PostcodeAnywhereInternational/Interactive/ListBuildings/v1.12/json2.ws?";

    // Build the query string
    url += "&Key=" + encodeURIComponent('UZ62-AY75-KP29-EE49');
    url += "&StreetId=" + encodeURIComponent(selectedStreetId);
    url += "&CallbackFunction=PostcodeAnywhereInternational_Interactive_ListBuildings_v1_12End";

    script.src = url;

    // Make the request
    script.onload = script.onreadystatechange = function () {
        if (!this.readyState || this.readyState === "loaded" || this.readyState === "complete") {
            script.onload = script.onreadystatechange = null;
            if (head && script.parentNode)
                head.removeChild(script);
        }
    }

    head.insertBefore(script, head.firstChild);
}

function PostcodeAnywhereInternational_Interactive_ListBuildings_v1_12End(response) {
	 document.getElementById("divLoading").style.display = 'none';

	 // Test for an error
    if (response.length == 1 && typeof(response[0].Error) != "undefined") {
        // Show the error message
		document.getElementById("selectstreet").style.display = '';
		document.getElementById("selectaddress").style.display = 'none';
		document.getElementById("btnFetch").style.display = 'none';
        alert(response[0].Description);
    }
    else {
        // Check if there were any items found
        if (response.length == 0) {
    		document.getElementById("selectstreet").style.display = '';
			document.getElementById("selectaddress").style.display = 'none';
			document.getElementById("btnFetch").style.display = 'none';
            alert("Sorry, there were no results");
        } else {
            // PUT YOUR CODE HERE
            //FYI: The output is an array of key value pairs (e.g. response[0].Building), the keys being:
            //Building
            //Description
        	
//        	document.forms[0]["selectstreet"].style.display = 'none';
        	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<response.length; i++) {
        		document.forms[0]["selectaddress"].options[document.forms[0]["selectaddress"].length] = new Option(response[i].Description, response[i].Building);
        	}

        }
    }
}

function PostcodeAnywhereInternational_FetchEnd() {
	
	var selectedAddress = document.forms[0]["selectaddress"];
	document.forms[0]["address1"].value = '' + selectedAddress[selectedAddress.selectedIndex].text;

	var selectedStreet = document.forms[0]["selectstreet"];

	for (i=0; i<streetArray.length; i++) {
		if (streetArray[i].StreetId == selectedStreet.value) {
			if (document.forms[0]["address1"].value == '') {
			    document.forms[0]["address1"].value = '' + streetArray[i].District;
				document.forms[0]["address2"].value = '';
			} else {
				document.forms[0]["address2"].value = '' + streetArray[i].District;
			}
			document.forms[0]["citytown"].value = '' + streetArray[i].City;
			document.forms[0]["postcode"].value = '' + streetArray[i].PostalCode;
			document.forms[0]["state"].value = '' + streetArray[i].State;
			break;
		}
	}
	
	var type = document.getElementById("type");
	type.focus();
}

