/*-------------------------------------*/
// VALIDATION FORM 	1.1 /
//                                    	/
// Creato Marco Pastorello 2008      	/
//                                    	/
// marco.pastorello@as3.it									  	/
//                                    	/
// Last revision: 23/07/08              /
/*-------------------------------------*/

/* parte da aggiungere alla pagina nel BODY:
 <!-- VALIDATION FORM START -->
 <script type="text/javascript" src="../../js/prototype.js"></script>
 <script type="text/javascript" src="../../js/error_messages_ita.js"></script>
 <script type="text/javascript" src="../../js/validation_form.js"></script>
 <!-- VALIDATION FORM END -->
 */
var flgErrPag;
var elementiMancanti = new Array();





function obbligatori(target){
    if (target == '') {
        target = 0;
    }
    var theForm = $(target);
    var field;
    var elements = theForm.getElements();
    var result = false;
    m = 0;
    for (i = 0; i < elements.length; i++) {
        field = elements[i];
        var classes = field.classNames().inspect()
        
        if (field.value == "" && classes.include('req')) {
            //				eval("document.forms['"+target+"']."+aCampi[i]+".select()");	
            if (field.alt != null) {
                elementiMancanti[m] = field.alt;
            }
            else 
                if (field.title != null) {
                    elementiMancanti[m] = field.title;
                }
                else {
                    elementiMancanti[m] = field.name;
                }
            
            
            m++;
        }
    }
    if (m == 0) 
        result = true;
    return result;
    
}


function correggiForm(target){
    var myForm = $(target.id);
    //Disable Privacy field
    Form.Element.disable($(myForm['legge_privacy']));
    var myInputName = $(document.createElement('input'))
    var myInputAlt = $(document.createElement('input'))
    var myInputValue = $(document.createElement('input'))
    myInputName.setAttribute('type', 'hidden');
    myInputAlt.setAttribute('type', 'hidden');
    myInputValue.setAttribute('type', 'hidden');
    
    $(myInputName).name = "nome_campi";
    $(myInputAlt).name = "alt_campi";
    $(myInputValue).name = "value_campi";
    var fChildren = myForm.getElements();
    //da modificareeee
    
    for (var i = 0; i < fChildren.length; i++) {
    
    
        //disattivo i campi hide
        if (Element.hasClassName($(fChildren[i]), 'hide')) {
            Form.Element.disable($(fChildren[i]));
        }
        
        //preparo le tre variabili che contengono nomi valori e alt
        if ($(fChildren[i]).type != 'button' && $(fChildren[i]).type != 'reset' && $(fChildren[i]).type != 'submit' && $(fChildren[i]).name != 'legge_privacy' && !Element.hasClassName($(fChildren[i]), 'hide')) {
            try {
                //Preparo gli Alt
                if ($(fChildren[i]).getAttribute('alt') != null) {
                    $(myInputAlt).value = $(myInputAlt).value + $(fChildren[i]).getAttribute('alt') + "-";
                }
                else 
                    if ($(fChildren[i]).getAttribute('title') != null) {
                        $(myInputAlt).value = $(myInputAlt).value + $(fChildren[i]).getAttribute('title') + "-";
                    }
                    else {
                        $(myInputAlt).value = $(myInputAlt).value + $(fChildren[i]).getAttribute('name') + "-";
                    }
                //Preparo i name
                if ($(fChildren[i]).getAttribute('name') != null) {
                    $(myInputName).value = $(myInputName).value + $(fChildren[i]).getAttribute('name') + "-";
                }
                
                //Preparo il value
                if ($(fChildren[i]).name == "nazione") {
                    //trasformo i numeri delle nazioni in valori ATTENZIONE IL CAMPO SI DEVE CHIAMARE NAZIONE
                    $(myInputValue).value = $(myInputValue).value + ARRAY_NAZIONI[$(fChildren[i]).value] + "-";
                }
                else {
                
                    $(myInputValue).value = $(myInputValue).value + $(fChildren[i]).value + "-";
                }
            } 
            catch (e) {
                alert("CorreggiForm:" + e.message);
            }
            
            
            
        }
    }
    
    //**************
    // alert($(myInputName).value)
    // alert($(myInputAlt).value)
    // alert($(myInputValue).value)
    myForm.appendChild(myInputName);
    myForm.appendChild(myInputAlt);
    myForm.appendChild(myInputValue);
    
    
    return myForm;
}


function invia_ctrl(target){
    if (target == '') {
        target = 0;
    }
    var errorMsg = MSG.errorAlert;
    if (obbligatori(target) && !flgErrPag) {
    
        correggiForm(document.forms[target]).submit()
        //correggiForm(document.forms[target]);
    }
    else {
        for (var i = 0; i < elementiMancanti.length; i++) {
            errorMsg += MSG.theField + "'" + elementiMancanti[i] + "'" + MSG.isRequired + "\n";
        }
        alert(errorMsg);
    }
    
}

/*********************************************************/




//========================================================
//========== General scripts ============================
//========================================================





function setFieldsToUpperCase(thisObj, thisEvent){
    var key = thisEvent.keyCode;
    if ((key != 37) && (key != 39) && (key != 8) && (key != 46)) {
        var y = thisObj.value;
        thisObj.value = y.toUpperCase();
    }
}


function padLength(val, len){
    val = "" + val;
    while (val.length < len) {
        val = "0" + val;
    }
    return val;
}

function editKeyBoard(evt, objKeyb){
    /*	Function:		editKeyBoard
     Creation Date:	October 11, 2001
     Programmer:		Edmond Woychowsky
     Purpose:		The purpose of this function is to edit edit keyboard input
     to determine if the keystrokes are valid.
     
     Update Date:		Programmer:			Description:
     */
    try {
        
		var objForm = Event.element(evt);
		var keyCode = evt.keyCode ? evt.keyCode : evt.which ? evt.which : evt.charCode;
        if (window.event) {
            evt = window.event;
        }
       //log
	   // alert(objForm.name+evt.type+keyCode)
        
		strWork = objKeyb.getValid();
        strMsg = ''; // Error message
        blnValidChar = false; // Valid character flag
        
			
		// Part 1: Validate input
        if (!blnValidChar) {
			
            for (i = 0; i < strWork.length; i++) {
	
				if (keyCode == strWork.charCodeAt(i)) {
					blnValidChar = true;
	//				alert("Ok");
					return true;
				}
				
			}
        // Part 2: Build error message

            if (objKeyb.getMessage().toString().length != 0 ) {
				//alert('Error: ' + objKeyb.getMessage());
//						alert("KO"+window.event);
				// Clear invalid character
				if (window.event) {
					evt.returnValue = false;
				//e.cancelBubble = true;
				}
				if (evt.preventDefault) {
					//alert("KO-Firefox");
				 evt.preventDefault();
				//e.stopPropagation();
				}
				objForm.focus(); // Set focus
			 return false;	
			}
            
           
        }
        
    } 
    catch (e) {
        alert(e.message);
    }
    
}




function keybEdit(strValid, strMsg){
    /*	Function:		keybEdit
     Creation Date:	October 11, 2001
     Programmer:		Edmond Woychowsky
     Purpose:		The purpose of this function is to be a constructor for
     the keybEdit object.  keybEdit objects are used by the
     function editKeyBoard to determine which keystrokes are
     valid for form objects.  In addition, if an error occurs,
     they provide the error message.
     
     Please note that the strValid is converted to both
     upper and lower case by this constructor.  Also, that
     the error message is prefixed with 'Error:'.
     
     The properties for this object are the following:
     valid	=	Valid input characters
     message	=	Error message
     
     The methods for this object are the following:
     getValid()	=	Returns a string containing valid
     characters.
     getMessage()=	Returns a string containing the
     error message.
     Update Date:	Programmer:			Description:
     */
    //	Variables
    var reWork = new RegExp('[a-z]', 'gi'); //	Regular expression\
    //	Properties
    if (reWork.test(strValid)) 
        this.valid = strValid.toLowerCase() + strValid.toUpperCase();
    else 
        this.valid = strValid;
    
    if ((strMsg == null) || (typeof(strMsg) == 'undefined')) 
        this.message = '';
    else 
        this.message = strMsg;
    
    //	Methods
    this.getValid = keybEditGetValid;
    this.getMessage = keybEditGetMessage;
    
    function keybEditGetValid(){
        /*	Function:		keybEdit
         Creation Date:	October 11, 2001
         Programmer:		Edmond Woychowsky
         Purpose:		The purpose of this function act as the getValid method
         for the keybEdit object.  Please note that most of the
         following logic is for handling numeric keypad input.
         Update Date:		Programmer:			Description:
         */
        return this.valid.toString();
    }
    
    function keybEditGetMessage(){
        /*	Function:		keybEdit
         Creation Date:	October 11, 2001
         Programmer:		Edmond Woychowsky
         Purpose:		The purpose of this function act as the getMessage method
         for the keybEdit object.
         Update Date:	Programmer:			Description:
         */
        return this.message;
    }
}








function trim(StringToTrim){
    if (typeof(StringToTrim) != "string") {
        return StringToTrim;
    }
    var StringBlank = StringToTrim.substring(0, 1);
    while (StringBlank == " ") {
        StringToTrim = StringToTrim.substring(1, StringToTrim.length);
        StringBlank = StringToTrim.substring(0, 1);
    }
    StringBlank = StringToTrim.substring(StringToTrim.length - 1, StringToTrim.length);
    while (StringBlank == " ") {
        StringToTrim = StringToTrim.substring(0, StringToTrim.length - 1);
        StringBlank = StringToTrim.substring(StringToTrim.length - 1, StringToTrim.length);
    }
    return StringToTrim;
}



function impostaFuoco(id){
    document.$(id).focus();
    return;
}



function vemail(campo){

    if (flgErrPag && (cmpErr != campo)) {
        return;
    }
    var valore = $(campo).value;//eval(campo+'.value');
    if (valore == "") {
        flgErrPag = false;
        cmpErr = '';
        return '';
    }
    var_email = trim(valore);
    if (var_email.length != valore.length) {
        cmpErr = campo;
        flgErrPag = true;
        alert(MSG.spaceNotValidValue);
        $(campo).focus();
    }
    else {
        //verifico validit� indirizzo
        pos = var_email.indexOf("@");
        if (pos > 0) {
            if (var_email.substr(pos + 1).indexOf(".") < 0) {
                cmpErr = campo;
                flgErrPag = true;
                alert(MSG.emailNotValid);
                $(campo).focus();
            }
            else {
                flgErrPag = false;
                cmpErr = '';
            }
        }
        else {
            cmpErr = campo;
            flgErrPag = true;
            alert(MSG.emailNotValid);
            $(campo).focus();
        }
    }
}




function vint(campo){
    //esce subito se c'e' gia' un'errore in pagina
    if (flgErrPag && (cmpErr != campo)) 
        return;
    var valore = eval(campo + '.value');
    if (valore.search('[^0-9]') != -1 && valore != "") {
        cmpErr = campo;
        flgErrPag = true;
        eval(campo + ".select()");
        alert(MSG.notValidValue);
    }
    else {
        eval(campo + ".value='" + valore + "'");
        cmpErr = '';
        flgErrPag = false;
    }
}


function vintr(campo, range){
    //esce subito se c'� gi� un'errore in pagina
    if (flgErrPag && (cmpErr != campo)) 
        return;
    var valore = eval(campo + '.value');
    if (valore.search('[^0-9]') != -1 && valore != "") {
        cmpErr = campo;
        flgErrPag = true;
        eval(campo + ".select()");
        alert(MSG.notValidValue);
    }
    else {
        var lb = 0, ub = 0;
        lb = parseInt(range.substr(0, range.indexOf(":")));
        ub = parseInt(range.substr(range.indexOf(":") + 1));
        if ((parseInt(valore) < lb) || (parseInt(valore) > ub)) {
            cmpErr = campo;
            flgErrPag = true;
            eval(campo + ".select()");
            alert(MSG.notValidValue);
        }
        else {
            eval(campo + ".value='" + valore + "'");
            cmpErr = '';
            flgErrPag = false;
        }
    }
}


function verificaLunghezza(thisObj, eventObj, size){
    var oggetto = thisObj.value;
    var lunghezza = oggetto.length;
    var ch = eventObj.keyCode;
    
    if (lunghezza >= size) {
        ch = "";
        alert("Raggiunta lunghezza massima consentita di " + size + " caratteri.");
        return false;
    }
}

var keybYN = new keybEdit('yn', MSG.notValidValue + 'Es.: \'Y\' or \'N\'.');
var keybNumeric = new keybEdit('01234567890., -°', MSG.notValidValue + ':Numeric input only.');
var keybNumericOnly = new keybEdit('01234567890', MSG.notValidValue + ':Numeric input only.');
var keybAlpha = new keybEdit("abcdefghijklmnopqurstuvwxyABCDEFGHILMNOPQRSTUVWZXYJK_+.,;:()/\\\"%&* -°'", MSG.notValidValue + ':Alpha input only.');
var keybAlphaOnly = new keybEdit("abcdefghijklmnopqurstuvwxy ", MSG.notValidValue + ':Alpha input only.');
var keybAlphaNumeric = new keybEdit("abcdefghijklmnopqurstuvwxy01234567890 ., -°'", MSG.notValidValue + ':Alpha-numeric input only.');
var keybAlphaNumericOnly = new keybEdit("abcdefghijklmnopqurstuvwxy01234567890 ", MSG.notValidValue + ':Alpha-numeric input only.');
var keybDecimal = new keybEdit('01234567890,.', MSG.notValidValue + ':Decimal input only.');
var keybDate = new keybEdit('01234567890/', MSG.notValidValue + ':Date input only');
;


