

////////////////////////////////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;
		});
	}
	// alert('END');
}

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///////////////////////////////////

//alert('START');

newsArray = new Array();
function initNews() {
	
	
	newsDataObject1 = new Object();
	newsDataObject2 = new Object();
	newsDataObject3 = new Object();
	newsDataObject4 = new Object();
	newsDataObject5 = new Object();
	newsDataObject6 = new Object();
	newsDataObject7 = new Object();
	newsDataObject8 = new Object();
	
	newsDataObject1.title = "";
	//newsDataObject1.title="Business owners struggle to raise working capital from banks";
	newsDataObject1.linkUrl = "/in-the-news/pawnbrokers-gain-in-credit-squeeze";
	//newsDataObject1.teaser = "Struggling businesses are turning to pawnbrokers..."; 
	newsDataObject1.teaser = "Volume of business customers on borro.com has increased \"several 100 per cent\" in the past 10 months.";
	newsDataObject1.logoPath = "/static/images/newsticker/fin-times.gif";
	
	newsDataObject2.title = "";
	//newsDataObject2.title = "Borro.com offering loans to wealthy individuals";
	newsDataObject2.linkUrl = "/in-the-news/times-online-more-people-turn-to-credit-to-make-ends-meet";
	newsDataObject2.teaser = "There has been a big upswing in people coming to borro.com for &pound;1,000 plus loans."; 
	newsDataObject2.logoPath = "/static/images/newsticker/times-online.gif";
	
	newsDataObject3.title = "";
	//newsDataObject3.title = "Fast cars and fine art for short term finance";
	newsDataObject3.linkUrl = "/in-the-news/channel-4-news";
	newsDataObject3.teaser = "Interview with founder of Borro.com, about the world's first online service offering loans against personal assets."; 
	newsDataObject3.logoPath = "/static/images/newsticker/channel4.jpg";
	
	newsDataObject4.title = "";
	//newsDataObject4.title = "Crisis win Borro.com &pound;10 million funding";
	newsDataObject4.linkUrl = "/in-the-news/metro";
	newsDataObject4.teaser = "Borro.com has secured &pound;10 million in funding after recession sparked a surge in demand."; 
	newsDataObject4.logoPath = "/static/images/newsticker/metro.gif";
	
	newsDataObject5.title = ""; 
	newsDataObject5.linkUrl = "/about-us/videos";
	newsDataObject5.teaser = "Jeff Randall interviews Paul Aitken about Borro.com's competitive advantage as an online pawnbroker."; 
	newsDataObject5.logoPath = "/static/images/newsticker/skynews.jpg";
	
	newsDataObject6.title = ""; 
	newsDataObject6.linkUrl = "/in-the-news/oxfordshire-business-of-the-year-awards";
	newsDataObject6.teaser = "Borro.com - Winner of Oxfordshire's New Business of the Year Award 2010."; 
	newsDataObject6.logoPath = "/static/images/newsticker/oxf-awards.jpg";
	
	newsDataObject7.title = ""; 
	newsDataObject7.linkUrl = "/in-the-news/bbc-new-age-of-pawnbrokers";
	newsDataObject7.teaser = "Borro, says it has seen a 45% rise in small business customers over the past six months alone."; 
	newsDataObject7.logoPath = "/static/images/newsticker/bbc-logo.jpg";
	
	newsDataObject8.title = ""; 
	newsDataObject8.linkUrl = "/in-the-news/mail-online-why-not-try-a-pawnbroker-for-a-fast-way-to-borrow";
	newsDataObject8.teaser = "Why not try a pawnbroker for a fast way to borrow?"; 
	newsDataObject8.logoPath = "/static/images/newsticker/mail-online.gif";
			
	newsArray[0] = newsDataObject1;
	newsArray[1] = newsDataObject2;
	newsArray[2] = newsDataObject3;
	newsArray[3] = newsDataObject4;
	newsArray[4] = newsDataObject5;
	newsArray[5] = newsDataObject6;
	newsArray[6] = newsDataObject7;
	newsArray[7] = newsDataObject8;
		
	return false;
		
	
	// alert('END');

}


/*
 * This method writes inner Html in the News Ticker box
 */
var tickerContent;
function writeNewsTickerContent(newsDataObject){
	
	var titleBlock = "";
	if(newsDataObject.title != ""){
		titleBlock = '<b><span class="newsTickerTitle">' + newsDataObject.title + '</span></b><br/>';
	}
	var teaserBlock = "";
	if(newsDataObject.teaser != ""){
		teaserBlock = '<div class="newsTickerTeaserContainer"><b><span class="newsTickerTeaser">'+ newsDataObject.teaser + '</span></b><br/>';
	}
	
	
	var moreInfo = "";
	if(newsDataObject.linkUrl.indexOf("/about-us/videos") != -1 || newsDataObject.linkUrl.indexOf("/channel-4-news") != -1){
		moreInfo = '<b><a href="'+ newsDataObject.linkUrl + '">Watch interview<a/></b>';
	}else{
		moreInfo = '<b><a href="'+ newsDataObject.linkUrl + '">Read more<a/></b>';
	}
	
	//special style for the oxford awards image 
	var OxfordImgStyle = "";
	if(newsDataObject.logoPath == '/static/images/newsticker/oxf-awards.jpg'){
		OxfordImgStyle = 'style=\"padding-left:43px;\"';
	}
	tickerContent = '<img class="newsTickerImage" '+OxfordImgStyle+' src="' + newsDataObject.logoPath +'"/> <br/>' 
			+ titleBlock
			+ teaserBlock
			+ moreInfo
			+ '</div>';

	//alert('built tickerContent '+ tickerContent);
	/*if(document.getElementById("newsticker") != null){
		alert('found element');
		document.getElementById("newsticker").innerHTML = tickerContent;
		alert('written '+ tickerContent);
	}*/
}


function newsRotater() {
	//alert('newsArray at top rotater'+ newsArray.length);
	var newsindex = Math.floor(Math.random() * (newsArray.length));
	//alert('pichked index: '+ newsindex);
	writeNewsTickerContent(newsArray[newsindex]);
	
	
}



//////////////////////////////// Initialise news if on homepage  ///////////////////////////////////


   var currentPath = window.location.pathname;
   if(currentPath == "/" || currentPath == "/start" || currentPath == "/home-ps"){
	   //alert('before init news');
	   initNews();
	   //alert('after init news');
	   newsRotater();
	   //aler
   }


//
// 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 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 = '';
	// 3rd party lookup
	pcaByPostcodeBegin();
	document.getElementById("selectaddress").style.display = '';

 }
 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';

 }
 
 // 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(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);
}

//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(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';
   }

//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 = '' + 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 = '';
   	}else{
   		if(desc.value.indexOf('Enter brief description...') != -1){
   			var auxString = desc.value.replace('Enter brief description...', '');
   			desc.value = auxString;   			
   		}   		
	   }
   }
   
   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 = '';
   	}
   	
   }
   /* 
   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()
   {
  
     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";

   }
   
   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 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';
			}
		}
	}
	
// ]]>
	

//////////////////////////////// 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('%', '%25');
			note.value = note.value.replace('£', '%C2%A3');
		}
		return true;
	}
	
	