var input_ResetValues_history = new Array();

if (typeof(NodeList) != "undefined") NodeList.prototype.toHash = function() {
	var obj = {};
	for(var i = 0;i<this.getLength();i++) {
		try {
			el = this.item(i);
			if (el.firstChild.nodeType == Node.TEXT_NODE) {
				var t = '';
				for(var j = 0; j < el.getChildNodes().getLength() ; j++) {
					switch(el.getChildNodes().item(j).nodeType) {
						case Node.ENTITY_REFERENCE_NODE:
							t += el.getChildNodes().item(j).nodeName;
							break;
						default:
							t += el.getChildNodes().item(j).nodeValue;
					}
				}
				obj[el.nodeName] = t;
			} else {
				obj[el.nodeName] = 'NodeType: '+el.firstChild.nodeType;
			}
		} catch (e) {};
	}
	return $H(obj);
}

function input_ResetValue(that) {
	if (input_ResetValues_history[that.name]) {
		return;
	};

	input_ResetValues_history[that.name] = true;
	that.value = '';
}

function mozilla_AddSearchPlugin() { 
  if ((typeof window.sidebar == "object") && (typeof
  window.sidebar.addSearchEngine == "function")) {

    window.sidebar.addSearchEngine(
      		"http://www.comicstripshop.com/support/ComicStripshopMycroft.src",
      		"http://www.comicstripshop.com/support/ComicStripshopMycroft.gif",
      		'Comic Stripshop',
      		'shopping'
			);
	} else {
		alert('Helaas, uw browser ondersteund geen search plugins');
  	}
}
function logClickOut(a) {
	
	new Ajax.Request('/out.txt?link=' + a.href, {
		asynchronous: false
	});

	return true;
}

var CompleteHandlers = {

	clearSystemMessageTimeout: 10*1000,
	clearSystemMessageInterval: null,

	// updates 
	addtocartResult: function(c) {
		// set the info string
		c.info_string = c.link ? '<a href="'+c.link+'">'+c.info_string+'</a>' : c.info_string;
		$('ci_cartadded').innerHTML = c.info_string ? '<p>'+c.info_string+'</p>' : '';

		// update the amount next to the article
		$('in_cart_amount_' + c.id).innerHTML = c.amount_padded;

		if (c.amount > 0) {
			$('ordered_' + c.id).className 		= 'visible';
			$('show_cart_link').className		= 'visible';
			$('not_ordered_' + c.id).className 	= 'hidden';
		} else {
			$('ordered_' + c.id).className 		= 'hidden';
			$('show_cart_link').className		= 'hidden';
			$('not_ordered_' + c.id).className 	= 'visible';
		}
	},

	addCouponResult: function (c) {
		if (c.ok == 1) {
			var cert_header = $('cert_header');
			var table = cert_header.parentNode;
			var r = table.insertRow(cert_header.rowIndex+1);
			r.id = 'coupon_row_' + c.code;

			// keep coupon in hidden field
			var input 	= document.createElement("INPUT");
			input.type	= 'hidden';
			input.name 	= "cert_code";
			input.value	= c.code;

			var button 			= document.createElement('INPUT');
			button.name 		= 'remove_code_' + c.code;
			button.className 	= 'inp_img';
			button.type 		= 'image';
			button.src			= '/images/cross-delete.gif';
			button.border		= '0';
			button.style.width	= '10px';
			button.style.height	= '10px';
			button.onclick		= function() {
				return removeCoupon(c.code);
			};
		
			var span	= document.createElement('SPAN');
			span.innerHTML = ' Certificaat met code: ' + c.code;
			if (c.issued_for) span.innerHTML += ' (Ontvangen voor bestelling ' + c.issued_for + ')';

			var cell	= r.insertCell(0);
			cell.appendChild(button);
			cell.appendChild(input);
			cell.appendChild(span);
			cell.colSpan = 5;

			cell	= r.insertCell(1);
			cell.innerHTML = '&euro;';

			cell	= r.insertCell(2);
			cell.innerHTML = "-" + c.value;

			$('cart_total').innerHTML = c.cart_total;
		};
	},

	removeCouponResult: function(c) {
		if (c.ok == 1) {
			var row = $('coupon_row_' + c.code);
			row.parentNode.removeChild(row);
			$('cart_total').innerHTML = c.cart_total;

			var adder = $('add_coupon');
			if (adder.nodeName == 'SELECT') {
				var opt = document.createElement('OPTION');
				adder.options.add(opt, adder.options.length-1);
				opt.innerHTML = c.code + ' (waarde: &euro; ' + c.coupon_value + ')';
				opt.value = c.code;
			}
		}
	},

	error: function(children) {
		/* let's do nothing */
	},

	__all: function(children) {
		if (children.system_message) {
			CompleteHandlers.__writeSystemMessage(children.system_message, children.link);
		}
		if (children.cart_contents) {
			$('ci_cartstate').innerHTML = '<p>'+children.cart_contents+'</p>';
		}
	},

	__writeSystemMessage: function(msg, link) {
		try {
		var t = this;
		
		// clear the timeout if there's one - should keep message for a new period
		if (this.clearSystemMessageInterval) {
			clearTimeout(this.clearSystemMessageInterval);
		}
		
		// auto hide message after the given timeout
		this.clearSystemMessageInterval = 
			setTimeout(function() { t.__clearSystemMessage() }, this.clearSystemMessageTimeout);

		// actually set the message
		//$('msg_container').style.display = 'block';
		$('msg').className = 'visible';
		$('system_message').innerHTML = link ? '<a style="color: white; text-decoration: underline" href="'+ link +'">'+ msg +'</a>' : msg;
		} catch (e) { /* alert('wsm: '+e); */ };
	},

	__clearSystemMessage: function() {
		$('system_message').innerHTML = '';
		$('msg').className = 'hidden';
		this.clearSystemMessageInterval = null;
	}
}

function ajaxCall(params) {
	CompleteHandlers.__writeSystemMessage('Bezig...');
	var r = new Ajax.Request('/ajax.phtml', {
					parameters: $H(params).toQueryString(),
					on200: function(req) {

						var result 		= eval('(' + req.responseText + ')');
						var root 		= result.rootName;
						var children	= result.data;

						CompleteHandlers.__all(children);

						try {
							CompleteHandlers[root](children);
						} catch(e) { alert('compl: ' + e); }

						/*
						var parser = new XMLParser();
						var doc = null;
						try {
							parser.parse(req.responseText);
							doc = parser.doc;
						} catch (e) { alert('parse: ' + e); };
						*/

						if (doc != null) {

						}
					},
					on500: function(r) {
						alert('Error 500: ' + t.statusText + "\n\n" + t.responseText);
					},
					on404: function(t) {
						alert('Error 404: location "' + t.statusText + '" was not found.');
					},
					onFailure: function(t) {
						alert('Error ' + t.status + ' -- ' + t.statusText);
					}
				}
			);
}
function ajax_add_to_cart(a_id, a) {
	try {
		document.body.focus();
	} catch (e) {};
	if (!a) a = 1;
	ajaxCall({action: 'addtocart', id: a_id, amount: a});
	return false;
}

function createTextField(_id, _name) {
	var inp 	= document.createElement('INPUT');
	inp.type	= 'text';
	inp.id 		= _id;
	inp.name 	= _name;

	return inp;
}

function add_coupon_CheckTypein(el_code) {
	if ($F(el_code.id) == 'typein') {
		var inp = createTextField('add_coupon', 'add_coupon');
		el_code.parentNode.replaceChild(inp, el_code);
	}
}

function removeCoupon(code, inp) {
	ajaxCall({action: 'removeCoupon', code: code});
	return false;
}

function addCoupon(el_code) {

	var code = $F('add_coupon');
	if (code == 'typein') {
		add_coupon_CheckTypein(el_code);
		return;
	}

	if (el_code.nodeName == 'SELECT') {

		// remove the selected child
		el_code.remove(el_code.selectedIndex);

		// If this was the last option, replace with input field
		// customer may have acquired a coupon from somebody else.
		// checking for length = 1 for the last option will always 
		// be a 'type on' one
		if (el_code.options.length == 1) {
			var inp = createTextField('add_coupon', 'add_coupon');
			el_code.parentNode.replaceChild(inp, el_code);
		}
	}
	
	if (code) {
		ajaxCall({action: 'addCoupon', code: code});
		el_code.value = '';
	};
}
