/*
	Take an input object and output values in a querystring format. name=value&name2=value2
*/
function toNameValueString(p_object) {
	var qs = "";
	for(property in p_object)
	{
		qs = qs + p_object[property].name + "=" + p_object[property].value + "&";
	}
	return qs.substring(0,(qs.length - 1));
}

/*
	Take in placeholder formatted HTML and replace the values with those matching in the data object.
	This is a {Placeholder}. So we find a property called "Placeholder" in the p_DataItem and inject it's value.
*/
function replaceDataPlaceholders(p_DataItem, p_UiTemplate)
{
	var placeholders = /{[\w|\.|\,|\[|\]|\#|\"|\-]*\}/g;
	//var placeholders = /\{\w+[^\{]}/g;
	
	p_UiTemplate.html(
		p_UiTemplate.html().replace('http://' + document.domain + '/','').replace(/%7B/, "{").replace(/%7D/, "}").replace(placeholders, function(match)
		{
			var innerMatch;
			try
			{
				innerMatch = match.substring(1, (match.length - 1));
				if (innerMatch.indexOf(",") != -1)
				{
					var formatRequired = eval(innerMatch.substring(innerMatch.indexOf(",") + 1, innerMatch.length));
					innerMatch = innerMatch.substring(0, innerMatch.indexOf(","));
					if (formatRequired)
					{ 
						return format(eval("p_DataItem." + innerMatch)) 
					}
					else
					{
						return eval("p_DataItem." + innerMatch);
					}
				}
				else
				{
					return format(eval("p_DataItem." + innerMatch));
				}
			}
			catch(err)
			{
				//alert("Error executing match of '" + innerMatch + "'");
			}
		})
	);
}

function replaceEncodedDataPlaceholders(p_DataItem, p_UiTemplate)
{
	// add %7B ({) and %7D (}) as these can be encoded by the dom on certain attributes
	var placeholders = /(\{|\%7B)[\w|\.|\,|\[|\]|\#|\"\'|\-]*(\}|\%7D)/g;
	
	p_UiTemplate.html
	(
		p_UiTemplate.html().replace('http://' + document.domain + '/','').replace
		(placeholders,
			function(match)
			{
				var innerMatch;
				try
				{
					innerMatch = decodeURI(match); // decode match as it could be encoded eg. url, href, src attributes
					innerMatch = innerMatch.substring(1, (innerMatch.length - 1)); // trim off prefix { and suffix }
					
					if (innerMatch.indexOf(",") != -1)
					{
						var formatRequired = eval(innerMatch.substring(innerMatch.indexOf(",") + 1, innerMatch.length));
						innerMatch = innerMatch.substring(0, innerMatch.indexOf(","));
						if (formatRequired)
						{ 
							return format(eval("p_DataItem." + innerMatch)) 
						}
						else
						{
							return eval("p_DataItem." + innerMatch);
						}
					}
					else
					{
						return format(eval("p_DataItem." + innerMatch));
					}
				}
				catch(err)
				{
					//alert("Error executing match of '" + innerMatch + "'");
				}
			}
		)
	);
}



function formatCurrency(num) {
    num = num.toString().replace(/\$|\,/g,'');
    if(isNaN(num))
    num = "0";
    sign = (num == (num = Math.abs(num)));
    num = Math.floor(num*100+0.50000000001);
    cents = num%100;
    num = Math.floor(num/100).toString();
    if(cents<10)
    cents = "0" + cents;
    for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
    num = num.substring(0,num.length-(4*i+3))+','+
    num.substring(num.length-(4*i+3));
    return (((sign)?'':'-') + '&pound;' + num + '.' + cents);
}

/*
	Provides the ability to apply numeric formatting.
*/
function format(p_Data)
{
	if(!p_Data) return p_Data;
	if(isNumeric(p_Data)) return formatNumber(p_Data);
	return p_Data;
}

/*
	Checks if the incoming value is an integer.
*/
function isInt(p_Data)
{
	var l_Int = parseInt(p_Data);
	if (isNaN(l_Int)) return false;
	return l_Int == p_Data && l_Int.toString() == p_Data.toString();
}

/*
	Checks if the incoming value is numeric.
*/
function isNumeric(p_Data)
{
	var ValidChars = "0123456789.";
	var IsNumber = true;
	var Char;
	for (i = 0; i < p_Data.length && IsNumber == true; i++) 
	{ 
		Char = p_Data.charAt(i); 
		if (ValidChars.indexOf(Char) == -1) IsNumber = false;
	}
	return IsNumber;
}


/*
	Formats the passed in data with tousand seperators so 1000000 = 1,000,000
*/
function formatNumber(p_Data)
{
	p_Data += "";
	x = p_Data.split(".");
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	x2 = x2.length == 2 ? x2 + '0' : x2;
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return x1 + x2;
}

//function used to validate the no claims discount entered by the user
function validateNoClaimsDiscount(field) {
    var ValidChars = "0123456";
    if((field.val().length > 1) || (ValidChars.indexOf(field.val()) == -1)) {
        field.next().show();
        return false;
    }
    else {
        field.next().hide();
        return true;       
    }
}

//function used to validate whether a field contains an integer
function validateInteger(field) {
    if(isInt(field.val())) {
        field.next().hide();
        return true;
    }
    else {
        field.next().show();
        return false;
    }
}

//function used to validate a full UK postcode
//first we need to ensure that a space has been included
function validateUkPostcode(field) {
	var regex  = /^([Gg][Ii][Rr] 0[Aa]{2})|((([A-Za-z][0-9]{1,2})|(([A-Za-z][A-Ha-hJ-Yj-y][0-9]{1,2})|(([A-Za-z][0-9][A-Za-z])|([A-Za-z][A-Ha-hJ-Yj-y][0-9]?[A-Za-z])))) [0-9][A-Za-z]{2})$/;
	
	//get rid of any spaces, then insert one in the correct place
	var postcode = field.val();
	postcode = postcode.replace(/ /g,'');
	postcode = postcode.substr(0,postcode.length-3) + ' ' + postcode.substr(postcode.length-3,3);
    
	if(postcode.match(regex)) {
		postcode = postcode.replace(/ /g,'');
        field.val(postcode);
		field.next().hide();
		return true;
	}
	else {
	    field.next().show();
	    return false;
	}	
}

//function used to check if the user has entered a valid email address
function validateEmail(field) {
	var regex = /^[a-zA-Z][\w\.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$/;
	if(field.val().match(regex)) {
		field.next().hide();
		return true;
	}	
	else {
		field.next().show();
		return false;
	}
}

//function used to ensure a data entered by the user appears in the format DD/MM/YYYY
function validateValidDate(field) {
	var regex = /(0[1-9]|[12][0-9]|3[01])[- /.](0[1-9]|1[012])[- /.](19|20)([0-9]{2})$/;
	if(field.val().match(regex)){
		field.next().hide();
		return true;
	}
	else {
		field.next().show();
		return false;
	}
}

//function used to check that a required field has been completed
function validateRequiredField(field) {
	if(field.val() == '') {
		field.next().show();
		return false;
	}
	else {
		field.next().hide();
		return true;
	}
}

//function used to validate that a given date is above the minimum age of 20years
function validateMinAge(field) {
    var currentDate = new Date();
    var day = currentDate.getDate();
    var month = currentDate.getMonth()+1;
    var year = currentDate.getFullYear();  
    var date = day+'/'+month+'/'+year;
    if(datedifference(field.val(),date)==false) {
		field.next().show();
		return false;
	}
	else {
		field.next().hide();
		return true;
	}
}

//function used to calculate a datediff
function datedifference(strDate1, strDate2) { 
    var bldatediff = false 

    //Start date split to UK date format and add 31 days for maximum datediff 
    strDate1 = strDate1.split("/"); 
    var starttime = new Date(strDate1[2],strDate1[1]-1,strDate1[0]); 
    starttime = new Date(starttime.valueOf()+(7670*86400000)); 

    //End date split to UK date format 
    strDate2 = strDate2.split("/"); 
    var endtime = new Date(strDate2[2],strDate2[1]-1,strDate2[0]); 
    endtime = new Date(endtime.valueOf()); 

    if(endtime > starttime) { 
        bldatediff = true 
    } 

    return bldatediff 
}
