var IEMAC = (navigator.userAgent.indexOf('Mac') != -1 && navigator.userAgent.indexOf('MSIE') != -1);
var W3CDOM = (document.createElement && document.getElementsByTagName && !IEMAC);

if (W3CDOM) {
	var extraTD = document.createElement('td');
	extraTD.className = 'empty';
	document.write('<style>#searchTable{display: block} .noscript{display: none} #orderHeader div {display: block}</style>');
	var extraButton = document.createElement('button');
	extraButton.className = 'extraButton';
	extraButton.appendChild(document.createTextNode('Collect all orders'));
	extraButton.onclick = moveAllToOrderTable;
}

window.onload = function () {
	if (!W3CDOM) return;
	var field = document.getElementById('searchField');
	if (!field) return;
	
	var marker = document.createElement('tr');
	marker.className = 'marker';
	var trashLink = document.createElement('a');
	trashLink.href = '#';
	trashLink.innerHTML = 'remove&nbsp;';
	trashLink.className = 'trash';
	var orderLink = document.createElement('a');
	orderLink.href = '#';
	orderLink.innerHTML = 'order&nbsp;';
	orderLink.className = 'order';
	
	var currentPrice = 0;

	var containers = document.getElementById('startTable').getElementsByTagName('tr'); 
	for (var i=0;i<containers.length;i++) {
		if (containers[i].getAttribute('price'))
			currentPrice = containers[i].getAttribute('price');
		var y = containers[i].getElementsByTagName('td');
		if (y.length != 4) continue;
		containers[i].ordered = false;
		containers[i].productName = y[1].firstChild.nodeValue.toLowerCase();
		containers[i].price = currentPrice;
		var tmp = marker.cloneNode(true);
		tmp.id = 'marker' + containers[i].productName;
		containers[i].parentNode.insertBefore(tmp,containers[i].nextSibling);
		var searchField = containers[i].getElementsByTagName('input')[0];
		searchField.onkeyup = orderSandwich;
		searchField.value = '';
		var extraLink = trashLink.cloneNode(true);
		extraLink.onclick = removeSandwich;
		var extraLink2 = orderLink.cloneNode(true);
		extraLink2.onclick = moveToOrderTable;
		searchField.parentNode.appendChild(extraLink2);
		searchField.parentNode.appendChild(extraLink);
	}
	document.getElementById('searchField').onkeyup = searchSandwich;
	showhidefield();
}

var toSearchResults = new Array();
var toOrderTable =  new Array();
var toStartTable = new Array();

/* SEARCH */

function searchSandwich() {
	this.value = this.value.replace(/\\/,'');
	if (this.value.length < 2) return;
	if (this.remember && this.remember == this.value) return;
	var containers = document.getElementById('startTable').getElementsByTagName('tr');
	for (var i=0;i<containers.length;i++) {
		var cells = containers[i].getElementsByTagName('td');
		if (cells.length != 4) continue;		
		if (containers[i].productName.match(this.value.toLowerCase()))
			toSearchResults.push(containers[i]);
	}	
	var containersSearch = document.getElementById('searchResults').getElementsByTagName('tr');
	for (var i=0;i<containersSearch.length;i++) {
		if (!containersSearch[i].productName.match(this.value.toLowerCase()))
			toStartTable.push(containersSearch[i]);
	}
	moveToSearchResults();
	moveToStartTable();
	this.remember = this.value;
}

function moveToSearchResults() {
	while (toSearchResults.length) 	{
		var node = toSearchResults.shift();
		if (!node.parentNode || node.parentNode.nodeName != 'TBODY') continue;
		checkAmountOfCells(node,4);
		document.getElementById('searchResults').appendChild(node);
	}
}

function moveToStartTable() {
	while (toStartTable.length) {
		var node = toStartTable.shift();
		if (!node.parentNode || node.parentNode.nodeName != 'TBODY') continue;
		checkAmountOfCells(node,4);
		var location = document.getElementById('marker'+node.productName);
		document.getElementById('startTable').insertBefore(node,location);
	}

}

/* ORDER */

function orderSandwich() {
	if (!this.remember)
		this.remember = '';
	if (this.value == this.remember) return;	
	this.value = this.value.replace(/ /,'');
	var amount = this.value * 1;
	if (isNaN(amount) || amount == 0)
		removeFromOrder(this);
	else
		moveToOrder(this);
	this.remember = this.value;
}

function moveToOrder(obj) {
	obj = obj.parentNode.parentNode;
	obj.className = 'highlight';
	obj.ordered = true;
	if (obj.parentNode.id != 'ordered')
		toOrderTable.push(obj);
	calculateTotalPrice();
	addExtraButton();
}

function removeSandwich() {
	removeFromOrder(this)
	if (this.parentNode.parentNode.parentNode.id == 'ordered')
		moveToStartTable();
}

function removeFromOrder(obj) {
	obj = obj.parentNode.parentNode;
	obj.className = '';
	obj.ordered = false;
	obj.getElementsByTagName('input')[0].value = '';
	toStartTable.push(obj);
	calculateTotalPrice();
	return false;
}

function moveToOrderTable() {
	var node = this.parentNode.parentNode;
	checkAmountOfCells(node,3);
	document.getElementById('ordered').appendChild(node);
	calculateTotalPrice();
	window.scrollTo(0,0);
	return false;
}

function moveAllToOrderTable() {
	while (toOrderTable.length) {
		var node = toOrderTable.shift();
		if (!node.ordered) continue;
		if (!node.parentNode || node.parentNode.nodeName != 'TBODY') continue;
		checkAmountOfCells(node,3);
		document.getElementById('ordered').appendChild(node);
	}
	calculateTotalPrice();
	removeButton();
	window.scrollTo(0,0);
}

function checkAmountOfCells(obj,required) {
	var cells = obj.getElementsByTagName('td');
	var current = cells.length;
	if (required == 4 && current == 3) {
		var newCell = extraTD.cloneNode(true);
		if (obj.description)
			newCell.innerHTML = obj.description;
		obj.appendChild(newCell);
	}
	else if (required == 3 && current == 4) {
		var tmp = cells[current-1];
		if (tmp.hasChildNodes() && tmp.firstChild.nodeValue)
			obj.description = tmp.firstChild.nodeValue;
		obj.removeChild(cells[current - 1]);
	}
}

function addExtraButton() {
	document.getElementById('extraButtonTarget').appendChild(extraButton);
}

function removeButton() {
	if (extraButton.parentNode)
		extraButton.parentNode.removeChild(extraButton);
}

function calculateTotalPrice() {
	var price = 0;
	var containers = document.getElementById('ordered').getElementsByTagName('tr');
	for (var i=1;i<containers.length;i++) {
		var searchFields = containers[i].getElementsByTagName('input');
		var amount = searchFields[0].value;
		price += containers[i].price * amount;
	}
var priceandtax = price * 1.094;
	document.getElementById('priceDisplay').innerHTML = round(priceandtax);
	document.getElementById('TotalPrice').value = round(priceandtax);
}

function round(price) {
	price = price.toFixed(2);
	price = price.replace(/\./,'.');
	return price;
}

/** PUSH AND SHIFT FOR IE5 **/

function Array_push() {
	var A_p = 0
	for (A_p = 0; A_p < arguments.length; A_p++) {
		this[this.length] = arguments[A_p]
	}
	return this.length
}

if (typeof Array.prototype.push == "undefined") {
	Array.prototype.push = Array_push
}

function Array_shift() {
	var A_s = 0
	var response = this[0]
	for (A_s = 0; A_s < this.length-1; A_s++) {
		this[A_s] = this[A_s + 1]
	}
	this.length--
	return response
}

if (typeof Array.prototype.shift == "undefined") {
	Array.prototype.shift = Array_shift
}
