function AjaxRequest() {
	Ajax = false;
	if (window.XMLHttpRequest) { // Mozilla, Safari,...
			Ajax = new XMLHttpRequest();
	} else if (window.ActiveXObject) { // IE
			try {
					Ajax = new ActiveXObject("Msxml2.XMLHTTP");
			} catch (e) {
					try {
							Ajax = new ActiveXObject("Microsoft.XMLHTTP");
					} catch (e) {}
			}
	}		
}

function inputareareservada(id,accao,exp){
	campo = document.getElementById(id);
	if (accao==1 && (campo.value=='' || campo.value==exp)){
		campo.value='';
		campo.style.color='#000';
		if (id=='palavrapasse')
			campo.type='password';
		if (id=='palavrapasse2')
			campo.type='password';
	}else if (campo.value==''){
		campo.value=exp;
		campo.type='text';
		campo.style.color='#808080';
	}	
}

ddsmoothmenu.init({
	mainmenuid: "smoothmenu1", //menu DIV id
	orientation: 'h', //Horizontal or vertical menu: Set to "h" or "v"
	classname: 'ddsmoothmenu', //class added to menu's outer DIV
	//customtheme: ["#1c5a80", "#18374a"],
	contentsource: "markup" //"markup" or ["container_id", "path_to_menu_file"]
})

var menutimer=new Array()
function menuout(img){
	document.getElementById('img'+img).src='img/'+img+'_off4.png';
}

function menuon(img){
	document.getElementById('img'+img).src='img/'+img+'_on4.png';
	clearTimeout(menutimer[img])
}

function loadPopup(divname){
		$("#backgroundPopup").css({
			"opacity": "0.7"
		});
		$("#backgroundPopup").fadeIn("slow");
		$(divname).fadeIn("slow");
}

function disablePopup(divname){
		$("#backgroundPopup").fadeOut("slow");
		$(divname).fadeOut("slow");
}

function subscribe(){
	var windowWidth = document.body.clientWidth+document.body.scrollLeft;
	var windowHeight = (document.body.scrollTop);
	var popupHeight = $('#popupContact').height();
	var popupWidth = $('#popupContact').width();
	$('#popupContact').css({
		"position": "absolute",
		"top": windowHeight,
		"left": windowWidth/2-popupWidth/2
	});
	//only need force for IE6
	$("#backgroundPopup").css({
		"height": $(document).height()
	});
	$("#backgroundPopup").css({
		"width": $(document).width()
	});
	loadPopup('#popupContact');
}

function recuperar(){
	var windowWidth = document.body.clientWidth+document.body.scrollLeft;
	var windowHeight = (document.body.scrollTop);
	var popupHeight = $('#popupPassword').height();
	var popupWidth = $('#popupPassword').width();
	$('#popupPassword').css({
		"position": "absolute",
		"top": windowHeight,
		"left": windowWidth/2-popupWidth/2
	});
	//only need force for IE6
	$("#backgroundPopup").css({
		"height": $(document).height()
	});
	$("#backgroundPopup").css({
		"width": $(document).width()
	});
	loadPopup('#popupPassword');
}

//CONTROLLING EVENTS IN jQuery
$(document).ready(function(){
	//Click out event!
	$("#backgroundPopup").click(function(){
		disablePopup('#popupContact');
		disablePopup('#popupPassword');
	});
	//Press Escape event!
	$(document).keypress(function(e){
		if(e.keyCode==27){
			disablePopup('#popupContact');
			disablePopup('#popupPassword');
		}
	});
});

// Gerar password
function getRandomNum(lbound, ubound) {
		return (Math.floor(Math.random() * (ubound - lbound)) + lbound);
}
function getRandomChar() {
		var numberChars = "0123456789";
		var lowerChars = "abcdefghijklmnopqrstuvwxyz";
		var upperChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
		var charSet = '';
		charSet += numberChars;
		charSet += lowerChars;
		charSet += upperChars;
		return charSet.charAt(getRandomNum(0, charSet.length));
}
function getPassword() {
		var length = 8;
		var rc = "";
		if (length > 0)
				rc = rc + getRandomChar();
				for (var idx = 1; idx < length; ++idx) {
				rc = rc + getRandomChar();
		}
		document.getElementById('regpalavrapasse').value = rc;
		document.getElementById('regpalavrapasse').style.color='#000';
}

function confirmaregisto(){
	
	if (document.getElementById("regcedula").value=='' || document.getElementById("regcedula").value=='Cédula Profissional'){
		alert("Por favor, preencha o campo 'Cédula Profissional'!");
		return false;
	}
	
	if (document.getElementById("regnome").value=='' || document.getElementById("regnome").value=='Nome'){
		alert("Por favor, preencha o campo 'Nome'!");
		return false;
	}
	
	if (document.getElementById("regmorada").value=='' || document.getElementById("regmorada").value=='Morada'){
		alert("Por favor, preencha o campo 'Morada'!");
		return false;
	}
	
	if (document.getElementById("regcp").value=='' || document.getElementById("regcp").value=='Código Postal'){
		alert("Por favor, preencha o campo 'Código Postal'!");
		return false;
	}
	
	if (document.getElementById("reglocalidade").value=='' || document.getElementById("reglocalidade").value=='Localidade'){
		alert("Por favor, preencha o campo 'Localidade'!");
		return false;
	}
	
	if (document.getElementById("regtel").value=='' || document.getElementById("regtel").value=='Telefone e/ou Telemóvel'){
		alert("Por favor, preencha o campo 'Telefone e/ou Telemóvel'!");
		return false;
	}
	
	var emailStr=document.getElementById("regemail").value;
	var checkTLD=1;
	var knownDomsPat=/^(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum)$/;
	var emailPat=/^(.+)@(.+)$/;
	var specialChars="\\(\\)><@,;:\\\\\\\"\\.\\[\\]";
	var validChars="\[^\\s" + specialChars + "\]";
	var quotedUser="(\"[^\"*\")";
	var atom=validChars + '+';
	var word="(" + atom + "|" + quotedUser + ")";
	var matchArray=emailStr.match(emailPat);					
	if(matchArray==null){
		alert("Por favor, verifique o seu endereço de email!");
		return false;
	}
	var user=matchArray[1];
	var domain=matchArray[2];
	for (i=0; i<user.length; i++){
		if (user.charCodeAt(i)>127){
			alert("Por favor, verifique o seu endereço de email!");
			return false;
		}
	}
	for (i=0; i<domain.length; i++){
		if (user.charCodeAt(i)>127){
			alert("Por favor, verifique o seu endereço de email!");
			return false;
		}
	}
	var domArr=domain.split(".");
	var len=domArr.length;
	if (checkTLD && domArr[domArr.length-1].length!=2 && domArr[domArr.length-1].search(knownDomsPat)==-1){
		alert("Por favor, verifique o seu endereço de email!");
		return false;
	}
	if(len<2){
		alert("Por favor, verifique o seu endereço de email!");
		return false;
	}
	
	if (document.getElementById("regpalavrapasse").value=='' || document.getElementById("regpalavrapasse").value=='Password' || document.getElementById("regpalavrapasse").value.length<4){
		alert("Por favor, preencha corretamente o campo 'Password'! A password deverá ter mais de 4 caracteres. Se pretender, clique no botão gerar password.");
		return false;
	}
	
	document.registo.submit();
}

function login(sid){
	var userStr=document.getElementById("utilizador").value;
	var passStr=document.getElementById("palavrapasse").value;
	AjaxRequest();
	if (!Ajax)
		alert ('ERRO: Problemas com o pedido AJAX! Verifique se tem a opção Javascript activa no seu browser ou contacte o APMI!')
	else{
		Ajax.onreadystatechange = function(){
			if (Ajax.readyState == 4) {
				if (Ajax.status == 200) {
					if(Ajax.responseText == 'ok')
						window.open('acessorestrito.php','_self')
					else
						alert('Combinação de username e password errada!')
				}
			}
		}
		Ajax.open('POST', 'include/validar.php?u='+userStr+'&p='+passStr+'&sessionid='+sid, true);
		Ajax.send(null);
	}
}

function login2(sid,submenu){
	var userStr=document.getElementById("utilizador2").value;
	var passStr=document.getElementById("palavrapasse2").value;
	AjaxRequest();
	if (!Ajax)
		alert ('ERRO: Problemas com o pedido AJAX! Verifique se tem a opção Javascript activa no seu browser ou contacte o APMI!')
	else{
		Ajax.onreadystatechange = function(){
			if (Ajax.readyState == 4) {
				if (Ajax.status == 200) {
					if(Ajax.responseText == 'ok')
						window.open('legislacao.php?submenu='+submenu,'_self')
					else
						alert('Combinação de username e password errada!')
				}
			}
		}
		Ajax.open('POST', 'include/validar.php?u='+userStr+'&p='+passStr+'&sessionid='+sid, true);
		Ajax.send(null);
	}
}

function logout(sid){
	AjaxRequest();
	if (!Ajax)
		alert ('ERRO: Problemas com o pedido AJAX! Verifique se tem a opção Javascript activa no seu browser ou contacte o APMI!')
	else{
		Ajax.onreadystatechange = function(){
			if (Ajax.readyState == 4) {
				if (Ajax.status == 200) {
					window.open('index.php','_self')
				}
			}
		}
		Ajax.open('POST', 'include/validar.php?logout&sessionid='+sid, true);
		Ajax.send(null);
	}
}

function confirmarecuperacao(){
	
	var emailStr=document.getElementById("recemail").value;
	var checkTLD=1;
	var knownDomsPat=/^(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum)$/;
	var emailPat=/^(.+)@(.+)$/;
	var specialChars="\\(\\)><@,;:\\\\\\\"\\.\\[\\]";
	var validChars="\[^\\s" + specialChars + "\]";
	var quotedUser="(\"[^\"*\")";
	var atom=validChars + '+';
	var word="(" + atom + "|" + quotedUser + ")";
	var matchArray=emailStr.match(emailPat);					
	if(matchArray==null){
		alert("Por favor, verifique o seu endereço de email!");
		return false;
	}
	var user=matchArray[1];
	var domain=matchArray[2];
	for (i=0; i<user.length; i++){
		if (user.charCodeAt(i)>127){
			alert("Por favor, verifique o seu endereço de email!");
			return false;
		}
	}
	for (i=0; i<domain.length; i++){
		if (user.charCodeAt(i)>127){
			alert("Por favor, verifique o seu endereço de email!");
			return false;
		}
	}
	var domArr=domain.split(".");
	var len=domArr.length;
	if (checkTLD && domArr[domArr.length-1].length!=2 && domArr[domArr.length-1].search(knownDomsPat)==-1){
		alert("Por favor, verifique o seu endereço de email!");
		return false;
	}
	if(len<2){
		alert("Por favor, verifique o seu endereço de email!");
		return false;
	}
	
	document.recuperacao.submit();
}

function newsletter(sid){
	var emailStr=document.getElementById("newsletter").value;
	var checkTLD=1;
	var knownDomsPat=/^(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum)$/;
	var emailPat=/^(.+)@(.+)$/;
	var specialChars="\\(\\)><@,;:\\\\\\\"\\.\\[\\]";
	var validChars="\[^\\s" + specialChars + "\]";
	var quotedUser="(\"[^\"*\")";
	var atom=validChars + '+';
	var word="(" + atom + "|" + quotedUser + ")";
	var matchArray=emailStr.match(emailPat);					
	if(matchArray==null){
		alert("Por favor, verifique o seu endereço de email!");
		return false;
	}
	var user=matchArray[1];
	var domain=matchArray[2];
	for (i=0; i<user.length; i++){
		if (user.charCodeAt(i)>127){
			alert("Por favor, verifique o seu endereço de email!");
			return false;
		}
	}
	for (i=0; i<domain.length; i++){
		if (user.charCodeAt(i)>127){
			alert("Por favor, verifique o seu endereço de email!");
			return false;
		}
	}
	var domArr=domain.split(".");
	var len=domArr.length;
	if (checkTLD && domArr[domArr.length-1].length!=2 && domArr[domArr.length-1].search(knownDomsPat)==-1){
		alert("Por favor, verifique o seu endereço de email!");
		return false;
	}
	if(len<2){
		alert("Por favor, verifique o seu endereço de email!");
		return false;
	}
	
	AjaxRequest();
	if (!Ajax)
		alert ('ERRO: Problemas com o pedido AJAX! Verifique se tem a opção Javascript activa no seu browser ou contacte o APMI!')
	else{
		Ajax.onreadystatechange = function(){
			if (Ajax.readyState == 4) {
				if (Ajax.status == 200) {
					if(Ajax.responseText == 'ok')
						alert('Obrigado por ter subscrito a nossa newsletter.')
				}
			}
		}
		Ajax.open('POST', 'include/actions.php?what=newsletter&newsletter='+emailStr+'&sessionid='+sid, true);
		Ajax.send(null);
	}
}
