// ----------------------------------------------------------------------------
// VALIDATORS
// ----------------------------------------------------------------------------
// v2.13
//
// HISTORICO:
// v2.01 - ALS@22/04/2010 - nova funcao NM_DateInterval
// v2.02 - ALS@29/04/2010 - nova funcao NM_Date3(day, month, year, message, isRequired, dateStart, dateEnd)
// v2.10 - EJR@21/05/2010 - <li></li> para colocar aspecto parecido aos validators tradicionais, 
//                          <div></div> com estilo para colocar a font a vermelho e espaçamento em baixo.
// v2.11 - ALS@26/05/2010 - alteracoes no ValidarForm() e CamposForm() para permitir identificar o form; 
//                          "myform" sera opcional.
// v2.12 - ALS@04/06/2010 - alteraçoes no estilo do validatorMessage
// v2.13 - ALS@31/08/2010 - nova funcao NM_Matricula
//
//
// REQUISITOS:
//
// 1) na página tem de existir: <script language="javascript" src="/js/validators.js"></script>
//
// 2) na página tem de existir: <div id="validatorMessage"></div>   (no caso de: showValidatorsInPage = true)
//
// 3) no Submit colocar o seguinte: onclick="return ValidarForm(); "
//
// 4) funcao a incluir em cada pagina:
//<script>
//function CamposForm(myform) {
//	showValidatorsInPage = true;
//	var msg="";
//	var rdoFields1 = ["rdoCampo1","rdoCampo2"];
//	msg += NM_ReqVal("txtNome","Nome");
//	msg += NM_Number(theField,theMessage,theLength);
//	msg += NM_Date("fieldId","message","dd-mm-aaaa");
//	msg += NM_Phone("fieldId","message");
//	msg += NM_CP("fieldId","message");
//	msg += NM_EmailVal("fieldId","Email (formato inválido)");
//	msg += NM_EmailConf("fieldId","fieldConfId","O Email de confirmação deverá ser igual ao Email");
//	msg += NM_Combo("fieldId","message");
//	msg += NM_Radio(rdoFields1,"Campo");
//	msg += NM_Radio2("fieldName","message");
//	msg += NM_DateInterval("fieldId","message","01-01-1901",""); // startDate=01-01-1901; endDate=TODAY
//	msg += NM_Matricula("txtMatricula","Matrícula - formato inválido (ex: xx-xx-xx)");
//	...
//	return msg;
//}
//</script>

var showValidatorsInPage = true;

function ValidarForm(myform) {
    var isValid = true;
    var msg = CamposForm(myform);

    if (msg.length > 0) {
        if (showValidatorsInPage) {
            //show validators in div (in the page)
            document.getElementById('validatorMessage').innerHTML = "<a name='validatorMessage'></a>";

            if (String(window.location).indexOf("#") != -1) {
                window.location = String(window.location).substring(0, String(window.location).indexOf("#")) + "#validatorMessage";
            } else {
                window.location = window.location + "#validatorMessage";
            }

            document.getElementById('validatorMessage').innerHTML = '<div style=\"color:#ff0000;font-weight:bold;\">Valide o correcto preenchimento dos seguintes campos:</div><div style=\"color:#ff0000;padding:10 0 10 0;\"><ul>' + msg + '</ul></div>';
        } else {
            //show validators in alert box
            msg = msg.replace(/<\/li>/gi, "\n");
            msg = msg.replace(/<li>/gi, "- ");
            alert('Valide o correcto preenchimento dos seguintes campos:\n' + msg);
        }

        isValid = false;
    } else {
        isValid = true;
    }

    Page_IsValid = isValid;
    Page_BlockSubmit = !Page_IsValid;

    return isValid;
}

// campos obrigatorios
function NM_ReqVal(theField, theMessage) {
    if (document.getElementById(theField).value == "") {
        return "<li>" + theMessage + "</li>"
    } else {
        return ""
    }
}

// numeros (se theLength estiver definido, tem de haver n digitos)
function NM_Number(theField, theMessage, theLength) {
    var len = theLength;
    var value = document.getElementById(theField).value;
    if (theLength == undefined) len = value.length;
    var reg = new RegExp("[0-9]{" + len + "}");

    if (value == "") return "";

    if (reg.test(value) == false) {
        return "<li>" + theMessage + "</li>";
    } else {
        return "";
    }
}

// datas (se theMask nao estiver definido assume dd-mm-aaaa)
function NM_Date(theField, theMessage, theMask) {
    var value = document.getElementById(theField).value;

    if (value == "") return "";

    if (!AUX_ValidDate(value, theMask)) {
        return "<li>" + theMessage + "</li>"
    } else {
        return ""
    }
}

// telefone (9 numeros)
function NM_Phone(theField, theMessage) {
    var value = document.getElementById(theField).value;
    var reg = /[0-9]{9}/;

    if (value == "") return "";

    if (reg.test(value) == false) {
        return "<li>" + theMessage + "</li>";
    } else {
        return "";
    }
}

// codigo postal (nnnn-nnn)
function NM_CP(theField, theMessage) {
    var value = document.getElementById(theField).value;
    var reg = /[0-9]{4}\-[0-9]{3}/;

    if (value == "") return "";

    if (reg.test(value) == false) {
        return "<li>" + theMessage + "</li>";
    } else {
        return "";
    }
}

// email valido		
function NM_EmailVal(theField, theMessage) {
    var value = document.getElementById(theField).value;
    var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;

    if (value == "") return "";

    if (reg.test(value) == false) {
        return "<li>" + theMessage + "</li>";
    } else {
        return "";
    }
}

// email de confirmacao
function NM_EmailConf(theField, theFieldConf, theMessage) {
    if (document.getElementById(theField).value != document.getElementById(theFieldConf).value) {
        return "<li>" + theMessage + "</li>"
    } else {
        return ""
    }
}

// combo
function NM_Combo(theField, theMessage) {
    if ((document.getElementById(theField).value == "0") || (document.getElementById(theField).value == "")) {
        return "<li>" + theMessage + "</li>"
    } else {
        return ""
    }
}

// validar Radio buttons
function NM_Radio(theField, theMessage) {
    var retVal = "";

    for (var i = 0; i < theField.length; i++) {
        if (document.getElementById(theField[i]).checked) retVal = "checked";
    }

    if (retVal != "checked") {
        return "<li>" + theMessage + "</li>"
    } else {
        return ""
    }
}

// validar Radio buttons
function NM_Radio2(theFieldName, theMessage) {
    var retVal = "";

    var theFieldName = document.getElementsByName(theFieldName)

    for (var i = 0; i < theFieldName.length; i++) {
        if (theFieldName[i].checked) retVal = "checked";
    }

    if (retVal != "checked") {
        return "<li>" + theMessage + "</li>"
    } else {
        return ""
    }
}

//v2.01
// validar data entre uma data de inicio e uma data de fim (se dateStart ou dateEnd forem "", assume data de hoje)
function NM_DateInterval(theField, theMessage, dateStart, dateEnd) {
    var value = document.getElementById(theField).value;

    //ignore empty field
    if (value == "") return "";

    if (!AUX_ValidDate(value, "dd-mm-aaaa")) {
        //ignore date in wrong format
        return ""
    } else {

        var date_value = AUX_ConvertToDate(value);
        var date_start = AUX_ConvertToDate(dateStart);
        var date_end = AUX_ConvertToDate(dateEnd);

        if ((date_value >= date_start) && (date_value <= date_end)){
            return ""
        } else {
            return "<li>" + theMessage + "</li>"
        }

    }
}

//v2.02
// validar data em campos separados; valida se é obrigatório; valida intervalo de datas
function NM_Date3(theDay, theMonth, theYear, theMessage, isRequired, dateStart, dateEnd) {
	if (dateStart == undefined) dateStart="";
	if (dateEnd == undefined) dateEnd="";
	
    var valDay = document.getElementById(theDay).value;
    var valMonth = document.getElementById(theMonth).value;
    var valYear = document.getElementById(theYear).value;
    
    var value = valDay + "-" + valMonth + "-" + valYear;
    
    //date is not required and the fields are empty
    if ((!isRequired) && (value == "--")) return ""; // ok

	if ((dateStart=="") && (dateEnd=="")) {
		//check if the date is valid
		if (!AUX_ValidDate(value, "dd-mm-aaaa")) return "<li>" + theMessage + "</li>"; // error (date is not valid)
		
	} else {

		if (AUX_ValidDate(value, "dd-mm-aaaa")) {
			//check if the date is inside the given range (dateStart, dateEnd)
			var date_value = AUX_ConvertToDate(value);
			var date_start = AUX_ConvertToDate(dateStart);
			var date_end = AUX_ConvertToDate(dateEnd);

			if ((date_value >= date_start) && (date_value <= date_end)){
				return ""; // ok
			} else {
				return "<li>" + theMessage + "</li>"; // error (date is out of range)
			}
		}		
	}

	return ""; // ok
}


function NM_Matricula(theField, theMessage) {

    var value = document.getElementById(theField).value;

    if (value == "") return "";

    var reg = new RegExp("[ABCDEFGHIJKLMNOPQRSTUVXZ][ABCDEFGHIJKLMNOPQRSTUVXZ]");

    var reg1 = new RegExp("[A-Z][A-Z]-[0-9][0-9]-[0-9][0-9]"); //example: AP-12-37
    var reg2 = new RegExp("[0-9][0-9]-[A-Z][A-Z]-[0-9][0-9]"); //example: 98-TX-19
    var reg3 = new RegExp("[0-9][0-9]-[0-9][0-9]-[A-Z][A-Z]"); //example: 56-44-RS

    if (reg.test(value.substr(0,2) )) { reg = reg1; }
    if (reg.test(value.substr(3,2) )) { reg = reg2; }
    if (reg.test(value.substr(6,2) )) { reg = reg3; }

    if (reg.test(value) == false) {
        return "<li>" + theMessage + "</li>";
    } else {
        return "";
    }
}

// ------------------
// funcoes auxiliares
// ------------------

// validar Data
function AUX_ValidDate(theDate, theMask) {
    var theFormat = theMask;
    if (theMask == undefined) theFormat = 'dd-mm-aaaa';

    var dtTemp, ano = '', mes = '', dia = '', dtOK = 0;
    var msg = false;
    var totalOK;

    dtTemp = theDate;
    if (dtTemp.length == 8) { totalOK = 3 } else { totalOK = 5 };

    for (i = 0; i < (dtTemp.length); i++) {
        if (dtTemp.charAt(i) == theFormat.charAt(i)) { dtOK = dtOK / 1 + 1 }
        if (theFormat.charAt(i) == 'd') { dia += dtTemp.charAt(i) }
        if (theFormat.charAt(i) == 'm') { mes += dtTemp.charAt(i) }
        if (theFormat.charAt(i) == 'a') { ano += dtTemp.charAt(i) }
    }

    if (dia.charAt(0) == '0') { diaZero = '0' } else { diaZero = '' }
    if (mes.charAt(0) == '0') { mesZero = '0' } else { mesZero = '' }

    if (dia != diaZero + parseInt(dia, 10)) { return msg } else { dia = eval(dia) };
    if (mes != mesZero + parseInt(mes, 10)) { return msg } else { mes = eval(mes) };
    if (ano != '' + parseInt(ano, 10)) { return msg } else { ano = eval(ano) };

    switch (mes) {
        case 2: if (ano % 4 == 0) { diasmes = 29 } else { diasmes = 28 }; break;
        case 4: diasmes = 30; break;
        case 6: diasmes = 30; break;
        case 9: diasmes = 30; break;
        case 11: diasmes = 30; break;
        default: diasmes = 31; break;
    };

    if ((dia > 0) && (dia <= diasmes)) { dtOK = dtOK / 1 + 1 }
    if ((mes > 0) && (mes < 13)) { dtOK = dtOK / 1 + 1 }
    if ((ano > 1800) && (ano < 9999)) { dtOK = dtOK / 1 + 1 }

    if (dtOK == totalOK) { msg = true }
    return msg;
}

function AUX_ConvertToDate(theDate) {
    // "theDate" must be in the format: dd-mm-yyyy 
    var retval = new Date();
    if (theDate != "") { retval.setFullYear(theDate.substring(6, 10), theDate.substring(3, 5) - 1, theDate.substring(0, 2)); }
    return retval;
}
