/*
* addCustomerDropdown(selectOptions)
* addToCart(sId, userId)
* addOfferItemToCart(itemRow)
* addOfferDiscountToCart(itemRow) 
* checkForCustomer(phone)
* confirmPassword() 
* disableOffers(disabledOffers)
* enableOffers(enabledOffers)
* eraseCookie(name)
* fillCustomerDetails(userId)
* getCookie(name)
* getHTTPObject()
* handleHttpResponseAddToCart()
* handleHttpResponse()
* isNumber(n)
* redeemOffer(offerId)
* removeOfferItemFromCart(itemRow) 
* removeOfferDiscountFromCart(itemRow)
* setCookie(name,value,days)
* submitForSignUp()
* toggleCookie(name)
*/


//var xmlHttp = getHTTPObject();//don't worry about this
var isBusy = false;
var keepOpen;
var isBusy2 = false;
var newLabel;
var newInput;

function addCustomerDropdown(selectOptions, contentId, insertBeforeId) {
	var newSpacer = document.createElement('div');
	newSpacer.className = 'fieldSeparator';
	
	if (document.getElementById('customerDropdown') != null) {
							document.getElementById('customerDropdown').parentNode.removeChild(document.getElementById('customerDropdown'));
	}
	var newRow = document.createElement('div');
	newRow.id = 'customerDropdown';
	
	var newLabel = document.createElement('label');
	newLabel.appendChild(document.createTextNode('Customer'));

	var newSelect = document.createElement('select');
	newSelect.name = 'customer';
	newSelect.id = 'customer';

	if (contentId == 'customerName') {
		// if we're just filling in the customer name
		newSelect.onchange = function(){ 
			document.getElementById('customer_id').value = this.options[this.selectedIndex].value;
			return false; 
		};
	}
	else if (insertBeforeId == 'form1') {
		// we're filling in the customer order form so all details
		newSelect.onchange = function(){
			fillCustomerDetails(this, 'id', 'signup');
			return false; 
		};
	}
	else if (contentId == 'content' || contentId == 'noCustomer') {
		// we're getting the offers for this customer
		newSelect.onchange = function(){
			checkForCustomerOffersByCustomerId(this.options[this.selectedIndex]);
		};
	}
	else {
		// we're filling in the customer order form so all details
		newSelect.onchange = function(){
			fillCustomerDetails(this, 'internalKey');
		};
	}

	var j = 1;
	for (var i in selectOptions) {
		if (j == 2) { // has be the second option cos the first option is the Please Select one
			var selectedOption = 'true';		
		}
		newSelect.options[newSelect.options.length] = new Option(selectOptions[i], i, selectedOption);
		selectedOption = false;
		j++;
	}
	//newSelect.appendChild(document.createTextNode(itemRow));
	newRow.appendChild(newLabel);
	newRow.appendChild(newSelect);
	newRow.appendChild(newSpacer);
	if (insertBeforeId == 'chooseCustomer') {
		document.getElementById(insertBeforeId).appendChild(newRow);
	}
	else {
		document.getElementById(contentId).insertBefore(newRow, document.getElementById(insertBeforeId));
	}
}


function addExtras(documentId, extras) {
	var inputString;
	for (var i in extras) { 
		var newInput = document.createElement('input');
		newInput.type = 'checkbox';
		newInput.name = 'extras[]';
		newInput.value = i;
		newInput.appendChild(document.createTextNode(extras[i]));
	} // end for all ids to remove from the cart
	inputString += newInput;
	document.getElementById(documentId + 'Options').appendChild(inputString);
	
} // end addExtras(documentId, extras)


//http://server/?id=106&option=displaylogin&refer=server?id=1&mode=showDetailListing&listing=7
function addToCart(sId, userId) {
	var xmlHttp = getHTTPObject();
	var path = 	location.pathname.substr(0,(location.pathname.lastIndexOf("index")));
	var url = 'http://' + location.host + path + 'assets/modules/restaurants/ajax_functions.php?mode=sItem&item_id=' + sId + '&user_id=' + userId;
	if (isBusy) {
		xmlHttp.onreadystatechange = function () {}
		xmlHttp.abort();
	}

    xmlHttp.open("GET", url, true); 
    isBusy = true;
    xmlHttp.onreadystatechange = handleHttpResponseAddToCart(xmlHttp);
    xmlHttp.send('');		
} // end addToCart(sId, userId)


function addOfferItemToCart(itemRow) {
	if (itemRow) {
		if (document.getElementById('quantity' + itemRow['code']) != null) {
			// this item is in the cart already
			if (document.getElementById('quantity' + itemRow['code']).innerHTML >= 1) {
				// there is only one of these items in the cart, replace the price and subtotal '\u20AC' + 
				document.getElementById('price' + itemRow['code']).innerHTML = itemRow['gPrice'];
				document.getElementById('subtotal').innerHTML = '\u20AC' + itemRow['subtotal'];
				document.getElementById('finalTotal').innerHTML = '\u20AC' + itemRow['finalTotal'];
				var namedField = 'item' + itemRow['code'];
				document.getElementById('item' + itemRow['code']).innerHTML = itemRow[namedField];
			}
			else {
				document.getElementById('quantity' + itemRow['code']).innerHTML = itemRow['gItemTotal'];
				
			}
		}
		else if (itemRow['deliveryFee']) {
			for (var i in itemRow) {
	    		document.getElementById(i).innerHTML = itemRow[i];
			} // end for all 
		}
		else {
			/**
			* Add a new row to the list of files
			*/
			// Row div
			var newRow = document.createElement('tr');
			newRow.className = 'cartItem';
			newRow.setAttribute('id', itemRow['offerId']);
			
			var cellImage = document.createElement('td');
			cellImage.className = 'cartItemImage';
			var cellImageTag = document.createElement('img');
			cellImageTag.setAttribute('src', itemRow['image']);
			cellImage.appendChild(cellImageTag);
			
			var cellName = document.createElement('td');
			cellName.className = 'cartItemName';
			cellName.appendChild(document.createTextNode(itemRow['gName']));
			
			var cellQty = document.createElement('td');
			cellQty.className = 'cartQty';
			var cellDecrement = document.createElement('a');
			cellDecrement.setAttribute('href', itemRow['gDecrementURL']);
			var cellDecrementImage = document.createElement('img');
			cellDecrementImage.setAttribute('src', 'assets/modules/restaurants/images/cart_minus.gif');
			cellDecrement.appendChild(cellDecrementImage);
			cellQty.appendChild(cellDecrement);
			cellQty.appendChild(document.createTextNode(itemRow['gQuantity']));
			var cellIncrement = document.createElement('a');
			cellIncrement.setAttribute('href', itemRow['gIncrementURL']);
			var cellIncrementImage = document.createElement('img');
			cellIncrementImage.setAttribute('src', 'assets/modules/restaurants/images/cart_plus.gif');
			cellIncrement.appendChild(cellIncrementImage);
			cellQty.appendChild(cellIncrement);
			
			var cellPrice = document.createElement('td');
			cellPrice.className = 'cartItemPrice';
			cellPrice.appendChild(document.createTextNode(itemRow['gPrice']));
			
			var cellTotal = document.createElement('td');
			cellTotal.className = 'cartItemTotal';
			cellTotal.appendChild(document.createTextNode(itemRow['gItemTotal']));	
			
			var cellClear = document.createElement('td');
			cellClear.className = 'cartQty';
			var cellClearAnchor = document.createElement('a');
			cellClearAnchor.setAttribute('href', itemRow['gClearItemURL']);
			var cellClearImage = document.createElement('img');
			cellClearImage.setAttribute('src', 'assets/modules/restaurants/images/redx.gif');
			cellClearAnchor.appendChild(cellClearImage);
			cellClear.appendChild(cellClearAnchor);
			
			newRow.appendChild(cellImage);
			newRow.appendChild(cellName);
			newRow.appendChild(cellQty);
			newRow.appendChild(cellPrice);
			newRow.appendChild(cellTotal);
			newRow.appendChild(cellClear);/**/
			
			// Add it to the table
			document.getElementById('mainCart').appendChild(newRow);
			//document.getElementById('mainCart').insertBefore(newRow, document.getElementById('totalRow'));
		}
	}
} // end addOfferItemToCart(itemRow)


// this is used for both offer percentage discounts and actual offer amounts discounts
function addOfferDiscountToCart(itemRow) {
	if (itemRow) {
		// Row div
		var newRowSubtotal = document.createElement('tr');
		newRowSubtotal.className = 'bottomText';
		newRowSubtotal.setAttribute('id', 'subtotalAmount' + itemRow['offerId']);
		
		var cellLabel = document.createElement('td');
		cellLabel.setAttribute('colspan', 3);
		cellLabel.className = 'bottomLabel';
		cellLabel.appendChild(document.createTextNode(itemRow['discountLabel'] + ':'));
		var cellValue = document.createElement('td');
		cellValue.className = 'bottomValue';
		cellValue.appendChild(document.createTextNode(itemRow['discount']));
		
		newRowSubtotal.appendChild(cellLabel);
		newRowSubtotal.appendChild(cellValue);		
		
		var newRowTotal = document.createElement('tr');
		newRowTotal.setAttribute('id', 'totalAmount' + itemRow['offerId']);
		
		var cellLabel = document.createElement('td');
		cellLabel.setAttribute('colspan', 3);
		cellLabel.className = 'bottomLabel';
		cellLabel.appendChild(document.createTextNode(itemRow['finalTotalLabel'] + ':'));
		var cellValue = document.createElement('td');
		cellValue.className = 'bottomValue';
		cellValue.appendChild(document.createTextNode(itemRow['finalTotal']));
		
		newRowTotal.appendChild(cellLabel);
		newRowTotal.appendChild(cellValue);	
		
		// Add it to the table
		document.getElementById('mainCart').appendChild(newRowSubtotal);
		document.getElementById('mainCart').appendChild(newRowTotal);
		//document.getElementById('mainCart').insertBefore(newRow, document.getElementById('totalRow'));
	}
} // end addOfferPercentageToCart(itemRow).setAttribute('disabled','disabled');


function applyAccountBalance(itemRow) {
	var accountBalanceRowId = 'accountBalanceRow';
	var accountBalanceAppliedId = 'amountApplied';
	
	if (itemRow) {
		/*if (document.getElementById('accountBalanceAmount') != null) {
			// at some point, there has been an account balance applied, then maybe the page was refreshed or we came back
			// we want to modify the row that says the balance
			accountBalanceRowId = 'accountBalanceAmount';
			accountBalanceAppliedId = 'accountBalanceApplied';	
		}*/
		
		// we haven't applied an account balance before, create the appropriate table row
		if (document.getElementById(accountBalanceRowId) == null) {
			var newRow = document.createElement('tr');
			newRow.className = 'total';
			newRow.setAttribute('id', accountBalanceRowId);
			
			var cellLabel = document.createElement('td');
			cellLabel.className = 'bottomLabel';
			cellLabel.colSpan = 3;
			cellLabel.appendChild(document.createTextNode(itemRow['applyAmountLabel']));
			var cellValue = document.createElement('td');
			cellValue.id = accountBalanceAppliedId;
			cellValue.className = 'bottomValue';
			cellValue.appendChild(document.createTextNode('-\u20AC' + itemRow['applyAmount']));
			
			newRow.appendChild(cellLabel);
			newRow.appendChild(cellValue);	
			
			document.getElementById('mainCartBody').insertBefore(newRow, document.getElementById('totalAmount'));
		}
		else {
			// is the amount applied 0? 
			if (itemRow['applyAmount'] == 0) {
				// yes, remove it
				document.getElementById(accountBalanceRowId).parentNode.removeChild(document.getElementById('accountBalanceRow'));
			}
			else {
				// no
				// we've applied some account balance. change the value in the existing element.
				document.getElementById(accountBalanceAppliedId).innerHTML = '-\u20AC' + itemRow['applyAmount'];	
			}
		}
		// modify the final amount
		document.getElementById('finalTotal').innerHTML = '\u20AC' + itemRow['finalTotal'];

	} // end if there is itemRow
} // end applyAccountBalance(itemRow)


function checkForCustomer(phone, where) {
	
	var xmlHttp = getHTTPObject();
	if (phone.value.length > 0) {
		var path = 	location.pathname.substr(0,(location.pathname.lastIndexOf("index")));
		var url = 'http://' + location.host + path + 'assets/modules/restaurants/ajax_functions.php?mode=gCustomer&phone=' + phone.value + '&fields=' + where;
		if (isBusy) {
			xmlHttp.onreadystatechange = function () {}
			xmlHttp.abort();
		}

	    xmlHttp.open("GET", url, true); 
	    isBusy = true;
	    //xmlHttp.onreadystatechange = handleHttpResponse;
	    xmlHttp.onreadystatechange = function() { 
			if (xmlHttp.readyState == 4) {
				if (xmlHttp.status == 200) {
					eval(xmlHttp.responseText);	
		      	}
	    	}
	    }
	    xmlHttp.send('');	
	}	
} // end checkForCustomer(phone)


function checkForCustomerName(phone) {
	var xmlHttp = getHTTPObject();
	var path = 	location.pathname.substr(0,(location.pathname.lastIndexOf('manager')));
	var url = 'http://' + location.host + path + 'assets/modules/restaurants/ajax_functions.php?mode=gCustomer&fields=name&phone=' + phone.value;
	
	if (isBusy) {
		xmlHttp.onreadystatechange = function () {}
		xmlHttp.abort();
	}

    xmlHttp.open("GET", url, true); 

    isBusy = true;
    //xmlHttp.onreadystatechange = handleHttpResponse;
    xmlHttp.onreadystatechange = function(){ handleHttpResponse(xmlHttp) }; 
    xmlHttp.send('');		
} // end checkForCustomerName(phone)


/* this is for when the call center user is logged in and we want to get the customer offers for the caller */
function checkForCustomerOffersByCustomerId(customer_id) {
	var xmlHttp = getHTTPObject();
	// only get the offers if we haven't done so yet (seems obvious but in case we blur multiple times
	var path = 	location.pathname.substr(0,(location.pathname.lastIndexOf("index")));
	var url = 'http://' + location.host + path + 'assets/modules/restaurants/ajax_functions.php?mode=gCustomer&fields=offers&referrer=' + document.getElementById('referrer_page').value + '&customer_id=' + customer_id.value;
	if (isBusy) {
		xmlHttp.onreadystatechange = function () {}
		xmlHttp.abort();
	}

	xmlHttp.open("GET", url, true); 

    isBusy = true;
    //xmlHttp.onreadystatechange = handleHttpResponse;
    xmlHttp.onreadystatechange = function(){ handleHttpResponse(xmlHttp) }; 
    xmlHttp.send('');
    
		
} // end checkForCustomerOffersByCustomerId(customer_id)

/* this is for when the call center user is logged in and we want to get the customer offers for the caller */
function checkForCustomerOffersByName(name) {
	var xmlHttp = getHTTPObject();
	if (document.getElementById('offersContainer') == null) {
		// only get the offers if we haven't done so yet (seems obvious but in case we blur multiple times
		var path = 	location.pathname.substr(0,(location.pathname.lastIndexOf("index")));
		var url = 'http://' + location.host + path + 'assets/modules/restaurants/ajax_functions.php?mode=gCustomer&fields=offers&referrer=' + document.getElementById('referrer_page').value + '&name=' + name.value;
		if (isBusy) {
			xmlHttp.onreadystatechange = function () {}
			xmlHttp.abort();
		}

	    xmlHttp.open("GET", url, true); 
	    isBusy = true;
	    //xmlHttp.onreadystatechange = handleHttpResponse;
	    xmlHttp.onreadystatechange = function() { 
			if (xmlHttp.readyState == 4) {
				if (xmlHttp.status == 200) {
					eval(xmlHttp.responseText);	
		      	}
	    	}
	    }
	    xmlHttp.send('');	
	}	
} // end checkForCustomerOffersByName(name)

/* this is for when the call center user is logged in and we want to get the customer offers for the caller */
function checkForCustomerOffersByPhone(phone) {
	var xmlHttp = getHTTPObject();
	if (document.getElementById('offersContainer') == null) {
		// only get the offers if we haven't done so yet (seems obvious but in case we blur multiple times
		var path = 	location.pathname.substr(0,(location.pathname.lastIndexOf("index")));
		var url = 'http://' + location.host + path + 'assets/modules/restaurants/ajax_functions.php?mode=gCustomer&fields=offers&referrer=' + document.getElementById('referrer_page').value + '&phone=' + phone.value;
		if (isBusy) {
			xmlHttp.onreadystatechange = function () {}
			xmlHttp.abort();
		}

	    xmlHttp.open("GET", url, true); 
	    isBusy = true;
	    //xmlHttp.onreadystatechange = handleHttpResponse;
	    xmlHttp.onreadystatechange = function() { 
			if (xmlHttp.readyState == 4) {
				if (xmlHttp.status == 200) {
					eval(xmlHttp.responseText);	
		      	}
	    	}
	    }
	    xmlHttp.send('');	
	}	
} // end checkForCustomerOffersByPhone(phone)


function checkForExtras(documentId) {
	var xmlHttp = getHTTPObject();
	var index = location.pathname.lastIndexOf("index");
	var path = 	location.pathname.substr(0,(location.pathname.lastIndexOf("index")));
	var managerIndex = location.pathname.lastIndexOf("manager");
	if (managerIndex != -1) {
		path = location.pathname.substr(0,(location.pathname.lastIndexOf('manager')));
	}
	if (index === -1) {
		path = location.pathname;
	}
	var url = 'http://' + location.host + path + 'assets/modules/restaurants/ajax_functions.php?mode=gExtras&document=' + documentId;

	if (isBusy) {
		xmlHttp.onreadystatechange = function () {}
		xmlHttp.abort();
	}

    xmlHttp.open("GET", url, true); 
    isBusy = true;
    //xmlHttp.onreadystatechange = handleHttpResponse;
    xmlHttp.onreadystatechange = function(){ handleHttpResponse(xmlHttp) }; 
    xmlHttp.send('');		
} // end checkForExtras(documentId)


function clearAddress() {

	var addressFields = new Array('district', 'postal_code', 'town', 'street_address', 'street_number', 'flat', 'flat_number', 'floor_number', 'building_name', 'location_details');
	for (var i in addressFields) {
		document.getElementById(addressFields[i]).value = '';
	} // end for all ids to remove from the cart
}

function confirmPassword() {
	var xmlHttp = getHTTPObject();
	
	var path = 	location.pathname.substr(0,(location.pathname.lastIndexOf("index")));
	var url = 'http://' + location.host + path + 'assets/modules/restaurants/ajax_functions.php?mode=confirmPassword&pw1=' + document.getElementById('password').value + '&pw2=' + document.getElementById('confirmPassword').value;
	if (isBusy) {
		xmlHttp.onreadystatechange = function () {}
		xmlHttp.abort();
	}

    xmlHttp.open("GET", url, true); 
    isBusy = true;
    xmlHttp.onreadystatechange = function() { 
		if (xmlHttp.readyState == 4) {
			if (xmlHttp.status == 200) {
				eval(xmlHttp.responseText);	
	      	}
    	}
    }
    xmlHttp.send('');			
}

function disableOffers(disabledOffers) {
	for (var i in disabledOffers) {
		if (document.getElementById('offer' + disabledOffers[i]) != null) {
	    	document.getElementById('offer' + disabledOffers[i]).disabled=true;
	    	document.getElementById('offerLabel' + disabledOffers[i]).className = 'disabled';
	    }
	} // end for all ids to remove from the cart
}

function enableOffers(enabledOffers) {
	for (var i in enabledOffers) {
    	//document.getElementById('offer' + enabledOffers[i]).setAttribute('disabled','false');
    	
		if (document.getElementById('offer' + enabledOffers[i]) != null) {
	    	document.getElementById('offer' + enabledOffers[i]).disabled=false;
	    	document.getElementById('offerLabel' + enabledOffers[i]).className = '';
	    }
	} // end for all ids to remove from the cart
}


function eraseCookie(name) {
	setCookie(name,"",-1);
}

function fillCustomerDetails(userId, basedOn, where) {
	var xmlHttp = getHTTPObject();
	var path = 	location.pathname.substr(0,(location.pathname.lastIndexOf("index")));
	var url = 'http://' + location.host + path + 'assets/modules/restaurants/ajax_functions.php?mode=gCustomer&' + basedOn + '=' + userId.value + '&fields=' + where;
	if (isBusy) {
		xmlHttp.onreadystatechange = function () {}
		xmlHttp.abort();
	}

    xmlHttp.open("GET", url, true); 
    isBusy = true;
    //xmlHttp.onreadystatechange = handleHttpResponse;
    xmlHttp.onreadystatechange = function(){ handleHttpResponse(xmlHttp) }; 
    xmlHttp.send('');		
} // end fillCustomerDetails(userId, basedOn, where)


// if send to self, then fill in the required recipient fields, used in orderForm chunk
function fillRecipient() {
	if (document.getElementById('sendToSelf').checked == true) { 
		document.getElementById('recipient').style.display='none';
		document.getElementById('delivery_str').value = document.getElementById('address_str').value;
		document.getElementById('delivery_str_number').value = document.getElementById('street_number').value;
		if (document.getElementById('flat_number').value != null) {
			document.getElementById('delivery_flat_number').value = document.getElementById('flat_number').value;
		}
		if (document.getElementById('floor_number').value != null) {
			document.getElementById('delivery_floor_number').value = document.getElementById('floor_number').value;
		}
		if (document.getElementById('building_name').value != null) {
			document.getElementById('delivery_building_name').value = document.getElementById('building_name').value;
		}
		if (document.getElementById('area').value != null) {
			document.getElementById('delivery_area').value = document.getElementById('area').value;
		}
		document.getElementById('delivery_town').value = document.getElementById('address_town').value;
		document.getElementById('delivery_postcode').value = document.getElementById('address_postcode').value;
	} else { 
		document.getElementById('delivery_str').value='';
		document.getElementById('delivery_str_number').value='';
		document.getElementById('delivery_flat_number').value='';
		document.getElementById('delivery_floor_number').value='';
		document.getElementById('delivery_building_name').value='';
		document.getElementById('delivery_area').value='';
		document.getElementById('delivery_town').value='';
		document.getElementById('delivery_postcode').value='';
		document.getElementById('recipient').style.display='block';
	}
}

function getAreas(sel) {
	var xmlHttp = getHTTPObject();
	if (document.getElementById('delivery_town') !== null) {
		document.getElementById('delivery_town').options.length = 0;
	}
	else {
		document.getElementById('town').options.length = 0;
	}
	var sId = sel.options[sel.selectedIndex].value;
	var url = 'http://' + location.host + getPath() + 'assets/modules/restaurants/ajax_functions.php?mode=gAreas&district=';
	
    //xmlHttp.open("GET", url + escape(sId), true);
    // to avoid the error Permission denied to call method XMLHttpRequest.open http://blog.strainu.ro/programming/html/permission-denied-to-call-method-xmlhttprequestopen/
   	xmlHttp.open("GET", url + sId, true); 
    //xmlHttp.onreadystatechange = handleHttpResponse;
    xmlHttp.onreadystatechange = function(){ handleHttpResponse(xmlHttp) }; 
    xmlHttp.send('');		
}


function getCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}


function getHTTPObject() {
	var xmlHttp = false;
	
	try {
		// Opera 8.0+, Firefox, Safari
		xmlHttp = new XMLHttpRequest();
		if (xmlHttp.overrideMimeType) {       
	        xmlHttp.overrideMimeType('text/xml');
	    }
	    try {
            netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead UniversalBrowserWrite");
			netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
        } catch (e) {
            var status = "Permission could be denied for cross-domain scripting.";
        }
	} catch (e){
		// Internet Explorer Browsers
		try {
			xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
				xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {
				// Something went wrong
				alert("Your browser broke!");
				xmlHttp = false;
				//return false;
			}
		}
	}
	return xmlHttp;
} // end function getHTTPObject()


function getMenuExtras(item) {
	var xmlHttp = getHTTPObject();
	var index = location.pathname.lastIndexOf("index");
	var path = 	location.pathname.substr(0,(location.pathname.lastIndexOf("index")));
	var managerIndex = location.pathname.lastIndexOf("manager");
	if (managerIndex != -1) {
		path = location.pathname.substr(0,(location.pathname.lastIndexOf('manager')));
	}
	if (index === -1) {
		path = location.pathname;
	}
	
	if ((document.getElementById(item + 'Extras') != null) && (document.getElementById(item + 'Extras').hasChildNodes())) {
		// we assume that if the id div has content in it then it is because we've generated it
		if (document.getElementById(item + 'Extras').className == 'hide') {
			// we need to show the menu items
			document.getElementById(item + 'Extras').className = '';	
		}
		else {
			// hide the menu items
			document.getElementById(item + 'Extras').className = 'hide';
		}
	}
	else {
		// no content, generate the menu items that fall under this category
		var url = 'http://' + location.host + path + 'assets/modules/restaurants/ajax_functions.php?mode=gMenuExtras&item=' + item;
		
		if (isBusy) {
			xmlHttp.onreadystatechange = function () {}
			xmlHttp.abort();
		}

	    xmlHttp.open("GET", url, true); 
	    isBusy = true;
	    //xmlHttp.onreadystatechange = handleHttpResponse;
	    xmlHttp.onreadystatechange = function() { 
			if (xmlHttp.readyState == 4) {
				if (xmlHttp.status == 200) {
					eval(xmlHttp.responseText);	
		      	}
	    	}
	    }
	    xmlHttp.send('');		
	}
} // end function getMenuExtras(item)


function getMenuItems(category) {
	var xmlHttp = getHTTPObject();
	
	var index = location.pathname.lastIndexOf("index");
	var path = 	location.pathname.substr(0,(location.pathname.lastIndexOf("index")));
	var managerIndex = location.pathname.lastIndexOf("manager");
	if (managerIndex != -1) {
		path = location.pathname.substr(0,(location.pathname.lastIndexOf('manager')));
	}
	if (index === -1) {
		path = location.pathname;
	}
	
	if ((document.getElementById(category + 'Category') != null) && (document.getElementById(category + 'Category').hasChildNodes())) {
		// we assume that if the id div has content in it then it is because we've generated it
		if (document.getElementById(category + 'Category').className == 'hide') {
			// we need to show the menu items
			document.getElementById(category + 'Category').className = '';	
		}
		else {
			// hide the menu items
			document.getElementById(category + 'Category').className = 'hide';
		}
	}
	else {
		// no content, generate the menu items that fall under this category
		var url = 'http://' + location.host + path + 'assets/modules/restaurants/ajax_functions.php?mode=gMenuItems&category=' + category;
		
		if (isBusy) {
			xmlHttp.onreadystatechange = function () {}
			xmlHttp.abort();
		}

	    xmlHttp.open("GET", url, true); 
	    //xmlHttp.setRequestHeader("Connection", "close");

	    isBusy = true;
	    xmlHttp.onreadystatechange = function() { 
			if (xmlHttp.readyState == 4) {
				if (xmlHttp.status == 200) {
					eval(xmlHttp.responseText);	
		      	}
	    	}
	    }
	    xmlHttp.send('');
	}
} // end function getMenuItems(category)


function getStreets(town) {
	var xmlHttp = getHTTPObject();
	var index = location.pathname.lastIndexOf("index");
	var path = 	location.pathname.substr(0,(location.pathname.lastIndexOf("index")));
	var managerIndex = location.pathname.lastIndexOf("manager");
	if (managerIndex != -1) {
		path = location.pathname.substr(0,(location.pathname.lastIndexOf('manager')));
	}
	if (index === -1) {
		path = location.pathname;
	}
	var url = 'http://' + location.host + path + 'assets/modules/restaurants/ajax_functions.php?mode=gStreets&town=' + town.value;
	
	if (isBusy) {
		xmlHttp.onreadystatechange = function () {}
		xmlHttp.abort();
	}

    xmlHttp.open("GET", url, true); 
    isBusy = true;
    //xmlHttp.onreadystatechange = handleHttpResponse;
	xmlHttp.onreadystatechange = function(){ handleHttpResponse(xmlHttp) }; 
    xmlHttp.send('');		
} // end function getStreets(town)


function getPath() {
	var index = location.pathname.lastIndexOf("index");
	var path = 	location.pathname.substr(0,(location.pathname.lastIndexOf("index")));
	var managerIndex = location.pathname.lastIndexOf("manager");
	if (managerIndex != -1) {
		path = location.pathname.substr(0,(location.pathname.lastIndexOf('manager')));
	}
	if (index === -1) {
		path = location.pathname;
	}
	return path;	
}


function handleHttpResponseAddToCart(xmlHttp) {   
	if (xmlHttp.readyState == 4) {
		if (xmlHttp.status == 200) {
			eval(xmlHttp.responseText);	
      	}
    }
} // end function handleHttpResponseAddToCart()


function handleHttpResponse(xmlHttp) {   
	var status;
	try {  
         if (xmlHttp.readyState == 4) {  
             if (xmlHttp.responseText) {
				eval(xmlHttp.responseText);
			} else {  
                //alert(xmlHttp.responseText);  
             }  
         }  
	 }  
	 catch(e) {  
	 	  status = 'Caught Exception: ' + e.description;
	     //alert('Caught Exception: ' + e.description);  
	 }  
	
} // end function handleHttpResponse(xmlHttp)


//http://stackoverflow.com/questions/18082/validate-numbers-in-javascript-isnumeric
function isNumber(n) {
  return !isNaN(parseFloat(n)) && isFinite(n);
}

function modifyIdProperty(elementId, attribute, method) {
	
	 if ((document.getElementById(elementId) !== null) && document.getElementById(elementId).getAttribute(attribute)) {
	 	 switch (method) {
          	case 'decrement':
				var currentElementAttributeValue = document.getElementById(elementId).getAttribute(attribute);
				if (currentElementAttributeValue > 1) {
					// only decrement if it's greater than 1
					var newElementAttributeValue = parseInt(currentElementAttributeValue) - 1;
					document.getElementById(elementId).setAttribute(attribute, newElementAttributeValue);// set default value, we need this for logic part
					document.getElementById(elementId).value = newElementAttributeValue;
				}
				return false;
				break; 
          	  
          	case 'increment':
				var currentElementAttributeValue = document.getElementById(elementId).getAttribute(attribute);
				var newElementAttributeValue = parseInt(currentElementAttributeValue) + 1;
				document.getElementById(elementId).setAttribute(attribute, newElementAttributeValue); // set default value, we need this for logic part
				document.getElementById(elementId).value = newElementAttributeValue; // needed for display
				return false;
				break;
			
		  }	// end switch
     } // end if it's a valid element and it has the attribute
	 else {
	 	var nodeNames; 
	 	for (i = 0; i <= document.getElementById(elementId).attributes.length; i++) {
	 		nodeNames = nodeNames + ' ' + (document.getElementById(elementId).attributes[i].nodeName);	
	 	}
	 	alert(nodeNames);
	 }
}

function redeemAmount(amount) {
	var xmlHttp = getHTTPObject();
	var path = 	location.pathname.substr(0,(location.pathname.lastIndexOf("index")));
	//var url = 'http://' + location.host + path + 'assets/modules/restaurants/ajax_functions.php?mode=redeemAmount&amount=' + amount.value + '&customer_id='+ document.getElementById('customer_id').value;
	var url = 'http://' + location.host + path + 'index.php?id=1795&mode=redeemAmount&amount=' + amount.value + '&customer_id='+ document.getElementById('customer_id').value;
	if (isBusy) {
		xmlHttp.onreadystatechange = function () {}
		xmlHttp.abort();
	}

    xmlHttp.open("GET", url, true); 
    isBusy = true;
    //xmlHttp.onreadystatechange = handleHttpResponse;
    xmlHttp.onreadystatechange = function(){ handleHttpResponse(xmlHttp) }; 
    xmlHttp.send('');		
} // end function redeemAmount(amount)


// apparently only used in ajax_functions: gCustomer
function redeemOffer(offerId, customerId) { 
	var xmlHttp = getHTTPObject();
	var externalPage = 1738;
	var path = 	location.pathname.substr(0,(location.pathname.lastIndexOf("index")));
	var url = 'http://' + location.host + path + 'assets/modules/restaurants/ajax_functions.php?mode=redeemOffer&offer_id=' + offerId;
	if (location.search.lastIndexOf(externalPage) != -1) {
		// we're coming from the externalPage
		url = url + '&referrer=' + 	externalPage;
		// also add in the customer id
		url = url + '&customer_id=' + customerId;
	}
	if (isBusy) {
		xmlHttp.onreadystatechange = function () {}
		xmlHttp.abort();
	}

    xmlHttp.open("GET", url, true); 
    isBusy = true;
    //xmlHttp.onreadystatechange = handleHttpResponse;
    xmlHttp.onreadystatechange = function(){ 
    	if (xmlHttp.readyState == 4) {
			if (xmlHttp.status == 200) {
				eval(xmlHttp.responseText);	
	      	}
    	} 
    }
    xmlHttp.send('');		
} // end function redeemOffer(offerId)


function removeOfferItemFromCart(itemRow) {
	if (itemRow) {
		//document.getElementById('mainCart').removeChild(document.getElementById(itemRow['offerId']));
		for (var i in itemRow) {
			if (!isNumber(itemRow[i])) {
				// not a number
				if (document.getElementById(itemRow[i]) != null) {
	    			document.getElementById('mainCart').removeChild(document.getElementById(itemRow[i]));
	    		}
	    	}
	    	else if (i.indexOf('#') != -1) {
	    		// if there is a # in the index then we are going to remove the element with id of i
	    		document.getElementById('mainCart').removeChild(document.getElementById(itemRow[i]));
	    	}
	    	else {
	    		if (document.getElementById(i) != null) {
	    			document.getElementById(i).innerHTML = '\u20AC' + itemRow[i];	
	    		}
	    	}
		} // end for all ids to remove from the cart
	}
} // end function removeOfferItemFromCart(itemRow)


// itemRow contains the array of elements referred to by ids to remove from the cart
function removeOfferDiscountFromCart(itemRow) {
	if (itemRow) {
		for (var i in itemRow) {
			if (!isNumber(itemRow[i])) {
	    		document.getElementById('mainCart').removeChild(document.getElementById(itemRow[i]));
	    	}
	    	else {
	    		document.getElementById(i).innerHTML = itemRow[i];	
	    	}
		} // end for all ids to remove from the cart
		// reset the subtotal if we need to
	}
} // end function removeOfferItemFromCart(itemRow)

//http://www.quirksmode.org/js/cookies.html
function setCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}


function showOrderDateDivs() {
	if (this.options[selectedIndex].value == groupCriterion) {
		document.getElementById('eligibilityGroupChoice').style.display = 'block'; 		
		document.getElementById('eligibilityAmountChoice').style.display = 'none';
	} else { 
		document.getElementById('eligibilityGroupChoice').style.display = 'none';
		document.getElementById('eligibilityAmountChoice').style.display = 'block';  
	}
	if (this.options[this.selectedIndex].value =='offers') 
		document.getElementById('offerCriteria').style.display='block'; 
	else 		
		document.getElementById('offerCriteria').style.display='none';
}


function submitForSignUp() {
	if (document.getElementById('noCustomer') != null) {
		document.getElementById('noCustomer').innerHTML = '';
	}
	if ((document.getElementById('phone').value == '') && (document.getElementById('mobile_phone').value == '')) { 
		// neither the phone nor the mobile has a value, don't submit
		document.getElementById('noCustomer').innerHTML = 'Please type in a phone number.';
		var newBr = document.createElement('br');
		document.getElementById('noCustomer').appendChild(newBr);
		return false;
	}
	else if (document.getElementById('mode').value == 'step1') { 
		// don't submit the form, we're only looking for the corresponding phone
		if (document.getElementById('where') != null) {
			checkForCustomer(document.getElementById('phone'), 'signupEasy');
		}
		else {
			checkForCustomer(document.getElementById('phone'), 'signup');
		}
		
		/*if (document.getElementById('phone').value != '') {
			
		}
		else {
			checkForCustomer(document.getElementById('mobile_phone'), 'signup');	
		}*/
		return false;
	}
	else if (document.getElementById('mode').value == 'cart') { 
		// don't submit the form, we're only looking for the corresponding phone
		if (document.getElementById('phone').value != '') {
			checkForCustomer(document.getElementById('phone'), 'signup');
		}
		else {
			checkForCustomer(document.getElementById('mobile_phone'), 'signup');	
		}
		return false;
	}
	else if (document.getElementById('mode').value == 'add') {
		// person has come to activate their account
		var myOption = -1;
		var thisForm = document.getElementById('form1');
		for (i = thisForm.address.length - 1; i > -1; i--) {
			if (thisForm.address[i].checked) {
				myOption = i; i = -1;
			}
		}
		if (myOption == -1) {
			alert('Please select a primary address');
			return false;
		}
		else { return true; }

	}
	else if (document.getElementById('mode').value == 'login') {
		if (document.getElementById('password').value.length == 0) {
			/* user exists and they are trying to log in */
			document.getElementById('noCustomer').innerHTML = 'Please type in an email.';
			document.getElementById('emailLabel').className = 'rules';
			return false;	
		}
		else {
			return true;	
		}
	}
	else if (document.getElementById('mode').value.length > 0) { 
		
		if (document.getElementById('email') != null && document.getElementById('email').value.length > 0) {
			// if we're signing up someone who doesn't exist in the db
			if (validateEmail(document.getElementById('email').value) == false) {
				// email is not properly formed, don't submit the form
				document.getElementById('emailLabel').className = 'rules';
				return false;	
			}
			else {
				return true;	
			}
		}
		else if ((document.getElementById('password').value.length > 0)) {
			if (document.getElementById('password').value == document.getElementById('confirmPassword').value) {
				return true;	
			}
			else {
				if (document.getElementById('errorMessage') != null) {
					document.getElementById('errorMessage').innerHTML = 'Please make sure the emails match.';
				}
				document.getElementById('emailLabel').className = 'rules';
				document.getElementById('confirmEmailLabel').className = 'rules';
				return false;	
			}
		}
		else {
			document.getElementById('noCustomer').innerHTML = 'Please type in an email.';
			document.getElementById('emailLabel').className = 'rules';
			return false;	
		}
	}
	else {	
		return true;
	}
}

function swapAddresses(addressId, basedOn) {
	var xmlHttp = getHTTPObject();
	var index = location.pathname.lastIndexOf("index");
	var path = 	location.pathname.substr(0,(location.pathname.lastIndexOf("index")));
	var managerIndex = location.pathname.lastIndexOf("manager");
	if (managerIndex != -1) {
		path = location.pathname.substr(0,(location.pathname.lastIndexOf('manager')));
	}
	if (index === -1) {
		path = location.pathname;
	}

	var url = 'http://' + location.host + path + 'assets/modules/restaurants/ajax_functions.php?mode=gAddress&for=' + basedOn + '&address_id=' + addressId.value;
	if (isBusy) {
		xmlHttp.onreadystatechange = function () {}
		xmlHttp.abort();
	}

    xmlHttp.open("GET", url, true); 
    isBusy = true;
    //xmlHttp.onreadystatechange = handleHttpResponse;
    xmlHttp.onreadystatechange = function(){ 
    	if (xmlHttp.readyState == 4) {
			if (xmlHttp.status == 200) {
				eval(xmlHttp.responseText);	
	      	}
    	} 
    }
    xmlHttp.send('');			
}



function toggleCookie(name) {
	var cookie = getCookie(name);	
	eraseCookie(name);
	if (cookie == 'false') { 
		setCookie(name,'true',7);		
	}
	else {
		setCookie(name,'false',7);
	}
}

//http://www.white-hat-web-design.co.uk/articles/js-validation.php
function validateEmail(email) {
   var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
   if (reg.test(email) == false) {
      return false;
   }
   else { return true; }
}
