var provinceSelect;
var municipalityInput;
var cityInput;
var orderButtonSpan;
var selectedProduct;
var orderButton;
var orderTable;
var autoDiv;
var autoCityDiv;
var selectedID;
var selectedCityID;
var recalculate;
var orderSubmit;
var shopform;
var totaalprijs = 0;
var administratiekosten = 7.5;

/******************* Initialization *******************/

window.onload
{
	/* Fill variables */
	provinceSelect = document.getElementById('webshopProvincie');
	orderButtonSpan = document.getElementById('WebShopShowOrderButton');
	selectedProduct = document.getElementById('WebShopCardsSelectedProduct');
	orderButton = document.getElementById('webshopOrder');
	orderTable = document.getElementById('webshopCardsOrderTable');
	municipalityInput = document.getElementById('gemeenteComplete');
	cityInput = document.getElementById('plaatsComplete');
	autoDiv = document.getElementById('autocompleteMunicipalitydiv');
	selectedID = document.getElementById('selectedMunicipalityID');
	selectedCityID = document.getElementById('selectedCityID');
	autoCityDiv = document.getElementById('autocompleteCitydivDeel');
	recalculate = document.getElementById('webshopRecalculate');
	orderSubmit = document.getElementById('webshopSubmit');
	shopform = document.getElementById('shop-overview');
	highlighted = -1;

	/* Fill selectbox */
	fillProvinceSelect();

	/* Add Events */
	if(provinceSelect)
		addEvent(provinceSelect, 'click', _provinceSelect);

	if(orderButton)
		addEvent(orderButton, 'click', _orderButton);

	if(municipalityInput)
		addEvent(municipalityInput, 'keyup', _municipalityInput);
		addEvent(municipalityInput, 'click', _municipalityInputClick);
		addEvent(municipalityInput, 'focus', _municipalityInputClick);

	if(cityInput)
		addEvent(cityInput, 'keyup', _cityInput);
		addEvent(cityInput, 'click', _cityInputClick);

	if(recalculate)
		addEvent(recalculate, 'click', recalculateShop);

	if(orderSubmit)
		addEvent(orderSubmit, 'click', _orderSubmit);
}

window.onbeforeunload = leavePage;


function _orderSubmit()
{
	shopform.action = base_href + 'index.php?goto=cart&oldItemID=556&PageId=27';
	var tablerows = orderTable.getElementsByTagName('tr');

	for(var i=1; i<tablerows.length; i++)
	{
		if(tablerows[i].className != 'totalorder')
		{
			var aantal = tablerows[i].childNodes[1].firstChild.value;
			var result;
			for(j=0; j<aantal;j++)
			{
				var matchProvince = /^\s*Provincie: .*/;
				var matchMunicipality = /^\s*Gemeente: (.*)/;
				var matchCity = /^\s*Plaats: (.*)/;

				if(tablerows[i].childNodes[0].firstChild.nodeValue.match(matchProvince))
				{
					nummer = parseFloat(jsArrayprovincie['ALL'][tablerows[i].lastChild.firstChild.nodeValue][1]);
				}
				else if(result = tablerows[i].childNodes[0].firstChild.nodeValue.match(matchMunicipality))
				{
					var letter = result[1];
					nummer = parseFloat(jsArraygemeente[letter.charAt(0)][tablerows[i].lastChild.firstChild.nodeValue][1]);
				}
				else if(result = tablerows[i].childNodes[0].firstChild.nodeValue.match(matchCity))
				{
					var letter = result[1];
					nummer = parseFloat(jsArrayplaats[letter.charAt(0)][tablerows[i].lastChild.firstChild.nodeValue][1]);
				}


				shopform.action = shopform.action+'&ItemIDs[]='+nummer;
			}
		}
	}

	window.onbeforeunload = null;

	var realsubmit = true;
	shopform.submit();
	return;
}


function _municipalityInputClick()
{
	cityInput.value='';
	if(document.getElementById('result-items') && autoCityDiv.style.display != 'none')
		autoCityDiv.removeChild(document.getElementById('result-items'));

	autoCityDiv.style.display = 'none';
	provinceSelect.options[0].selected = true;
}

function _cityInputClick()
{
	municipalityInput.value='';

	if(document.getElementById('result-items') && autoDiv.style.display != 'none')
		autoDiv.removeChild(document.getElementById('result-items'));

	autoDiv.style.display = 'none';
	provinceSelect.options[0].selected = true;
}

function fillProvinceSelect()
{
	for(var shop_id in jsArrayprovincie['ALL'])
	{
		var option = document.createElement('option');
		option.setAttribute('value', shop_id);
		option.id = shop_id;
		option.appendChild(document.createTextNode(jsArrayprovincie['ALL'][shop_id][0]));
		provinceSelect.appendChild(option);
	}
}

function _provinceSelect()
{
	cityInput.value='';
	autoCityDiv.style.display = 'none';
	municipalityInput.value='';
	autoDiv.style.display = 'none';

	var me=this;

	if(provinceSelect.value != "")
	{	/* Check if it is not changed to the 'chose' value */
		orderButtonSpan.className='show';
		selectedProduct.firstChild.nodeValue = 'Deellevering provincie  '+jsArrayprovincie['ALL'][provinceSelect.value][0] +' kost '+String.fromCharCode(8364)+' '+jsArrayprovincie['ALL'][provinceSelect.value][3];
	}
	else
	{	/* Disable the selectbox for municipality */
		selectedProduct.firstChild.nodeValue = ''
		orderButtonSpan.className='hide';
	}
}

function _orderButton()
{
	if(provinceSelect.value != "")
	{
		document.location.href = base_href + 'index.php?goto=cart&TreeID='+ TreeID +'&ItemID='+ jsArrayprovincie['ALL'][provinceSelect.value][1];
	}
	else if(municipalityInput.value != "")
	{
		var letter = municipalityInput.value.charAt(0);
		document.location.href = base_href + 'index.php?goto=cart&TreeID='+ TreeID +'&ItemID='+ jsArraygemeente[letter][selectedID.firstChild.nodeValue][1];
	}
	else if(cityInput.value != "")
	{
		var letter = cityInput.value.charAt(0);
		document.location.href = base_href + 'index.php?goto=cart&TreeID='+ TreeID +'&ItemID='+ jsArrayplaats[letter][selectedCityID.firstChild.nodeValue][1];
	}
}

this.getKeyCode = function(ev)
{
	if(ev)					/* Moz */
	{
		return ev.keyCode;
	}

	if(window.event)		/* IE */
	{
		return window.event.keyCode;
	}
};

function inputKeyPress(ev)
{
	var key = getKeyCode(ev);
	var ENTER = 13;

	if(key == ENTER)
	{
		recalculateShop();
	}
}

function removeButton()
{
	this.parentNode.parentNode.removeChild(this.parentNode);

	var tablerows = orderTable.getElementsByTagName('tr');
	var aantal = 0;

	for(var i=0; i<tablerows.length; i++)
	{
		if(tablerows[i].className != 'totalorder')
		{
			aantal++;
		}
	}

	if(aantal == 1)
	{
		totaalprijs = 0;
		document.getElementById('debestelling').className='hide';
	}
	else
	{
		var input = this.parentNode.childNodes[2].firstChild.nodeValue;
		var regexppattern = /([0-9]+\.[0-9]{2})/
		var result = input.match(regexppattern);
		totaalprijs -= this.parentNode.childNodes[1].firstChild.value * result[0];
		printTotalPrice();
	}
}

function _municipalityInput(ev)
{
	municipalityInput = document.getElementById('gemeenteComplete');
	selectedManucipality = document.getElementById('selectedManucipality');

	var me = this;
	var letter = municipalityInput.value.charAt(0);
	var direction = 'down';

	/* Different keys that can be used to navigate trough div. */
	var TAB = 9;
	var ESC = 27;
	var KEYUP = 38;
	var KEYDN = 40;
	var KEYLEFT = 37;
	var KEYRIGHT = 39;
	var ENTER = 13;

	var key = getKeyCode(ev);

	if(letter && key != TAB && key != ESC && key != KEYUP && key != KEYDN && key != KEYLEFT && key != KEYRIGHT && key != ENTER)
	{
		if(letter == "'")
		{
			letter = "ZZ";
			var kwote = true;
		}

		autoDiv.style.display='block';
		letter = letter.toString().toUpperCase();

		var letterdata=jsArraygemeente[letter];

		if(letterdata)
		{
			if(document.getElementById('result-items'))
			{
				resultitem = document.getElementById('result-items');
				resultitem.parentNode.removeChild(resultitem);
			}
			var ul = document.createElement('ul');

			ul.id = "result-items";

			var upperTekst = municipalityInput.value.toUpperCase();
			var aantal=0;
			for(var shop_id in letterdata)
			{
				var itemTekst = letterdata[shop_id][0].replace(/zz/,"'");
				if(itemTekst.substr(0, municipalityInput.value.length) == upperTekst)
				{
					aantal = aantal+1;
					var li=document.createElement('li');
					li.id = shop_id;
					li.onmouseover = function()
					{
						this.className = 'selected';
						me.highlightThis(this,'mouseOver');
					};
					li.onmouseout  = function()
					{
						this.className = '';
						me.highlightThis(this,'mouseOut');
					};
					li.onclick = function()
					{
						var municipalityInput = document.getElementById('gemeenteComplete');
						var selectedMunicipality = document.getElementById('selectedMunicipality');
						var letter = municipalityInput.value.charAt(0).toUpperCase();

						municipalityInput.value = this.firstChild.nodeValue;

						if(selectedID.firstChild)
						{
							selectedID.removeChild(selectedID.firstChild);
						}
						selectedID.appendChild(document.createTextNode(this.id));

						if(selectedMunicipality.firstChild)
						{
							selectedMunicipality.removeChild(selectedMunicipality.firstChild);
						}
						selectedMunicipality.appendChild(document.createTextNode(jsArraygemeente[letter][this.id][2]));

						autoDiv.style.display='none';
						orderButtonSpan.className='show';
						selectedProduct.firstChild.nodeValue = 'Het door u gekozen product: `Gemeente: '+ jsArraygemeente[letter][this.id][0] +'` kost € '+jsArraygemeente[letter][this.id][3];

						return false;
					};

					li.appendChild(document.createTextNode(itemTekst));

					ul.appendChild(li);
				}
			}

			if(aantal >= 1)
			{
				autoDiv.appendChild(ul);
			}
			else
			{
				autoDiv.style.display='none';
			}
		}
		else
		{
			autoDiv.style.display='none';
			selectedProduct.firstChild.nodeValue = 'Het door u gekozen product:';
		}
	}
	else if(letter && key == TAB || key == ESC || key == KEYUP || key == KEYDN || key == KEYLEFT || key == KEYRIGHT || key == ENTER)
	{
		switch(key)
			{
				case TAB:
				case ENTER:
					var selectedMunicipality = document.getElementById('selectedMunicipality');
					if(me.highlighted != -1 && me.highlighted)
					{
						municipalityInput.value =me.highlighted.firstChild.nodeValue;
						letter = letter.toString().toUpperCase();

						if(selectedID.firstChild)
							selectedID.removeChild(selectedID.firstChild);

						selectedID.appendChild(document.createTextNode(me.highlighted.id));

						if(selectedMunicipality.firstChild)
							selectedMunicipality.removeChild(selectedMunicipality.firstChild);


						selectedMunicipality.appendChild(document.createTextNode(jsArraygemeente[letter][me.highlighted.id][2]));

						autoDiv.style.display='none';

						orderButtonSpan.className='show';
						selectedProduct.firstChild.nodeValue = 'Het door u gekozen product: `Gemeente: '+me.highlighted.firstChild.nodeValue+'` kost € '+jsArraygemeente[letter][me.highlighted.id][3];
						return false;
					}
				break;
				case ESC:
					autoDiv.style.display='none';
					return false;
				break;

				case KEYUP:
					direction = 'up';
				case KEYDN:
					me.changeHighlight(direction);
					return false;
				break;
			}
	}
	else
	{
		if(autoCityDiv.style.display != 'none')
		{
			cityInput.value='';
			autoCityDiv.style.display = 'none';
			if(document.getElementById('result-items'))
				autoCityDiv.removeChild(document.getElementById('result-items'));
			provinceSelect.options[0].selected = true;
		}
		else if(autoDiv.style.display != 'none')
		{
			municipalityInput.value='';
			autoDiv.style.display = 'none';
			if(document.getElementById('result-items'))
				autoDiv.removeChild(document.getElementById('result-items'));
			provinceSelect.options[0].selected = true;
		}
	}

	this.highlightThis = function(liItem, mouseOverOut)
	{
		if(!me.highlighted)
			me.highlighted = -1;

		if (mouseOverOut == 'mouseOver')
		{
			me.highlighted.className = ''; /* Double because otherwise the currently selected item will not be deselected */
			me.highlighted = liItem;
			me.highlighted.className = 'selected';
			me.city_id = me.highlighted.id;
		}
		else
		{
			liItem.className = '';
			/* de snor mot geen bananen
			me.highlighted = null;  !! <-- Srry snor, zonder bananen krijg je JS error... --> !!*/
			me.highlighted = '';
		}
	};

		/* Move the highligt one up or down, depending on the key pressed. */
	this.changeHighlight = function(direction)
	{
		if(autoDiv.childNodes[0] != undefined)
		{
			if(autoDiv.style.display == 'none')
			{
				autoDiv.style.display == 'block';
				var zoeken = 1;
				/* go trough the DOM and look for the li that is selected */

				for(var i=0; i <= autoDiv.childNodes[0].childNodes.length && zoeken; i++)
				{
					if(autoDiv.childNodes[0].childNodes[i] != undefined) /* check whether there is a childNode, if not, don't go further. */
					{
						if(autoDiv.childNodes[0].childNodes[i].className == 'selected')
						{
							autoDiv.childNodes[0].childNodes[i].className = '';
							zoeken = 0;
						}
					}
				}
				autoDiv.scrollTop = 0;
				municipalityInput.focus();
			}
			var ulResults = document.getElementById('result-items');

			var x = null;
			if (me.highlighted == '' || me.highlighted == null || me.highlighted == -1)
			{
				me.highlighted = direction == "up" ? ulResults.lastChild : ulResults.firstChild;
			}
			else
			{
				me.highlighted.className = '';

				switch(direction)
				{
					case 'up':
						if(ulResults.firstChild == me.highlighted)
						{
							autoDiv.scrollTop = autoDiv.scrollHeight;
							me.highlighted = ulResults.lastChild;
						}
						else
						{
							if ( me.highlighted.offsetTop - 15 <= autoDiv.scrollTop)
							{
								autoDiv.scrollTop -= (me.browser == 'IE' ? 15 : 17);
							}

							me.highlighted = me.highlighted.previousSibling;
						}
					break;
					case 'down':

						if(ulResults.lastChild == me.highlighted)
						{
							autoDiv.scrollTop = 0;
							me.highlighted = ulResults.firstChild;
						}
						else
						{
							if ( me.highlighted.offsetTop + 30 >= autoDiv.offsetHeight)
							{
								autoDiv.scrollTop += (me.browser == 'IE' ? 15 : 17);
							}

							me.highlighted = me.highlighted.nextSibling;
						}
					break;

				}
			}

			me.highlighted.className = 'selected';

			municipalityInput = x
		}
	};
}

function _cityInput(ev)
{
	cityInput = document.getElementById('plaatsComplete');
	selectedCity = document.getElementById('selectedCity');

	var me = this;
	var letter = cityInput.value.charAt(0);
	var direction = 'down';

	/* Different keys that can be used to navigate trough div. */
	var TAB = 9;
	var ESC = 27;
	var KEYUP = 38;
	var KEYDN = 40;
	var KEYLEFT = 37;
	var KEYRIGHT = 39;
	var ENTER = 13;

	var key = getKeyCode(ev);

	if(letter && key != TAB && key != ESC && key != KEYUP && key != KEYDN && key != KEYLEFT && key != KEYRIGHT && key != ENTER)
	{
		if(letter == "'")
		{
			letter = "ZZ";
			var kwote = true;
		}

		autoCityDiv.style.display='block';
		letter = letter.toString().toUpperCase();

		var letterdata=jsArrayplaats[letter];

		if(letterdata)
		{
			if(document.getElementById('result-items'))
			{
				resultitem = document.getElementById('result-items');
				resultitem.parentNode.removeChild(resultitem);
			}

			var ul = document.createElement('ul');

			ul.id = "result-items";

			var upperTekst = cityInput.value.toUpperCase();
			var aantal=0;
			for(var shop_id in letterdata)
			{
				var itemTekst = letterdata[shop_id][0].replace(/zz/,"'");
				if(itemTekst.substr(0, cityInput.value.length) == upperTekst)
				{
					aantal = aantal + 1;
					var li=document.createElement('li');
					li.id = shop_id;
					li.onmouseover = function()
					{
						this.className = 'selected';
						me.highlightThis(this,'mouseOver');
					};
					li.onmouseout  = function()
					{
						this.className = '';
						me.highlightThis(this,'mouseOut');
					};
					li.onclick = function()
					{
						var cityInput = document.getElementById('plaatsComplete');
						var selectedCity = document.getElementById('selectedCity');
						var letter = cityInput.value.charAt(0).toUpperCase();

						cityInput.value = this.firstChild.nodeValue;

						if(selectedCityID.firstChild)
						{
							selectedCityID.removeChild(selectedCityID.firstChild);
						}
						selectedCityID.appendChild(document.createTextNode(this.id));

						if(selectedCity.firstChild)
						{
							selectedCity.removeChild(selectedCity.firstChild);
						}
						selectedCity.appendChild(document.createTextNode(jsArrayplaats[letter][this.id][0]));

						autoCityDiv.style.display='none';
						orderButtonSpan.className='show';
						selectedProduct.firstChild.nodeValue = 'Het door u gekozen product: `Plaats: '+ jsArrayplaats[letter][this.id][0] +'` kost € '+jsArrayplaats[letter][this.id][3];

						return false;
					};

					li.appendChild(document.createTextNode(itemTekst));

					ul.appendChild(li);
				}

			}

			if(aantal >= 1)
			{
				autoCityDiv.appendChild(ul);
			}
			else
			{
				autoCityDiv.style.display = 'none';
			}
		}
	}
	else if(letter && key == TAB || key == ESC || key == KEYUP || key == KEYDN || key == KEYLEFT || key == KEYRIGHT || key == ENTER)
	{
		switch(key)
			{
				case TAB:
				case ENTER:
					var selectedCity = document.getElementById('selectedCity');
					if(me.highlighted != -1 && me.highlighted)
					{
						cityInput.value =me.highlighted.firstChild.nodeValue;
						letter = letter.toString().toUpperCase();

						if(selectedCityID.firstChild)
							selectedCityID.removeChild(selectedCityID.firstChild);
						selectedCityID.appendChild(document.createTextNode(me.highlighted.id));

						if(selectedCity.firstChild)
							selectedCity.removeChild(selectedCity.firstChild);


						selectedCity.appendChild(document.createTextNode(jsArrayplaats[letter][me.highlighted.id][2]));

						autoCityDiv.style.display='none';

						orderButtonSpan.className='show';
						selectedProduct.firstChild.nodeValue = 'Het door u gekozen product: `Plaats: '+me.highlighted.firstChild.nodeValue+'` kost '+jsArrayplaats[letter][me.highlighted.id][3];
						return false;
					}
				break;
				case ESC:
					autoCityDiv.style.display='none';
					return false;
				break;

				case KEYUP:
					direction = 'up';
				case KEYDN:
					me.changeHighlight(direction);
					return false;
				break;
			}
	}
	else
	{
		if(autoDiv.style.display != 'none')
		{
			municipalityInput.value='';
			autoDiv.style.display = 'none';
			if(document.getElementById('result-items'))
				autoDiv.removeChild(document.getElementById('result-items'));
			provinceSelect.options[0].selected = true;
		}
		else if(autoCityDiv.style.display != 'none')
		{
			cityInput.value='';
			autoCityDiv.style.display = 'none';
			if(document.getElementById('result-items'))
				autoCityDiv.removeChild(document.getElementById('result-items'));
			provinceSelect.options[0].selected = true;
		}
	}

	this.highlightThis = function(liItem, mouseOverOut)
	{
		if(!me.highlighted)
			me.highlighted = -1;

		if (mouseOverOut == 'mouseOver')
		{
			me.highlighted.className = ''; /* Double because otherwise the currently selected item will not be deselected */
			me.highlighted = liItem;
			me.highlighted.className = 'selected';
			me.city_id = me.highlighted.id;
		}
		else
		{
			liItem.className = '';
			/* de snor mot geen bananen
			me.highlighted = null;  !! <-- Srry snor, zonder bananen krijg je JS error... --> !!*/
			me.highlighted = '';
		}
	};

		/* Move the highligt one up or down, depending on the key pressed. */
	this.changeHighlight = function(direction)
	{
		if(autoCityDiv.childNodes[0] != undefined)
		{
			if(autoCityDiv.style.display == 'none')
			{
				autoCityDiv.style.display == 'block';
				var zoeken = 1;
				/* go trough the DOM and look for the li that is selected */

				for(var i=0; i <= autoCityDiv.childNodes[0].childNodes.length && zoeken; i++)
				{
					if(autoCityDiv.childNodes[0].childNodes[i] != undefined) /* check whether there is a childNode, if not, don't go further. */
					{
						if(autoCityDiv.childNodes[0].childNodes[i].className == 'selected')
						{
							autoCityDiv.childNodes[0].childNodes[i].className = '';
							zoeken = 0;
						}
					}
				}
				autoCityDiv.scrollTop = 0;
				cityInput.focus();
			}
			var ulResults = document.getElementById('result-items');

			var x = null;
			if (me.highlighted == '' || me.highlighted == null || me.highlighted == -1)
			{
				me.highlighted = direction == "up" ? ulResults.lastChild : ulResults.firstChild;
			}
			else
			{
				me.highlighted.className = '';

				switch(direction)
				{
					case 'up':
						if(ulResults.firstChild == me.highlighted)
						{
							autoCityDiv.scrollTop = autoCityDiv.scrollHeight;
							me.highlighted = ulResults.lastChild;
						}
						else
						{
							if ( me.highlighted.offsetTop - 15 <= autoCityDiv.scrollTop)
							{
								autoCityDiv.scrollTop -= (me.browser == 'IE' ? 15 : 17);
							}

							me.highlighted = me.highlighted.previousSibling;
						}
					break;
					case 'down':
						if(ulResults.lastChild == me.highlighted)
						{
							autoCityDiv.scrollTop = 0;
							me.highlighted = ulResults.firstChild;
						}
						else
						{
							if ( me.highlighted.offsetTop + 30 >= autoCityDiv.offsetHeight)
							{
								autoCityDiv.scrollTop += (me.browser == 'IE' ? 15 : 17);
							}

							me.highlighted = me.highlighted.nextSibling;
						}
					break;

				}
			}

			me.highlighted.className = 'selected';


			cityInput = x
		}
	};
}

