var mailHandler = Class.create();
var mailer;
mailHandler.prototype = {
	/**
	 * Author:		Hans Duedal (Lintoo I/S)
	 * Email & URL:	hans@lintoo.dk www.lintoo.dk
	 * Copyright: 	2006 Lintoo I/S
	 *
	 */
	initialize: function() {
		this.input = null;
		this.type = $F('mailerType');
		this.successMsg = $H({
			da:	'Din hilsen er afsendt, den vil ankomme om et øjeblik.',
			en: 'Your greeting is sent, it will arrive in a moment.',
			de:	'Your greeting is sent, it will arrive in a moment.'
		});
		this.commentSuccess = $H({
			da:	'Din kommentar er afsendt, tak for din henvendelse.',
			en: 'Your comment is sent, thank you for your attention.',
			de:	'Your comment is sent, thank you for your attention.'
		});
		this.failureMsg = $H({
			da:	'Det lykkes desvære ikke at sende din meddelse, kontroller venligst at alt er udfyldt korrekt.',
			en: 'Your greeting has not been sent, please check that everything is filled out correctly',
			de:	'Your greeting has not been sent, please check that everything is filled out correctly'
		});
		var languagePart = document.location.search.match(/l=\w+/);
		this.activeLanguage = (languagePart == null)? 'da' : languagePart[0].substr(2);
		
		$S('div.keyBoardButtons a').action( {
			onmousedown: function() {
				Element.addClassName(this, 'active');
			},
			onmouseup: function() {
				Element.removeClassName(this, 'active');
			}
		});
		//initialize gatewayRequest
		this.gatewayRequest = new Ajax.Request('', {
			method: 'post',
			parameters: '',
			onComplete: this.gatewayResult
		});
		$S('div#freeStyleContainer div#inputFieldsContainer div input','div#freeStyleContainer div#inputFieldsContainer div textarea').action( {
			onfocus: function() {
				mailer.focusEvent(this);
			}
		});	
	},
	
	setType: function(type) {
		this.type = type;
		if (type == 'comment') {
			this.input = $('commentText');
			this.input.focus();
		}
	},
	
	focusEvent: function(elm) {
		this.input = elm;
		if (this.input.type == 'text') this.input.onkeypress = this.cleanEmailInput; //must be set at present time
	},
	
	cleanEmailInput: function(event) {
		/**
		 * IE quirks:
		 *  - IE does not give event param, instead one must rely on window.event
		 *  - IE does not set charCode, but does not fire onkeypress when system keys such as Left and Right is pressed.
		 */
		if (event == undefined) event = window.event; //ie compability
		var emailInvalidRegEx = /[^a-z\d@,\.\-_æøå]/i;
		var charCode = (event.keyCode != 0)? charCode = event.keyCode : event.charCode; //ie compability
		if (emailInvalidRegEx.test(String.fromCharCode(charCode)) && (navigator.appVersion.match(/MSIE/) || event.keyCode != Event.KEY_DELETE && event.keyCode != Event.KEY_BACKSPACE && event.keyCode != Event.KEY_LEFT && event.keyCode != Event.KEY_RIGHT && event.keyCode != Event.KEY_TAB)) {
			if (event.cancelable) { //if cancelable, then cancel
				event.preventDefault();
				return;
			} else { //attempt to instruct browser not to return a value, IE
				event.returnValue = false;
				return;
			}
		}
	},
	
	gatewayResult: function(result) {
		if (result.responseXML.documentElement.getAttribute('success') == 'true') {
			if (mailer.type == 'comment') {
				alert(mailer.commentSuccess[mailer.activeLanguage]);
			} else {
				alert(mailer.successMsg[mailer.activeLanguage]);
			}
		} else {
			alert(mailer.failureMsg[mailer.activeLanguage]);
		}
	},
	
	button: function(key) {
		key = key + ''; //cast to String
		switch (key) {
			case 'del':
				this.delOneChar();
			break;
			case 'ok':
				switch (this.type) {
					case 'comment':
						var params = $H( {
							language:	this.activeLanguage,
							type: this.type,
							senderEmail: 'noreply@infospot.nu',
							recipentEmail: 'anje@odense.dk',
							//recipentEmail: 'hans@lintoo.dk',
							subject: 'Kommentar fra infostander',
							message: $F('commentText')
						});
						break;
					case 'postCard':
						var imageSrc = $('image').src;
						imageSrc = imageSrc.replace('http://infospot.w2.onlinecity.dk/', '../');
						var params = $H( {
							language:	this.activeLanguage,
							type: this.type,
							senderEmail: $F('senderEmail'),
							recipentEmail: $F('recipentEmail'),
							subject: 'En hilsen fra Odense',
							message: $F('message'),
							image: imageSrc
						});
						break;
					case 'picture':
						var params = $H( {
							language:	this.activeLanguage,
							type: this.type,
							senderEmail: $F('senderEmail'),
							recipentEmail: $F('recipentEmail'),
							subject: 'En hilsen fra Odense',
							message: $F('message'),
							image: camControl.id
						});
						break;
					case 'video':
						var params = $H( {
							language:	this.activeLanguage,
							type: this.type,
							senderEmail: $F('senderEmail'),
							recipentEmail: $F('recipentEmail'),
							subject: 'En hilsen fra Odense',
							message: $F('message'),
							image: camControl.id
						});
						break;
				}
				if (this.gatewayRequest.transport.readyState == 4 || this.gatewayRequest.transport.readyState == 0) {
					this.gatewayRequest.options.parameters = params.toQueryString();
					this.gatewayRequest.request('datasource/sendMail.php');
				}
			break;
			case 'newline':
				if (this.input.type == 'textarea') {
					this.input.value += '\r\n';
				}
			break;
			default: 
				if( document.createEvent ) {
					if( window.KeyEvent ) {
					  var evObj = document.createEvent('KeyEvents');
					  evObj.initKeyEvent( 'keypress', true, true, window, false, false, false, false, 0, key.charCodeAt(0) );
					} else {
					  var evObj = document.createEvent('UIEvents');
					  evObj.initUIEvent( 'keyup', true, true, window, 1 );
					  evObj.keyCode = key.charCodeAt(0);
					}
				  	this.input.dispatchEvent(evObj);
				} else if( document.createEventObject ) {
					/*
					 * IE is broken, it will get the event, and handle it correctly, but do data is added to the field,
					 * this goes for IE7 as well. So we just quickly add the key to the field.
					 */
					this.input.value += key;
				}
				this.input.focus();
			break;
		}
	},
	
	delOneChar: function() {
		if (navigator.appVersion.match(/MSIE/)) { //by using textRanges IE will delete newlines and such as well
			var textR = this.input.createTextRange();
			textR.text = textR.text.substr(0,textR.text.length-1);
		} else {
			this.input.value = this.input.value.substr(0,this.input.value.length-1);	
		}
		
	}
}

addLoadEvent(function() { //initialize and start object
	mailer = new mailHandler();
});