/**
 * Moved from jquery.autocomplete.js
 * @param CPO jQuery customizations
 * @author Mazhar Choudhry
 * date moved: 11/10/2010
 */
function addSuggestion(fieldName, val ) {
    var list = getArrayFromCookie(fieldName);
    if ($.trim(val)=='')
    	return;

	if ($.trim(fieldName).toLowerCase().indexOf('postalcode')!=-1)
		val=FormatValidatedPostalCode(val);

    if (!list)
        list = [''];

    // add if not there yet
    if ($.inArray(val, list) < 0) {
    	list.unshift(val);
    	if (list.length > 5)
    		list.length =5;
    	setArrayToCookie(fieldName, list,5);
    }
}

function FormatValidatedPostalCode(validPostalCode)
{
	validPostalCode=validPostalCode.replace(' ','');//remove all spaces
	validPostalCode = validPostalCode.substring(0,3) + ' ' + validPostalCode.substring(3,6); // insert middle space
	return validPostalCode.toUpperCase();

}

//unfortunately our web site has 6 setCookie. all of them doing it differently.
//of course autocomplete is calling the wrong one.  I have no choice but to write a 7th setCookie
function setCookieFromAC(c_name, value, expiredays) {
	var exdate = new Date();
	exdate.setDate(exdate.getDate() + expiredays);
	document.cookie = c_name + "=" + escape(value) + ((expiredays == null) ? "" : "; expires=" + exdate.toGMTString()) + "; path=/;domain=canadapost.ca";
}

//unfortunately our web site has 6 getCookie. all of them doing it differently.
//of course autocomplete is calling the wrong one.  I have no choice but to write a 7th getCookie
function getCookieFromAC(c_name) {
	if (document.cookie.length > 0) {
		c_start = document.cookie.indexOf(c_name + "=");
		if (c_start != -1) {
			c_start = c_start + c_name.length + 1;
			c_end = document.cookie.indexOf(";", c_start);
			if (c_end == -1) {
				c_end = document.cookie.length;
			}
			return unescape(document.cookie.substring(c_start, c_end));
		}
	}
	return "";
}

function getArrayFromCookie(name) {
	var ary = ['']; //to make sure we never retun an arry of null;
	var ent = getCookieFromAC(name);

	if (ent)
	{
		ary = ent.split('^');
	}

	$.each(ary, function( i, value ){
		if ($.trim(value)==''){
			ary.splice(i,1);
		}
	});
	return ary;
}

function setArrayToCookie(name, ary, expiredays) {
	var value = '';
	for ( var i = 0; i< ary.length; i++) {
		if ($.trim(ary[i])!='')
		{
			value += ary[i] + (i< (ary.length-1) ? '^' : '');
		}
	}
	setCookieFromAC(name, value, expiredays);
}
