/**
 *	IEFP Javascript Library
 *
 *  Copyright (c) 2001 GE Capital IT Solutions
 */
// JavaScript Document

//defaults Dreamweaver - load, swap e restore de imagens
function MM_openBrWindow2(theURL,winName,features) { //v2.0
  window.open(theURL,winName,features);
}

function MM_openBrWindow(theURL,winName,features) { //v2.0
  window.open(theURL,winName,features,target);
}

function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}

//utilizado nas páginas de conduta
function MM_goToURL() { //v3.0
  var i, args=MM_goToURL.arguments; document.MM_returnValue = false;
  for (i=0; i<(args.length-1); i+=2) eval(args[i]+".location='"+args[i+1]+"'");
}

// RB 20060511 - Utilizado para definir qual o caminho a colocar no frame de topo
function CandidatoEntidade(str, link)
{
//	return 'texto= > <a target="Main" href="' + link + '">' + str + '</a>&Contexto=' + str;	  
	return 'texto=' + link + '&Contexto=' + str;	  
}

//RB 20060511 - Realiza encode sobre um determinado valor. Usado para passar caracteres especiais aatravés de querystring
function encode(val)
{
		 var encodedStr = '';
		 var i = 0;
		 while(i < val.length)
		 {
		 	encodedStr = encodedStr + "%" + decToHex(val.charCodeAt(i), 16);
			i = i + 1;
		 }	
	  	return encodedStr;
}

//RB encaminha uma funcionalidade dentro do frameset da aplicação.
function encaminha(path, val)
 {
	return "/IEFP/frameSet.jsp?path=" + path + "&parameters=" + encode(val);
 }

// Utilizado para o utente confirmar os pedidos de declarações
function changeAction(form,newAction){
	form.action.value = newAction;
	if(newAction=="NEXT")
	{
		if(!confirm("Tem a certeza que pretende continuar o pedido da declaração?"))
		{
			return false;
		}
	}
	return true;
}


//Utilizado para a entidade comunicar mais resultados de apresentações de utentes
function actualizar(form,action){
	form.action.value=action;
	return true;
}


//Utilizado para retirar a selecçao de tipos de cartas de condução (apenas permite escrever se tiver carta)
function clearSelection(form){
	if(!form.cartaConducao.options[2].selected){
		for(var i=0;i<form.cartaConducaoType.length;i++){
			form.cartaConducaoType.options[i].selected = false;
		}
    }
}

//Utilizado para criar janelas pop_up de ajuda com o tamanho definido 
function ajuda_popup(url,pageName){
	window.open(url, pageName, "width=5,height=250,resizable=no,scrollbars=no");
    return false;
}

var pop_up;

//Utilizado para criar janelas pop_up com o tamanho definido (ver melhor se sao precisas mais)
function open_popup(url,pageName){
	pop_up = window.open(url, pageName, "width=550,height=370,resizable=yes,scrollbars=yes");
    return false;
}

//PopUPs: cnps
function open_popup630(url,pageName){
	pop_up = window.open(url, pageName, "width=630,height=490,resizable=yes,scrollbars=yes");
    return false;
}

function open_popup645(url,pageName){
	pop_up = window.open(url, pageName, "width=645,height=336,resizable=yes,scrollbars=yes");
    return false;
}

//PopUps: cnps depois da pesquisa por palavra-chave
function open_popup630_370(url,pageName){
	pop_up = window.open(url, pageName, "width=630,height=370,resizable=yes,scrollbars=yes");
    return false;
}

//PopUPs: Freguesia; distrito; 
function open_popup350(url,pageName){
	pop_up = window.showModalDialog(url, pageName, "width=350,height=262,resizable=yes,scrollbars=yes");
    return false;
}

function open_popup350NoScroll(url,pageName){
//	try
//	{
	if(window.showModalDialog)
	{
	pop_up = window.showModalDialog(url, pageName, "dialogWidth:400px;dialogHeight:280px;resizable:no;scrollbars:no");
	}
	else
	{
	 pop_up = window.open(url,pageName,
'height=580px,width=400px,toolbar=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no,modal=yes');
	}
    return false;
}

function open_popupNoScroll(url, pageName, width, height){
	if (!width) 
	{
		width = 100;
	}

	if (!height) 
	{
		height = 100;
	}

	if(window.showModalDialog)
	{
		window.showModalDialog(url, pageName, "dialogWidth:" + width + "px;dialogHeight:" + height + "px;resizable:no;scrollbars:no");
	}
	else
	{
		window.open(url, pageName, "width=" + width + "px,height=" + height +"px,toolbar=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no,modal=yes");
	}
	
    return false;
}


//PopUPs:area de formação; area estudos
function open_popup500(url,pageName){
	pop_up = window.open(url, pageName, "width=500,height=311,resizable=yes,scrollbars=yes");
    return false;
}

//Utilizado para limpar todos os campos relativos a uma determinada área de formação na altura de inscrição
function clean(label,text,list,txarea)
{
	label.value="";
	text.value="";
	list.value="0";
	txarea.value="";
	return false;
}

//utilizado no pedido de anulacao de oferta para limpar o campo de texto que serve para especificar outros motivos (radio button)
function clearTextField(form)
{
	if(!form.motivo[form.motivo.length-1].checked)
		form.outros.value="";
	else
		form.outros.focus();
}

//utilizado para facilitar o preenchimento do formulário da candidatura a emprego
function changeCateg(motivo, categoria)
{
	if(motivo.value=='06' || motivo.value=='05' || motivo.value=='08')
    	{
    		categoria.value='1';
    	}
    	else if(motivo.value=='01' || motivo.value=='02')
    	{
    		categoria.value='2';
    	}
    	return false;
}


//utilizado para fechar as popups de ajuda
function fechar(){

    window.close();
    return false;
}

// Funçoes para alterar a CSS de referência
// retirado de: http://www.alistapart.com/articles/alternate
function setActiveStyleSheet(title) {
	var i, a, main;
	for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
		if(a.getAttribute("rel")!=null && a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title")) {
		a.disabled = true;
			if(a.getAttribute("title") == title) a.disabled = false;
		}
	}
}

function getActiveStyleSheet() {
	var i, a;
	for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
		if(a.getAttribute("rel")!= null && a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title") && !a.disabled) return a.getAttribute("title");
	}
	return null;
}

function getPreferredStyleSheet() {
	var i, a;
	for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
		if(a.getAttribute("rel")!=null && a.getAttribute("rel").indexOf("style") != -1
		&& a.getAttribute("rel").indexOf("alt") == -1
		&& a.getAttribute("title"))
		return a.getAttribute("title");
	}
	return null;
}

function createCookie(name,value,days) {
		if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

window.onload = function(e) {
	SetCookie(); // Código que passou para uma função para que possa ser chamada.
}

window.onunload = function(e) {
	var title = getActiveStyleSheet();
	createCookie("style", title, 365);
}
//Função que contem o código executado na função OnLoad para que passa ser utilizada nas páginas onde a Função OnLoad está a ser chamada
function SetCookie() {
	var cookie = readCookie("style");
	var title = cookie ? cookie : getPreferredStyleSheet();
	setActiveStyleSheet(title);
}

var cookie = readCookie("style");
var title = cookie ? cookie : getPreferredStyleSheet();
setActiveStyleSheet(title);
// FIM - Funçoes para alterar a CSS de referência

function EnableDisableElement(element, enable)
{
    if (enable)
    {
        element.disabled = false;
    }
    else
    {
        element.disabled = true;
    }
}

function ShowHideElement(element, show)
{
    if (show)
    {
        element.style.display = "block";
    }
    else
    {
        element.style.display = "none";        
    }
}

function UpdateSelectOptions(response, objId)
{
	var textValueArray = eval(response);
	var selectObject;
	if(typeof objId == 'object')
   	{
		selectObject = objId;
   	} 
   	else 
   	{
		selectObject = document.getElementById(objId);
   	}

   	selectObject.options.length=0;
   	for (var i = 0; i < textValueArray.length; i++)
  	{
		selectObject.options[i] = new Option(textValueArray[i][0], textValueArray[i][1]);
  	}
}

var debug =false;

/**
Browser Compatability function.
Returns the correct XMLHttpRequest depending on the current browser.
*/
function GetXmlHttp() {	
	var xmlhttp = false;
	if (window.XMLHttpRequest)
	{
		xmlhttp = new XMLHttpRequest();
	}
	else if (window.ActiveXObject)// code for IE
	{
		try 
		{
			xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
		} 
		catch (e) 
		{
			try 
			{
				xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (E) {
				xmlhttp=false;
			}
		}
	}
	
	return xmlhttp;
}

/**
<summary>
Gets the response stream from the passed url, and then calls the callbackFuntion passing the response and the div_ids.
</summary>
<param name="url">The url to make the request to get the response data.</param>
<param name="callbackFunction">The function to call after the response has been recieved. the response <b>must</b> always be the first argument to the function.</param>
<param name="params"> (optional) Any other parameters you want to pass to the functions. (Note: only constants/strings/globals can be passed as params, most variables will be out of scope.) </param>
</summary>
<example>
	<code>
		PassAjaxResponseToFunction('?getsomehtml=1', 'FunctionToHandleTheResponse', "\'div1\',\'div2\',\'div3\'');

		function FunctionToHandleTheResponse(response, d1, d2, d3){
	        var data = response.split(';');
	        document.getElementById(d1).innerHTML = data[0];
	        document.getElementById(d2).innerHTML = data[1];
	        document.getElementById(d3).innerHTML = data[2];
		}
	</code>
</example>
*/
function PassAjaxResponseToFunction(url, callbackFunction, params)
{	
	var xmlhttp = new GetXmlHttp();
	//now we got the XmlHttpRequest object, send the request.
	if (xmlhttp)
	{
		xmlhttp.onreadystatechange = function () 
		{
			if (xmlhttp && xmlhttp.readyState==4)
			{//we got something back..
				if (xmlhttp.status==200)
				{
					var response = xmlhttp.responseText;
					var functionToCall = callbackFunction+'(response,'+params+')';
					if(debug)
					{
						alert(response);
						alert (functionToCall);
					}
					eval(functionToCall);
				} 
				else if(debug) 
				{
					alert(xmlhttp.responseText);
				}
			}
		}
		xmlhttp.open("GET",url,true);
		xmlhttp.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT");
		xmlhttp.send(null);
	}
}


/**
///<summary>
///Sets the innerHTML property of obj_id with the response from the passed url./
///</summary>
///<param name="url">The url to make the request to get the response data.</param>
///<param name="obj_id">The object or the id of the object to set the innerHTML for.</param>
*/
function SetInnerHTMLFromAjaxResponse(url, obj_id)
{	
	var xmlhttp = new GetXmlHttp();
	//now we got the XmlHttpRequest object, send the request.
	if (xmlhttp)
	{
		xmlhttp.onreadystatechange = function () 
		{
			if (xmlhttp && xmlhttp.readyState==4)
			{//we got something back..
				if (xmlhttp.status==200)
				{
					if(debug)
					{
						alert(xmlhttp.responseText);
					}
					if(typeof obj_id == 'object')
					{
						obj_id.innerHTML = xmlhttp.responseText;
					} 
					else 
					{
						document.getElementById(obj_id).innerHTML = xmlhttp.responseText;
					}
				} 
				else if(debug)
				{
					alert(xmlhttp.responseText);
				}
			}
		}
		xmlhttp.open("GET",url,true);
		xmlhttp.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT");
		xmlhttp.send(null);
	}
}