karw.formLogin = new Class({
	
	Implements: [Events,Options],
	
	hashCode: null,
	userData: null,
	
	aanmeldurl: 'https://aanvragen.lasercards.nl',
	aanmeldurlTest: 'https://uat-aanvragen.lasercards.nl',
	production: false,
	formId: 'loginform',
	formElement: null,
	barcodeValue: null,
	zipValue: null,
	surnameValue: null,
	emailValue: null,	
	countryValue: null,
	loader: null,
	
	initialize: function(productionmode){
		this.production = productionmode;
		this.formElement = $(this.formId);
		this.enableSubmit();
		this.loader = new karw.Loader();
	},
	
	retreiveFields: function(){
		
		this.barcodeValue = this.formElement.getElement('input.barcode').value;
		this.zipValue = this.formElement.getElement('input.zipcode').value;
	},
	
	enableSubmit: function(){
		this.submitButton = this.formElement.getElement('.btn-verzenden');
		this.submitButton.addEvent('click',this.submitAction.bind(this));

		this.submitButtonNew = this.formElement.getElement('#imbAanvragenZonderVoordeelpas');
		this.submitButtonNew.addEvent('click',this.submitActionNew.bind(this));
	},
	
	submitAction: function(){
		this.loader.setMessage("Uw gegevens worden opgehaald");
		this.loader.show();
		
		this.retreiveFields();
		
		var request = new Request({
			url: karw.context+ '/IGGammaServices/resources/client/hash',
			method:'get',
			onSuccess: this.doSubmitAction.bind(this),
			onFailure: this.failMessage.bind(this)
		}).send('barcode='+this.barcodeValue+'&zipcode='+this.zipValue+'&random='+Math.random()); //+'&country='+this.countryValue+'&surname='+this.surnameValue+'&email='+this.emailValue+'&random='+Math.random());	
		
	},
	submitActionNew: function(){
		this.loader.setMessage("Even geduld alstublieft.");
		this.loader.show();
		
		this.hashCode = '';
		this.retrieveNextCardForVisa();
	},
	doSubmitAction: function(response){
		//this.loader.hide();
		//this.formElement.setStyle('display','none');
		
		this.hashCode = response;
		this.retreiveCustomer();
	},
	
	retreiveCustomer: function(){
		//karw.setShowGenericFormError(false);
		//this.loader.setMessage("Uw gegevens worden opgehaald");
		//this.loader.show();
		var request = new Request.JSON({
			url: karw.context+ '/IGGammaServices/resources/client/customer/'+this.hashCode+'?random='+Math.random(),
			method: 'get',
			onSuccess: this.fillCustomerData.bind(this),
			onFailure: this.failMessage.bind(this)
		}).send();	
	},

	fillCustomerData: function (response) {
		this.UID = response.id;
		this.userData = response;
		
		this.retrieveNextCardForVisa();
	},
	
	retrieveNextCardForVisa: function(){
		var request = new Request({
			url: karw.context+ '/IGGammaServices/resources/client/nextCardForVisa',
			method: 'get',
			onSuccess: this.redirectToVisa.bind(this),
			onFailure: this.failMessage.bind(this)
		}).send('hash='+this.hashCode+'&random='+Math.random());	
	},
	
	redirectToVisa: function(newCard) {
		
		var convDate = "";
		var sex = "";
		var initials = "";
		var surname = "";
		var email = "";
		var number = "";
		var zipcode = "";
		var street = "";
		var city = "";
		var phone = "";
		
		if(this.userData != null){
			if($type(this.userData.birthdate) != "object"){
				var birthdateArr = this.userData.birthdate.split('-');
				convDate = birthdateArr[2]+birthdateArr[1]+birthdateArr[0];
			}
			if($type(this.userData.sex) != "object"){
				sex = (this.userData.sex == "Vrouw" ? "MW mevrouw" : "HR heer");
			}
			if($type(this.userData.initials) != "object"){
				initials = escape(this.userData.initials.replace(/(\.)|( )/g, ''));
			}
			if($type(this.userData.surname) != "object"){
				surname = escape(this.userData.surname);
			}
			if($type(this.userData.email) != "object"){
				email = escape(this.userData.email);
			}
			if($type(this.userData.address.number) != "object"){
				number = this.userData.address.number;
				if($type(this.userData.address.numberSuffix) != "object"){
					number += ' ' + escape(this.userData.address.numberSuffix);
				}
			}
			if($type(this.userData.address.zipcode) != "object"){
				zipcode = this.userData.address.zipcode;
			}
			if($type(this.userData.address.street) != "object"){
				street = escape(this.userData.address.street);
			}
			if($type(this.userData.address.city) != "object"){
				city = escape(this.userData.address.city);
			}
			if($type(this.userData.phone) != "object"){
				phone = escape(this.userData.phone);
			}
		}
		
		var link = (this.production == true ? this.aanmeldurl : this.aanmeldurlTest);
		link = link + '?site=pc1.oud.silver.visa.gamma.nl' +
			'&ExternalCustomerReference=' + newCard +
			'&Title1=' + sex +
			'&Initials=' + initials +
			'&Surname=' + surname +
			'&DateOfBirth=' + convDate +
			'&EmailAddress=' + email +
			'&HouseNumber=' + number +
			'&Postcode=' + zipcode +
			'&StreetName=' + street +
			'&Town=' + city +
			'&Telephone1=' + phone;
		
		window.location.href = link;
	},
	
	failMessage: function(xhr){
		this.loader.hide();
		
		$('ValidationSummary1').setStyles({'display':'none'});
		$('cardempty').setStyles({'display':'none'});
		$('cardnotvalid').setStyles({'display':'none'});
		$('zipempty').setStyles({'display':'none'});
		$('zipnotvalid').setStyles({'display':'none'});
		$('cardzipnotvalid').setStyles({'display':'none'});
		if(xhr.status == "422" || xhr.status == "409"){
			if(xhr.responseText == 'INVALID_CREDENTIALS'){
				$('ValidationSummary1').setStyles({'display':'block'});
				if(this.zipValue.trim() == ""){
					$('zipempty').setStyles({'display':'block'});
				}
				else {
					$('cardzipnotvalid').setStyles({'display':'block'});
				}
//				var errorArea2 = this.formElement.getElement('div.error_barcode');
//				errorArea2.setStyles({'opacity':'0','border-color':'#ff0000'});
//				
//				var errorArea = this.formElement.getElement('div.error_credentials');
//				errorArea.setStyles({'opacity':'1','border-color':'#ff0000'});
			}
			if(xhr.responseText == 'NEW_CARD'){
				this.formElement.setStyle('display','none');
				var newcard = new karw.formNewcard('loginform');				
			}
			if(xhr.responseText == 'NO_CARD_AVAILABLE') {
				alert('NO_CARD_AVAILABLE');
			}
		}
		if(xhr.status == "409"){
			var responseTextArray = xhr.responseText.split(", ");
			//alert(xhr.responseText.split(", "));
			
			for(i=0;i<responseTextArray.length;i++){
				var error = responseTextArray[i].split(" ");
				if(error[0] == "PARAMETER_MISSING" || error[0] == "PARAMETER_INVALID"){
					var field = this.formElement.getElement('input.'+error[1]);
					if(field === null){
						var field = this.formElement.getElement('input#'+error[1]);
					}
//					var mainRow = false;
//					while(mainRow === false){
//						
//						var field = field.getParent();
//						if(field.hasClass('form-row')){
//							var mainElement = field;
//							mainRow = true;
//						}
//					}					
					$('ValidationSummary1').setStyles({'display':'block'});
					if(error[1] == 'barcode' && error[0] == "PARAMETER_INVALID" && this.zipValue.trim() != ""){
						$('cardzipnotvalid').setStyles({'display':'block'});
//						$('cardnotvalid').setStyles({'display':'block'});
					}
					if(error[1] == 'zipcode' && error[0] == "PARAMETER_INVALID" && this.barcodeValue.trim() != ""){
						$('cardzipnotvalid').setStyles({'display':'block'});
//						$('zipnotvalid').setStyles({'display':'block'});
					}

					if(error[1] == 'barcode' && error[0] == "PARAMETER_MISSING"){
						$('cardempty').setStyles({'display':'block'});
					}
					if((error[1] == 'zipcode' && error[0] == "PARAMETER_MISSING") || this.zipValue.trim() == ""){
						$('zipempty').setStyles({'display':'block'});
					}
				}
				if(error[0] == "NO_OPTIN" ){
					var field = this.formElement.getElement('span#optin_text');
					field.setStyle('color','#ff0000');
					var errorArea = this.formElement.getElement('.error_optin');
					errorArea.setStyles({'opacity':'1','border-color':'#ff0000'});
				}
			}
		};
	}
});
