var xmlHttp;
var httpRequest;
var httpRequest2;
var lastProduct;
var lastRequest;
var timeoutId;
var lastSearchValue = '';
var lastEcoChoice = -1;
var nextLocation = '';

window.onresize = resize;
window.onload = resize;

function blendout() {
	if (timeoutId)
		clearTimeout(timeoutId);
	if (lastRequest == 'add')
		do_blendout('edited_product', 50, 255, 0, 255, 255, 255, 10, 0, 50);
	else if (lastRequest == 'remove') {
		do_blendout('edited_product', 255, 50, 0, 255, 255, 255, 10, 0, 50);
	}
}

function do_blendout(id, startRed, startGreen, startBlue, endRed, endGreen, endBlue, stepCount, step, wait) {
	function rgb(r, g, b) {
		return 'rgb(' + r + ',' + g + ',' + b +')';
	}
	function nextColor(start, end) {
		dif = end-start;
		value = start + dif / stepCount * step;
		return Math.round(value);
	}
	e = document.getElementById('edited_product');
	if (!e)
		return;
	if (step >= stepCount)
		e.style.backgroundColor = rgb(endRed, endGreen, endRed);
	else {
		nextRed = nextColor(startRed, endRed);
		nextGreen = nextColor(startGreen, endGreen);
		nextBlue = nextColor(startBlue, endBlue);
		e.style.backgroundColor = rgb(nextRed, nextGreen, nextBlue);
		timeoutId = setTimeout(
			'do_blendout("'+
				id+'",'+
				startRed+','+
				startGreen+','+
				startBlue+','+
				endRed+','+
				endGreen+','+
				endBlue+','+
				stepCount+','+
				(step+1)+','+
				wait+')', wait);
	}
}

function popup(url) {
	newwindow = window.open(url, '_blank', 'scrollbars=1,height=400,width=600');
	return false;
}

function resize() {
	scrH = document.body.scrollHeight;
	offH = document.body.offsetHeight
	h = scrH > offH ? scrH : offH;
	// h = document.body.clientHeight;

	if (h < 576)
		h = 576;
	pn = document.getElementById('nav_product');
	if (pn) {
		pn.style.display = 'block';
		pn.style.top = (h - pn.clientHeight - 20) + 'px';
	}
	f = document.getElementById('footer');
	if (f) {
		f.style.display = 'block';
		f.style.top = (h - f.clientHeight) + 'px';
	}
	o = document.getElementById('orders');
	if (o) {
		o.style.height = (h-355) + 'px';
		s = document.getElementById('scroller');
		if (s) {
			s.style.height = (h - 195-355) + 'px';
		}
		l = document.getElementById('login');
		if (l) {
			l.style.height = (h-355) + 'px';
		}
	}
	ps = document.getElementById('product_selection');
	if (ps) {
		ps.style.height = (h-480) + 'px';
		//ps.style.height = (h-390) + 'px';
	}
}


<!--
var count1 = 0;
var count2 = 0;

function insertOptionBefore(elSel,num)
{
  if (elSel.selectedIndex >= 0) {
    var elOptNew = document.createElement('option');
    elOptNew.text = 'Insert' + num;
    elOptNew.value = 'insert' + num;
    var elOptOld = elSel.options[elSel.selectedIndex];  
    try {
      elSel.add(elOptNew, elOptOld); // standards compliant; doesn't work in IE
    }
    catch(ex) {
      elSel.add(elOptNew, elSel.selectedIndex); // IE only
    }
  }
}

function removeOptionSelected(elSel)
{
  var i;
  for (i = elSel.length - 1; i>=0; i--) {
    if (elSel.options[i].selected) {
      elSel.remove(i);
    }
  }
}

function appendOptionLast(elSel, value, text)
{
  var elOptNew = document.createElement('option');
  elOptNew.value = value;
  elOptNew.text = text;

  try {
    elSel.add(elOptNew, null); // standards compliant; doesn't work in IE
  }
  catch(ex) {
    elSel.add(elOptNew); // IE only
  }
}

function removeOptionLast(elSel)
{
  if (elSel.length > 0)
  {
    elSel.remove(elSel.length - 1);
  }
}

function removeOptionAll(elSel)
{
  for (;elSel.length > 0;)	
  {
    elSel.remove(elSel.length - 1);
  }
}

//-->



function super_search() {
	e = document.getElementById('search_query');
	o = document.getElementById('only_eco');
	if (e.value != lastSearchValue || o.checked != lastEcoChoice) {
		lastSearchValue = e.value;
		lastEcoChoice = o.checked;
		if (lastSearchValue != '')
			if (e.className != 'searching')
				e.className = 'searching';
		if (timeoutId)

			clearTimeout(timeoutId);
		timeoutId = setTimeout('do_super_search("' + e.value + '")', 500);
	}
}

function do_super_search(query) {

	function encode_query(str) {
		safe_chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-';
		hex = '0123456789ABCDEF';
		result = '';
		for (i = 0; i < str.length; i++) {
			c = str.charAt(i);
			if (safe_chars.indexOf(c) != -1)
				result += c;
			else {
				code = c.charCodeAt(0);
				result += "%" + hex.charAt((code >> 4) & 0xF) + hex.charAt(code & 0xF);
			}
		}
		return result;
	}

	xmlHttp = GetXmlHttpObject();

	if (xmlHttp == null) {
		alert ("Browser does not support HTTP Request");
		return;
	}

	eco = document.getElementById('only_eco').checked ? 1 : 0;

	if (query == '') {
		ps = document.getElementById("product_selection");
		if (ps) {
			ps.innerHTML = '';
			ps.style.display = 'none';
		}
		document.getElementById('search_query').className = '';
		resize();
	} else {
		var url='super_search.php?q=' + encode_query(query) + '&e=' + eco + '&z=' + (new Date()).getTime();
		xmlHttp.onreadystatechange = update_search;
		xmlHttp.open("GET", url, true);
		xmlHttp.send(null);
	}
}

function update_search() {
	if (xmlHttp.readyState == 4 || xmlHttp.readyState == "complete") {
		document.getElementById('index').style.display = 'none';
		document.getElementById('splash').style.background = 'none';
		ps = document.getElementById("product_selection");
		if (!ps) {
			ps = document.createElement('div');
			ps.setAttribute('id', 'product_selection');
			document.getElementById('content').appendChild(ps);
			resize();
		}
		ps.innerHTML = xmlHttp.responseText;
		ps.style.display = '';
		document.getElementById('search_query').className = '';
	}
}

function validate_order() {

	var is_valid = true;

	function ge(n) {
		return document.getElementsByName(n)[0];
	}

	function val(n) {
		e = ge(n);
		if (e.value == '')
			invalidate(e);
		else
			validate(e);
	}
	
	function invalidate(e) {
		is_valid = false;
		if (e.className.indexOf('invalid') == -1) {
			if (e.className == '')
				e.className = 'invalid';
			else
				e.className = 'invalid ' + e.className;
		}
	}

	function validate(e) {
		e.className = e.className.replace(/invalid */, '');
	}

	function checkMail(mail) {
		if (mail == '')
			return false;
		var filter  = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
		return filter.test(mail);
	}

	function validateCpr(cpr_nr) {
		cpr_nr = cpr_nr.replace('-', '');
		if (cpr_nr.length == 10) {
			multipliers = new Array(4, 3, 2, 7, 6, 5, 4, 3, 2, 1);
			sum = 0;
			for (i = 0; i < 10; i++) {
				sum += parseInt(cpr_nr.substring(i, i+1)) * multipliers[i];
			}
			if (sum % 11 != 0) {
				alert('Person-nummeret havde ikke et gyldigt kontrol-ciffer.');
				return false;
			}
		} else {
			return false;
		}
		return true;
	}

	nr = ge('user[cpr]');
	if (validateCpr(nr.value)) {
		validate(nr);
	} else {
		is_valid = false;
		invalidate(nr);
	}

/*
	must_validate = new Array('navn', 'adresse', 'postnr', 'by');
	for (i = 0; i < must_validate.length; i++) {
		val('user[' + must_validate[i] + ']');
	}

	m = ge('user[email]');
	if (checkMail(m.value)) {
		validate(m);
	} else {
		is_valid = false;
		invalidate(m);
	}

	t = ge('user[telefon]');
	m = ge('user[mobil]');
	if (t.value == '' && m.value == '') {
		is_valid = false;
		invalidate(t);
		invalidate(m);
	} else {
		validate(t);
		validate(m);
	}

	d = ge('user[dato]');
	t = ge('user[tid]');
	if (is_valid && d.options[d.selectedIndex].text.indexOf('Fredag') == 0 &&
		t.selectedIndex == 1) {
		is_valid = false;
		alert('Der er ingen levering om fredagen mellem 18:00 - 21:00');
	}
*/

	c = ge('user[confirm]');
	if (!c.checked && is_valid) {
		is_valid = false;
		alert('Du skal acceptere handelsbetingelserne for at afsende ordren.');
	}

	return is_valid;
}

function scroll_to_id(id) {
	e = document.getElementById('product_selection');
	t = document.getElementById(id);
	if (e && t) {
		e.scrollTop = t.offsetTop + 10;
	}
}

function goto_page(sel) {
	val = sel.options[sel.options.selectedIndex].value;
	if (val != '')
		window.location = val;
}

function search_category() {
	needle = document.getElementById('search_query').value; // text-field value
	eco = document.getElementById('only_eco').checked; // only ecological products

	// the haystack we're searching, is all child-nodes in "product_selection".
	haystack = document.getElementById('product_selection').getElementsByTagName('TR');

	// replace stupid HTML chars
	needle = needle.replace(/&/, '&amp;');//.replace(/\</, '&lt;').replace(/\>/, '&gt;');

	// lowercase and split the search string by spaces into array
	needles = needle.toLowerCase().split(' ');

	lastHeader = null;

	wasItemFound = false;

	// search the haystack
	for (i = 0; i < haystack.length; i++) {
		straw = haystack[i];

		// if the element is a header, we save it for later
		if (straw.childNodes.length == 2) {
			if (lastHeader != null) {
				lastHeader.style.display = wasItemFound ? '' : 'none';
				wasItemFound = false; // no items were found after the header
			}
			lastHeader = straw;
		}

		// if the element is a list, we search through ths list-items
		else if (straw.childNodes.length == 5) {
			found = !eco || (straw.childNodes[0].className == 'ecological'); // initialize
			subject = straw.childNodes[1].firstChild.innerHTML.toLowerCase(); // lowercase subject to search
			// search the subject. Every occurence of of the splitted search-string must apply.
			for (j = 0; (j < needles.length) && found; j++) {
				found = (subject.indexOf(needles[j]) != -1);
			}
			// set display-style acording to found
			for (j = 0; j < straw.childNodes.length; j++) {
				straw.childNodes[j].style.display = found ? '' : 'none';
			}
			straw.style.display = found ? '' : 'none';
			if (found)
				wasItemFound = true;
		}
	}
	lastHeader.style.display = wasItemFound ? '' : 'none';
}

function add(id, offerweek) {
	lastRequest = 'add';
	update_orders(id, lastRequest, offerweek);
}

function remove(id) {
	lastRequest = 'remove';
	update_orders(id, lastRequest, 0);
}

function remove_all(id) {
	if (confirm('Vil du fjerne varen?')) {
		lastRequest = 'remove_all';
		update_orders(id, lastRequest, 0) ;
	}
}

function add_go(id, loc) {
	lastRequest = 'add_go';
	nextLocation = loc;
	update_orders(id, 'add');
}

function do_login() {
	xmlHttp = GetXmlHttpObject();
	if (xmlHttp == null) {
		alert ("Browser does not support HTTP Request");
		return;
	}

	var url = 'login.php';

	a = new Array('username', 'password', 'id', 'mode');
	for (i = 0; i < a.length; i++) {
		if (i == 0)
			url += '?';
		else
			url += '&';
		url += a[i] + '=' + document.getElementsByName(a[i])[0].value;
	}
	xmlHttp.onreadystatechange = login_return;
	xmlHttp.open('GET', url, true);
	xmlHttp.send(null);
}

function do_cpr_login() {
	xmlHttp = GetXmlHttpObject();
	if (xmlHttp == null) {
		alert ("Browser does not support HTTP Request");
		return;
	}

	var url = 'cprlogin.php';

	a = new Array('cpr', 'name', 'number','id', 'mode');
	for (i = 0; i < a.length; i++) {
		if (i == 0)
			url += '?';
		else
			url += '&';
		url += a[i] + '=' + document.getElementsByName(a[i])[0].value;
	}

	xmlHttp.onreadystatechange = login_return;
	xmlHttp.open('GET', url, true);
	xmlHttp.send(null);
}


function login_return() {
	if (xmlHttp.readyState == 4 || xmlHttp.readyState == "complete") {
		eval(xmlHttp.responseText);
	}
}

function update_orders(id, mode, offerweek) {
	xmlHttp = GetXmlHttpObject();
	lastProduct = id;
	if (offerweek==undefined) offerweek=0;

	if (xmlHttp == null) {
		alert ("Browser does not support HTTP Request");
		return;
	}

	var url='add.php?id=' + id + '&mode=' + mode + '&offerweek=' + offerweek + '&z=' + (new Date()).getTime();
	xmlHttp.onreadystatechange = order_changed;
	xmlHttp.open("GET", url, true);
	xmlHttp.send(null);
}

function update_time_select(e) {
	ut = document.getElementsByName('user[tid]')[0];

	if (e.options[e.selectedIndex].innerHTML.indexOf('Fredag') != -1) { // friday
		if (ut.selectedIndex == 1)
			ut.selectedIndex = 0;
		ut.options[1].style.display = 'none';
	} else {
		ut.options[1].style.display = '';
	}
}

function update_final_order(e) {

	day = e.options[e.options.selectedIndex].value;

	update_final_order_with_day(day);
	
}

function update_final_order_with_day(day) {
	
	xmlHttp = GetXmlHttpObject();

	if (xmlHttp == null) {
		alert ("Browser does not support HTTP Request");
		return;
	}

	var url='order_table.php?day=' + day + '&z=' + (new Date()).getTime();
	xmlHttp.onreadystatechange = final_order_changed;
	xmlHttp.open("GET", url, true);
	xmlHttp.send(null);

	document.getElementById("leveringstid").innerHTML = '';
	var url='check_delivertime.php?day=' + day + '&z=' + (new Date()).getTime();
	httpRequest2 = GetXmlHttpObject();	
	httpRequest2.onreadystatechange = calc_deliver_time;
	httpRequest2.open("GET", url, true);
	httpRequest2.send(null);
	
	// Update time
	httpRequest = GetXmlHttpObject();	
	var url = 'order_calc_time.php?day=' + day + '&z=' + (new Date()).getTime();
	httpRequest.onreadystatechange = final_day_changed;
	httpRequest.open("GET", url, true);
	httpRequest.send(null);
}

function calc_deliver_time() {
	if (httpRequest2.readyState == 4 || httpRequest2.readyState == "complete") {
		document.getElementById("leveringstid").innerHTML = httpRequest2.responseText;
		resize();
	}
}

function final_order_changed() {
	if (xmlHttp.readyState == 4 || xmlHttp.readyState == "complete") {
		document.getElementById("order_table").innerHTML = xmlHttp.responseText;
		resize();
	}
}

function final_day_changed() {
	if (httpRequest.readyState == 4 || httpRequest.readyState == "complete") {
		var time_option = document.getElementById("time");
		var output = httpRequest.responseText;
		
		option_array = output.split("\n");
/*
		removeOptionAll(time_option);
	
		var count = 0;
		for (i=0;i<option_array.length;++i)
		{
			option_text = option_array[i];
			options = option_text.split(";");
			if (options[2]>0) // still avaliable hours
			{
				appendOptionLast(time_option, options[0], options[1]);
				++count;
			}
		}
		//alert("here2"+count);
		
		if (count==0) appendOptionLast(time_option, "", "Ingen ledige tider");
*/
		
	}
}


function order_changed() {
	if (xmlHttp.readyState == 4 || xmlHttp.readyState == "complete") {
		if (lastRequest == 'add_go' && nextLocation != '') {
			window.location = nextLocation;
			return;
		}
		o = document.getElementById("orders");
		if (!o) {
			s = document.getElementById('spots');
			s.innerHTML = '<div id="orders"></div>';
			s.className = 'orders';
			o = document.getElementById("orders");
		}

		o.innerHTML = xmlHttp.responseText;

		added = true;
		//alert(xmlHttp.responseText.substring(0,14)); 
		if (xmlHttp.responseText.substring(0,14) == "<!-- noadd -->") added = false;
		
		if (!document.getElementById('login')) {
			e = document.getElementById('p' + lastProduct);
			if (e) {
				e = e.firstChild;
				count = parseInt(e.innerHTML);
				
				if (!count)
					count = 0;

				if (lastRequest == 'add'){
					if (added) count++;
				}else if (lastRequest == 'remove'){
					count--;
				}else if (lastRequest == 'remove_all')	
					count = '';
					
				if (count <= 0)
					count = '';
				e.innerHTML = count;
			}
			blendout();
		}

		resize();

		if (document.getElementById("order_table"))
			update_final_order(document.getElementsByName('user[dato]')[0]);
	}
}


function GetXmlHttpObject() {
	var objXMLHttp=null;
	if (window.XMLHttpRequest) {
		objXMLHttp=new XMLHttpRequest();
	} else if (window.ActiveXObject) {
		objXMLHttp=new ActiveXObject("Microsoft.XMLHTTP");
	}
	return objXMLHttp;
}