/********************************
 * KentekenCheck version 2		*
 * Author: Bas van Elburg		*
 * contact: ict@intrasurance.nl	*
 ********************************/

/**********************
 * Class: kentekenCheck			
 * purpose: provide the base structure for gathering information based on a licenseplate
 * requires: mootools (v1.2 minimal)
 * requires: inclusion BEFORE DIVDynamicOptions!
 ***/

var kentekenCheckV2 = new Class({
	Implements: [Options, Events],
	options: {
		initKenteken: ''
	},
	initialize: function(options) {
		this.setOptions(options);
	},
	mappings: [],
	addMapping: function(optionID,hint,dataType) {
		// add the mapping
		this.mappings[hint] = {'optionID':optionID,'dataType':dataType};
		// check for UI in dom, if not present, inject a hidden field for processing it to the DIV application
		if(hint != 'LicensePlate') {
			switch(this.mappings[hint].dataType.toLowerCase()) {
				case "string": 
				case "number":
				case "curruncy":
				case "longstring":
					if(!$chk(this.getObjectByName("InsOption_"+this.mappings[hint].optionID))) {
						new Element('input',{"type":"hidden","value":"","hint":hint,"name":"InsOption_"+this.mappings[hint].optionID,"id":"InsOption_"+this.mappings[hint].optionID}).inject($('kentekenCheckWrapper'));
					} 
				break;
				case "date":
					if(!$chk(this.getObjectByName("InsOption_" + this.mappings[hint].optionID + "DateField"))) {
						new Element('input',{"type":"hidden","value":"","hint":hint,"name":"InsOption_"+this.mappings[hint].optionID+"DateField","id":"InsOption_"+this.mappings[hint].optionID+"DateField"}).inject($('kentekenCheckWrapper'));
						new Element('input',{"type":"hidden","value":"","hint":hint,"name":"InsOption_"+this.mappings[hint].optionID+"Day","id":"InsOption_"+this.mappings[hint].optionID+"Day"}).inject($('kentekenCheckWrapper'));
						new Element('input',{"type":"hidden","value":"","hint":hint,"name":"InsOption_"+this.mappings[hint].optionID+"Month","id":"InsOption_"+this.mappings[hint].optionID+"Month"}).inject($('kentekenCheckWrapper'));
						new Element('input',{"type":"hidden","value":"","hint":hint,"name":"InsOption_"+this.mappings[hint].optionID+"Year","id":"InsOption_"+this.mappings[hint].optionID+"Year"}).inject($('kentekenCheckWrapper'));
					} 
				break;
			}
		}
	},
	handleKentekenUpdate: function() {
		if(($('kentekenFlyout').getStyle('display') == 'none') || ($('kentekenFlyout').getStyle('visibility') == 'hidden') || (this.laatstOpgezochteKenteken != $('inp_kenteken').value)) {
			this.showFlyout();
			this.showLoading();
			var req = new Request({
				method:'post',
				url: '/DIVKentekenLookup/KentekenLookupProxy.asmx',
				urlEncoded: false,
				onSuccess: this.handleServiceReply.bind(this),
				onFailure: this.handleServiceFailure.bind(this)
			});
			req.setHeader("Content-Type", "text/xml");
			req.setHeader("SOAPAction", "services.intrasurance.nl/DIVKentekenLookup/lookupKenteken");
	
			req.send('<?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"><soap:Body><lookupKenteken xmlns="services.intrasurance.nl/DIVKentekenLookup"><kenteken><![CDATA['+$('inp_kenteken').value+']]></kenteken></lookupKenteken></soap:Body></soap:Envelope>');
		}
	},
	
	handleServiceReply: function(responseText,responseXML) {

		this.lastServiceResponse = responseXML;
		
		//var statuscode = this.lastServiceResponse.selectSingleNode('//lookupKentekenResult/statusCode').text;
		var statuscode = parseInt(this.lastServiceResponse.getElementsByTagName('statusCode')[0].firstChild.nodeValue,10);
		if(statuscode < 199) {
			$('inp_kenteken').value=this.lastServiceResponse.getElementsByTagName('Kenteken')[0].firstChild.nodeValue;
			this.laatstOpgezochteKenteken = $('inp_kenteken').value;
			// pak uitvoeringen
			//var kentekenUitvoeringenList = new Array().extend(this.lastServiceResponse.selectNodes("//lookupKentekenResult/data/Parameters/Typen/Type"));
			var kentekenUitvoeringenList = new Array().extend(this.lastServiceResponse.getElementsByTagName('Type'));
			if(kentekenUitvoeringenList.length == 0) {
				this.hideLoading(); // hide the loading div;
				$('flyoutContent').set('text','Sorry, het door u opgegeven kenteken kon niet worden gevonden');
			} else if(kentekenUitvoeringenList.length == 1) { // we hebben maar 1 uitvoering, die kunnen we zo invullen
				this.updateDataFields(
					this.lastServiceResponse.getElementsByTagName('Merk')[0].getElementsByTagName('Naam')[0].firstChild.nodeValue.toUpperCase(),
					this.lastServiceResponse.getElementsByTagName('Model')[0].getElementsByTagName('Naam')[0].firstChild.nodeValue,
					this.lastServiceResponse.getElementsByTagName('Bouwjaar')[0].firstChild.nodeValue,
					this.lastServiceResponse.getElementsByTagName('Bouwmaand')[0].firstChild.nodeValue,
					this.lastServiceResponse.getElementsByTagName('Type')[0]
				);
				this.hideFlyout.delay(500,this);
			} else {
				this.hideLoading(); // hide the loading div;
				// content clearen van flyout
				//$('flyoutContent').set("html","<span id=\"kentekenSelectModelMerkTypeText\">" + this.lastServiceResponse.selectSingleNode("//lookupKentekenResult/data/Parameters/Merk/Naam").text + " " + this.lastServiceResponse.selectSingleNode("//lookupKentekenResult/data/Parameters/Model/Naam").text + "</span>");
				$('flyoutContent').set("html","<span id=\"kentekenSelectModelMerkTypeText\">" +  this.lastServiceResponse.getElementsByTagName('Merk')[0].getElementsByTagName('Naam')[0].firstChild.nodeValue + " " + this.lastServiceResponse.getElementsByTagName('Model')[0].getElementsByTagName('Naam')[0].firstChild.nodeValue + "</span>");
				// opties listen en select van maken
				var kentekenUitvoeringSelect = new Element('select',{'id':'kentekenUitvoeringSelect'});
				
				new Element('option',{"selected":"selected","text":"Selecteer de juiste uitvoering","value":"0"}).inject(kentekenUitvoeringSelect);
				
				kentekenUitvoeringenList.each(function(uitvoering) {
					//new Element('option',{"text":uitvoering.selectSingleNode("Naam").text,'value':uitvoering.selectSingleNode('Id').text}).inject(kentekenUitvoeringSelect);
					new Element('option',{"text":uitvoering.getElementsByTagName('Naam')[0].firstChild.nodeValue,'value':uitvoering.getElementsByTagName('Id')[0].firstChild.nodeValue}).inject(kentekenUitvoeringSelect);
				});
				
				kentekenUitvoeringSelect.inject($('flyoutContent'));
				
				kentekenUitvoeringSelect.addEvents({
					'change':this.handleUitvoeringSelected.bind(this,[this.lastServiceResponse])
				});
			}
		} else {
			this.hideLoading(); // hide the loading div;
			$('flyoutContent').set('text','Sorry, het door u opgegeven kenteken is niet correct');
		}
	},
	handleUitvoeringSelected: function(xmlData) {
		this.updateDataFields(
			this.lastServiceResponse.getElementsByTagName('Merk')[0].getElementsByTagName('Naam')[0].firstChild.nodeValue.toUpperCase(),
			this.lastServiceResponse.getElementsByTagName('Model')[0].getElementsByTagName('Naam')[0].firstChild.nodeValue,
			this.lastServiceResponse.getElementsByTagName('Bouwjaar')[0].firstChild.nodeValue,
			this.lastServiceResponse.getElementsByTagName('Bouwmaand')[0].firstChild.nodeValue,
			//xmlData.selectSingleNode("//Typen/Type[Id='"+$('kentekenUitvoeringSelect').options[$('kentekenUitvoeringSelect').selectedIndex].value+"']")
			this.lastServiceResponse.getElementsByTagName('Type')[$('kentekenUitvoeringSelect').selectedIndex - 1]
		)
		this.hideFlyout();
	}, 
	updateDataFields: function(strMerk,strModel,strBouwjaar,strBouwmaand,xmlType) {
		
		try {	
			// Merk
			if($chk(this.mappings['Identifier'])) {
				this.klSetSelectOption(this.getObjectByName('InsOption_'+this.mappings['Identifier'].optionID),strMerk);
			} // end set Merk
			// Type
			if($chk(this.mappings['Identifier2'])) {
				this.klSetTextOption(this.getObjectByName('InsOption_'+this.mappings['Identifier2'].optionID),strModel + " " + xmlType.getElementsByTagName('Naam')[0].firstChild.nodeValue);
			} // end type
			// datum
			if($chk(this.mappings['BOUWJAAR'])) {
				var int_bouwmaand = parseInt(strBouwmaand,10);
				if(int_bouwmaand < 10) { strBouwmaand = "0" + strBouwmaand; }
				if($chk(this.getObjectByName('InsOption_'+this.mappings['BOUWJAAR'].optionID+'DateField'))) {
					this.klSetTextOption(this.getObjectByName('InsOption_'+this.mappings['BOUWJAAR'].optionID+'DateField'),"01-"+strBouwmaand+"-"+strBouwjaar);
					this.klSetTextOption(this.getObjectByName('InsOption_'+this.mappings['BOUWJAAR'].optionID+'Day'),'01');
					this.klSetTextOption(this.getObjectByName('InsOption_'+this.mappings['BOUWJAAR'].optionID+'Month'),strBouwmaand);
					this.klSetTextOption(this.getObjectByName('InsOption_'+this.mappings['BOUWJAAR'].optionID+'Year'),strBouwjaar);
				} else {
					this.klSetSelectOption(this.getObjectByName('InsOption_'+this.mappings['BOUWJAAR'].optionID+'Day'),'01');
					this.klSetSelectOption(this.getObjectByName('InsOption_'+this.mappings['BOUWJAAR'].optionID+'Month'),strBouwmaand);
					this.klSetSelectOption(this.getObjectByName('InsOption_'+this.mappings['BOUWJAAR'].optionID+'Year'),strBouwjaar);
				} 
			}// end set datum

			// Koetswerk
			if($chk(this.mappings['UITVOERING'])) {
				switch(xmlType.getElementsByTagName('Koetswerk')[0].firstChild.nodeValue) {
					case "1":
						this.klSetSelectOption(this.getObjectByName('InsOption_'+this.mappings['UITVOERING'].optionID),"SEDAN");
						break;
					case "2":
						this.klSetSelectOption(this.getObjectByName('InsOption_'+this.mappings['UITVOERING'].optionID),"HATCHBACK");
						break;
					case "3":
						this.klSetSelectOption(this.getObjectByName('InsOption_'+this.mappings['UITVOERING'].optionID),"COUPE");
						break;
					case "4":
					case "16":
						this.klSetSelectOption(this.getObjectByName('InsOption_'+this.mappings['UITVOERING'].optionID),"CABRIOLET");
						break;
					case "5":
					case "14":
						this.klSetSelectOption(this.getObjectByName('InsOption_'+this.mappings['UITVOERING'].optionID),"TERREINWAGEN");
						break;
					case "6":
						this.klSetSelectOption(this.getObjectByName('InsOption_'+this.mappings['UITVOERING'].optionID),"STATIONWAGEN");
						break;
					case "7":
						this.klSetSelectOption(this.getObjectByName('InsOption_'+this.mappings['UITVOERING'].optionID),"MPV");
						break;
					case "8":
						this.klSetSelectOption(this.getObjectByName('InsOption_'+this.mappings['UITVOERING'].optionID),"BESTELAUTO");
						break;
					case "9":
						this.klSetSelectOption(this.getObjectByName('InsOption_'+this.mappings['UITVOERING'].optionID),"PICK-UP");
						break;
					case "15":
						this.klSetSelectOption(this.getObjectByName('InsOption_'+this.mappings['UITVOERING'].optionID),"SUV");
						break;
					default:
						this.klSetSelectOption(this.getObjectByName('InsOption_'+this.mappings['UITVOERING'].optionID),"HATCHBACK");
						break;
				} 
			}// end set koetswerk
			
			// zet brandstof
			if($chk(this.mappings['BRANDSTOF'])) {
				switch(xmlType.getElementsByTagName('Brandstof')[0].firstChild.nodeValue) {
					case "1":
						this.klSetSelectOption(this.getObjectByName('InsOption_'+this.mappings['BRANDSTOF'].optionID),"Benzine");
					break;
					case "2":
						this.klSetSelectOption(this.getObjectByName('InsOption_'+this.mappings['BRANDSTOF'].optionID),"Diesel");
					break;
					case "3":
					case "4":
					case "5":
						this.klSetSelectOption(this.getObjectByName('InsOption_'+this.mappings['BRANDSTOF'].optionID),"Hybride");
					break;
					case "6":
						this.klSetSelectOption(this.getObjectByName('InsOption_'+this.mappings['BRANDSTOF'].optionID),"LPG (Gas)");
					break;
					default:
						this.klSetSelectOption(this.getObjectByName('InsOption_'+this.mappings['BRANDSTOF'].optionID),"Benzine");
						break;
				} 
			}// end zet brandstof		
			
			// zet catalogus waarde
			if($chk(this.mappings['CATWAARDE'])) {
				catWaardeNode = xmlType.getElementsByTagName('Rollsnieuwwaardebruto');
				if (catWaardeNode .length!=0) {
					this.klSetTextOption(this.getObjectByName('InsOption_'+this.mappings['CATWAARDE'].optionID), catWaardeNode[0].firstChild.nodeValue);
				}
				else { //explicitly set value to 0
					this.klSetTextOption(this.getObjectByName('InsOption_'+this.mappings['CATWAARDE'].optionID), "0");
				}
			} // end zet catalogus waarde
			
			// Vermogenkw
			if($chk(this.mappings['VERMOGENKW'])) {
				this.klSetTextOption(this.getObjectByName('InsOption_'+this.mappings['VERMOGENKW'].optionID),xmlType.getElementsByTagName('Vermogen')[0].firstChild.nodeValue);
			} // end Vermogenkw
			
			// zet gewicht
			if($chk(this.mappings['GEWICHT'])) {
				this.klSetTextOption(this.getObjectByName('InsOption_'+this.mappings['GEWICHT'].optionID),xmlType.getElementsByTagName('Gewicht')[0].firstChild.nodeValue);
			} // end zet geweicht
			 
			// zet beveiliging
			if($chk(this.mappings['BEVEILIGING'])) {
				switch(xmlType.getElementsByTagName('Beveiligingsklasse')[0].firstChild.nodeValue) {
					case "0":
						this.klSetSelectOption(this.getObjectByName('InsOption_'+this.mappings['BEVEILIGING'].optionID),"Geen");
						break;
					case "1":
						this.klSetSelectOption(this.getObjectByName('InsOption_'+this.mappings['BEVEILIGING'].optionID),"SCM klasse I");
						break;
					case "2":
						this.klSetSelectOption(this.getObjectByName('InsOption_'+this.mappings['BEVEILIGING'].optionID),"SCM klasse II");
						break;
					case "3":
						this.klSetSelectOption(this.getObjectByName('InsOption_'+this.mappings['BEVEILIGING'].optionID),"SCM klasse III");
						break;
					case "4":
						this.klSetSelectOption(this.getObjectByName('InsOption_'+this.mappings['BEVEILIGING'].optionID),"SCM klasse IV");
						break;
					case "5":
						this.klSetSelectOption(this.getObjectByName('InsOption_'+this.mappings['BEVEILIGING'].optionID),"SCM klasse V");
						break;
					default:
						this.klSetSelectOption(this.getObjectByName('InsOption_'+this.mappings['BEVEILIGING'].optionID),"SMC klasse I");
						break;
				} 
			}// einde beveiliging
		} catch (err) {/*gotta catch'em all */} 
	},
	klSetTextOption: function(objInput,strText) { try{ objInput.value = strText; } catch (err){}},
	klSetSelectOption: function(objInput,strText) {
		try {
			for(j = 0; j < (objInput.options).length; j++) {
				var itsOption = objInput.options[j];
				if(strText == this.klTrim(itsOption.text)) {
					objInput.selectedIndex = j;
					return true;
				}
			}
		} catch (err) {}
		return false;
	},
	getObjectByName: function(name){ try{ return $$('*[name='+name+']')[0];	}catch (err){}},
	getObjectByHint: function(hint){ try{ return $$('*[hint='+hint+']')[0];	}catch (err){}},
	klTrim: function(value) {value = value.replace(/^\s+/,''); value = value.replace(/\s+$/,''); return value;},
	handleServiceFailure: function(xhr) {
		this.hideLoading();
		this.showFlyout();
		$('flyoutContent').set('text',"Sorry, er deed zich een communicatie fout voor. Probeert u het later nog eens");
	},
	checkKeyDown: function(event) {
		if(event.key == 'enter') {
			event.stop();
			this.handleKentekenUpdate();
		}
	},
	raiseError: function(strMsg) {
		alert(strMsg);
	},
	initKentekenUI: function() {
		
		$('kentekenFlyout').fade('hide'); // zeker weten dat flyout weg is
		$('kentekenFlyout').setStyle('display','block');
		
		if($chk(this.mappings['LicensePlate'])) {
			// als bestaat destroy eerst die row en recreate de row als kenteken input
			if($chk($('InsOptionRow_'+this.mappings['LicensePlate'].optionID))) {
				$('inp_kenteken').value = $$('*[Hint=LicensePlate]')[0].value;
				$('InsOptionRow_'+this.mappings['LicensePlate'].optionID).destroy();
			} else {
				if($chk(this.getObjectByHint('LicensePlate'))) {
					var licensePlateObject = this.getObjectByHint('LicensePlate');
					if($chk(licensePlateObject.nextElementSibling)) {
						if(licensePlateObject.nextElementSibling.hasClass('clsImageRequired')) {
							licensePlateObject.nextElementSibling.destroy();
						}
					}
					licensePlateObject.destroy();
				} else {
					// we hoeven niets te doen, mapping hebben we waar we mee vooruit kunnen
				}
			}
			// recreate row on top
			// rename
			var inpKenteken = new Element('input',{'name':'InsOption_'+this.mappings['LicensePlate'].optionID,'value':this.options.initKenteken});
			
			inpKenteken.replaces($('inp_kenteken'));
			inpKenteken.set('id','inp_kenteken');
			
			
			var newKentekenRow = $('InsContractKentekenRow').clone(true,true);
			newKentekenRow.set('id','InsOptionRow_'+this.mappings['LicensePlate'].optionID);
			
			
			newKentekenRow.replaces($('InsContractKentekenRow'));
			// events koppelen voor updates.
			
			$('inp_kenteken').addEvents({
				'change':this.handleKentekenUpdate.bind(this),
				'keydown':this.checkKeyDown.bind(this)
			});
			$('kentekenFlyoutCloseBtn').addEvent('click',this.hideFlyout.bind(this));
			
			// show
			$('InsOptionRow_'+this.mappings['LicensePlate'].optionID).setStyle('display','');
		} else {
			this.raiseError('sorry, kenteken mapping bestaat niet!');
		}

	},
	showOverlay: function() {
		$('kentekenOverlay').setStyle('display','block');
	},
	hideOverlay: function() {
		$('kentekenOverlay').setStyle('display','none');
	},
	showFlyout: function() {
		this.showOverlay();
		$('kentekenFlyout').fade('in');
	},
	hideFlyout: function() {
		$('kentekenFlyout').fade('out');
		this.hideOverlay();
	},
	showLoading: function() {
		$('flyoutContent').setStyle('display','none');
		$('kentekenWait').setStyle('display',"block");

	},
	hideLoading: function() {
		$('kentekenWait').setStyle('display','none');
		$('flyoutContent').setStyle('display','block');
	}

});