var path='/community/';//per myroom.php

// Per compatibilità con MSIE...
if ('undefined' == typeof Node)
    Node = { ELEMENT_NODE: 1, TEXT_NODE: 3 };

MSG_BLANK = ' vuoto.';
MSG_NOCHECK = 'Devi selezionare "';
MSG_NORADIO = 'Devi accettare "';
MSG_NOT_A_DATE = ' non è una data.';
MSG_NOT_A_DOUBLE = ' non è un numero.';
MSG_NOT_AN_INTEGER = ' non è un numero intero.';
MSG_NOT_AN_EMAIL = ' non corretto.';
MSG_NOT_VALID = ' non è un valore valido.';
MSG_TOO_LOW = ' è troppo piccolo.';
MSG_TOO_HIGH = ' è troppo grande.';

REGEX_AUTO_FIELD = /^[^_]+(_Req)?(_(Int|Dbl|Date|Email|Username|Password|CF)(_[0-9.]+){0,2})?$/;
REGEX_BLANK = /^\s*$/;
REGEX_DAY = /^(0?[1-9]|[1-2][0-9]|3[01])$/;
REGEX_MONTH = /^(0?[1-9]|1[0-2])$/;
REGEX_TYPED_FIELD = /_(Int|Dbl|Date|Email|Username|Password|CF)(_([0-9.]+))?(_([0-9.]+))?$/;
REGEX_YEAR = /^[0-9]{2,4}$/;


function checkFormFeedback(e) {
	Event.stop(e);
	var form= Event.element(e);
	if(form.id=="registration_form" || form.id=="forgot_form" || form.id=="confirm_form" || form.id=="account_form" || form.id=="form_email_this"){
		Element.hide(form.id+'_invia');
		Element.show(form.id+'_spinner');
	}
	risultato=checkForm(form);
	if(risultato===true){
		if(form.id=="forgot_form"){
			new Ajax.Request( path+'user_control.php',{
				method: 'get',
				parameters: $H({'action': 'forgot_password', 'email': $F('emailFP_Req_Email')}).toQueryString(),
				onComplete: function(requester){
					$('forgot_form_invia').show();
					$('forgot_form_spinner').hide();
					if(requester.responseText=='1'){
						$('forgot_form_feedback').update('Riceverai a breve un\'email da casasegafredo.it');
						$('forgot_form').hide();
					}else{
						$('forgot_form_feedback').update(requester.responseText);
					}
				}
			});
		}else if(form.id=="confirm_form"){
			new Ajax.Request( path+'user_control.php',{
				method: 'get',
				parameters: $H({'action': 'confirm_email', 'email': $F('emailCE_Req_Email')}).toQueryString(),
				onComplete: function(requester){
					$('confirm_form_invia').show();
					$('confirm_form_spinner').hide();
					if(requester.responseText=='1'){
						$('confirm_form_feedback').update('Riceverai a breve un\'email da casasegafredo.it');
						$('confirm_form').hide();
					}else{
						$('confirm_form_feedback').update(requester.responseText);
					}
				}
			});
		}else if(form.id=="form_email_this"){
			new Ajax.Request( form.getAttribute('action'), {
				method: 'post',
				parameters: $H({'recipient_email': $F('recipientEmail_Req_Email'), 'message': $F('message_Req'), 'sender_name': $F('senderName_Req'), 'sender_email': $F('senderEmail_Req_Email'), 'ccid': $F('email_this_ccid'), 'email_this': $F('email_this')}).toQueryString(),
				onComplete: function(requester){
					$('form_email_this_invia').show();
					$('form_email_this_spinner').hide();
					$('form_email_this_feedback').update(requester.responseText);
				}
			});
		}else{
			form.submit();
		}
	}else{
		$(form.id+'_feedback').show();
		$(form.id+'_feedback').update(risultato.replace(/\n/g,'<br />'));
		if(form.id=="registration_form" || form.id=="account_form"){
			location.replace('#');
		}//per farlo risalire

		if(form.id=="registration_form" || form.id=="forgot_form" || form.id=="confirm_form" || form.id=="account_form" || form.id=="form_email_this"){
			Element.show(form.id+'_invia');
			Element.hide(form.id+'_spinner');
		}
	}
}//checkFormFeedback

/*function checkForm(e) {
	Event.stop(e);
	var form= Event.element(e);*/
function checkForm(form) {
    var errors = '';
    var faulty = null;
    for (var index = 0; index < form.elements.length; ++index) {
		var field = form.elements.item(index);
        // Verifica sintassi e che il campo sia visibile
        if (!field.id.match(REGEX_AUTO_FIELD) || !Element.visible(field.id))
            continue;
        var value = $F(field);
        // Campo obbligatorio?
        if (field.id.match(/_Req/)){
			//type text
			if(field.type=="text" && value.match(REGEX_BLANK)) {
            errors += getFieldName(field) + MSG_BLANK + '\n';
            faulty = faulty || field;
            continue;
			}
			//type password
			if(field.type=="password" && value.match(REGEX_BLANK)) {
            errors += getFieldName(field) + MSG_BLANK + '\n';
            faulty = faulty || field;
            continue;
			}
			//textarea
			if(field.tagName=="textarea" || field.tagName=="TEXTAREA" && value.match(REGEX_BLANK)) {
            errors += getFieldName(field) + MSG_BLANK + '\n';
            faulty = faulty || field;
            continue;
			}
			//type checkbox
			if(field.type=="checkbox" && !field.checked) {
            errors += MSG_NOCHECK + getFieldName(field) + '".\n';
            faulty = faulty || field;
            continue;
			}
			//type radio
			if(field.type=="radio" && !field.checked) {
            errors += MSG_NORADIO + getFieldName(field) + '".\n';
            faulty = faulty || field;
            continue;
			}
        }
		// Campo tipizzato?
		var match = field.id.match(REGEX_TYPED_FIELD);
		if (match) {
			var type = match[1];
			var min = match[3];
			var max = match[5];
			var error = checkTypedField(value, type, min, max);
			if (error) {
				errors += getFieldName(field) + error + '\n';
				faulty = faulty || field;
				continue;//così altri controlli lo fa solo se non sono stati trovati errori fin qui
			}
		}
		
		//ulteriori controlli particolari a seconda del campo
		if(value){
			var error=altriControlli(field, value, form.id);
			if (error) {
				errors += getFieldName(field) + error + '\n';
				faulty = faulty || field;
			}
		}
		
	}//chiude il for

	//ultimi controlli fuori dal for
	var error=altriControlli('', '', form.id);
	if (error) {
		errors += error + '\n';
	}
	
	if (!faulty && !errors){
		//form.submit();
		return true;
	}else{
		errors='Errore:\n'+errors;
		//alert(errors);
		if(faulty){//se vengo da altriControlli potrebbe essere null
		faulty.focus();
		}
		return errors;
	}
} // checkForm

function checkTypedField(value, type, min, max) {
    // Valori predefiniti
    min = min || Number.NEGATIVE_INFINITY;
    max = max || Number.POSITIVE_INFINITY;
    var val;
    if ('Int' == type) {
		if(value){
			try {
				val = parseInt(value, 10);
			if (String(val) != value)
				throw val;
			} catch (e) {
				return MSG_NOT_AN_INTEGER;
			}
		}
    }
    if ('Dbl' == type) {
   		if(value){
			try {
				val = parseFloat(value);
			if (String(val) != value)
				throw val;
			} catch (e) {
				return MSG_NOT_A_DOUBLE;
			}
		}
    }
    if ('Int' == type || 'Dbl' == type) {
		if(value){
			if (val < min)
				return MSG_TOO_LOW;
			if (val > max)
				return MSG_TOO_HIGH;
		}
    }
    if ('Date' == type) {//formato aaaa-mm-gg
		if(value){
			var comps = value.split('-');
			if (3 != comps.length || !comps[2].match(REGEX_DAY) ||
				!comps[1].match(REGEX_MONTH) ||
				!comps[0].match(REGEX_YEAR))
				return MSG_NOT_A_DATE;
		}
    }
    if ('Email' == type) {
		if(value){
			pattern=/^[a-z0-9][_\.a-z0-9-]+@([a-z0-9][0-9a-z-]+\.)+([a-z]{2,4})$/;
			if(!pattern.exec(value)){
				return MSG_NOT_AN_EMAIL;
			}
		}
    }
    if ('Username' == type) {
		if(value){
			pattern=/^[a-zA-Z0-9_-]+$/;
			if(!pattern.exec(value) ||  value.length>15){
				return MSG_NOT_VALID;
			}
		}
    }
    if ('Password' == type) {
		if(value){
			pattern=/^[a-zA-Z0-9_.-]+$/;
			if(!pattern.exec(value) ||  value.length>15){
				return MSG_NOT_VALID;
			}
		}
    }
    if ('CF' == type) {
		if(value){
			value = value.toUpperCase();
			pattern=/^[A-Z0-9]+$/;
			set1 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
			set2 = "ABCDEFGHIJABCDEFGHIJKLMNOPQRSTUVWXYZ";
			setpari = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
			setdisp = "BAKPLCQDREVOSFTGUHMINJWZYX";
			s = 0;
			for( i = 1; i <= 13; i += 2 ){
				s += setpari.indexOf( set2.charAt( set1.indexOf( value.charAt(i) )));
			}
			for( i = 0; i <= 14; i += 2 ){
				s += setdisp.indexOf( set2.charAt( set1.indexOf( value.charAt(i) )));
			}
			if(!pattern.exec(value) ||  value.length!=16 || s%26 != value.charCodeAt(15)-'A'.charCodeAt(0)){
				return MSG_NOT_VALID;
			}
		}
    }
    return null;
} // checkTypedField

function getFieldName(field) {
    var label = getLabelFor(field);
    if (!label)
        return field.name;
    var text = '';
    var node = label.firstChild;
    // Percorso in profondità, eliminata la ricorsione, del frammento sotto l'etichetta
    while (true) {
        if (Node.ELEMENT_NODE == node.nodeType && (node.tagName=='IMG' || node.tagName=='img')){ //se è un tag img
            text += node.getAttribute('alt'); //leggo l'alt
		}else if (Node.ELEMENT_NODE == node.nodeType && node.hasChildNodes()){ //se è un tag e ha figli
            node = node.firstChild; //prendo il primo figlio
		}else if (Node.TEXT_NODE == node.nodeType){ //se è testo
            text += node.nodeValue; //prendo il testo
		}
		if (node.nextSibling){
            node = node.nextSibling;
		} else {
            node = node.parentNode;
            if (node == label)
                break;
            node = node.nextSibling;
        }
    }
    return text;
} // getFieldName

function getLabelFor(field) {
    var labels = document.getElementsByTagName('label');
    for (var index = 0; index < labels.length; ++index) {
        var label = labels.item(index);
        if (label.htmlFor == field.id)
            return label;
    }
    return null;
} // getLabelFor
