//
// JSON class for generic DOM functions.
// ****************************************************************************
// Developer notes ::
// ** MDC : Initial creation.
//
var headscapeDOM = {
	//
	// Generic getElementsByClassName function.
	//
	// Developer notes ::
	// ** MDC : Courtesy of Dustin Diaz (http://www.dustindiaz.com/getelementsbyclass/).
	//
	getElementsByClassName : function(searchClass, node, tag) {
		var classElements = new Array();
		if (node == null)
			node = document;
		if (tag == null)
			tag = '*';
		var els = node.getElementsByTagName(tag);
		var elsLen = els.length;
		var pattern = new RegExp("(^|\\s)" + searchClass + "(\\s|$)");
		for (i = 0, j = 0; i < elsLen; i++) {
			if (pattern.test(els[i].className)) {
				classElements[j] = els[i];
				j++;
			}
		}
		return classElements;
	},
	// ----------------------------------------------------------------------------



	//
	// Generic addEvent function.
	//
	// Developer notes ::
	// ** MDC : Initial creation.
	//
	addEvent : function(obj, evType, fn, useCapture) {
		if (obj.addEventListener){
			obj.addEventListener(evType, fn, useCapture);
			return true;
		} else if (obj.attachEvent){
			var r = obj.attachEvent("on"+evType, fn);
			return r;
		} else {
			//alert("Handler could not be attached");
		}
	},
	// ----------------------------------------------------------------------------



	//
	// Generic addEvent function.
	//
	// Developer notes ::
	// ** MDC : Initial creation.
	//
	removeEvent : function(obj, evType, fn, useCapture) {
		if (obj.removeEventListener){
			obj.removeEventListener(evType, fn, useCapture);
			return true;
		} else if (obj.detachEvent){
			var r = obj.detachEvent("on"+evType, fn);
			return r;
		} else {
			//alert("Handler could not be detached");
		}
	},
	// ----------------------------------------------------------------------------



	//
	// Generic Trim function to remove leading and trailing spaces.
	//
	// Developer notes ::
	// ** MDC : Initial creation.
	//
	trim : function(strString) {
		while (strString.substring(0,1) == ' ') {
			strString = strString.substring(1, strString.length);
		}
		while (strString.substring(strString.length-1, strString.length) == ' ') {
			strString = strString.substring(0,strString.length-1);
		}
		return strString;
	},
	// ----------------------------------------------------------------------------



	//
	// Generic read cookie function.
	//
	// Developer notes ::
	// ** MDC : Initial creation.
	//
	getCookie : function(strName) {
		var aryCookies = document.cookie.split(";");
		var nameEQ = strName + "=";
		for(var i=0; i < aryCookies.length; i++) {
			aryCookies[i] = this.trim(aryCookies[i]);
			if (aryCookies[i].indexOf(nameEQ) == 0) return aryCookies[i].substring(nameEQ.length, aryCookies[i].length);
		}
		return null;
	},
	// ----------------------------------------------------------------------------



	//
	// Reads a sub cookie (URL Encoded) from a cookie.
	//
	// Developer notes ::
	// ** MDC : Initial creation.
	//
	getSubCookie : function(strName, strSubName) {
		var strReturnValue = null;
		var strFullCookie = this.getCookie(strName);
		if (strFullCookie) {
			var arySubCookies = strFullCookie.split("&");
			var nameEQ = strSubName + "=";
			for (var i=0; i < arySubCookies.length; i++) {
				arySubCookies[i] = this.trim(arySubCookies[i]);
				if (arySubCookies[i].indexOf(nameEQ) == 0) {
					strReturnValue = arySubCookies[i].substring(nameEQ.length, arySubCookies[i].length);
					break;
				}
			}
		}
		return strReturnValue;
	},
	// ----------------------------------------------------------------------------



	//
	// Generic write cookie function.
	//
	// Developer notes ::
	// ** MDC : Initial creation.
	//
	setCookie : function(strName, strValue, intExpiryDays) {
		var aryCookies = document.cookie.split(";");
		var nameEQ = strName + "=";
		var strNewCookieFull = "";
		var intThisCookie = -1;
		var strExpires = "";

		if (intExpiryDays) {
			var date = new Date();
			date.setTime(date.getTime()+(intExpiryDays*24*60*60*1000));
			strExpires = "; expires="+date.toGMTString();
		}

		strNewCookieFull = nameEQ + strValue + strExpires + "; path=/";

		for(var i=0; i < aryCookies.length; i++) {
			aryCookies[i] = this.trim(aryCookies[i]);
			if (aryCookies[i].indexOf(nameEQ) == 0) {
				// We have a match
				intThisCookie = i;
				aryCookies[i] = strNewCookieFull;
				break;
			}
		}

		// Check if we need to add the cookie
		if (intThisCookie == -1) {
			aryCookies.push(strNewCookieFull);
			intThisCookie = aryCookies.length - 1;
		}

		// Write this cookie back - not the full cookie list as this is not what JS expects
		document.cookie = aryCookies[intThisCookie];
	},
	// ----------------------------------------------------------------------------



	//
	// Updates a sub cookie.
	//
	// Developer notes ::
	// ** MDC : Initial creation.
	//
	setSubCookie : function(strCookieName, strSubCookieName, strValue) {
		var strFullCookie = this.getCookie(strCookieName);
		if (strFullCookie) {
			var arySubCookies = strFullCookie.split("&");
			var nameEQ = strSubCookieName + "=";
			var strNewCookieFull = nameEQ + strValue;
			var intThisSubCookie = -1;

			for(var i=0; i < arySubCookies.length; i++) {
				arySubCookies[i] = this.trim(arySubCookies[i]);
				if (arySubCookies[i].indexOf(nameEQ) == 0) {
					// We have a match
					intThisSubCookie = i;
					break;
				}
			}

			// Check if we need to add or update the cookie
			if (intThisSubCookie == -1) {
				arySubCookies.push(strNewCookieFull)
			} else {
				// Update our found cookie
				arySubCookies[intThisSubCookie] = strNewCookieFull;
			}

			// Write the full cookie back
			this.setCookie(strCookieName, arySubCookies.join("&"), 365);
		}
	},
	// ----------------------------------------------------------------------------

	isInteger : function(sInteger) {
		var deccount = 0;
		var isInt = true;
		var inputStr;
		inputStr = sInteger.toString(); // in case sInteger is not a string
		for (var i = 0; i < inputStr.length; i++) {
			var oneChar = inputStr.charAt(i);
			if (oneChar < "0" || oneChar > "9" || oneChar == ".") {
				isInt = false;
				i = inputStr.length;
			}
		}
		return isInt;
	},
	// ----------------------------------------------------------------------------



	externalLinks : function() {
		if (document.getElementsByTagName) {
			var links = this.getElementsByClassName("externalLink");
			for (var i=0; i < links.length; i++) {
				if (links[i].title == "") {
					links[i].title = "(new window)";
				} else {
					links[i].title = links[i].title + " (new window)";
				}
				links[i].onclick = function(e) {
					if (!e) e=window.event;
					if (e.shiftKey || e.ctrlKey || e.altKey) return;
					window.open(this.href);
					return false;
				}
			}
		}
	}
}
// ****************************************************************************




//
// JSON class for QO address extra lines.
// Deals with the expanding and collapsing of FAQs
// ****************************************************************************
// Developer notes ::
// ** SG : Initial creation
//
var wffQOAddress = {
	//
	// This does the initial hiding of the extra address lines
	//
	// Developer notes ::
	// ** SG : Initial creation
	//
	
	hideLines : function() {
		if (document.getElementById("address2") && document.getElementById("address3")) {
		    if(document.getElementById("address2").value=='') document.getElementById("div_address2").style.display='none';
		    if(document.getElementById("address3").value=='') document.getElementById("div_address3").style.display='none';
		}
	},
	// ----------------------------------------------------------------------------


	//
	// Hide or show the extra address lines
	//
	// Developer notes ::
	// ** SG : Initial creation
	//
	showLines : function(e) {
		var addressLine2 = document.getElementById("div_address2");
		var addressLine3 = document.getElementById("div_address3");
		
		if(addressLine2.style.display=='none')
		    addressLine2.style.display='block';
		else
		    addressLine3.style.display='block';
		    

		if (window.event) {
			window.event.cancelBubble = true;
			window.event.returnValue = false;
		}
		if (e && e.stopPropagation && e.preventDefault) {
			e.stopPropagation();
			e.preventDefault();
		}

	},
	// ----------------------------------------------------------------------------


	//
	// Call the handler function when an extra line is requested.
	//
	// Developer notes ::
	// ** SG : Initial creation
	//
	
	watch : function(e) {
		var blnReturnValue = false;
		if (document.getElementById('moreLines')) {
		//alert(document.getElementById('moreLines').nodeName);
		
			var moreLinesLink = document.getElementById('moreLines');
			headscapeDOM.addEvent(moreLinesLink, 'click', wffQOAddress.showLines, false);

			blnReturnValue = true;
			
		}
		return blnReturnValue;
	}
	// ----------------------------------------------------------------------------

}
// ****************************************************************************




//
// JSON class for QO address extra lines.
// Deals with the expanding and collapsing of FAQs
// ****************************************************************************
// Developer notes ::
// ** SG : Initial creation
//
var wffQOBilling = {

	//
	// Hide or show the billing address
	//
	// Developer notes ::
	// ** SG : Initial creation
	//
	hideOrShow : function(e) {
		if(document.getElementById("billing_address_check")) {
			var check_box = document.getElementById("billing_address_check");
			var arrBillingFields = headscapeDOM.getElementsByClassName("billing");
			var vHideShow = (check_box.checked==true) ? 'none' : 'block' ;
    		
			for (var i=0; i<arrBillingFields.length; i++) {
				arrBillingFields[i].style.display=vHideShow;
			}
			wffQOAddress.hideLines();	   
		}
	},
	// ----------------------------------------------------------------------------


	//
	// Call the handler function when the check box is clicked.
	//
	// Developer notes ::
	// ** SG : Initial creation
	//
	
	watch : function(e) {
		var blnReturnValue = false;
		if (document.getElementById('billing_address_check')) {

			var bill_addr_chk = document.getElementById('billing_address_check');
			headscapeDOM.addEvent(bill_addr_chk, 'click', wffQOBilling.hideOrShow, false);

			blnReturnValue = true;
			
		}
		return blnReturnValue;
	}
	// ----------------------------------------------------------------------------

}
// ****************************************************************************






//
// JSON class for QO Place Order submit button
// ****************************************************************************
// Developer notes ::
// ** SG : Initial creation
//
var wffQOOrderConfirmation = {

	seconds : 2,
	milisec : 0,
	blnStopTimer : 0,
	
	
	// 
	// Show the please wait overlay
	//
	showPleaseWaitOverlay : function(e) {
		document.getElementById('popup').className = '';
	},


	redirect : function(e) {
		location="https://" + location.host + "/quick_order_final.asp";
	},
			

	display : function(e) {
		if (document.getElementById('popup').className != '') document.getElementById('popup').className = '';
		
		if (this.milisec <= 0) {
			this.milisec = 9;
			this.seconds -= 1;
		}
		if (this.seconds <= -1) {
			this.milisec = 0;
			this.seconds += 1 ;
			this.blnStopTimer = 1;
			this.redirect();
		}
		else {
			this.milisec -= 1;
		}
		window.status = this.seconds + "." + this.milisec + " before redirection !!!";
    if (this.blnStopTimer == 0) setTimeout("wffQOOrderConfirmation.display()", 100);
	},



	//
	// Call the handler function when the submit button is clicked.
	//
	// Developer notes ::
	// ** SG : Initial creation
	//
	
	watch : function(e) {
		if (document.getElementById('popup')) {
			if ((window.location.search == '?e=0') && (document.getElementById('popup').className == '')) {
				//document.getElementById('p_popupbox').innerHTML = document.getElementById('p_popupbox').innerHTML + "<br/>" + this.seconds;
				window.status = this.seconds + " before redirection !!!";
				this.display();
			}
		}

		if (document.getElementById('step5')) {
			if ((window.location.search == '?e=0') && (document.getElementById('popup').className != '')) {
				headscapeDOM.addEvent(document.getElementById('step5'), 'load', this.display(), false);
			}
		}

		if (document.getElementById('sbt_step5')) {
			headscapeDOM.addEvent(document.getElementById('sbt_step5'), 'click', this.showPleaseWaitOverlay, false);
		}
	}
	// ----------------------------------------------------------------------------

}
// ****************************************************************************







//
// JSON class for hiding / showing information.
// Deals with the expanding and collapsing of FAQs
// ****************************************************************************
// Developer notes ::
// ** SG : Initial creation
//
var wffQOInfo = {

	//
	// Hide all the extra info rows
	//
	// Developer notes ::
	// ** SG : Initial creation
	//
	hideAll : function(e) {
		var arrInfoRows = headscapeDOM.getElementsByClassName("row_info");

		if (arrInfoRows.length>0) {
			for (var i=0; i < arrInfoRows.length; i++) {
				arrInfoRows[i].style.display='none';
			}
		}
	},
	// ----------------------------------------------------------------------------

	//
	// Hide or show the extra info rows
	//
	// Developer notes ::
	// ** SG : Initial creation
	//
	hideOrShow : function(e) {
		var elementTable;
		var elementLink;
		var strId;

		// Get a handle on the link that was clicked
		if (window.event) {
			elementLink = window.event.srcElement;
		}
		else {
			if (e.target) {
				elementLink = e.target;
			}
			else {
				//fix on the homepage for Firefox
				elementLink = e.currentTarget;
			}
		}

//		strId = elementLink.getAttribute('id').substr(3, elementLink.getAttribute('id').length - 2)
		strId = elementLink.id.substr(2, elementLink.id.length)
//		alert('strId = ' + strId);
		elementTable = $(strId);

//		alert(elementTable.getElementsByTagName("tr")[1].nodeName);
//		alert(elementTable.getElementsByTagName("tr")[1].getAttribute('class'));

		elementTable.getElementsByTagName("tr")[1].style.display = (elementTable.getElementsByTagName("tr")[1].style.display == 'none') ? '' : 'none';

		//cancel the fired event.        
		if (window.event) {
			window.event.cancelBubble = true;
			window.event.returnValue = false;
		}
		if (e && e.stopPropagation && e.preventDefault) {
			e.stopPropagation();
			e.preventDefault();
		}

	},
	// ----------------------------------------------------------------------------


	//
	// Call the handler function when the info button is clicked.
	//
	// Developer notes ::
	// ** SG : Initial creation
	//
	
	watch : function(e) {
		var blnReturnValue = false;
		
		var arrInfoBtns = headscapeDOM.getElementsByClassName("info");
        if(arrInfoBtns.length>0) {
		    
		    for (var i=0; i<arrInfoBtns.length; i++) {
			    headscapeDOM.addEvent(arrInfoBtns[i], 'click', wffQOInfo.hideOrShow, false);
            }
            
			blnReturnValue = true;
			
		}
		return blnReturnValue;
	}
	// ----------------------------------------------------------------------------

}
// ****************************************************************************



//
// JSON class for clearing the code / qty fields on focus.
// ****************************************************************************
// Developer notes ::
// ** SG : Initial creation
//
var wffQOInputFields = {

	//
	// Clear the value of the box
	//
	// Developer notes ::
	// ** SG : Initial creation
	//
	focus : function(e) {

	    var element;
	    
	    if(e.srcElement)
	        element = e.srcElement;
	    else
	        element = this;
	    if(element.value == element.title) {
	        if(element.id=='quantity')
	            element.value = '1';
	        else
	            element.value = '';
	        wffQOInputFields.clear(element,false);
        }
        element.select();
	},
	// ----------------------------------------------------------------------------

	//
	// Reset the value of the box
	//
	// Developer notes ::
	// ** SG : Initial creation
	//
	blur : function(e) {

	    var element;
	    
	    if(e.srcElement)
	        element = e.srcElement;
	    else
	        element = this;
	    
	    if(element.value == '' || element.value == element.title)
	        wffQOInputFields.clear(element,true);
	    else
	        wffQOInputFields.clear(element,false);
		
	},
	// ----------------------------------------------------------------------------
	
	clear : function(e,b) {
	    
	    if(b) {
	        e.value = e.title;
	        e.style.color = '#555';
	    }
	    else
	        e.style.color = '#000';
	    
	},


	//
	// Call the handler function when the input field is entered.
	//
	// Developer notes ::
	// ** SG : Initial creation
	//
	
	watch : function(e) {
		var blnReturnValue = false;
		
        if(document.getElementById) {
		    
		    headscapeDOM.addEvent(document.getElementById('code'), 'focus', wffQOInputFields.focus, false);
		    headscapeDOM.addEvent(document.getElementById('quantity'), 'focus', wffQOInputFields.focus, false);
		    headscapeDOM.addEvent(document.getElementById('code'), 'blur', wffQOInputFields.blur, false);
		    headscapeDOM.addEvent(document.getElementById('quantity'), 'blur', wffQOInputFields.blur, false);
		    wffQOInputFields.clear(document.getElementById('code'),true);
		    wffQOInputFields.clear(document.getElementById('quantity'),true);
        }
            
		blnReturnValue = true;
			
		return blnReturnValue;
	}
	// ----------------------------------------------------------------------------

}
// ****************************************************************************
















//
// JSON class for WFF QO basket
// ****************************************************************************
// Developer notes ::
// ** SG : Initial creation
//
var wffQOBasket = {

    basketLineToFlash: -1,

    requestInProgress: false,
    basketTotal: '',


    // Get all the prod <form>s and attach new onSubmit event
    // to them.
    //
    // Developer notes ::
    // ** SG : Initial creation
    //
    watch: function(e) {

        var validNav = navigator.appVersion.indexOf('MSIE') > 0 ? (parseFloat(navigator.appVersion.substring(navigator.appVersion.indexOf('MSIE') + 4, navigator.appVersion.indexOf(';', navigator.appVersion.indexOf('MSIE')))) > 5.5 ? true : false) : true;

        if ((document.getElementById) && (validNav)) {

            var aryAddOrUpdateForms = document.getElementsByTagName("form");
            for (var i = 0; i < aryAddOrUpdateForms.length; i++) {
                // Add an event observer to this form onsubmit
                if (aryAddOrUpdateForms[i].className == '') {
                    headscapeDOM.addEvent(aryAddOrUpdateForms[i], 'submit', this.add, false);
                }
            }

            var aryRemoveLinks = headscapeDOM.getElementsByClassName("remove", document.getElementById("basket"), "a");
            for (var i = 0; i < aryRemoveLinks.length; i++) {
                // Add an event observer to this form onsubmit
                headscapeDOM.addEvent(aryRemoveLinks[i], 'click', this.remove, false);
            }

        }
    },
    // ----------------------------------------------------------------------------





    //
    // ***DEPENDS ON PROTOTYPE***
    // Add/update a product or menu pack in the basket. Uses an Ajax call.
    //
    // Developer notes ::
    // ** MDC : Initial creation
    //
    add: function(e) {

        var frmAddForm;

        var intQty = 0;
        var intBid = 0;
        var intSid = 0;
        var intFid = 0;
        var strPage = "";
        var strZip = "";
        var strIP = "";
        var strZip = "";
        var strPid = "";
        var strMid = "";
        var strPrice = "";
        var strCode = "";


        // Get a handle on the form that was submitted
        if (window.event) {
            frmAddForm = window.event.srcElement;
        }
        else {
            if (e.target) {
                //frmAddForm = e.target;
                if (!this)
                    frmAddForm = e.target;
                else
                    frmAddForm = this;
            }
            else {
                //fix on the homepage for Firefox
                frmAddForm = e.currentTarget;
            }
        }

        /*alert('this ='+this.value);
        alert('frmAddForm = ' + frmAddForm);
        alert('quantity = ' + frmAddForm.value);*/



        if (frmAddForm) {
            intQty = frmAddForm.quantity.value;

            intBid = frmAddForm.bid.value;

            intSid = frmAddForm.sid.value;
            intFid = frmAddForm.fid.value;

            strPid = frmAddForm.pid.value;
            strMid = frmAddForm.mid.value;

            strIP = frmAddForm.ip.value;
            strZip = frmAddForm.zip.value;

            strPage = frmAddForm.page.value;
            strPrice = frmAddForm.price.value;
            strCode = frmAddForm.code.value;



            /*
            alert('intQty = ' + intQty + '\r\n' +
            'intBid = ' + intBid + '\r\n' +
            'intSid = ' + intSid + '\r\n' +
            'intFid = ' + intFid + '\r\n' +
            'strIP = ' + strIP + '\r\n' +
            'strZip = ' + strZip + '\r\n' +
            'strPage = ' + strPage + '\r\n' +
            'strCode = ' + strCode);
            */


            // Ensure valid quantity
            if (!headscapeDOM.isInteger(intQty)) intQty = 1;
            if (intQty.length == 0) intQty = 1;
            if (isNaN(intQty)) intQty = 1;
            if (intQty > 99) intQty = 99;

            //alert(wffQOBasket.requestInProgress);
            if (!wffQOBasket.requestInProgress) {
                //Pre Ajax house keeping
                wffQOBasket.clearErrorMsgs()

                wffQOBasket.basketTotal = $('basket_total').innerHTML;
                $('basket_total').innerHTML = '<strong>Updating basket contents...</strong>';
                wffQOBasket.requestInProgress = true;

                $('code').blur();
                $('quantity').blur();
                wffQOInputFields.clear($('code'), true);
                //wffQOInputFields.clear($('quantity'),true);
                $('quantity').value = '1';

                // Call the API using XHT (PROTOTYPE)
                var strURL = location.protocol + "//" + location.host + "/api/quick_order_basket.api.asp";
                var strParams = "bid=" + intBid + "&pid=" + strPid + "&mid=" + strMid + "&sid=" + intSid + "&fid=" + intFid + "&qty=" + intQty + "&ip=" + strIP + "&zip=" + strZip + "&code=" + strCode + "&page=" + strPage + "&price=" + strPrice;
                var objAjax = new Ajax.Request(strURL, { method: "post", parameters: strParams, onSuccess: wffQOBasket.redraw, onFailure: wffQOBasket.ajaxFail });
            }

            wffQOBasket.removeForwardLinks();

            // Stop the form submitting
            if (window.event) {
                window.event.cancelBubble = true;
                window.event.returnValue = false;
            }
            if (e && e.stopPropagation && e.preventDefault) {
                e.stopPropagation();
                e.preventDefault();
            }

            return false;
        }
    },
    // ----------------------------------------------------------------------------





    //
    // ***DEPENDS ON PROTOTYPE***
    // Remove a product or menu pack in the basket. Uses an Ajax call.
    //
    // Developer notes ::
    // ** MDC : Initial creation
    //
    remove: function(e) {

        var intQty = 0;
        var intBid = 0;
        var intSid = 0;
        var intFid = 0;
        var strPage = "";
        var strZip = "";
        var strIP = "";
        var strZip = "";
        var strPid = "";
        var strMid = "";
        var strPrice = "";
        /*
        var strHref = "";
        var strSearch = "";
        var strUrl = "";
        var aryParameters;
        */

        var aryParametersList;

        var i;

        var blnContinue = false;

        var elementLink;

        // Get a handle on the link that was clicked
        if (window.event) {
            elementLink = window.event.srcElement;
        }
        else {
            if (e.target) {
                elementLink = e.target;
            }
            else {
                //fix on the homepage for Firefox
                elementLink = e.currentTarget;
            }
        }

        /*
        alert('elementLink = ' + elementLink.nodeName);
        alert('elementLink.href = ' + elementLink.getAttribute('href'));
        alert('elementLink.class = ' + elementLink.getAttribute('class'));
        */

        //alert('elementLink = ' + elementLink.nodeName);
        //alert('elementLink.className = ' + elementLink.className);
        //alert('elementLink.class = ' + elementLink.getAttribute('class'));

        aryParametersList = elementLink.className.split(" ");
        //alert('link classes:'+elementLink.nodeName);
        //aryParametersList = elementLink.getAttribute('class').split(" ");
        if (aryParametersList.length == 6) {

            if (aryParametersList[0] == 'remove') {
                intBid = aryParametersList[1];
                //intBid = this.trim(aryParametersList[1]);

                if (aryParametersList[2] == 'pid') {
                    strPid = aryParametersList[3];
                    //strPid = this.trim(aryParametersList[3]);
                }

                if (aryParametersList[2] == 'mid') {
                    strMid = aryParametersList[3];
                    //strMid = this.trim(aryParametersList[3]);
                }

                if (aryParametersList[4] == 'fid') {
                    intFid = aryParametersList[5];
                    //strMid = this.trim(aryParametersList[3]);
                }

            }

        }

        if ((intBid != 0) && ((strPid != '') || (strMid != ''))) {
            blnContinue = true;
        }


        /*
        alert('intBid = ' + intBid + '\r\n' +
        'intFid = ' + intFid + '\r\n' +
        'strPid = ' + strPid + '\r\n' +
        'strMid = ' + strMid);
        */

        //alert(wffQOBasket.requestInProgress);
        if (blnContinue && !wffQOBasket.requestInProgress) {
            //Pre Ajax house keeping
            wffQOBasket.clearErrorMsgs()
            wffQOBasket.basketTotal = $('basket_total').innerHTML;
            $('basket_total').innerHTML = '<strong>Removing item from basket...</strong>'
            wffQOBasket.requestInProgress = true;

            // Call the API using XHT (PROTOTYPE)
            var strURL = location.protocol + "//" + location.host + "/api/quick_order_basket.api.asp";
            var strParams = "bid=" + intBid + "&pid=" + strPid + "&mid=" + strMid + "&sid=" + intSid + "&fid=" + intFid + "&qty=" + intQty + "&ip=" + strIP + "&zip=" + strZip + "&page=" + strPage + "&price=" + strPrice;
            var objAjax = new Ajax.Request(strURL, { method: "post", parameters: strParams, onSuccess: wffQOBasket.redraw, onFailure: wffQOBasket.ajaxFail });
        }

        wffQOBasket.removeForwardLinks();

        // Stop the form submitting
        if (window.event) {
            window.event.cancelBubble = true;
            window.event.returnValue = false;
        }
        if (e && e.stopPropagation && e.preventDefault) {
            e.stopPropagation();
            e.preventDefault();
        }

        return false;
    },
    // ----------------------------------------------------------------------------


    ajaxFail: function(objResponse) {
        //remove any error messages
        wffQOBasket.clearErrorMsgs()

        //alert the user to the failed request.
        elementSectionContentTop = $("section_content_top");

        elementDivError = document.createElement('div');
        elementDivError.className = 'error';
        elementDivError.innerHTML = '\r\n' + '<h3>There is a problem with your submission</h3>' + '\r\n' + '<ul>' + '\r\n We\'re sorry, there was a problem processing your request. Please try again. </ul>' + '\r\n';

        elementSectionContentTop.insertBefore(elementDivError, elementSectionContentTop.childNodes[0]);

        $('basket_total').innerHTML = wffQOBasket.basketTotal;
        wffQOBasket.requestInProgress = false;
    },


    clearErrorMsgs: function() {
        elementDivError = headscapeDOM.getElementsByClassName("error", $("section_content_top"), "div")[0];
        if (elementDivError) {
            elementDivError.parentNode.removeChild(elementDivError);
        }
        $('code_err').className = 'fielderror_div';
        $('quantity_err').className = 'fielderror_div';
    },



    flashBasketLineOn: function(basketLine) {
        var i;
        var aryChildTds;

        if (document.getElementById) {
            if (basketLine) {
                // Turn the basket orange

                wffQOBasket.basketLineToFlash = basketLine

                aryChildTds = wffQOBasket.basketLineToFlash.getElementsByTagName("td");
                for (i = 0; i < aryChildTds.length; i++) {
                    aryChildTds[i].className = 'basket_col0' + (i + 1) + ' active';
                }
                //alert('flash on '+aryChildTds[0].className);

                // Wait a bit then turn it back to green
                setTimeout("wffQOBasket.flashBasketLineOff()", 1000)
            }
        }
    },
    // ----------------------------------------------------------------------------


    //	flashBasketLineOff : function(basketLine) {
    flashBasketLineOff: function() {
        var basketLine = wffQOBasket.basketLineToFlash;
        var aryChildTds;


        if (document.getElementById) {
            if (basketLine) {
                // Turn it green again
                aryChildTds = basketLine.getElementsByTagName("td");
                for (i = 0; i < aryChildTds.length; i++) {
                    aryChildTds[i].className = 'basket_col0' + (i + 1);
                    //alert(i + ' = ' + aryChildTds[i].getAttribute('class'));

                }
                //alert(aryChildTds[0].className);

            }
        }
    },

    // sets the styles for alternate tables in the basket
    setRowStyles: function() {
        var rows;
        var odd = true;

        rows = document.getElementsByTagName('tr');

        for (var i = 0; i < rows.length; i++) {
            if (rows[i].className == 'row' || rows[i].className == 'alt_row') {
                //alert('setting row style');
                if (odd)
                    rows[i].className = 'alt_row';
                else
                    rows[i].className = 'row';
                odd = !odd;
            }
        }

    },

    removeForwardLinks: function() {
        var li;
        li = headscapeDOM.getElementsByClassName('stage03done', $('stages'), 'li');
        if (li.length > 0) {
            li[0].className = 'stage03';
            li[0].innerHTML = '<span>Confirm Delivery Address</span>';
        }
        li = headscapeDOM.getElementsByClassName('stage04done', $('stages'), 'li');
        if (li.length > 0) {
            li[0].className = 'stage04';
            li[0].innerHTML = '<span>Payment Details</span>';
        }
        li = headscapeDOM.getElementsByClassName('stage05done', $('stages'), 'li');
        if (li.length > 0) {
            li[0].className = 'stage05';
            li[0].innerHTML = '<span>Checkout</span>';
        }
    },


    //
    // ***DEPENDS ON PROTOTYPE***
    // Redraw the basket based on the Ajax call. Cannot be called directly.
    //
    // Developer notes ::
    // ** MDC : Initial creation
    //
    redraw: function(objResponse) {

        var blnInsert;
        var blnIsMenuPack;
        var intPid = '';
        var intMid = '';
        var intQty = '';
        var strCode = '';
        var strName = '';
        var strDesc = '';
        var strImage = '';
        var strWeight = '';
        var bnlLF = '';
        var bnlD = '';
        var bnlMS = '';
        var bnlGF = '';
        var bnlV = '';
        var bnlRS = '';
        var dblPrice = '';
        var dblTotalLine = '';
        var intTotalQty = '';
        var dblTotalPrice = '';
        var strErrorText = '';
        var strPage = '';
        var strSessionId = '';
        var strFranchiseId = '';
        var strIp = '';
        var strPostcode = '';
        var strBasketId = '';

        var elementTable = null;
        var elementSectionContentTop = null;
        var elementSectionContent = null;
        var elementBasket = null;
        var eleNewProdClone = null;
        var elementBasketContent = null;
        var elementDivError = null;

        var aryChildTds = null;
        var strItemToAdd = '';
        var row_info_string;

        //		var elementQty;
        //		var cellTotalPrice;
        //		var aryQtyCell;
        //		var aryLinePriceCell;
        //		var collectionTables;
        //		var aryChildHiddenInputs;


        //		var aryCellRowInnerHtml = new Array();
        //		var aryCellRowInfoInnerHtml = new Array();

        //		var strTableHeader = '<table><tr><th class="basket_col01"><span class="hidden">Info</span></th><th class="basket_col02">Product</th><th class="basket_col03">Code</th><th class="basket_col04">Qty</th><th class="basket_col05">Action</th><th class="basket_col06">Price</th><th class="basket_col07">Sub Total</th><th class="basket_col08"><span class="hidden">Remove Items</span></th></tr></table>';
        //		var strItemsHtml = '';
        //		var strHtmlToAdd = '';
        var i;

        if (document.getElementById) {
            // Collect the JSON object from the API call
            eval("var wffAPIResponse = " + objResponse.responseText);

            //alert(objResponse.responseText);

            blnInsert = wffAPIResponse.blnInsert;
            blnIsMenuPack = wffAPIResponse.blnIsMenuPack;

            intPid = wffAPIResponse.intPid;
            intMid = wffAPIResponse.intMid;
            intQty = wffAPIResponse.intQty;

            strCode = wffAPIResponse.strCode;
            strName = wffAPIResponse.strName;
            strDesc = wffAPIResponse.strDesc;
            strImage = wffAPIResponse.strImage;
            strWeight = wffAPIResponse.strWeight;

            bnlLF = wffAPIResponse.bnlLF;
            bnlD = wffAPIResponse.bnlD;
            bnlMS = wffAPIResponse.bnlMS;
            bnlGF = wffAPIResponse.bnlGF;
            bnlV = wffAPIResponse.bnlV;
            bnlRS = wffAPIResponse.bnlRS;

            // For some reason (content encoding?) the £ sign comes back as a weird character which we need to strip
            dblPrice = wffAPIResponse.dblPrice.substring(1, wffAPIResponse.dblPrice.length).replace(",", "");
            dblTotalLine = wffAPIResponse.dblTotalLine.substring(1, wffAPIResponse.dblTotalLine.length).replace(",", "");

            strErrorText = wffAPIResponse.strErrorText;

            strPage = wffAPIResponse.strPage;
            strSessionId = wffAPIResponse.strSessionId;
            strFranchiseId = wffAPIResponse.strFranchiseId;
            strIp = wffAPIResponse.strIp;
            strPostcode = wffAPIResponse.strPostcode;
            strBasketId = wffAPIResponse.strBasketId;
            intTotalQty = wffAPIResponse.intTotalQty;
            dblTotalPrice = wffAPIResponse.dblTotalPrice.substring(1, wffAPIResponse.dblTotalPrice.length).replace(",", "");


            /*
            alert('blnInsert = ' + blnInsert + '\r\n' +
            'blnIsMenuPack = ' + blnIsMenuPack + '\r\n' +

'intPid = ' + intPid + '\r\n' +
            'intMid = ' + intMid + '\r\n' +
            'intQty = ' + intQty + '\r\n' +

'strCode = ' + strCode + '\r\n' +
            'strName = ' + strName + '\r\n' +
            'strDesc = ' + strDesc + '\r\n' +
            'strImage = ' + strImage + '\r\n' +
            'strWeight = ' + strWeight + '\r\n' +

'bnlLF = ' + bnlLF + '\r\n' +
            'bnlLF = ' + bnlLF + '\r\n' +
            'bnlMS = ' + bnlMS + '\r\n' +
            'bnlGF = ' + bnlGF + '\r\n' +
            'bnlV = ' + bnlV + '\r\n' +
            'bnlRS = ' + bnlRS + '\r\n' +

'dblPrice = ' + dblPrice + '\r\n' +
            'dblTotalLine = ' + dblTotalLine + '\r\n' +

'strErrorText = ' + strErrorText + '\r\n' +

'strSessionId = ' + strSessionId + '\r\n' +
            'strFranchiseId = ' + strFranchiseId + '\r\n' +
            'strIp = ' + strIp + '\r\n' +
            'strPostcode = ' + strPostcode + '\r\n' +
            'strBasketId = ' + strBasketId);
            */


            //remove any error message if there are some (this should have been done when the request is submited)
            wffQOBasket.clearErrorMsgs()
            /*elementDivError = headscapeDOM.getElementsByClassName("error", $("section_content_top"), "div")[0];
            if (elementDivError) {
            elementDivError.parentNode.removeChild(elementDivError);
            }*/


            //check if the item has already been added to the basket
            if (intPid != 0) {
                strItemToAdd = "pid" + intPid;
            }
            else {
                strItemToAdd = "mid" + intMid;
            }
            if ($(strItemToAdd)) {
                blnInsert = false;
            }


            //alert('blnInsert = ' + blnInsert);

            if (!blnInsert) {
                if (strErrorText.length == 0) {
                    // Get a handle on the table we need to update
                    if (intPid != 0) {
                        elementTable = $(strItemToAdd);
                    }
                    else {
                        elementTable = $(strItemToAdd);
                    }

                    //if the qty is 0 we need to remove the table
                    if (intQty == 0) {
                        elementTable.parentNode.removeChild(elementTable);
                        //alert('qty is zero? '+intTotalQty);
                        //elementBasket.style.display='block';
                        //document.getElementById('infoText').style.display='';
                    }
                    else {
                        aryChildTds = elementTable.getElementsByTagName("td");

                        aryChildTds[3].getElementsByTagName("input")[0].value = intQty;
                        aryChildTds[5].innerHTML = '£' + dblTotalLine;
                    }
                }
                else {
                    elementSectionContentTop = $("section_content_top");

                    elementDivError = document.createElement('div');
                    elementDivError.className = 'error';
                    elementDivError.innerHTML = '\r\n' + '<h3>There is a problem with your submission</h3>' + '\r\n' + '<ul>' + '\r\n' + strErrorText + '</ul>' + '\r\n';

                    elementSectionContentTop.insertBefore(elementDivError, elementSectionContentTop.childNodes[0]);
                    //probably a problem with the code
                    $('code_err').className = 'fielderror_div_err';
                }

            }
            else {
                //it's a insert
                if ((intQty == 0) || (strErrorText.length != 0)) {
                    //if the qty is 0 we need to display an error message
                    elementSectionContentTop = $("section_content_top");

                    elementDivError = document.createElement('div');
                    elementDivError.className = 'error';
                    elementDivError.innerHTML = '\r\n' + '<h3>There is a problem with your submission</h3>' + '\r\n' + '<ul>' + '\r\n' + strErrorText + '</ul>' + '\r\n';

                    elementSectionContentTop.insertBefore(elementDivError, elementSectionContentTop.childNodes[0]);
                    //put the markers by the fields
                    if (intQty == 0)
                        $('quantity_err').className = 'fielderror_div_err';
                    else
                        $('code_err').className = 'fielderror_div_err';
                }
                else {
                    //fix to set a value on the "bid" hidden input field when the 1st product is added, otherwise this field has a value set to 0
                    $("bid").value = strBasketId;

                    //Duplicate this item table for use in the basket list
                    elementClone = $("clone");
                    eleNewProdClone = elementClone.cloneNode(true);

                    //keep a ref to the new <table> element for alter use (flashing)
                    elementTable = eleNewProdClone;

                    if (blnIsMenuPack) {
                        strItemToAdd = 'mid' + intMid;
                    }
                    else {
                        strItemToAdd = 'pid' + intPid;
                    }
                    eleNewProdClone.id = strItemToAdd;

                    //fix for IE copying attached event
                    headscapeDOM.removeEvent(eleNewProdClone.getElementsByTagName("form")[0], 'submit', wffQOBasket.add, false);
                    headscapeDOM.addEvent(eleNewProdClone.getElementsByTagName("form")[0], 'submit', wffQOBasket.add, false);


                    eleNewProdClone.getElementsByTagName("tr")[0].className = 'row';

                    aryChildTds = eleNewProdClone.getElementsByTagName("td");

                    //trick for IE which have already attached the event when we clone the table element					
                    headscapeDOM.removeEvent(aryChildTds[0].getElementsByTagName("a")[0], 'click', wffQOInfo.hideOrShow, false);
                    headscapeDOM.addEvent(aryChildTds[0].getElementsByTagName("a")[0], 'click', wffQOInfo.hideOrShow, false);

                    aryChildTds[0].getElementsByTagName("a")[0].id = 'a_' + strItemToAdd;

                    aryChildTds[1].innerHTML = strName;
                    aryChildTds[2].innerHTML = strCode;
                    aryChildTds[3].getElementsByTagName("input")[0].value = intQty;
                    aryChildTds[3].getElementsByTagName("input")[1].value = intPid;
                    aryChildTds[3].getElementsByTagName("input")[2].value = intMid;
                    aryChildTds[3].getElementsByTagName("input")[7].value = strBasketId;
                    aryChildTds[3].getElementsByTagName("input")[8].value = strCode;
                    aryChildTds[3].getElementsByTagName("input")[9].value = dblPrice;


                    aryChildTds[4].innerHTML = '£' + dblPrice;
                    aryChildTds[5].innerHTML = '£' + dblTotalLine;

                    if (blnIsMenuPack) {
                        aryChildTds[6].getElementsByTagName("a")[0].href = '/quick_order_2.asp?basket_id=' + strBasketId + '&mid=' + intMid;
                        aryChildTds[6].getElementsByTagName("a")[0].className = 'remove ' + strBasketId + ' mid ' + intMid + ' fid ' + strFranchiseId;
                    }
                    else {
                        aryChildTds[6].getElementsByTagName("a")[0].href = '/quick_order_2.asp?basket_id=' + strBasketId + '&pid=' + intPid;
                        aryChildTds[6].getElementsByTagName("a")[0].className = 'remove ' + strBasketId + ' pid ' + intPid + ' fid ' + strFranchiseId;
                    }

                    //alert('remove = ' + aryChildTds[6].getElementsByTagName("a")[0].getAttribute('class'));

                    //fix for IE copying attached event.
                    headscapeDOM.removeEvent(aryChildTds[6].getElementsByTagName("a")[0], 'click', wffQOBasket.remove, false);
                    headscapeDOM.addEvent(aryChildTds[6].getElementsByTagName("a")[0], 'click', wffQOBasket.remove, false);

                    //alert('addEvent remove');
                    row_info_string = '<img src="/gallery_resize.ashx?img=' +
																			escape('images/product_list/product_images/' + strImage) +
																			'&amp;t=132x120" width="132" height="120" alt="' + strName + '" />' +
																			'<p>' + strDesc + '</p>' +
																			'<p><span class="prod_code">Product Code: ' + strCode + '</span>';
                    if (!blnIsMenuPack) row_info_string += '<br/>Weight: ' + strWeight + 'g';
                    row_info_string += '</p>';

                    if (bnlLF || bnlD || bnlMS || bnlGF || bnlV || bnlRS) {
                        row_info_string += '<ul>';
                        if (bnlD) row_info_string += ' <li><img src="/images/iDiabetic.gif" alt="Suitable for Diabetic diet" width="18" height="18" title="Suitable for Diabetic diet" /></li>';
                        if (bnlLF) row_info_string += ' <li><img src="/images/iLowFat.gif" alt="Suitable for Lower Fat diet" width="19" height="18" title="Suitable for Lower Fat diet" /></li>';
                        if (bnlRS) row_info_string += ' <li><img src="/images/iReducedSalt.gif" alt="Suitable for Reducing diet" width="18" height="18" title="Suitable for Reducing diet" /></li>';
                        if (bnlMS) row_info_string += ' <li><img src="/images/iModeratedSalt.gif" alt=""Suitable for Moderate Salt diet" width="18" height="18" title=""Suitable for Moderate Salt diet" /></li>';
                        if (bnlGF) row_info_string += ' <li><img src="/images/iGlutton.gif" alt="Suitable for Gluten Free diet" width="18" height="18" title="Suitable for Gluten Free diet" /></li>';
                        if (bnlV) row_info_string += ' <li><img src="/images/iVeg.gif" alt="Suitable for Vegetarian diet" width="18" height="18" title="Suitable for Vegetarian diet" /></li>';
                        row_info_string += '</ul>';
                    }
                    aryChildTds[7].innerHTML = row_info_string;

                    elementBasket = $("basket");
                    //alert('elementBasket = ' + elementBasket.nodeName);


                    //Write it to the basket list
                    elementBasketContent = document.getElementById('basket_content');
                    //alert('elementBasketContent = ' + elementBasketContent.nodeName);

                    elementBasketContent.insertBefore(eleNewProdClone, elementBasketContent.childNodes[0]);

                    //elementBasket.style.display='block';
                    //document.getElementById('infoText').style.display='none';

                }
            }


            if (elementTable) {
                //alert(elementTable.nodeName);
                //alert(elementTable.getElementsByTagName("tr")[0].nodeName);
                //flash the inserted or updated line
                wffQOBasket.flashBasketLineOn(elementTable.getElementsByTagName("tr")[0]);
                //alert('DONE');
            }

            wffQOBasket.setRowStyles();
            if (dblTotalPrice == '')
                dblTotalPrice = '0.00';

            $('basket_total').innerHTML = '<strong>' + intTotalQty + '</strong> items [<strong>£' + dblTotalPrice + '</strong>] in your basket';


            if (intTotalQty > 0) {
                /*
                $("section_bottom").className= 'section_bottom hidden';
                $("section_bottom_foot").className= 'section_bottom_foot';
                $("section_bottom_total").className= 'section_bottom_total';
                */
                $("basket").className = '';
                $("infoText").className = 'hidden';
            }
            else {
                /*
                $("section_bottom").className= 'section_bottom';
                $("section_bottom_foot").className= 'section_bottom_foot hidden';
                $("section_bottom_total").className= 'section_bottom_total hidden';
                */
                $("basket").className = 'hidden';
                $("infoText").className = '';
            }

        }

        //alert('finished success');
        wffQOBasket.requestInProgress = false;
    }
    // ----------------------------------------------------------------------------


}
// ****************************************************************************












/*
//
// JSON class for removing an item.
// ****************************************************************************
// Developer notes ::
// ** SG : Initial creation
//
var wffQORemove = {


	// ----------------------------------------------------------------------------
	// remove function
	
	fire : function(e) {

	    var element;
	
	    if(e.srcElement)
	        element = e.srcElement;
	    else
	        element = this;

	
	    alert('method to remove item ['+element.href+']');

        //cancel the fired event.        
        if (window.event) {
		    window.event.cancelBubble = true;
		    window.event.returnValue = false;
	    }
	    if (e && e.stopPropagation && e.preventDefault) {
		    e.stopPropagation();
		    e.preventDefault();
	    }
	},


	//
	// Call the handler function when the remove button is clicked.
	//
	// Developer notes ::
	// ** SG : Initial creation
	//
	
	watch : function(e) {
		var blnReturnValue = false;
		
		var arrRemoveBtns = headscapeDOM.getElementsByClassName("remove");
        if(arrRemoveBtns.length>0) {
		    
		    for (var i=0; i<arrRemoveBtns.length; i++) {
			    headscapeDOM.addEvent(arrRemoveBtns[i], 'click', wffQORemove.fire, false);
            }
            
			blnReturnValue = true;
			
		}
		return blnReturnValue;
	}
	// ----------------------------------------------------------------------------

}
// ****************************************************************************
*/










//document.write('<style type="text/css" media="screen">#pas {display:none;}</style>');


//
// Load the functions we need immediately.
//
// Developer notes ::
// ** MDC : Initial creation
//
window.onload = function() {
	if (document.getElementById('moreLines')) {
		wffQOAddress.hideLines();
		wffQOAddress.watch();
	}
    
	if (document.getElementById('billing_address_check')) {
		wffQOBilling.hideOrShow();
		wffQOBilling.watch();
	}


	wffQOOrderConfirmation.watch();

    
	if (document.getElementById('quantity')) {
		wffQOInputFields.watch();
	}

/*
	if (headscapeDOM.getElementsByClassName("remove").length > 0) {
		wffQORemove.watch();
	}
*/

	if (headscapeDOM.getElementsByClassName("info").length > 0) {
		wffQOInfo.hideAll();
		wffQOInfo.watch();
	}

	if (location.href.indexOf("quick_order_2.asp", 1) != -1) {
		wffQOBasket.watch();
	}

	if(document.getElementById('house_number'))
		document.getElementById('house_number').focus();
		
	// External links
	headscapeDOM.externalLinks();
}

