/*---------------------------------------------------------------------------------
validate User Funcs
----------------------------------------------------------------------------------*/

function ValidateFields() {

        var valid_form = true;
        var error='';

        error = UserAndPasswordValidator() + PasswordsAreEqual() + check_passwords() + username() + telefone() +  BirthDate() +
                EmailsAreFilled() +  InteressesOutroValido() + TomouConhecimentoOutroValido() + TomouConhecimentoPeloBanco()+
                CheckRegisteredRadio() + NIFValido() + ConcordoChecked();

        
        if (error != ''){
                window.alert (error);
                valid_form = false;
        }

        return valid_form;

}

function isSeleccionadoRadio(radioobject) {
        if (typeof(radioobject.length)=="undefined")
                return radioobject.checked;

        for (var i = 0; i < radioobject.length; i++) {
                if (radioobject[i].checked)
                        return true;
        }

        return false;
}

function check_passwords ()	{
        window_alert='';

        if (document.InputRegistrationForm.secretQuestion.value=="") {
                window_alert += ('\n    Por favor introduza a pergunta secreta.');
        }
        if (document.InputRegistrationForm.secretAnswer.value=="") {
                window_alert += ('\n    Por favor introduza a resposta à pergunta secreta.');
        }

        return window_alert;
}

//		function check_checkbox(flag) {
//		if (flag==1) {
//		if (document.InputRegistrationForm.text_interesses_outro.value != "") {
//		document.InputRegistrationForm.check_interesses_outro.checked=true;
//		}
//		}
//		if (flag==2) {
//		if (document.InputRegistrationForm.text_tomou_conhecimento_outro.value != "") {
//		document.InputRegistrationForm.check_tomou_conhecimento_outro.checked=true;
//		}
//		}
//		}

function deleteInput(flag) {	
        if (flag==1) {
//				document.InputRegistrationForm.select_funcao_empresa.disabled = false;
                document.InputRegistrationForm.isCompanyRegistred.disabled = false;								
                document.InputRegistrationForm.companyNIF.disabled = false;
                document.InputRegistrationForm.companyID.disabled = false;
                document.InputRegistrationForm.personNIF.disabled = true;
                return;
        }
        if (flag==2) {
                document.InputRegistrationForm.registrationType[0].checked = true;
                document.InputRegistrationForm.companyNIF.disabled = false;			
                document.InputRegistrationForm.companyID.disabled = true;
                document.InputRegistrationForm.personNIF.disabled = true;
                return;
        }
        if (flag==3) {
                document.InputRegistrationForm.registrationType[0].checked = true;			
                document.InputRegistrationForm.companyNIF.disabled = true;		
                document.InputRegistrationForm.companyID.disabled = false;
                document.InputRegistrationForm.personNIF.disabled = true;
                return;
        }
        if (flag==4) {
                document.InputRegistrationForm.registrationType[1].checked = true;
                document.InputRegistrationForm.personNIF.disabled = false;
                document.InputRegistrationForm.isCompanyRegistred.disabled = true;				
//				document.InputRegistrationForm.select_funcao_empresa.disabled = true;
                document.InputRegistrationForm.companyNIF.disabled = true;
                document.InputRegistrationForm.companyID.disabled = true;
                return;
        }
}						

function username() {
        if (document.InputRegistrationForm.name.value.length <= 1) {
                return ('\n    Por favor introduza o nome.');
        }

        return '';
}

function telefone() {
        if (document.InputRegistrationForm.telephone.value.length <= 1) {
                return ('\n    Por favor introduza o telefone.');
        }

        return '';
}

function BirthDate() {

        var window_alert='';

        if (document.InputRegistrationForm.birthDay.selectedIndex == 0) {
                window_alert += ('\n    Por favor introduza o dia de nascimento.');
        }
        if (document.InputRegistrationForm.birthMonth.selectedIndex == 0) {
                window_alert += ('\n    Por favor introduza o mês de nascimento.');
        }
        if (document.InputRegistrationForm.birthYear.selectedIndex == 0 || document.InputRegistrationForm.birthYear.value == "9999") {
                window_alert += ('\n    Por favor introduza o ano de nascimento.');
        }

        return window_alert;
}

function UserAndPasswordValidator() {
        window_alert='';

        if (document.InputRegistrationForm.username.value.length < 6 
        || document.InputRegistrationForm.username.value.length > 30) {
                window_alert += ('\n    O username tem de ter no minimo 6 caracteres e no máximo 30.');
        } else {
                var invalidchars = ",; ";
                var charindex;

                usernamestring = document.InputRegistrationForm.username.value;

                for(charindex = 0; charindex < invalidchars.length; charindex ++) {
                        var currchar = invalidchars.charAt(charindex);

                        if(usernamestring.indexOf(currchar) != -1) {
                                window_alert += ('\n   O username contém caracteres inválidos.');
                                valid_form = false;
                                break;
                        }
                }
        }
        if (document.InputRegistrationForm.password.value.length < 6 
        || document.InputRegistrationForm.password.value.length > 30) {
                window_alert += ('\n    A sua password tem de ter no minimo 6 caracteres e no máximo 30.');
        }

        return window_alert;
}

function NIFValido() {
        if (document.InputRegistrationForm.registrationType[0].checked == true 
        && document.InputRegistrationForm.isCompanyRegistred[0].checked == true 
        && document.InputRegistrationForm.companyNIF.value.length != 9) {
                return '\n    O nº de contribuinte da empresa tem de ter 9 dígitos de comprimento.';
        }
        if (document.InputRegistrationForm.registrationType[0].checked == true 
        && document.InputRegistrationForm.isCompanyRegistred[0].checked == true 
        && !isPositiveInteger(document.InputRegistrationForm.companyNIF.value)) {
                return '\n    Número de contribuinte da empresa inválido.';
        }
        if (document.InputRegistrationForm.registrationType[0].checked == true 
        && document.InputRegistrationForm.isCompanyRegistred[0].checked == true 
        && document.InputRegistrationForm.companyNIF.value < 500000000) {
                return '\n    Número de contribuinte da empresa inválido.';
        }

        return '';
}			

function CheckRegisteredRadio() {
        var returnMsg = '';

        if (!isSeleccionadoRadio(document.InputRegistrationForm.registrationType)) {
                returnMsg += '\n    Por favor indique o tipo de registo.';
        } else {
                if (document.InputRegistrationForm.registrationType[0].checked == true) {
//					if (document.InputRegistrationForm.select_funcao_empresa.value == "") {
//						returnMsg += '\n    Por favor indique a sua função na empresa.';
//					}
                        if (document.InputRegistrationForm.isCompanyRegistred[0].checked == true 
                        && document.InputRegistrationForm.companyNIF.value == "") {
                                returnMsg += '\n    Por favor introduza o nº de contribuinte da empresa.';											
                        }
                        if (document.InputRegistrationForm.isCompanyRegistred[1].checked == true 
                        && document.InputRegistrationForm.companyID.value == "") {
                                returnMsg += '\n    Por favor introduza a chave de identificação da empresa.';						
                        }				
                }
                if (document.InputRegistrationForm.registrationType[1].checked == true 
                && document.InputRegistrationForm.personNIF.value.length != 9) {
                        returnMsg += '\n    O nº de contribuinte individual tem de ter 9 dígitos de comprimento.';					
                } else {
                        if (document.InputRegistrationForm.registrationType[1].checked == true 
                        && (!isPositiveInteger(document.InputRegistrationForm.personNIF.value) 
                        || document.InputRegistrationForm.personNIF.value >= 500000000)) {
                                returnMsg += '\n    Número de contribuinte individual inválido.';
                        }
                }
        }							

        return returnMsg;
}

function ConcordoChecked() {
        if (document.InputRegistrationForm.agreeWithTerms.checked != true) {
                return '\n    Para prosseguir, tem de concordar com as condições de utilização.';
        }

        return '';
}

function InteressesOutroValido() {
//			if (document.InputRegistrationForm.check_interesses_outro.checked == true &&
//				document.InputRegistrationForm.text_interesses_outro.value == "") {
//				return '\n    Por favor especifique a área de interesse adicional.';
//			}

        return '';
}

function TomouConhecimentoOutroValido() {
//			if (document.InputRegistrationForm.check_tomou_conhecimento_outro.checked == true &&
//				document.InputRegistrationForm.text_tomou_conhecimento_outro.value == "") {
//				return ('\n    Por favor especifique a fonte de informação adicional.');					
//			}

        return '';
}

function TomouConhecimentoPeloBanco() {
        if (!isSeleccionadoRadio(document.InputRegistrationForm.sourceOfAwareness)) {
                return '\n    Por favor especifique o Banco através do qual tomou conhecimento do pmelink.pt.';
        }

        return '';
}

function PasswordsAreEqual() {
        if (document.InputRegistrationForm.password.value !=  document.InputRegistrationForm.passwordRepeat.value) {
                return '\n    A Password e a Password de confirmação não coincidem.';
        }

        return '';
}

function trim(strText, char1) {
        // this will get rid of leading spaces 
        while (strText.substring(0,1) == char1) 
                strText = strText.substring(1, strText.length);

        // this will get rid of trailing spaces 
        while (strText.substring(strText.length-1,strText.length) == char1)
                strText = strText.substring(0, strText.length-1);

        return strText;
}

function EmailsAreFilled() {
        //fazer trim aso espacos antes da validacao
        document.InputRegistrationForm.emailUser.value = trim(document.InputRegistrationForm.emailUser.value, ' ');
        document.InputRegistrationForm.emailServer.value = trim(document.InputRegistrationForm.emailServer.value, ' ');

        if (document.InputRegistrationForm.emailUser.value == "" 
        && document.InputRegistrationForm.emailServer.value == "") {
                return '\n    O Endereço de e-mail é obrigatório.';
        }
        if ((document.InputRegistrationForm.emailUser.value.length + document.InputRegistrationForm.emailServer.value.length) > 49) {
                return '\n    O campo email é demasiado longo.';
        }
        if (document.InputRegistrationForm.emailUser.value == "" 
        || document.InputRegistrationForm.emailServer.value == "" 
        || document.InputRegistrationForm.emailUser.value.indexOf("@") != -1 
        || document.InputRegistrationForm.emailServer.value.indexOf("@") != -1) {
                return '\n   O campo email contém um erro. Verifique, por favor, o endereço de email.';
        }
        if (document.InputRegistrationForm.emailUser.value.indexOf(" ")!=-1 
        || document.InputRegistrationForm.emailServer.value.indexOf(" ")!=-1){
                return '\n    O campo email contém um erro. Verifique, por favor, o endereço de email.';
        }
        if (document.InputRegistrationForm.emailServer.value.indexOf(".")==-1){
                return '\n    O campo email contém um erro. Verifique, por favor, o endereço de email.';
        }
        if (document.InputRegistrationForm.emailServer.value.length < 5){
                return '\n    O campo email contém um erro. Verifique, por favor, o endereço de email.';
        }

        var regex = /[^a-zA-Z0-9._-]/;
        if (regex.test(document.InputRegistrationForm.emailUser.value) 
        || regex.test(document.InputRegistrationForm.emailServer.value)) {
                return '\n    O campo email contém um erro. Verifique, por favor, o endereço de email.';
        }

        return '';
}


function InputRegistrationForm_com_bes_additional_code_post() 
{
        return ValidateFields();
}


function InputRegistrationForm_com_bes_check_all_fields() {
        var invalid_fields = '';
        var valid_form = true;

        if(! InputRegistrationForm_com_bes_additional_code_post()) {
                return false;
        }
        if(!isSpecialAlphanumeric(document.forms.InputRegistrationForm.username.value)) {
                invalid_fields += ('\n    ' + 'Valor inválido em Utilizador: ' + document.forms.InputRegistrationForm.username.value);
                valid_form = false;
        }if(!isSpecialAlphanumeric(document.forms.InputRegistrationForm.password.value)) {
                invalid_fields += ('\n    ' + 'Valor inválido em Password ou repetição: ' + document.forms.InputRegistrationForm.password.value);
                valid_form = false;
        }if(!isSpecialAlphanumeric(document.forms.InputRegistrationForm.passwordRepeat.value)) {
                invalid_fields += ('\n    ' + 'Valor inválido em Password ou repetição: ' + document.forms.InputRegistrationForm.passwordRepeat.value);
                valid_form = false;
        }if(!isString(document.forms.InputRegistrationForm.secretQuestion.value)) {
                invalid_fields += ('\n    ' + 'Valor inválido em Pergunta Secreta: ' + document.forms.InputRegistrationForm.secretQuestion.value);
                valid_form = false;
        }if(!isString(document.forms.InputRegistrationForm.secretAnswer.value)) {
                invalid_fields += ('\n    ' + 'Valor inválido em Resposta à Pergunta Secreta: ' + document.forms.InputRegistrationForm.secretAnswer.value);
                valid_form = false;
        }if(!isString(document.forms.InputRegistrationForm.title.value, true)) {
                invalid_fields += ('\n    ' + 'Valor inválido em Tíulo: ' + document.forms.InputRegistrationForm.title.value);
                valid_form = false;
        }if(!isString(document.forms.InputRegistrationForm.name.value)) {
                invalid_fields += ('\n    ' + 'Valor inválido em Nome: ' + document.forms.InputRegistrationForm.name.value);
                valid_form = false;
        }if(!isString(document.forms.InputRegistrationForm.birthDay.value)) {
                invalid_fields += ('\n    ' + 'Valor inválido em Data nascimento - dia: ' + document.forms.InputRegistrationForm.birthDay.value);
                valid_form = false;
        }if(!isString(document.forms.InputRegistrationForm.birthMonth.value)) {
                invalid_fields += ('\n    ' + 'Valor inválido em Data nascimento - mês: ' + document.forms.InputRegistrationForm.birthMonth.value);
                valid_form = false;
        }if(!isPositiveInteger(document.forms.InputRegistrationForm.birthYear.value)) {
                invalid_fields += ('\n    ' + 'Valor inválido em Data nascimento - ano: ' + document.forms.InputRegistrationForm.birthYear.value);
                valid_form = false;
        }if(!isPortuguesePhoneNumber(document.forms.InputRegistrationForm.telephone.value)) {
                invalid_fields += ('\n    ' + 'Valor inválido em Telefone para contacto: ' + document.forms.InputRegistrationForm.telephone.value);
                valid_form = false;
        }if(!isPortuguesePhoneNumber(document.forms.InputRegistrationForm.fax.value, true)) {
                invalid_fields += ('\n    ' + 'Valor inválido em Fax: ' + document.forms.InputRegistrationForm.fax.value);
                valid_form = false;
        }if(!isSpecialAlphanumericEmail(document.forms.InputRegistrationForm.emailUser.value)) {
                invalid_fields += ('\n    ' + 'Valor inválido em Utilizador email: ' + document.forms.InputRegistrationForm.emailUser.value);
                valid_form = false;
        }if(!isSpecialAlphanumericEmail(document.forms.InputRegistrationForm.emailServer.value)) {
                invalid_fields += ('\n    ' + 'Valor inválido em Servidor email: ' + document.forms.InputRegistrationForm.emailServer.value);
                valid_form = false;
        }
        if (! valid_form) {
                alert('Foram encontrados alguns campos inválidos: ' + invalid_fields);
        }
        return valid_form
} 

function disableSubmit (form) { 
        for (var i = 0; i < form.elements.length; i++) 
                if (form.elements[i].type.toLowerCase() == 'submit') 
                        form.elements[i].disabled = true; 
}				  	  
	
function InputRegistrationForm_submit() {

        if(InputRegistrationForm_com_bes_check_all_fields()) {
                if (document.forms.InputRegistrationForm.submitted) {
                        return false;
                } else {
                        document.forms.InputRegistrationForm.submitted=true;
                        disableSubmit(document.forms.InputRegistrationForm);
                }			
                document.forms.InputRegistrationForm.submit();
        } else {
                document.forms.InputRegistrationForm.submitted=false;
        }
        return false;
}
