var Orderwizard = Class.create();

/**
 * Winkelwagen is the javascript class for winkelwagen on Artihove
 *
 * Changelog
 * ---------
 *
 * Bas de Winter - Mon Sep 24 2007
 * -------------------------------
 * - added updateTextKeyUp, _getcurrentArray, updateTextKeyDown
 *  this is for updating multiple "persoonlijke boodschap" and/or "gravering" textarea's at the same time
 *
 * @since Thu Jul 26 2007
 * @author Vanja de Keizer - vanja@connectholland
 **/
Orderwizard.prototype = {
	/**
	 * initialize
	 *
	 * Does nothing
	 *
	 * @since Tue Jul 31 2007
	 * @access public
	 * @return void
	 **/
	initialize: function() {
		ajaxEngine.registerRequest('wmdbtable_Wmcadeaubon', '/index.php');
		ajaxEngine.registerAjaxElement("wmdbtable_Wmcadeaubon", $("cadeaubon") );
		ajaxEngine.registerRequest('wmwebservices', '/index.php');
		ajaxEngine.registerAjaxObject("wmwebservices", this);
	},

	/**
	 * showAdres
	 *
	 * Shows or hides @soort
	 *
	 * @since unknown
	 * @access public
	 * @param boolean show
	 * @param string soort
	 * @return void
	 **/
	showAdres: function(show, soort) {
		if (show) {
			document.getElementById(soort).style.display = 'block';
		}
		else {
			document.getElementById(soort).style.display = 'none';
		}
	},

	/**
	 * changeAddress
	 *
	 * Switches param soort field between radiobuttons and checkbox
	 *
	 * @since Fri Aug 31 2007
	 * @param string soort
	 * @access public
	 * @return void
	 **/
	changeAddress: function(soort) {
		for (var i = 0; i < document.orderform[soort].length; i++) {
			if (document.orderform["ander" + soort].checked == true) {
				if (document.orderform[soort][i].checked == true) {
					this["previousSelected" + soort + "Address"] = document.orderform[soort][i].value;
					document.orderform[soort][i].checked = false;
				}
			}
			else {
				if (document.orderform[soort][i].value == this["previousSelected" + soort + "Address"] ) {
					document.orderform[soort][i].checked = true;
				}
			}
		}
	},

	/**
	 * showAllPersonalisering
	 *
	 * Shows all personalisering options for a product
	 *
	 * @since Fri Sep 07 2007
	 * @access public
	 * @param integer id
	 * @return void
	 **/
	showAllPersonalisering: function(id) {
		var cur = 1;
		while ($("personalisering_" + id + "_" + cur) ) {
			$("personalisering_" + id + "_" + cur).style.display = "block";
			cur++;
		}
	},

	/**
	 * hidePersonalisering
	 *
	 * Hides all personalisering options for a product (except the first)
	 * @since Fri Sep 07 2007
	 * @access public
	 * @param integer id
	 * @return void
	 **/
	hidePersonalisering: function(id) {
		var cur = 1;
		while ($("personalisering_" + id + "_" + cur) ) {
			$("personalisering_" + id + "_" + cur).style.display = "none";
			cur++;
		}
		cur--;
		$("personalisering_" + id + "_" + cur).style.display = "block";
	},

	/**
	 * handleCadeaubon
	 *
	 * Tries to pay (a portion of) the costs of the a bestelling with a cadeaubon
	 *
	 * @since Wed Sep 12 2007
	 * @access public
	 * @return void
	 **/
	handleCadeaubon: function() {
		var code = document.Wmdbtable_form.code.value;
		ajaxEngine.sendRequest("wmdbtable_Wmcadeaubon", "ct=wmcadeaubon", "mode=getsaldo", "code=" + code, "dt=wmcadeaubon_editor");		
	},

	/**
	 * cadeaubonForm
	 *
	 * Shows a div popup form to enter a cadeaubon code
	 *
	 * @since Wed Aug 29 2007
	 * @access public
	 * @return void
	 **/
	cadeaubonForm: function() {
		ajaxEngine.sendRequest("wmdbtable_Wmcadeaubon", "ct=wmcadeaubon", "mode=searchform", "dt=wmcadeaubon_editor");		
		$("cadeaubon").style.display = "block";
	},

	/**
	 * cancel
	 *
	 * Hides the cadeaubon div
	 *
	 * @since Wed Sep 12 2007
	 * @access public
	 * @return void
	 **/
	cancel: function() {
		$("cadeaubon").style.display = "none";
	},

	/**
	 * next
	 *
	 * Moves on to the next step
	 *
	 * @since Wed Sep 12 2007
	 * @access public
	 * @return void
	 **/
	next: function() {
		this.handleCadeaubon();
	},

	/**
	 * ok
	 *
	 * Adds a transaction for a cadeaubon and closes the popup
	 *
	 * @since Wed Sep 12 2007
	 * @access public
	 * @return void
	 **/
	ok: function() {
		var code = $("cadeauboncode").value;
		ajaxEngine.registerAjaxObject("wmdbtable_Wmcadeaubon", this);
		ajaxEngine.sendRequest("wmdbtable_Wmcadeaubon", "ct=wmcadeaubon", "code=" + code, "__cms_Wmcadeaubon=true", "__function_Wmcadeaubon=addTransaction"); 
	},

	/**
	 * ajaxUpdate
	 *
	 * Reloads the page
	 * 
	 * @since Wed Sep 12 2007
	 * @access public
	 * @param response
	 * @return void
	 **/
	ajaxUpdate: function(response) {
		var postcode = response.getElementsByTagName("postcode");
		var p = postcode.item(0);
		if (p) {
			if (p.getAttribute("straatnaam") != "" && p.getAttribute("plaatsnaam") != "") {
				document.registratieform.adres.value = p.getAttribute("straatnaam");
				document.registratieform.plaats.value = p.getAttribute("plaatsnaam");
				if ($("postcode_message") ) {
					$("postcode_message").remove();
				}
			}
			else {
				if (location.hostname.match("mijnamber")[0]) {
					if ($$("div.pos_missingmessage")[0]) {
						var missingmessage = $$("div.pos_missingmessage")[0];
						missingmessage.innerHTML = missingmessage.innerHTML + "<p id='postcode_message'>" + "U heeft een onbekende postcode / huisnummer combinatie ingevuld. Wij verzoeken u uw gegevens te controleren en desnoods de velden straat en woonplaats met de hand in te vullen."+ "</p>";
					}
				}
			}
		}
		else {
			var transaction = response.getElementsByTagName("transaction").item(0);
			if (transaction) {
				var id = transaction.getElementsByTagName("id").item(0);
				var md5 = transaction.getElementsByTagName("md5").item(0);
				ajaxEngine.registerAjaxObject("wmdbtable_Wmcadeaubon", this);
				ajaxEngine.sendRequest("wmdbtable_Wmcadeaubon", "ct=wmcadeaubon", "transactionid=" + id, "__cms_Wmcadeaubon=true", "__function_Wmcadeaubon=deleteTransaction", "md5=" + md5); 
			}
			else {
				document.location.href = "/?ct=bestellen&step=300";
			}
		}
	},

	/**
	 * firstAreaFocus
	 *
	 * Handle's the focus event on the first area
	 *
	 * @since Fri Nov 9 2007
	 * @access public
	 * @param Event event
	 * @return void
	 **/
	firstAreaFocus : function(event) {
		var element = Event.element(event);
		var initialValue = element.value;
		
		this.similarareas = this._findSimilar(element, initialValue);

		if (typeof(this.keyupObserver) != "function") {
			this.keyupObserver = this.updateSimilar.bindAsEventListener(this);
			Event.observe(element, "keyup", this.keyupObserver);
			Event.observe(element, "change", this.keyupObserver);
		}
		
		if (typeof(this.blurObserver) != "function") {
			this.blurObserver = this.cleanArray.bindAsEventListener(this);
			Event.observe(element, "blur", this.blurObserver);
		}
	},

	/**
	 * cleanArray
	 *
	 * Clean's the similarareas array
	 *
	 * @since Fri Nov 9 2007
	 * @access public
	 * @param Event event
	 * @return void
	 **/
	cleanArray : function(event) {
		this.similarareas = [];
	},
	
	/**
	 * updateSimilar
	 *
	 * updates all element in the similarareas array to the value of the fireing textarea
	 *
	 * @since Fri Nov 9 2007
	 * @access public
	 * @param Event event
	 * @return void
	 **/
	updateSimilar: function(event, element) {
		if (this.similarareas.length == 0) {
			return;
		}
		if (event != null) {
			element = Event.element(event);
		}
		this.similarareas.each(function(newValue, area) {
			area.value = newValue;
			area.onkeyup();
		}.bind(this, element.value) );

		return true;
	},
	
	/**
	 * _findSimilar
	 *
	 * Finds all textarea's with the same name, not being the fireing area and having the same value
	 *
	 * @since Fri Nov 9 2007
	 * @access protected
	 * @param DOMElement textarea
	 * @param string value
	 * @return array
	 **/
	_findSimilar : function(textarea, value) {
		return $A(document.getElementsByTagName("textarea") ).findAll(function(textarea, value, area) {
			return ( (area.value == value) && (area.id != textarea.id) && (area.name == textarea.name) );
		}.bind(this, textarea, value) );
	},

	/**
	 * setLand
	 *
	 * sets the default country according to the current language
	 *
	 * @since Fri Sep 28 2007
	 * @access public
	 * @param string clanguage
	 * @param string id
	 * @return void
	 **/
	setLand: function(clanguage, id) {
		var citem = $(id);
		switch (clanguage) {
			case "de_DE":
				var cCountry = "Duitsland";
				break;
			case "en_US":
				var cCountry = "Groot Brittannie";
				break;
			case "en_GB":
				var cCountry = "Groot Brittannie";
				break;
			default:
				var cCountry = "Nederland";
				break;
		}
		var landOptions = $A(citem.getElementsByTagName("option") );

		var selectedLand = this._getSelectedOption(landOptions);
		if (selectedLand.value === "") {
			for (i=0; i < citem.options.length; i++) {
				if (citem.options[i].value == cCountry) {
					citem.options[i].selected = "selected";
				}
			}
		}
	},

	/**
	 * showMissing
	 *
	 * Shows a div with missing fields message
	 *
	 * @since Thu Oct 4 2007
	 * @access public
	 * @param string id
	 * @return void
	 **/
	showMissing: function(id) {
		var missing = $$("span.missing");
	
		if (missing.length > 0) {
			var divje = $(id);
			var notice = document.createElement("p");
			notice.innerHTML = "Wilt u alstublieft de onderstaande rood opgelichte ontbrekende velden invullen?";
			divje.appendChild(notice);
		}
	},

	/**
	 * updateBTW
	 *
	 * recalculates BTW if an valid DE BTW number is fill-in / removed
	 *
	 * @since Mon Oct 7 2007	
	 * @access public
	 * @param string btwid
	 * @param string btw
	 * @return void
	 **/
	updateBTW: function(id, btw) {
		var btwField = $(id);
		if (btwField) {
		var myForm = btwField.up("form");

		var selectionFields = $A(myForm.getElementsByTagName("select") );
		var landField = selectionFields.find(function(e) {
			return e.name == "land";
		});
		var landOptions = $A(landField.getElementsByTagName("option") );
			var selectedLand = this._getSelectedOption(landOptions);

			if (selectedLand.value == "Duitsland") {
				var zakelijkField = myForm.getInputs("radio", "zakelijk");
		var selectedZakelijk = this._getSelectedOption(zakelijkField);
			}

		if (btwField.value.search(/^DE[\ -]{0,1}[0-9]{9}$/) === 0 && selectedLand.value == "Duitsland" && selectedZakelijk.value === "1") {
			$("btw_verzend").innerHTML = "0,00";
		}
			else if (btwField.value.search(/^BE[\ -]{0,1}[0-9]{10}$/) === 0 && selectedLand.value == "Belgie") {
				$("btw_verzend").innerHTML = "0,00";
			}
		else {
			if (Math.round(btw) <= 0) {
				$("btw_verzend").innerHTML = "?";
			}
			else {
				$("btw_verzend").innerHTML = btw.replace(".", ",");
			}
		}
		}
	},

	/**
	 * tryPostcode
	 *
	 * If a postcode is complete, 4 number, 2 letters, fill out straat and woonplaats (and make them readonly)
	 *
	 * @since Wed Oct 31 2007
	 * @access public
	 * @return void
	 **/
	tryPostcode: function() {
		var postcode = document.registratieform.postcode.value;
		var postcodeletters = document.registratieform.postcodeletters.value;
		if (postcodeletters != "") {
			postcode = postcode + postcodeletters;
		}
		postcode = postcode.replace(" ", "");
		if (postcode.match(/(\d{4})([a-zA-Z]{2})/) ) {
			var huisnummer = document.registratieform.huisnummer.value;
			if (huisnummer != "") {
				var queryobj = {};
				queryobj["ct"] = "wmwebservice";
				queryobj["huisnummer"] = huisnummer;
				queryobj["postcode"] = postcode;
				ajaxEngine.sendRequest("wmwebservices", {parameters: queryobj});
			}
		}
	},

	/**
	 * _getSelectedOption
	 *
	 * returns the selected value in and array of selection values
	 *
	 * @since Tue Oct 8 2007
	 * @access private
	 * @param array array
	 * @return string
	 **/
	_getSelectedOption: function(array) {
		return array.find(function(e) {
			return e.selected == true || e.checked == true;
		});
	},

	/**
	 * updateTextCounter
	 *
	 * Updates a field indicating the number of characters left
	 *
	 * @since Wed Apr 1 2009
	 * @access public
	 * @param Element textarea
	 * @param integer allowed
	 * @return void
	 **/
	updateTextCounter: function(textarea, allowed) {
		var counter = textarea.up().down("div.counter_boodschap");
		if (textarea.value.length == 0 && counter) {
			counter.update("");
		}
		else if (counter) {
			counter.update(allowed - textarea.value.length);
		}
	}
}

var Wmorderwizard = new Orderwizard();

