function in_array (needle, haystack, argStrict) {

	var key = '',
	strict = !! argStrict;
	
	if (strict) {
		for (key in haystack) {
			if (haystack[key] === needle) {
				return true;
			}
		}
	} else {
		for (key in haystack) {
			if (haystack[key] == needle) {
				return true;
			}
		}
	} 
	return false;
}

function is_object (mixed_var) {
	if (mixed_var instanceof Array) {
		return false;
	} else {
		return (mixed_var !== null) && (typeof(mixed_var) == 'object');
	}
}

var f = {}

f.lng = 'it';

f.messages = {
	it:{
		field:{
			name: 'Nome',
			surname: 'Cognome',
			materia: 'Docente di',
			company: 'Azienda',
			docente: 'Docente',
			alunno: 'Genitore dell\'alunno/a',
			address: 'Indirizzo',
			subject: 'Oggetto',
			room: 'Classe',
			role: 'Ruolo Aziendale',
			phone: 'Telefono',
			fax: 'Fax',
			mobile: 'Cellulare',
			'e-mail': 'E-mail',
			date: 'Data richiesta',
			time: 'Ora richiesta',
			message: 'Richiesta'
		},
		msg:{
			required: 'Il campo <span>{$}</span> &egrave; obbligatorio.',
			invalid: 'Il campo <span>{$}</span> non &egrave; valido.',
			short: 'Il campo <span>{$}</span> &egrave; troppo breve.',
			email: "Inserire una <span>{$}</span> valida.",
			date: "Inserire una <span>{$}</span> valida nel formato gg/mm/aaaa.",
			time: "Inserire un' <span>{$}</span> valida nel formato hh:mm.",
			number: "Inserire un numbero di <span>{$}</span> valido.",
			sending: ' Invio {$} in corso...'
		}
	},
	
	en:{
		field:{
			name: 'Name',
			surname: 'Surname',
			company: 'Company',
			address: 'Address',
			role: 'Role',
			phone: 'Phone',
			fax: 'Fax',
			mobile: 'Mobile',
			mail: 'E-mail',
			event: 'Event date',
			message: 'Request'
		},
		msg:{
			required: 'The field <span>{$}</span> is required.',
			invalid: 'The field <span>{$}</span> is invalid.',
			short: 'The field <span>{$}</span> is too short.',
			email: "Insert a valid <span>{$}</span>.",
			date: "Insert <span>{$}</span> in format (dd/mm/yyyy)",
			number: "Insert a valid number for the field <span>{$}</span>.",
			sending: "Sending {$} ..."
		}
	}
}

f.required = ['name', 'surname', 'e-mail', 'message'];

f.get_msg = function(input, type){
	var field = this.messages[this.lng].field[input],
		msg = this.messages[this.lng].msg[type];
	
	msg = msg.replace(/\{\$\}/g,field);

	return msg;
}

f.setNotification = function(action, timing, func){
	var act = ( is_object(action) ) ? action.act : action;
	switch(act){
		case 'hide':
			if(this.errorNode.is(':visible')){
				this.errorNode.slideUp(timing, func);
			}
		break;
		
		case 'show':
			this.errorNode.delay(timing).slideDown(timing, func);
		break;
		
		case 'html':
			this.errorNode.html(action.html);
		break;
		
		case 'append':
			$(action.html).appendTo( $(this.errorNode) );
		break;
	}
}

f.submitForm = function(form){
	
	this.setNotification('hide', 300, 
	function()
	{
		f.setNotification(obj = { act: 'html', html: '<div id="sending">' + f.get_msg('message', 'sending') + '</div>' });
		f.setNotification('show', 300);
	});
	

	$.postJSON(gecom.baseurl + "bin/ajax.php?action=" + this.action, form, function (j){
		setTimeout(function(){
			$.each(j, function(i, res){
				if(res.status == 'ok'){
					f.setNotification('hide', 300, 
					function()
					{
						f.setNotification(obj = { act: 'html', html: '<div class="success">' + res.msg + '</div>' });
						
						$.fancybox('<div class="success">' + res.msg + '<br /><b>Risponderemo a breve!</b></div>');
						
						setTimeout(function(){
							$.fancybox.close();
						},5000);
						
						f.setNotification('show', 300);
						document.getElementById("submit").disabled = false;
					});
				}else{
					f.setNotification('hide', 300,
					function()
					{
						if(res.msg.indexOf('#') != -1){
							var server_errors = res.msg.split('#');
							f.setNotification(obj = { act: 'html', html: '' });
							for(var i = 0 in server_errors){
								obj = {
									act: 'append',
									html: '<div class="error">' + server_errors[i] + '</div>'
								};
								f.setNotification(obj);
							}
						}else{
							f.setNotification(obj = { act: 'html', html: '<div class="error">' + res.msg + '</div>' });
						}
						
						f.setNotification('show', 300);
						document.getElementById("submit").disabled = false;
					});
				}
			});
		},2500);
	});
}
	
f.validateInput = function(input){
	var e;
	
	switch(input.name){
		case 'name':
		case 'surname':
		case 'materia':
		case 'subject':
		case 'alunno':
		case 'docente':
			if ( ( in_array(input.name, this.required) ) && !input.value.length ){
				e = this.get_msg(input.name, 'required');
			}else
			if( input.value.length < 2 ){
				e = this.get_msg(input.name, 'short');
			}else
			if ( (!input.value.match(/^[A-Za-z\u00C0-\u00F6\u00F8-\u00FF ']{2,}$/)) ) {  
				e = this.get_msg(input.name, 'invalid');
			} else {
				e = 'OK';
			}
		break;

		case 'company':
		case 'address':
		case 'room':
			if ( ( in_array(input.name, this.required) ) && !input.value.length ){
				e = this.get_msg(input.name, 'required');
			}else
			if ( input.value.length < 2 ){
				e = this.get_msg(input.name, 'short' );
			}else
			if(!input.value.match(/^[A-Za-z0-9\u00C0-\u00F6\u00F8-\u00FF '.&]{2,}$/) ) {  
				e = this.get_msg(input.name, 'invalid');
			} else {
				e = 'OK';
			}
		break;

		case 'role':
			if ( ( in_array(input.name, this.required) ) && !input.value.length ){
				e = this.get_msg(input.name, 'required');
			}else
			if ( input.value.length < 1){
				e = this.get_msg(input.name, 'short' );
			}else
			if(!input.value.match(/^[A-Za-z\u00C0-\u00F6\u00F8-\u00FF '.&]{1,}$/) ) {  
				e = this.get_msg('role', 'invalid');
			} else {
				e = 'OK';
			}
		break;
					
		case 'phone':
		case 'fax':
		case 'mobile':
			if ( ( in_array(input.name, this.required) ) && !input.value.length ){
				e = this.get_msg(input.name, 'required');
			}else
			if ( input.value.length < 4){
				e = this.get_msg(input.name, 'short' );
			}else
			if(!input.value.match(/^[0-9]+$/) ) {
				e = this.get_msg(input.name, 'number');
			} else {
				e = 'OK';
			}
		break;
		
		case 'e-mail':
			if ( ( in_array(input.name, this.required) ) && !input.value.length ){
				e = this.get_msg(input.name, 'required');
			}else
			if ( input.value.length < 6){
				e = this.get_msg(input.name, 'email' );
			}else
			if(!input.value.match(/^([a-z0-9._\-]+@[a-z0-9._\-]+\.[a-z]{2,4}$)/i) ) {
				e = this.get_msg(input.name, 'email');
			} else {
				e = 'OK';
			}
		break;
		
		case 'date':
			if ( ( in_array(input.name, this.required) ) && !input.value.length ){
				e = this.get_msg(input.name, 'required');
			}else
			if ( input.value.length < 8){
				e = this.get_msg(input.name, 'short' );
			}else
			if(!input.value.match(/^\d{1,2}[\/-]\d{1,2}[\/-]\d{4}$/) ) {
				e = this.get_msg(input.name, 'date');
			} else {
				e = 'OK';
			}
		break;
		
		case 'time':
			if ( ( in_array(input.name, this.required) ) && !input.value.length ){
				e = this.get_msg(input.name, 'required');
			}else
			if ( input.value.length < 5){
				e = this.get_msg(input.name, 'short' );
			}else
			if(!input.value.match(/^\d{1,2}:\d{2}$/) ) {
				e = this.get_msg(input.name, 'time');
			} else {
				e = 'OK';
			}
		break;
		
		case 'message':
			if ( ( in_array(input.name, this.required) ) && !input.value.length ){
				e = this.get_msg(input.name, 'required');
			}else
			if ( input.value.length < 6 ) {
				e = this.get_msg(input.name, 'short' );
			} else {
				e = 'OK';
			}
		break;
		
		default:
			e = 'Errore imprevisto! Contattare l\'amministratore grazie.';
		break;
	}
	
	return e;
}

f.validateForm = function(form, act, req){
	document.getElementById("submit").disabled = true;

	if(act){
		this.action = act;
	}else{
		this.action = 'send';
	}

	if(req){
	
		for(var i = 0; i < (req.length); i++){
			if(!in_array(req[i], this.required)){
				this.required.push(req[i]);
			}
		}
	
	}

	var err = [],
		m = '',
		array = [];
		
	for(var i = 0; i < (form.length); i++){
		if(form[i].name === 'language'){
			this.lng = form[i].value;
			form.splice(i, 1);
		}
	}

	for(var i = 0; i < (form.length); i++){
		if ( (in_array(form[i].name, this.required)) || (form[i].value.length >= 1) ){
			array.push(form[i]);
			
			m = this.validateInput(form[i]);
			if( m != 'OK' ){
				err.push(m);
			}
		}
	}
	

	if( err.length === 0){
		form.push({name: 'language', value: this.lng});
		
		this.submitForm(form);
		
	}else{
		this.setNotification('hide', 300,
		function()
		{
			f.setNotification(obj = { act: 'html', html: '' });
			
			for(var i = 0;i < err.length; i++){
				obj = {
					act: 'append',
					html: '<div class="error">' + err[i] + '</div>'
				};
				f.setNotification(obj);
			}
			f.setNotification('show', 300,
			function()
			{
				document.getElementById("submit").disabled = false;
			});
		});
	}
}

$(function(){
	f.errorNode = $('#form_errors');
});
