<!--
// ========================================================================
// Global console debugging
// ========================================================================
var debugging = false; // or true
// do we have a console?
if (typeof console == "undefined")
{
    var console = { log: function() {
        if(debugging && arguments.length > 0)
        {
            var alertMessage = '';
            for(var itrArg = 0; itrArg < arguments.length; itrArg++)
            {
                if (arguments[itrArg] != "undefined")
                    alertMessage += '\n' + arguments[itrArg];
            }
            alert(alertMessage);
        }
    } };
}
// are we debugging?
else if (!debugging || typeof console.log == "undefined")
{
    console.log = function() {};
}

// ========================================================================
// Utility DOM manipulation
// ========================================================================
function layerDisplay(pElemId,pDisplayVal){
	if(pDisplayVal == "none")
	{
		$('#' + pElemId).hide()
	}
	else
	{
		$('#' + pElemId).show()
	}
}


// ========================================================================
// Type checking
// ========================================================================
/*
Source - http://www.crockford.com/javascript/remedial.html
*/
function isAlien(a) {
   return isObject(a) && typeof a.constructor != 'function';
}
function isArray(a) {
    return isObject(a) && a.constructor == Array;
}
function isBoolean(a) {
    return typeof a == 'boolean';
}
function isEmpty(o) {
    var i, v;
    if (isObject(o)) {
        for (i in o) {
            v = o[i];
            if (isUndefined(v) && isFunction(v)) {
                return false;
            }
        }
    }
    return true;
}
function isFunction(a) {
    return typeof a == 'function';
}
function isNull(a) {
    return typeof a == 'object' && !a;
}
function isNumber(a) {
    return typeof a == 'number' && isFinite(a);
}
function isObject(a) {
    return (a && typeof a == 'object') || isFunction(a);
}
function isString(a) {
    return typeof a == 'string';
}
function isUndefined(a) {
    return typeof a == 'undefined';
}

// ========================================================================
// Validation helpers
// ========================================================================
function isBlank(val){
	if(val==null){return true;}
	for(var i=0;i<val.length;i++) {
		if ((val.charAt(i)!=' ')&&(val.charAt(i)!="\t")&&(val.charAt(i)!="\n")&&(val.charAt(i)!="\r")){return false;}
	}
	return true;
}
function isValidEmailAddress(s)
{
 //return s.match(/\b(^(\S+@).+((\.com)|(\.net)|(\.edu)|(\.mil)|(\.gov)|(\.org)|(\..{2,2}))$)\b/gi);
 //New email regexp - CM
 return s.match(/^[-^!#$%&'*+\/=?`{|}~.\w]+@[a-z0-9]([-a-z0-9]*[a-z0-9])*(\.[a-z0-9]([-a-z0-9]*[a-z0-9])*)+$/gi)
}
function trim(inputString) {
   // Removes leading and trailing spaces from the passed string. Also removes
   // consecutive spaces and replaces it with one space. If something besides
   // a string is passed in (null, custom object, etc.) then return the input.
   if (typeof inputString != "string") { return inputString; }
   var retValue = inputString;
   var ch = retValue.substring(0, 1);
   while (ch == " ") { // Check for spaces at the beginning of the string
      retValue = retValue.substring(1, retValue.length);
      ch = retValue.substring(0, 1);
   }
   ch = retValue.substring(retValue.length-1, retValue.length);
   while (ch == " ") { // Check for spaces at the end of the string
      retValue = retValue.substring(0, retValue.length-1);
      ch = retValue.substring(retValue.length-1, retValue.length);
   }
   while (retValue.indexOf("  ") != -1) { // Note that there are two spaces in the string - look for multiple spaces within the string
      retValue = retValue.substring(0, retValue.indexOf("  ")) + retValue.substring(retValue.indexOf("  ")+1, retValue.length); // Again, there are two spaces in each of the strings
   }
   return retValue; // Return the trimmed string back to the user
}
function errorMessage(elem,message){
	alert(message);
	elem.focus();
	elem.select();
}

function isNumeric(val){return(parseFloat(val,10)==(val*1));}
// ========================================================================
// Event helpers
// ========================================================================
function cancelTheBubble(e){
	if (!e) var e = window.event;
	e.cancelBubble = true;
	if (e.stopPropagation) e.stopPropagation();
}

function goToUrl(e, url)
{
	if (!e) var e = window.event;
	e.cancelBubble = true;
	if (e.stopPropagation) e.stopPropagation();
	if(url != '#') window.location = url;
}
// ========================================================================
// String Formatters
// ========================================================================
function linkIt(p_strLink, p_strText, p_strTarget){
	var lnk = '<a href="' + p_strLink + '"';
	if(!isBlank(p_strTarget)) lnk += ' target="' + p_strTarget + '"';
	lnk += '>' + p_strText + '</a>';
	return lnk;
}

// ========================================================================
// Cpaint Ajax Helpers
// ========================================================================
function decodeCpaint(p_strCpaintContent){
	var re = /\\u0026amp;/gi;
	var sanitised = p_strCpaintContent.replace(re,"&");
	re = /\\u0026/gi;
	sanitised = sanitised.replace(re,"&");
	return sanitised;
}

function populateDDWithXml(p_dd,p_xml){
	for( var i = 0; i < p_xml.length; i++ ) {
		var id = decodeCpaint(p_xml[i].childNodes.item(0).childNodes.item(0).data);
		var name = decodeCpaint(p_xml[i].childNodes.item(1).childNodes.item(0).data);
		p_dd.options[p_dd.options.length] = new Option(name, id);
		if(p_xml[i].childNodes.item(2).childNodes.item(0).data == 'true' || p_xml[i].childNodes.item(2).childNodes.item(0).data == 'True') p_dd.options[p_dd.options.length - 1].selected = true;
	}
}

// ========================================================================
// Cpaint Ajax Calls
// ========================================================================
// dynamic search
function searchEvent(e,pInput) {
	var cursorKeys ="8;46;37;38;39;40;33;34;35;36;45;";
	g_srchElement = pInput;
	// miss out control keys we don't want to process
	if (cursorKeys.indexOf(e.keyCode+";") == -1) {
		// don't bother processing if we have a small amount of text to process
		if (pInput.value.length > 2) {
			callVendorCodeSearch(pInput.value);
		}
	}
	return true;
}

// Ajax call
function callVendorCodeSearch(p_strSearch){
	g_liveResultsSearchPhrase = p_strSearch;
	var cp = new cpaint();
	cp.set_transfer_mode('get');
	cp.set_response_type('xml');
	// cp.set_debug(true);
	var fileToUse = '/ajax/search_controller.asp';
	cp.call(fileToUse, 'VendorCodeSearch', vendorCodeSearchCallback, p_strSearch);
}
// ========================================================================
function vendorCodeSearchCallback(p_xmlResult)
{
	loadLiveSearchResults(p_xmlResult);
}

// Shopping cart
function callAddToCart(e,p_frm){
	var item_id = p_frm.hdnItemID.value;
	var item_quantity = p_frm.txtQuantity.value;
	var item_type = p_frm.hdnItemType.value;
	var cp = new cpaint();
	cp.set_transfer_mode('get');
	cp.set_response_type('xml');
	var fileToUse = '/ajax/cart_controller.asp';
	if (!e) var e = window.event;
	e.cancelBubble = true;
	if (e.stopPropagation) e.stopPropagation();
	cp.call(fileToUse, 'AddToCart', addToCartCallback, item_id, item_quantity, item_type);
}

function addToCartCallback(p_xmlResult){
	var xmlNodeList = p_xmlResult.getElementsByTagName('cart_items_in');	
	var cart_items_in = decodeCpaint(xmlNodeList[0].childNodes.item(0).data);
	var xmlNodeList = p_xmlResult.getElementsByTagName('cart_subtotal');	
	var cart_subtotal = decodeCpaint(xmlNodeList[0].childNodes.item(0).data);
	$('#cart_items_in').html(cart_items_in);
	$('#cart_subtotal').html(cart_subtotal);
	$('#cart_glow').highlightFade({speed:2000,iterator:'linear', color:g_theme_highlightfade_color, end: g_theme_highlightfade_end_color});
}

// ========================================================================
// Live Search Functions
// ========================================================================
var g_liveResultsOpen = 0;
var g_liveResultsCycle = 250;
var g_liveResultsShelfLife = 15000;
var g_liveResultsSearchPhrase = '';
var g_liveResultTimeout;
var g_srchElement;

function loadLiveSearchResults(p_xmlResult)
{
	var xml_results = p_xmlResult.getElementsByTagName('search_result');
	var got_results = false;
	//clear any existing results
	$('#live_results').children().remove();
	
	for( var i = 0; i < xml_results.length; i++ ) {
		try{
			var prod_name = decodeCpaint(xml_results[i].childNodes.item(0).childNodes.item(0).data);
			var prod_img = decodeCpaint(xml_results[i].childNodes.item(1).childNodes.item(0).data);
			var img_width = xml_results[i].childNodes.item(2).childNodes.item(0).data;
			var img_height = xml_results[i].childNodes.item(3).childNodes.item(0).data;
			var price = xml_results[i].childNodes.item(4).childNodes.item(0).data;
			var prod_link = decodeCpaint(xml_results[i].childNodes.item(5).childNodes.item(0).data);
			addResultRow("live_results",prod_img,img_width,img_height,prod_name,price,prod_link);
			got_results = true;
		}
		catch(ex){
			console.log(ex);
		}
	}
	if(got_results){
		positionBox();
		g_liveResultsOpen = 0;
		g_liveResultTimeout = window.setTimeout("liveResultsListener()", g_liveResultsCycle);
	}
	else{
		closeLiveSearchResultsBox();
	}
}

function positionBox(){
	$('#ajax_results').show("blind",500);
}

function closeLiveSearchResultsBox(){
	$('#ajax_results').hide("blind",500);
	g_liveResultsOpen = 0;
	window.clearTimeout(g_liveResultTimeout);
}

function addResultRow(tbl_name,img_src,img_w,img_h,prod_name,prod_price,prod_link){
	var tbl = document.getElementById(tbl_name);
	var lastRow = tbl.rows.length;
	var row = tbl.insertRow(lastRow);
	var cell = row.insertCell(0);
	cell.innerHTML = linkIt(prod_link,'<img src="' + img_src + '" width="' + img_w + '" height="' + img_h + '" border="0" alt="' + prod_name + '" />');
	var cell = row.insertCell(1);
	cell.innerHTML = linkIt(prod_link,prod_name);
	var cell = row.insertCell(2);
	cell.innerHTML = "&pound;" + prod_price;
}

function liveResultsListener(){
	g_liveResultsOpen += g_liveResultsCycle;
	// close if the timeout is reached
	if(g_liveResultsOpen > g_liveResultsShelfLife){
		closeLiveSearchResultsBox();
	}
	// check for search reductions to insignificant length
	else if(g_srchElement.value.length < 3){
		closeLiveSearchResultsBox();
	}
	// research if they are backing up
	else if(g_liveResultsSearchPhrase.substr(0,g_srchElement.value.length) == g_srchElement.value && g_liveResultsSearchPhrase != g_srchElement.value){
		callVendorCodeSearch(g_srchElement.value);
	}
	else
	{
		g_liveResultTimeout = window.setTimeout("liveResultsListener()", g_liveResultsCycle);
	}
}
