function valida_comentarios(){
   var ajaxRequest;

   try{
      ajaxRequest = new XMLHttpRequest();
   } catch (e){
      try{
         ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
      } catch (e) {
         try{
            ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
         } catch (e){
            alert("Your browser broke!");
            return false;
         }
      }
   }
   ajaxRequest.onreadystatechange = function(){
      if(ajaxRequest.readyState == 4){
         var ajaxDisplay = document.getElementById('ajaxDiv');
         ajaxDisplay.innerHTML = ajaxRequest.responseText;
         if (ajaxRequest.responseText== "ok") {
            parent.location.href=document.getElementById('ref').value;
         }
      }
   }

   var nome = document.getElementById('nome').value;
   var email = document.getElementById('email').value;
   var description = document.getElementById('description').value;
   var security_code = document.getElementById('security_code').value;
   var fkpointer = document.getElementById('fkpointer').value;
   var ref = document.getElementById('ref').value;

   description = description.replace(/\n/g, "<br />");

   var queryString = "?page=1&nome=" + nome + "&email=" + email + "&description=" + description + "&security_code=" + security_code + "&fkpointer=" + fkpointer + "&ref=" + ref;

   ajaxRequest.open("GET", "comentarios_popup_handler.html" + queryString, true);
   ajaxRequest.send(null);


}

function valida_passo1(){
	var ajaxRequest; 
	
	try{
		ajaxRequest = new XMLHttpRequest();
	} catch (e){
		try{
			ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try{
				ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e){
				alert("Your browser broke!");
				return false;
			}
		}
	}
	ajaxRequest.onreadystatechange = function(){
		if(ajaxRequest.readyState == 4){
			var ajaxDisplay = document.getElementById('ajaxDiv');
			ajaxDisplay.innerHTML = ajaxRequest.responseText;
			if (ajaxRequest.responseText== "") {
				document.formname.submit();
			}
		}
	}

	var url = document.getElementById('url').value;
	var title = document.getElementById('title').value;
	var description = document.getElementById('description').value;
	var keywords = document.getElementById('keywords').value;  
   var campoCats = document.getElementById('catsSpace');
   var campoGeos = document.getElementById('geoSpace');

   var aCats = campoCats.getElementsByTagName('SELECT'); 
   var oStr = {};
   for(var i=0; i < aCats.length; i++) {
      oStr[aCats[i].name] = aCats[i].value;
   }
   var aStr = [];
   for(var i in oStr) {
      aStr.push(oStr[i]);
   }
   var strCats = aStr.join(',');

   var aGeos = campoGeos.getElementsByTagName('SELECT');
   var oStr = {};
   for(var i=0; i < aGeos.length; i++) {
      oStr[aGeos[i].name] = aGeos[i].value;
   }
   var aStr = [];
   for(var i in oStr) {
      aStr.push(oStr[i]);
   }
   var strGeos = aStr.join(',');

	var queryString = "?page=1" + "&url=" + url + "&title=" + title + "&description=" + description + "&keywords=" + keywords + "&child="+strCats + "&geochild=" + strGeos;
	
	ajaxRequest.open("GET", "validacao.html" + queryString, true);
	ajaxRequest.send(null); 
}

function valida_passo2(){
   var ajaxRequest;

   try{
      ajaxRequest = new XMLHttpRequest();
   } catch (e){
      try{
         ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
      } catch (e) {
         try{
            ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
         } catch (e){
            alert("Your browser broke!");
            return false;
         }
      }
   }
   ajaxRequest.onreadystatechange = function(){
      if(ajaxRequest.readyState == 4){
         var ajaxDisplay = document.getElementById('ajaxDiv');
         ajaxDisplay.innerHTML = ajaxRequest.responseText;
         if (ajaxRequest.responseText== "") {
            document.formname.submit();
         }
      }
   }

   var proposerName = document.getElementById('proposerName').value;
   var cpostal1 = document.getElementById('cpostal1').value;
   var cpostal2 = document.getElementById('cpostal2').value;
   var cpostall = document.getElementById('cpostall').value;
   var proposerEmail = document.getElementById('proposerEmail').value;

   var queryString = "?page=2" + "&proposerName=" + proposerName + "&cpostal1=" + cpostal1 + "&cpostal2=" + cpostal2 + "&cpostall=" + cpostall + "&proposerEmail=" + proposerEmail;

   ajaxRequest.open("GET", "validacao.html" + queryString, true);
   ajaxRequest.send(null);
}

function valida_passo3(){
   var ajaxRequest;

   try{
      ajaxRequest = new XMLHttpRequest();
   } catch (e){
      try{
         ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
      } catch (e) {
         try{
            ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
         } catch (e){
            alert("Your browser broke!");
            return false;
         }
      }
   }
   ajaxRequest.onreadystatechange = function(){
      if(ajaxRequest.readyState == 4){
         var ajaxDisplay = document.getElementById('ajaxDiv');
         ajaxDisplay.innerHTML = ajaxRequest.responseText;
         if (ajaxRequest.responseText== "") {
            document.formname.submit();
         }
      }
   }

   var radio1 = document.getElementById('radio1').value;
   var radio2 = document.getElementById('radio2').value;
   var validacao = 0;
	var modo = 0;

	if(document.getElementById('validacao').checked) {
		validacao=1;
	}
   if(document.getElementById('radio1').checked) {
      modo=1;
   }
	if(document.getElementById('radio2').checked) {
      modo=2;
   }



   var queryString = "?page=3" + "&modo=" + modo + "&validacao=" + validacao;

   ajaxRequest.open("GET", "validacao.html" + queryString, true);
   ajaxRequest.send(null);
}


function charAlert(campo, max) {

    if(campo.value.length >= max)
    {
        campo.value = campo.value.substr(0, max);
        alert('Limite de caracteres ultrapassado');
    }
}


function validaUrl(url) {

    //var urlValido = /^(http:\/\/|https:\/\/)([çáàâãäéèêëíìîïóòôõöúùûü0-9a-z](-?[çáàâãäéèêëíìîïóòôõöúùûü0-9a-z])\.)+[a-z]{2,4}/;

    var myRegexpGeral = /^(http:\/\/|https:\/\/)(.*\.)/;
    var myRegexpTuga = /([0-9a-zA-Z](-?[0-9a-zA-Z])\.)+[a-zA-Z]{2,4}/;
    var myRegexpAcentos = /(46|231|199|225|193|224|192|226|194|227|195|228|196|233|201|232|200|234|202|235|203|237|205|236|204|238|206|239|207|243|211|242|210|244|212|245|213|246|214|250|218|249|217|251|219|252|220)/;

    if(myRegexpGeral.test(url)) {
        var aUrl = url.split('/');
        if(myRegexpTuga.test(aUrl[2])) {
            return true;
        } else {
            var contaCertos = 0;
            var str = '';
            for(var i=0; i < aUrl[2].length; i++) {
                var myDec = aUrl[2].charCodeAt(i);
                str += myDec+' ';
                if((myDec > 47 && myDec < 58) || (myDec > 64 && myDec < 91) || (myDec >96 && myDec < 123) || myRegexpAcentos.test(myDec)) {
                    contaCertos++;
                }
            }
            if(contaCertos != aUrl[2].length) {
                return false;
            } else {
                return true;
            }
        }
    } else {
        return false;
    }
}


function validaEmail(email) {

    //var emailValido = /^[_a-z0-9-]+(\.[_a-z0-9-]+)*@([çáàâãäéèêëíìîïóòôõöúùûü0-9a-z](-?[çáàâãäéèêëíìîïóòôõöúùûü0-9a-z])*\.)+[a-z]{2,4}$/;
    var emailValido = /^[_a-z0-9-]+(\.[_a-z0-9-]+)*@([\w]*-?[\w]*\.)+[a-z]{2,4}$/;
    if(!emailValido.test(email)) {
        return false;
    } else {
        return true;
    }
}

function validaCpostal(cpostal) {
    var cpostalValido = /^[0-9]{4}$/;
    if(!cpostalValido.test(cpostal))
        return false;
    else
        return true;
}


function submitNormal() {

    var formname = document.formname;

    if(formname['url'].value == '' || 
            formname['title'].value == '' || 
            formname['description'].value == '' ||  
            formname['proposerName'].value == '' || 
            formname['proposerEmail'].value == ''
            ) {
        alert('Por favor, preencha os campos obrigatórios');
        return false;
    }
    if(!validaUrl(formname['url'].value)) {
        alert('URL inválido');
        formname['url'].value = 'http://';
        formname['url'].focus();
        return false;
    }
    if(!validaEmail(formname['proposerEmail'].value)) {
        alert('Email inválido');
        formname['proposerEmail'].focus();
        return false;
    }
    if(formname['cpostal1'].value != '') {
        if(!validaCpostal(formname['cpostal1'].value)) {
            alert('Codigo postal inválido');
            formname['cpostal1'].value = '';
            formname['cpostal1'].focus();
            return false;
        }
        if(formname['cpostal2'].value != '') {
            var validaCpostal2 = /^[0-9]{3}$/;
            if(!validaCpostal2.test(formname['cpostal2'].value)) {
                alert('Codigo postal inválido');
                formname['cpostal2'].value = '';
                formname['cpostal2'].focus();
                return false;
            }
        }
    }
    if(formname['termos']) {
        if(!formname['termos'].checked) {
            alert('Terá de aceitar os termos de utilização para submeter os dados.');
            return false;
        }
    }
    formname['submitPointer'].value = true;
    formname.submit();
}

function submitAlterar() {

    var formname = document.formname;
    formname['alterarPointer'].value = true;
    formname.action = 'form_expresso.html';
    formname.submit();
}

function submitConfirm() {
    document.formname.submitPointer.value = true;
    document.formname.submit();
}


function submitPay() {
    document.formname.submitPay.value = true;
    document.formname.submit();
}

function verificaPointer() {

    if(validaUrl(document.formname.urlpagina.value) == true) {
        document.formname.submit();
    } else {
        alert('URL invalido');
    }
}


function subLogin() {

    var campo = document.getElementById("formlogin");
    if(campo.user.value == '' || campo.user.pass == '') {
        alert('Preencha o campo Email e Password.');
    } else {
        campo.b_submit.value = true;
        campo.submit();
    }
}

function removePointer(id, state) {
    var campo = document.getElementById("formremove");
    if(confirm('Deseja remover o apontador com ID ['+id+']')) {
        campo.pointerid.value = id;
        campo.pointerstate.value = state;
        campo.removepointer.value = true;
        campo.submit();
    } else {
        return false;
    }
}

function editPointer() {

    var formname = document.formname;

    if(formname['url'].value == '' || 
            formname['title'].value == '' || 
            formname['description'].value == '' ||  
            formname['proposerName'].value == '' || 
            formname['proposerEmail'].value == ''
            ) {
        alert('Por favor, preencha os campos obrigatórios');
        return false;
    }
    if(!validaUrl(formname['url'].value)) {
        alert('URL inválido');
        formname['url'].value = 'http://';
        formname['url'].focus();
        return false;
    }
    if(!validaEmail(formname['proposerEmail'].value)) {
        alert('Email inválido');
        formname['proposerEmail'].focus();
        return false;
    }
    if(formname['cpostal1'].value != '') {
        if(!validaCpostal(formname['cpostal1'].value)) {
            alert('Codigo postal inválido');
            formname['cpostal1'].value = '';
            formname['cpostal1'].focus();
            return false;
        }
        if(formname['cpostal2'].value != '') {
            var validaCpostal2 = /^[0-9]{3}$/;
            if(!validaCpostal2.test(formname['cpostal2'].value)) {
                alert('Codigo postal inválido');
                formname['cpostal2'].value = '';
                formname['cpostal2'].focus();
                return false;
            }
        }
    }
    if(formname['termos']) {
        if(!formname['termos'].checked) {
            alert('Terá de aceitar os termos de utilização para submeter os dados.');
            return false;
        }
    }
    formname['editPointer'].value = true;
    formname.submit();
}

function pagarPointer(url) {
    var formname = document.formpagar;
    formname.urlpagina.value = url;
    formname.submit();
}

function textCounter(field,cntfield,maxlimit) {
    if (field.value.length > maxlimit)
       field.value = field.value.substring(0, maxlimit);
    else
       cntfield.value = maxlimit - field.value.length;
}








function submitAll() {

    var formname = document.formname;

    if(formname['url'].value == '' ||
            formname['title'].value == '' ||
            formname['description'].value == '' ||
	    formname['keywords'].value == ''
            ) {
        alert('Por favor, preencha os campos obrigatórios');
        return false;
    }
    if(!validaUrl(formname['url'].value)) {
        alert('URL inválido');
        formname['url'].value = 'http://';
        formname['url'].focus();
        return false;
    }
    formname['submitPointer'].value = true;
    formname.submit();
}



/*
	CRIR - Checkbox & Radio Input Replacement
	Author: Chris Erwin (me[at]chriserwin.com)
	www.chriserwin.com/scripts/crir/

	Updated July 27, 2006.
	Jesse Gavin added the AddEvent function to initialize
	the script. He also converted the script to JSON format.
	
	Updated July 30, 2006.
	Added the ability to tab to elements and use the spacebar
	to check the input element. This bit of functionality was
	based on a tip from Adam Burmister.
*/

crir = {
	init: function() {
		arrLabels = document.getElementsByTagName('label');
	
		searchLabels:
		for (var i=0; i<arrLabels.length; i++) {			
			// get the input element based on the for attribute of the label tag
			if (arrLabels[i].getAttributeNode('for') && arrLabels[i].getAttributeNode('for').value != '') {
				labelElementFor = arrLabels[i].getAttributeNode('for').value;				
				inputElement = document.getElementById(labelElementFor);
			}
			else {				
				continue searchLabels;
			}	
							
			inputElementClass = inputElement.className;	
		
			// if the input is specified to be hidden intiate it
			if (inputElementClass == 'crirHiddenJS') {
				inputElement.className = 'crirHidden';
				
				inputElementType = inputElement.getAttributeNode('type').value;	
				
				// add the appropriate event listener to the input element
				if (inputElementType == "checkbox") {
					inputElement.onclick = crir.toggleCheckboxLabel;
				}
				else {
					inputElement.onclick = crir.toggleRadioLabel;
				}
				
				// set the initial label state
				if (inputElement.checked) {
					if (inputElementType == 'checkbox') { arrLabels[i].className = 'checkbox_checked'}
					else { arrLabels[i].className = 'radio_checked' }
				}
				else {
					if (inputElementType == 'checkbox') { arrLabels[i].className = 'checkbox_unchecked'}
					else { arrLabels[i].className = 'radio_unchecked' }
				}
			}
			else if (inputElement.nodeName != 'SELECT' && inputElement.getAttributeNode('type').value == 'radio') { // this so even if a radio is not hidden but belongs to a group of hidden radios it will still work.
				arrLabels[i].onclick = crir.toggleRadioLabel;
				inputElement.onclick = crir.toggleRadioLabel;
			}
		}			
	},	
	
	findLabel: function (inputElementID) {
		arrLabels = document.getElementsByTagName('label');
	
		searchLoop:
		for (var i=0; i<arrLabels.length; i++) {
			if (arrLabels[i].getAttributeNode('for') && arrLabels[i].getAttributeNode('for').value == inputElementID) {				
				return arrLabels[i];
				break searchLoop;				
			}
		}		
	},	
	
	toggleCheckboxLabel: function () {
		labelElement = crir.findLabel(this.getAttributeNode('id').value);
	
		if(labelElement.className == 'checkbox_checked') {
			labelElement.className = "checkbox_unchecked";
		}
		else {
			labelElement.className = "checkbox_checked";
		}
	},	
	
	toggleRadioLabel: function () {			 
		clickedLabelElement = crir.findLabel(this.getAttributeNode('id').value);
		
		clickedInputElement = this;
		clickedInputElementName = clickedInputElement.getAttributeNode('name').value;
		
		arrInputs = document.getElementsByTagName('input');
	
		// uncheck (label class) all radios in the same group
		for (var i=0; i<arrInputs.length; i++) {			
			inputElementType = arrInputs[i].getAttributeNode('type').value;
			if (inputElementType == 'radio') {
				inputElementName = arrInputs[i].getAttributeNode('name').value;
				inputElementClass = arrInputs[i].className;
				// find radio buttons with the same 'name' as the one we've changed and have a class of chkHidden
				// and then set them to unchecked
				if (inputElementName == clickedInputElementName && inputElementClass == 'crirHidden') {				
					inputElementID = arrInputs[i].getAttributeNode('id').value;
					labelElement = crir.findLabel(inputElementID);
					labelElement.className = 'radio_unchecked';
				}
			}
		}
	
		// if the radio clicked is hidden set the label to checked
		if (clickedInputElement.className == 'crirHidden') {
			clickedLabelElement.className = 'radio_checked';
		}
	},
	
	addEvent: function(element, eventType, doFunction, useCapture){
		if (element.addEventListener) 
		{
			element.addEventListener(eventType, doFunction, useCapture);
			return true;
		} else if (element.attachEvent) {
			var r = element.attachEvent('on' + eventType, doFunction);
			return r;
		} else {
			element['on' + eventType] = doFunction;
		}
	}
}

crir.addEvent(window, 'load', crir.init, false);
