//**************************
// EXTEND jQuery
//**************************
jQuery.fn.iframe=function(opt)
{
	return this.each(function()
	{
		var $this = jQuery(this);
		var cls = this.className;
		var ids = this.id;
		var opts = jQuery.extend( { name: ids, cls: cls, src: $this.attr('href') || $this.attr('src') }, opt || {});

        // convert anchor to span/div/whatever...
        var el = jQuery('<iframe name="' + opts.name + '" src="' + opts.src + '" class="' + opts.cls + '" frameborder="0" scrolling="auto" style="float:none;"><p>O seu <span class="i">browser</span> não está configurado para aceitar iframes ou objects. Para ver o conteúdo que deveria estar aqui <a href="' + opts.src + '" rel="external">veja esta página</a></p></iframe>');
		$this.after(el).remove();
    });
};

//cookies
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toGMTString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toGMTString(); // use expires attribute, max-age is not supported by IE
        }
        var path = options.path ? '; path=' + options.path : '';
        var domain = options.domain ? '; domain=' + options.domain : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};

//swapclass
$.fn.swapClass = function(c1, c2){
return this.each(function(){
var t = $(this);
(!t.is('.'+c1)) ?t.addClass(c1).removeClass(c2) : t.addClass(c2).removeClass(c1);
});
}

$.fn.extend({ reset: function()
{
    return this.each(function() { $(this).is('form') && this.reset(); })
}
});
/*
if(!Array.indexOf){
	Array.prototype.indexOf = function(obj, start){
		for(var i=(start||0); i<this.length; i++){
			if(this[i]==obj){
				return i;
			}
		}
	}
}
*/

//**************************
//Global functions
//**************************
var tSizes = new Array( "text1", "text2", "text3", "text4");
var default_tSize=tSizes[1];
var default_tStyle="widthNormal";
var cookieoptions = { path: '/', expires: 10 };

//PRELOAD IMAGES
if (document.images)
{
	preload_image_object = new Image();
	image_url = new Array();
	image_url[0] = "/xtra/template/ima/exp_whte.gif";
	image_url[1] = "/xtra/template/ima/cc_loader.gif";
	image_url[2] = "/xtra/template/css/jquery-ui.1.8.0/smoothness/images/ui-bg_flat_0_aaaaaa_40x100.png";
	image_url[3] = "/xtra/template/css/jquery-ui.1.8.0/smoothness/images/ui-bg_flat_75_ffffff_40x100.png";
	image_url[4] = "/xtra/template/css/jquery-ui.1.8.0/smoothness/images/ui-bg_glass_55_fbf9ee_1x400.png";
	image_url[5] = "/xtra/template/css/jquery-ui.1.8.0/smoothness/images/ui-bg_glass_65_ffffff_1x400.png";
	image_url[6] = "/xtra/template/css/jquery-ui.1.8.0/smoothness/images/ui-bg_glass_75_e6e6e6_1x400.png";
	image_url[7] = "/xtra/template/css/jquery-ui.1.8.0/smoothness/images/ui-bg_glass_75_dadada_1x400.png";
	image_url[8] = "/xtra/template/css/jquery-ui.1.8.0/smoothness/images/ui-bg_glass_95_fef1ec_1x400.png";
	image_url[9] = "/xtra/template/css/jquery-ui.1.8.0/smoothness/images/ui-bg_highlight-soft_75_cccccc_1x100.png";
	image_url[10] = "/xtra/template/css/jquery-ui.1.8.0/smoothness/images/ui-icons_2e83ff_256x240.png";
	image_url[11] = "/xtra/template/css/jquery-ui.1.8.0/smoothness/images/ui-icons_222222_256x240.png";
	image_url[12] = "/xtra/template/css/jquery-ui.1.8.0/smoothness/images/ui-icons_454545_256x240.png";
	image_url[13] = "/xtra/template/css/jquery-ui.1.8.0/smoothness/images/ui-icons_888888_256x240.png";
	image_url[14] = "/xtra/template/css/jquery-ui.1.8.0/smoothness/images/ui-icons_cd0a0a_256x240.png";

	var i = 0;
	for(i=0; i<=3; i++) 
		preload_image_object.src = image_url[i];
}  

function switchStylestyleText(styleName)
{
	var cookiestyleName=$.cookie('styletext');
	if (styleName=="less" || styleName=="more")
	{
		var i1=parseInt(cookiestyleName.replace(/text/gi, ''));
		var pos=i1-1;
		if (styleName=="less") pos=(pos==0)?pos:pos-1;
		if (styleName=="more") pos=(pos==tSizes.length-1)?pos:pos+1;
		var endstyleName=tSizes[pos];
	}
	else if (styleName=="start")
	{
		if (cookiestyleName==null) endstyleName=default_tSize;
		else var endstyleName=cookiestyleName;
	}
	$('link[rel*=style][title*=text]').each(function(i)
	{
			this.disabled = true;
			if (this.getAttribute('title') == endstyleName) this.disabled = false;
	});
	$.cookie('styletext', endstyleName,cookieoptions);

	return endstyleName;
};

function switchStylestyle(styleName)
{
		if (styleName=="start") styleName=$.cookie('stylewidth');
		if (styleName==null) styleName=default_tStyle;
		$('link[rel*=style][title*=width]').each(function(i)
		{
			this.disabled = true;
			if (this.getAttribute('title') == styleName) this.disabled = false;
		});
		$.cookie('stylewidth', styleName,cookieoptions);
};

function indexOf(needle, haystack)
{
	for (var i=0;i<haystack.length;i++)
		if (haystack[i] == needle) return i;
	return false;
};

function cokSession()
{
	var cookieName=$.cookie('ALEPH_SESSION_ID');

	if (cookieName!=$('#sessid').text())
	{
		$.cookie('ALEPH_SESSION_ID', $('#sessid').text(),cookieoptions);
	}
};

function open_window (loc)
{
	self.name="main";
	if ((navigator.appVersion.indexOf("MSIE 5.0") != -1) && (navigator.appName.indexOf("Explorer") != -1))
	{
		var w = window.open ("","win1","height=550,width=770,toolbar=no,scrollbars=yes,resizable=yes,status=yes");
		w.document.write("<html>\n");
		w.document.write('<body onLoad="window.location.href=');
		w.document.write("'" + loc + "';\n"); 
		w.document.write('"'); 
		w.document.write("</body>\n");
		w.document.write("</html>\n");
		w.document.close();
    }
	else { var w = window.open (loc,"win1","height=550,width=770,toolbar=no,scrollbars=yes,resizable=yes,status=yes"); }
	w.focus();
};

function open_window_medium (loc)
{
	self.name="main";
	if ((navigator.appVersion.indexOf("MSIE 5.0") != -1) && (navigator.appName.indexOf("Explorer") != -1))
	{
		var w = window.open ("","win1","height=350,width=450,toolbar=no,scrollbars=yes,resizable=yes,status=yes");
		w.document.write("<html>\n");
		w.document.write('<body onLoad="window.location.href=');
		w.document.write("'" + loc + "';\n"); 
		w.document.write('"'); 
		w.document.write("</body>\n");
		w.document.write("</html>\n");
		w.document.close();
    }
	else { var w = window.open (loc,"win1","height=350,width=450,toolbar=no,scrollbars=yes,resizable=yes,status=yes"); }
	w.focus();
};


function open_window_small (loc)
{
	self.name="main";
	if ((navigator.appVersion.indexOf("MSIE 5.0") != -1) && (navigator.appName.indexOf("Explorer") != -1))
	{
		var w = window.open ("","win1","height=225,width=208,toolbar=no,scrollbars=yes,resizable=yes,status=yes");
		w.document.write("<html>\n");
		w.document.write('<body onLoad="window.location.href=');
		w.document.write("'" + loc + "';\n"); 
		w.document.write('"'); 
		w.document.write("</body>\n");
		w.document.write("</html>\n");
		w.document.close();
    }
	else { var w = window.open (loc,"win1","height=225,width=208,toolbar=no,scrollbars=yes,resizable=yes,status=yes"); }
	w.focus();
};

function open_window_confirm (loc,frame)
{
	self.name=frame; 
	if ((navigator.appVersion.indexOf("MSIE 5.0") != -1) && (navigator.appName.indexOf("Explorer") != -1))
	{
		var w = window.open ("","win1","height=220,width=450,scrollbars,resizable");
		w.document.write("<html>\n");
		w.document.write('<body onLoad="window.location.href=');
		w.document.write("'" + loc + "';\n");
		w.document.write('"');
		w.document.write("</body>\n");
		w.document.write("</html>\n");
		w.document.close();
    }
	else { var w = window.open (loc,"win1","height=220,width=450,scrollbars,resizable"); }
	w.focus();
}

function googleTranslateElementInit()
{
	new google.translate.TranslateElement(
	{
		pageLanguage: 'pt',
		includedLanguages: 'de,es,fr,en'
	},
	'google_translate_element');
}

function mensagemCC(what,selector, elementid, msgtype, msgimage,msgwith, msghtml)
{
	if (elementid!="") { $('#'+elementid).remove(); elementid='id="'+elementid+'" '; }
	if (msgwith!="100%" && msgwith!="") msgwith='width:'+msgwith+';';
	else msgwith="";
	if (msghtml!='')
	{
		if (what=="prepend") $(selector).prepend('<div '+elementid+'class="'+msgtype+' ui-corner-all" style="'+msgwith+'padding: 0.4em;"><p><span class="'+msgimage+'" style="float: left;margin-right: 0.3em;"></span>'+msghtml+'</p></div>');
		else if (what=="append") $(selector).append('<div '+elementid+'class="'+msgtype+' ui-corner-all" style="'+msgwith+'padding: 0.4em;"><p><span class="'+msgimage+'" style="float: left;margin-right: 0.3em;"></span>'+msghtml+'</p></div>');
		else if (what=="before") $(selector).before('<div '+elementid+'class="'+msgtype+' ui-corner-all" style="'+msgwith+'padding: 0.4em;"><p><span class="'+msgimage+'" style="float: left;margin-right: 0.3em;"></span>'+msghtml+'</p></div>');
		else if (what=="after") $(selector).after('<div '+elementid+'class="'+msgtype+' ui-corner-all" style="'+msgwith+'padding: 0.4em;"><p><span class="'+msgimage+'" style="float: left;margin-right: 0.3em;"></span>'+msghtml+'</p></div>');
		else if (what=="html") $(selector).html('<div '+elementid+'class="'+msgtype+' ui-corner-all" style="'+msgwith+'padding: 0.4em;"><p><span class="'+msgimage+'" style="float: left;margin-right: 0.3em;"></span>'+msghtml+'</p></div>');
	}
};


function mensagem_MODAL(what,selector, v_title, v_icon, v_message)
{
	var r_message=	"<div id=\"dialog-message\" title=\""+v_title+"\">\n"+
					"	<p>\n"+
					"		<span class=\"ui-icon "+v_icon+"\" style=\"float:left; margin:0 7px 50px 0;\"></span>\n"+
							v_message+
					"	</p>\n"+
					"</div>\n";
	if (v_title!="")
	{
		if (what=="prepend") $(selector).prepend(r_message);
		else if (what=="append") $(selector).append(r_message);
		else if (what=="before") $(selector).before(r_message);
		else if (what=="html") $(selector).html(r_message);
		$("#dialog-message").dialog(
		{
			modal: true,
			buttons:
			{
				Ok: function()
				{ $(this).dialog('close'); }
			}
		});
	}
};


/* resto */
function isValidEmailAddress(emailAddress)
{
	var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
	return pattern.test(emailAddress);
}

function isValidCodigopostal(codigopostal)
{
	var pattern = new RegExp(/^([0-9]{4})(|\-([0-9]{3}))$/i);
	return pattern.test(codigopostal);
}

function isValidTelefone(telefone)
{
	var pattern = new RegExp(/^(|00([0-9]{2,3})( |)|\+([0-9]{2,3})( |)|\(([0-9]{2,3})\)( |))([0-9]{7,})$/i);
	return pattern.test(telefone);
}

function isValidUserPass(userpass)
{
	userpass=userpass.replace(/\@ciejd\.pt/,"");
	var pattern = new RegExp(/^[A-Za-z\d\.\-_@]{4,20}$/i);

	return pattern.test(userpass);
}

function limpacamposformulario(LNG,lang,pagina)
{
	$.each(LNG[lang][pagina], function(indice, valor)
	{
		if (indice!="page_title" && indice!="page_title2")
		{
			if ($("#"+indice).val() == valor) { $("#"+indice).val(""); }
		}
	});
}

function toTitleCase(str)
{
	str=str.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});

	//Particulas apassivantes
	str=str.replace(/ Se /g, " se ");
	str=str.replace(/\-Se /g, "-se ");

	//Preposições - http://gramaticaportuguesa.blogs.sapo.pt/5865.html
	str=str.replace(/ A /g, " a ");
	str=str.replace(/ Ante /g, " ante ");
	str=str.replace(/ Após /g, " após ");
	str=str.replace(/ Até /g, " até ");
	str=str.replace(/ Com /g, " com ");
	str=str.replace(/ Conforme /g, " conforme ");
	str=str.replace(/ Contra /g, " contra ");
	str=str.replace(/ Consoante /g, " consoante ");
	str=str.replace(/ De /g, " de ");
	str=str.replace(/ Desde /g, " desde ");
	str=str.replace(/ Durante /g, " durante ");
	str=str.replace(/ Em /g, " em ");
	str=str.replace(/ Excepto /g, " excepto ");
	str=str.replace(/ Entre /g, " entre ");
	str=str.replace(/ Mediante /g, " mediante ");
	str=str.replace(/ Para /g, " para ");
	str=str.replace(/ Perante /g, " perante ");
	str=str.replace(/ Por /g, " por ");
	str=str.replace(/ Salvo /g, " salvo ");
	str=str.replace(/ Sem /g, " sem ");
	str=str.replace(/ Segundo /g, " segundo ");
	str=str.replace(/ Sob /g, " sob ");
	str=str.replace(/ Sobre /g, " sobre ");
	//str=str.replace(/ Trás /g, " trás ");

	//Artigos definidos - http://gramaticaportuguesa.blogs.sapo.pt/5865.html
	str=str.replace(/ O /g, " o ");
	str=str.replace(/ A /g, " a ");
	str=str.replace(/ Os /g, " os ");
	str=str.replace(/ As /g, " as ");

	//Contração de preposições com artigos definidos - http://gramaticaportuguesa.blogs.sapo.pt/5865.html
	str=str.replace(/ Ao /g, " ao ");
	str=str.replace(/ À /g, " à ");
	str=str.replace(/ Aos /g, " aos ");
	str=str.replace(/ Às /g, " às ");
	str=str.replace(/ Do /g, " do ");
	str=str.replace(/ Da /g, " da ");
	str=str.replace(/ Dos /g, " dos ");
	str=str.replace(/ Das /g, " das ");
	str=str.replace(/ No /g, " no ");
	str=str.replace(/ Na /g, " na ");
	str=str.replace(/ Nos /g, " nos ");
	str=str.replace(/ Nas /g, " nas ");
	str=str.replace(/ Pelo /g, " pelo ");
	str=str.replace(/ Pela /g, " pela ");
	str=str.replace(/ Pelos /g, " pelos ");
	str=str.replace(/ Pelas /g, " pelas ");

	//Artigos indefinidos - http://gramaticaportuguesa.blogs.sapo.pt/5865.html
	str=str.replace(/ Um /g, " um ");
	str=str.replace(/ Uma /g, " uma ");
	str=str.replace(/ Uns /g, " uns ");
	str=str.replace(/ Umas /g, " umas ");

	//Contração de preposições com artigos indefinidos - http://gramaticaportuguesa.blogs.sapo.pt/5865.html
	str=str.replace(/ Dum /g, " dum ");
	str=str.replace(/ Duma /g, " duma ");
	str=str.replace(/ Duns /g, " duns ");
	str=str.replace(/ Dumas /g, " dumas ");
	str=str.replace(/ Num /g, " num ");
	str=str.replace(/ Numa /g, " numa ");
	str=str.replace(/ Nuns /g, " nuns ");
	str=str.replace(/ Numas /g, " numas ");

	//Conjunções subordinativas - http://www.prof2000.pt/users/drfilipeaz/PagsParali/FuncLing/conjuncao.htm
	str=str.replace(/ Que /g, " que ");
	str=str.replace(/ Quando /g, " quando ");
	str=str.replace(/ Porque /g, " porque ");

	//Conjunções coordenativas - http://www.prof2000.pt/users/drfilipeaz/PagsParali/FuncLing/conjuncao.htm
	str=str.replace(/ E /g, " e ");
	str=str.replace(/ Ou /g, " ou ");
	str=str.replace(/ Mas /g, " mas ");

    return str;
}

function criacampodata(fieldid) 
{
	var d = new Date();
	var curr_year = d.getFullYear();

	$("#"+fieldid).datepicker({
		dateFormat: 'yy-mm-dd',
		prevText: 'Anterior',
		nextText: 'Seguinte',
		monthNamesShort: ['Jan','Fev','Mar','Abr','Mai','Jun','Jul','Ago','Set','Out','Nov','Dez'],
		monthNames: ['Janeiro','Fevereiro','Março','Abril','Maio','Junho','Julho','Agosto','Setembro','Outubro','Novembro','Dezembro'],
		dayNamesMin: ['Do', 'Se', 'Te', 'Qu', 'Qu', 'Se', 'Sá'],
		dayNamesShort: ['Dom', 'Seg', 'Ter', 'Qua', 'Qui', 'Sex', 'Sáb'],
		dayNames: ['Domingo', 'Segunda-feira', 'Terça-feira', 'Quarta-feira', 'Quinta-feira', 'Sexta-feira', 'Sábado'],
		showAnim: 'blind',
		yearRange: '1900:'+curr_year,
		changeMonth: true,
		changeYear: true
	});
}

function criacampodata_pequeno(fieldid) 
{
	var d = new Date();
	var curr_year = d.getFullYear();
	var end_year = curr_year+10;

	$("#"+fieldid).datepicker({
		dateFormat: 'yy-mm-dd',
		prevText: 'Anterior',
		nextText: 'Seguinte',
		monthNamesShort: ['Jan','Fev','Mar','Abr','Mai','Jun','Jul','Ago','Set','Out','Nov','Dez'],
		monthNames: ['Janeiro','Fevereiro','Março','Abril','Maio','Junho','Julho','Agosto','Setembro','Outubro','Novembro','Dezembro'],
		dayNamesMin: ['Do', 'Se', 'Te', 'Qu', 'Qu', 'Se', 'Sá'],
		dayNamesShort: ['Dom', 'Seg', 'Ter', 'Qua', 'Qui', 'Sex', 'Sáb'],
		dayNames: ['Domingo', 'Segunda-feira', 'Terça-feira', 'Quarta-feira', 'Quinta-feira', 'Sexta-feira', 'Sábado'],
		showAnim: '',
		yearRange: '1900:'+end_year,
		changeMonth: true,
		changeYear: true
	});
}

function forms_predefined_value(LNG,what,formid)
{
	$.each(LNG[lang][what], function(indice, valor)
	{
		if (indice!="page_title" && indice!="page_title2")
		{
			if ($("#"+indice).val()==valor) { $("#"+indice).removeClass("inactive").addClass("inactive");}
			else if ($("#"+indice).val()=='') {$("#"+indice).addClass("inactive");$("#"+indice).val(valor); }
			else $("#"+indice).removeClass("inactive");
			$("#"+indice).bind("focus", function() { if ($(this).val()==valor) { $(this).val(""); $(this).removeClass("inactive");} })
			             .bind("blur", function() { if ($(this).val()=='') {$(this).addClass("inactive");$(this).val(valor); } });
		}
	});

	$("#"+formid).bind("submit", function(e)
	{
		if (formid!="fPe" && formid!="formCCLSpecial")
		{
			$.each(LNG[lang][what], function(indice, valor)
			{
				if (indice!="page_title" && indice!="page_title2")
				{
					if ($("#"+indice).val() == valor) { $("#"+indice).val(""); }
				}
			});
		}
		//Pesquisa catalogos
		else if (formid=="formCCLSpecial")
		{
			if (what=="Financial support")
			{
				$('#ccl_term').val('alldocuments');
				if ($('#partccl1').val()!="" && $("#partccl1").val()!=LNG[lang][what]["partccl1"]) $('#ccl_term').val($('#ccl_term').val()+" AND "+$('#partccl1').val())
				if ($('#partccl2').val()!="") $('#ccl_term').val($('#ccl_term').val()+" AND "+$('#partccl2').val())
				if ($('#partccl3').val()!="") $('#ccl_term').val($('#ccl_term').val()+" AND "+$('#partccl3').val())
			}
			else if (what=="Bibliographic")
			{
				if ($('#partccl1').val()!="" && $("#partccl1").val()!=LNG[lang][what]["partccl1"] && $('#partccl2').val()=="") $('#ccl_term').val($('#partccl1').val());
				else if ($('#partccl1').val()!="" && $("#partccl1").val()!=LNG[lang][what]["partccl1"] && $('#partccl2').val()!="") $('#ccl_term').val($('#partccl1').val()+" AND "+$('#partccl2').val());
				else if (($('#partccl1').val()=="" || $("#partccl1").val()==LNG[lang][what]["partccl1"]) && $('#partccl2').val()!="") $('#ccl_term').val($('#partccl2').val());
				else if (($('#partccl1').val()=="" || $("#partccl1").val()==LNG[lang][what]["partccl1"]) && $('#partccl2').val()=="") $('#ccl_term').val('WDT=(19790101->20201231)');
			}
			else
			{
				if ($("#ccl_term_cat").val() == "" || $("#ccl_term_cat").val() == LNG[lang][what]["ccl_term_cat"] || $("#ccl_term_cat").val().length < 3)
				{
					if ($('#caterr_search').length == 0) mensagemCC('append','label[for=ccl_term_cat]', 'caterr_search', 'ui-state-error ui-corner-all', 'ui-icon ui-icon-alert','46.8em', 'Tem de preencher o campo \'Expressão de pesquisa\' com mais de 3 caracteres.<br/>Exemplo: europa.');
					//alert(LNG_FillSearch);
					return false;
				}
			}
		}
		//Pesquisa geral
		else
		{
			if ($("#cPe").val() == "" || $("#cPe").val() == LNG[lang][what]["cPe"])
			{
				alert(LNG_FillSearch);
				return false;
			}
			else if ($("#cPe").val().length < 3 )
			{
				alert(LNG_FillSearchWord);
				return false;
			}
		}
		return true;
	});
}

function isSet( variable )
{
return( typeof( variable ) != 'undefined' );
}


function url_encode_text(str) {
return escape(str).replace(/\+/g,'%2B').replace(/%20/g, '+').replace(/\*/g, '%2A').replace(/\//g, '%2F').replace(/@/g, '%40');
}

function urldecode(str) {
str = unescape(str).replace(/\+/g, ' ');
return str;
}