
// Copyright © 2001 by Apple Computer, Inc., All Rights Reserved.
//
// You may incorporate this Apple sample code into your own code
// without restriction. This Apple sample code has been provided "AS IS"
// and the responsibility for its operation is yours. You may redistribute
// this code, but you are not permitted to redistribute it as
// "Apple sample code" after having made changes.

// Other Examples
/*    why += checkPhone(theForm.phone.value);
    why += checkPassword(theForm.password.value);
    why += checkUsername(theForm.username.value);
    why += isEmpty(theForm.password.value, theForm.passwordConfirm.value);
    why += isDifferent(theForm.different.value);
    for (i=0, n=theForm.radios.length; i<n; i++) {
        if (theForm.radios[i].checked) {
            var checkvalue = theForm.radios[i].value;
            break;
        } 
    }
    why += checkRadio(checkvalue);
    why += checkDropdown(theForm.choose.selectedIndex);*/

function setSubmitStatus(){
	if($('submitstatus').value == '1'){
		if($('InsertSubmitButton') != null){
			$('InsertSubmitButton').style.visibility = 'hidden';
			$('InsertSubmitLabel').style.visibility = 'visible';
			$('InsertSubmitLabel2').style.visibility = 'hidden';
		}
		if($('EditSubmitButton') != null){
			$('EditSubmitButton').style.visibility = 'hidden';
			$('EditCancelButton').style.visibility = 'hidden';
			$('EditSubmitLabel').style.visibility = 'visible';
			$('EditSubmitLabel2').style.visibility = 'hidden';
		}
	}
}

function isPasswordKey (key)
{
	var str = String.fromCharCode(key);
	var acceptedValues = "1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
	
	if(acceptedValues.indexOf(str) == -1){
		return false;
	}else{
		return true;
	}
}

function isEmailKey (key)
{
	var str = String.fromCharCode(key);
	var acceptedValues = "1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-_@.";
	
	if(acceptedValues.indexOf(str) == -1){
		return false;
	}else{
		return true;
	}
}

function isDigit (key)
{
	if (key <= 46 || key > 57)
		return false;
	else
		return true;
}

function setNewPropertyRules(searchType, propertyType, duracao)
{
	if(searchType == 'A'){
		if(propertyType == 9){
			$('onlygay').style.visibility = 'visible';
			$('onlygay_label').style.visibility = 'visible';
		}else{
			$('onlygay').style.visibility = 'hidden';
			$('onlygay_label').style.visibility = 'hidden';
		}
			
		if(duracao == 2)
		{
			$('minimo_label').style.visibility = 'visible';
			$('duracaominima').style.visibility = 'visible';
			$('duracaodia').style.visibility = 'visible';
			$('duracaomes').style.visibility = 'visible';
			$('duracaodia_label').style.visibility = 'visible';
			$('duracaomes_label').style.visibility = 'visible';
			$('rent_label').innerHTML = 'Custo diário &euro;';
		}else{
			$('minimo_label').style.visibility = 'hidden';
			$('duracaominima').style.visibility = 'hidden';
			$('duracaodia').style.visibility = 'hidden';
			$('duracaomes').style.visibility = 'hidden';
			$('duracaodia_label').style.visibility = 'hidden';
			$('duracaomes_label').style.visibility = 'hidden';
			$('rent_label').innerHTML = 'Renda mensal &euro;';
		}
	}
	else{
		return true;
	}
}

function SetRegisterNewUserRules(userType){
	if(userType.toUpperCase() == 'PARTICULAR'){
		$('Dados_Particular').style.display = 'block';
		$('Dados_Profissional').style.display = 'none';
	}
	
	if(userType.toUpperCase() == 'PROFISSIONAL'){
		$('Dados_Particular').style.display = 'none';
		$('Dados_Profissional').style.display = 'block';
		$('nomeempresa').innerHTML = 'Nome da empresa mediadora/promotora:';
	}
	
	if(userType.toUpperCase() == 'TURRURAL'){
		$('Dados_Particular').style.display = 'none';
		$('Dados_Profissional').style.display = 'block';
		$('nomeempresa').innerHTML = 'Nome do espaço de turismo rural';
	}
}

function setSearchRules()
{
	var searchType = $('searchtype_select').value;
	var propertyType = $('propertytype').value;
	var refValue = $('ref').value;

	if(window.location.search.substring(1).length > 0){
		$('refErrada').style.visibility = 'visible';
	}else{
		$('refErrada').style.visibility = 'hidden';
	}
	
	if(searchType == 'A'){
		if(propertyType == 9){
			$('onlygay').style.visibility = 'visible';
			$('onlygay_label').style.visibility = 'visible';
		}
		else{
			$('onlygay').style.visibility = 'hidden';
			$('onlygay_label').style.visibility = 'hidden';
		}

		$('temprent').style.visibility = 'visible';
		$('temprent_label').style.visibility = 'visible';
	}
	else{
		$('onlygay').style.visibility = 'hidden';
		$('onlygay_label').style.visibility = 'hidden';
		$('temprent').style.visibility = 'hidden';
		$('temprent_label').style.visibility = 'hidden';
	}

	if(refValue.length > 0){
		$('propertytype').disabled=true;
		$('distrito').disabled=true;
		$('concelho').disabled=true;
		$('location').disabled=true;
		$('orderby').disabled=true;
		$('wfoto').disabled=true;
		$('onlygay').disabled=true;
		$('propertytype_label').disabled=true;
		$('distrito_label').disabled=true;
		$('concelho_label').disabled=true;
		$('location_label').disabled=true;
		$('orderby_label').disabled=true;
		$('wfoto_label').disabled=true;
		$('onlygay_label').disabled=true;
		$('temprent').disabled=true;
		$('temprent_label').disabled=true;
		$('searchtype_1').disabled=true;
		$('searchtype_2').disabled=true;
		$('searchtype_3').disabled=true;
		$('searchtype_aloj_label').disabled=true;
		$('searchtype_com_label').disabled=true;
		$('searchtype_tur_label').disabled=true;
	}else{
		$('propertytype').disabled=false;
		$('distrito').disabled=false;
		$('concelho').disabled=false;
		$('location').disabled=false;
		$('orderby').disabled=false;
		$('wfoto').disabled=false;
		$('onlygay').disabled=false;
		$('propertytype_label').disabled=false;
		$('distrito_label').disabled=false;
		$('concelho_label').disabled=false;
		$('location_label').disabled=false;
		$('orderby_label').disabled=false;
		$('wfoto_label').disabled=false;
		$('onlygay_label').disabled=false;
		$('temprent').disabled=false;
		$('temprent_label').disabled=false;
		$('searchtype_1').disabled=false;
		$('searchtype_2').disabled=false;
		$('searchtype_3').disabled=false;
		$('searchtype_aloj_label').disabled=false;
		$('searchtype_com_label').disabled=false;
		$('searchtype_tur_label').disabled=false;
	}
}

function setPaymentExecuteRules() {
	var productValue = $RadioValue($('paymentExecute'), 'product');
	// if produto is free... deactivate the rest
	if(productValue == 9 || productValue == 10 || productValue == 11)
	{
		$('choosepaymentmethod').hide();
		$('chooseinvoicedata').hide();
	}else{
		$('choosepaymentmethod').show();
		$('chooseinvoicedata').show();
	}
}


function checkPaymentExecuteForm(theForm, submitType) {
    var why = "";
	var header = "Formulário incompleto\n\n";
	var productValue = $RadioValue($('paymentExecute'), 'product');
	
	// if produto is free
	if(productValue != 9 && productValue != 10 && productValue != 11)
	{
		why += isEmpty(theForm.name.value, "- Nome: ", true);
		why += isEmpty(theForm.address.value, "- Morada: ", true);
		why += isEmpty(theForm.postcode.value, "- Código postal: ", true);
		why += isEmpty(theForm.nipc.value, "- NIPC: ", true);
	}
	
    if (why != "") {
       alert(header + why);
       return false;
    }
	return true;
}

function checkDeactivatePropertyForm(theForm) {
    var why = "";
	var header = "Formulário incompleto\n\n";
	why += checkDropdown(theForm.reason.selectedIndex, "- Razão: ");
	if(theForm.reason.value == 3){why += isEmpty(theForm.outromotivo.value, "- Outro Motivo: ", true);}
	why += isEmpty(theForm.message.value, "- Mensagem: ", true);

    if (why != "") {
       alert(header + why);
       return false;
    }
	return true;
}

function checkContactForm(theForm) {
    var why = "";
	var header = "Formulário incompleto\n\n";
	why += isEmpty(theForm.firstname.value, "- Nome: ", true);
	why += isEmpty(theForm.lastname.value, "- Apelido: ", true);
	why += checkPhone(theForm.phone.value, "- Telefone: ", false);
	why += checkEmail(theForm.email.value, "- E-mail: ", true);
	why += isEmpty(theForm.message.value, "- Mensagem: ", true);

    if (why != "") {
       alert(header + why);
       return false;
    }
return true;
}

function checkSearchForm(theForm) {
    var why = "";
	var header = "Formulário de pesquisa\n\n";
	why += checkNumeric(theForm.ref.value, "- Referência: ", false);
	if(theForm.ref.value.length > 0 && theForm.ref.value.length < 6){why += "A referência tem um mínimo de 6 digitos";}
	//if(theForm.distrito.value == 0 && theForm.ref.value.length == 0){why += "Tem de seleccionar um distrito";}

    if (why != "") {
       alert(header + why);
       return false;
    }
	return true;
}

function checkNewPropertyForm(theForm) {
    var why = "";
	var header = "Formulário incompleto\n\n";
	why += isEmpty(theForm.name.value, "- Nome: ");
    why += checkEmail(theForm.email.value, "- E-mail: ", true);
	why += checkPhone(theForm.phone.value, "- Telefone: ", false);
	why += checkNumeric(theForm.rent.value, "- Renda Mensal: ", true);
	if(theForm.newproperty_actiontype.value != 'T'){
		why += checkNumeric(theForm.area.value, "- Área: ", true);
	}
    why += isEmpty(theForm.title.value, "- Titulo: ");
	why += checkDropdown(theForm.propertytype.selectedIndex, "- Tipo de aluguer: ");
	why += checkDropdown(theForm.distrito.selectedIndex, "- Distrito: ");
	why += checkDropdown(theForm.concelho.selectedIndex, "- Concelho: ");
	why += checkDropdown(theForm.location.selectedIndex, "- Freguesia: ");
	if(theForm.newproperty_actiontype.value == 'A'){
		why += checkDropdown(theForm.duracao.selectedIndex, "- Duração: ");
		if(theForm.duracao.selectedIndex == 2 && theForm.duracaominima.value.length == 0){why += "- Duração: Introduza a duração mínima\n";}
	}
	if(theForm.newproperty_actiontype.value == 'T'){
		if(theForm.duracaominima.value.length == 0){why += "- Duração: Introduza a duração mínima\n";}
	}
	why += isEmpty(theForm.description.value, "- Descrição: ");

	// Features and Amenities
	var i;
	var featuresSet = false;
	var amenitiesSet = false;
	var termosSet = false;
	for(i=0; i<theForm.elements.length; i++){
		if(theForm.elements[i].name != null && theForm.elements[i].name.toUpperCase() == 'TERMOSUTILIZACAO'){
			if(theForm.elements[i].checked){termosSet = true;}
		}
		if(theForm.elements[i].name != null && theForm.elements[i].name.length >=8){
			if (theForm.elements[i].name.substring(0, 8).toUpperCase() == 'FEATURES'){
				if(theForm.elements[i].checked){featuresSet = true;}
			}
			if (theForm.elements[i].name.substring(0, 9).toUpperCase() == 'AMENITIES'){
				if(theForm.elements[i].checked){amenitiesSet = true;}
			}
		}
   	}
	if(!featuresSet){why += "- Propriedades: Escolha uma das opções\n";}
	if(!amenitiesSet){why += "- Zona envolvente: Escolha uma das opções\n";}
	why += isEmpty(theForm.latitude.value, "- Mapa: ");


    if (why != "") {
       alert(header + why);
       return false;
    }
	
	return true;
}

function checkRecuperarPasswordForm(theForm) {
    var why = "";
	var header = "Formulário incompleto\n\n";
    why += checkEmail(theForm.email.value, "- E-mail: ", true);

    if (why != "") {
       alert(header + why);
       return false;
    }
return true;
}

function checkContactProprietarioForm(theForm){
    var why = "";
	var header = "Formulário incompleto\n\n";
	why += isEmpty(theForm.username.value, "- O seu nome: ", true);
	why += checkEmail(theForm.useremail.value, "- O seu email: ", true);
	why += checkPhone(theForm.userphone.value, "- Telefone: ", false);
	why += isEmpty(theForm.message.value, "- Mensagem: ", true);

    if (why != "") {
       alert(header + why);
       return false;
    }
	return true;
}

function checkEnviarAmigoForm(theForm){
    var why = "";
	var header = "Formulário incompleto\n\n";
	why += isEmpty(theForm.nameclient.value, "- O seu nome: ", true);
	why += checkEmail(theForm.emailclient.value, "- O seu email: ", true);
	why += isEmpty(theForm.namefriend.value, "- O nome do seu amigo: ", true);
	why += checkEmail(theForm.emailfriend.value, "- O email do seu amigo: ", true);

    if (why != "") {
       alert(header + why);
       return false;
    }
	return true;
}

function checkRegisterNewUserForm(theForm, submitType) {
    var why = "";
	var header = "Formulário incompleto\n\n";

	why += checkEmail(theForm.email.value, "- E-mail: ", true);
	why += checkPassword(theForm.password.value, "- Password: ", true);
	why += checkPassword(theForm.passwordConfirm.value, "- Password de confirmação: ", true);

	if(theForm.usertype_particular.checked == true){
		why += isEmpty(theForm.firstName.value, "- Nome: ");
		why += isEmpty(theForm.lastName.value, "- Apelido: ");
		why += isDifferent(theForm.password.value, theForm.passwordConfirm.value, "- Introdução de password de confirmação errada\n");
	}else{
		if(theForm.usertype_profissional.checked == true){
			why += isEmpty(theForm.nomeProfissional.value, "- Nome da empresa: ");
		}else{
			why += isEmpty(theForm.nomeProfissional.value, "- Nome do espaço de turismo rural: ");
		}
		why += isEmpty(theForm.moradaProfissional.value, "- Morada: ");
		why += isEmpty(theForm.codPostalProfissional.value, "- Código postal: ");
		why += isEmpty(theForm.distritoProfissional.value, "- Distrito: ");
		why += checkPhone(theForm.telefoneProfissional.value, "- Telefone: ", true);
		why += checkNIF(theForm.nifProfissional.value, "- NIF: ", true);
	}

	if(submitType.toUpperCase() != 'EDIT'){why += checkDropdownQuestion(theForm.question.selectedIndex, theForm.questionReason.value, "- Passo 3: ");}
	//if(submitType.toUpperCase() != 'EDIT'){if(!auth_terms_value){why += "Tem de concordar com os termos de utilização e política de privacidade\n";}}

    if (why != "") {
       alert(header + why);
       return false;
    }
	return true;
}

function checkRegisterNewUserSearchForm(theForm) {
    var why = "";
	var header = "Formulário incompleto\n\n";

	why += isEmpty(theForm.name.value, "- Nome: ");
	why += checkEmail(theForm.email.value, "- E-mail: ", true);
	why += checkDropdown(theForm.propertytype.selectedIndex, "- Tipo de alojamento: ");
	why += checkDropdown(theForm.distrito.selectedIndex, "- Distrito: ");
	why += isEmpty(theForm.rent.value, "- Valor da renda: ");
	why += isEmpty(theForm.message.value, "- Mensagem: ");

    if (why != "") {
       alert(header + why);
       return false;
    }
	return true;
}

// email

function checkEmail (strng, fieldName, isMandatory) {
	var error="";
	if (strng == "" || strng == null) 
	{
		if(isMandatory)
		{
			error = fieldName + "Campo de preenchimento obrigatório\n";
		}
	}
	else 
	{
		var emailFilter=/^.+@.+\..{2,3}$/;
		if (!(emailFilter.test(strng)))
		{ 
			error = fieldName + "Introduza um endereço de e-mail válido\n";
		}
		else 
		{
			//test email for illegal characters
			var illegalChars= /[\(\)\<\>\,\;\:\\\"\[\]]/
			if (strng.match(illegalChars))
			{
				error = fieldName + "Uso de caracteres inválidos\n";
			}
		}
	}
	return error;    
}


// phone number - strip out delimiters and check for 10 digits
function checkPhone (strng, fieldName, isMandatory) {
	var error = "";
	if (strng == "")
	{
		if (isMandatory)
		{
			error = fieldName + "Campo de preenchimento obrigatório\n";
		}
	}
	else
	{
		var stripped = strng.replace(/[\(\)\.\-\ ]/g, ''); //strip out acceptable non-numeric characters
		if (isNaN(parseInt(stripped)))
		{
			error = fieldName + "Uso de caracteres inválidos";
		}
		if (!(stripped.length == 9))
		{
			error = fieldName + "Número inválido. Certifique-se que introduz o indicativo seguido do número. Ex: '961234567' \n";
		}
	}
	return error;
}

// phone number - strip out delimiters and check for 10 digits
function checkNIF (strng, fieldName, isMandatory) {
	var error = "";
	if (strng == "")
	{
		if (isMandatory)
		{
			error = fieldName + "Campo de preenchimento obrigatório\n";
		}
	}
	else
	{
		var stripped = strng.replace(/[\(\)\.\-\ ]/g, ''); //strip out acceptable non-numeric characters
		if (isNaN(parseInt(stripped)))
		{
			error = fieldName + "Uso de caracteres inválidos";
		}
		if (!(stripped.length == 9))
		{
			error = fieldName + "Número inválido. Insira 9 digitos obrigatórios.\n";
		}
	}
	return error;
}

// password - between 6-8 chars, uppercase, lowercase, and numeral

function checkPassword (strng, fieldName, isMandatory) {
	var error = "";
	if (strng == "")
	{
		if (isMandatory)
		{
			error = fieldName + "Campo de preenchimento obrigatório\n";
		}
	}
	else
	{
		var illegalChars = /[\W_]/; // allow only letters and numbers
		
		if ((strng.length < 6) || (strng.length > 8))
		{
			error = fieldName + "Password inválida. Introduza entre 6 e 8 caracteres obrigatórios\n";
		}
		else if (illegalChars.test(strng))
		{
			error = fieldName + "Uso de caracteres inválidos\n";
		} 
/*		else if (!((strng.search(/(a-z)+/)) && (strng.search(/(A-Z)+/)) && (strng.search(/(0-9)+/)))) {
		error = fieldName + ": A password tem de ter pelo menos um caracter em maiúsculas, um caracter em minusculas e um numérico.\n";
		}*/
	}
	return error;    
}    


// username - 4-10 chars, uc, lc, and underscore only.

function checkUsername (strng, fieldName, isMandatory) {
	var error = "";
	if (strng == "")
	{
		if (isMandatory)
		{
			error = fieldName + "Campo de preenchimento obrigatório\n";
		}
	}
	else
	{
		var illegalChars = /\W/; // allow letters, numbers, and underscores
		if ((strng.length < 4) || (strng.length > 10))
		{
			error = fieldName + "Nome de utilizador inválido. Introduza entre 4 e 10 caracteres obrigatórios\n";
		}
		else if (illegalChars.test(strng))
		{
			error = fieldName + "Uso de caracteres inválidos\n";
		}
	}
	return error;
}       

// Numeric - Check for only numeric values
function checkNumeric (strng, fieldName, isMandatory) {
	var error = "";
	if (strng == "")
	{
		if (isMandatory)
		{
			error = fieldName + "Campo de preenchimento obrigatório\n";
		}
	}
	else
	{
		var stripped = strng.replace(/[\(\)\.\-\ ]/g, ''); //strip out acceptable non-numeric characters
		if (isNaN(parseInt(stripped)))
		{
			error = fieldName + "Uso de caracteres inválidos\n";
		}
	}
	return error;
}

// non-empty textbox
function isEmpty(strng, fieldName) {
	var error = "";
	if (strng.length == 0)
	{
		error = fieldName + "Campo de preenchimento obrigatório\n"
	}
	return error;	  
}

// was textbox altered
function isDifferent(strFirst, strSecond, errorMessage) {
	var error = ""; 
	if (strFirst != strSecond)
	{
		error = errorMessage;
	}
	return error;
}

// exactly one radio button is chosen

function checkRadio(checkvalue, fieldName) {
	var error = "";
	if (!(checkvalue))
	{
		error = fieldName + "Escolha uma das opções\n";
	}
	return error;
}

// valid selector from dropdown list

function checkDropdown(choice, fieldName) {
	var error = "";
	if (choice == 0)
	{
		error = fieldName + "Escolha uma das opções\n";
	}    
	return error;
}    

// valid selector from dropdown list - type question

function checkDropdownQuestion(questionValue, reasonValue, fieldName) {
	var error = "";
	if (questionValue == 0)
	{
		error = fieldName + "Escolha uma das opções\n";
	}
	else if (questionValue == 5){
		if (reasonValue == '')
		{
			error = fieldName + "Introduza como teve conhecimento do LxRent.com\n";
		}
	}
	return error;
}    