
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_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_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];
		}
}

function MM_openBrWindow(theURL,winName,features) { //v2.0
  window.open(theURL,winName,features);
}

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]+"'");
}
function MM_popupMsg(msg) { //v1.0
	alert(msg);
}

/* Alterar a CLASS de um objecto */
function toggleClass(_id,_class)
{
	document.getElementById(_id).className = _class;
}

function html_entity_decode_all(str){
 var ta=document.createElement("textarea");
 ta.innerHTML=str.replace(/</g,"&lt;").replace(/>/g,"&gt;");
 return ta.value;
}

function html_entity_decode(str){
 var ta=document.createElement("textarea");
 ta.innerHTML=str.replace(/</g,"&lt;").replace(/>/g,"&gt;");
 return ta.value;
}


function rgb2hex(rgbString){

    var hexString = "";
    if (rgbString) {
        if((rgbString.indexOf("rgb"))!=-1) {

            var parts = rgbString.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
            // parts now should be ["rgb(0, 70, 255", "0", "70", "255"]

            delete (parts[0]);
            for (var i = 1; i <= 3; ++i) {
                parts[i] = parseInt(parts[i]).toString(16);
                if (parts[i].length == 1) parts[i] = '0' + parts[i];
            }
            hexString = parts.join('');

        } else if ((rgbString.indexOf("#"))!=-1) {
            hexString = rgbString.substring(1);
        }

    }
    return hexString;
}

// elementos a serem esticados a 100%
var time_stretch_portal_content;

function stretch_portal_content() {

	var rodapeInnerHeight = $('#rodape_interior').height();
	$('#corpo_interior').css("padding-bottom", rodapeInnerHeight);

	var alturaPrincipal = $('#corpo_interior').height();
	var alturaDocument = $(document).height();
	var alturaWindow = $(window).height();

	var alturaTotal = (alturaPrincipal>alturaDocument) ? alturaPrincipal : alturaDocument;
    
	if (alturaWindow>alturaPrincipal) {
		alturaTotal=alturaWindow
	}

	if (alturaPrincipal<alturaDocument && alturaWindow<alturaDocument) {
		alturaTotal=alturaDocument
	}

    alturaTotal=(alturaPrincipal+(rodapeInnerHeight*1.25));

    if (alturaTotal<alturaWindow) {
		alturaTotal=alturaWindow;
	}


    //$("title").text(" rodapeInnerHeight:"+rodapeInnerHeight+" "+"alturaPrincipal:"+alturaPrincipal+" "+"alturaDocument:"+alturaDocument+" "+"alturaWindow:"+alturaWindow+" "+"alturaTotal:"+alturaTotal);

	$('#fundo_sombras').height(
		alturaTotal - $('#fundo_topo').height()
		);

	var rodapeNewHeight = ( alturaTotal - rodapeInnerHeight );
	$('#rodape').css("top", rodapeNewHeight);

	// verificar se algo mudou as alturas
	//setTimeout("stretch_portal_content()", 200 );
         time_stretch_portal_content = setTimeout(function(){
            stretch_portal_content();
         }, 200);

}

// mostrar submenus ou activar link
var default_main_sub_menu_id = "";
function default_main_sub_menu(){
	$(".sub_main_menu").each(function () {
		if ( $(this).is(':visible')){
			default_main_sub_menu_id = $(this).attr('id');
		}
	});
}

var t;
function hide_main_sub_menu(){
	$(".sub_main_menu").hide();

	if (default_main_sub_menu_id!="" && $('#'+default_main_sub_menu_id) ) {
		$('#'+default_main_sub_menu_id).show();
	}
}

function stopTimeout(){
	clearTimeout(t);
}

// mostrar submenus ou activar link
function show_main_sub_menu(who){

	if (who!="") {

		stopTimeout();
		hide_main_sub_menu();

		$('#sub_menu_principal_'+who).show();

		if (default_main_sub_menu_id!="" && $('#'+default_main_sub_menu_id) && default_main_sub_menu_id!="sub_menu_principal_"+who ) {
			$('#'+default_main_sub_menu_id).hide();
		}


	} else {
		t=setTimeout("hide_main_sub_menu()",100);
	}



	return false;
}


//funcao home links 
function home_links(){
	$('.close_link').mouseover(function() {
		$('.close_link #link_msg').show();
		$('.open_link').removeClass('open_link').addClass('close_link');
		$(this).removeClass('close_link')
		$(this).addClass('open_link');
		$('.close_link #link_msg').hide();
            
	});
	$("#link").addClass('open_link').removeClass('close_link');
	$("#link_msg").show();
}


//funcao home slideshow 
function home_slideshow(){
	
	
	var time_slideshow = new Array();
	
	$(".li_slideshow").each(function (index) {
			time_slideshow[index] = $(this).attr('alt');
	});	

	
	
	//alert(time_slideshow.join('\n'));
    if (typeof(time_slideshow)=='object'&&(time_slideshow instanceof Array)) {

        $('.anythingSlider').anythingSlider({
            easing: "easeInQuad",        // Anything other than "linear" or "swing" requires the easing plugin
            autoPlay: true,                 // This turns off the entire FUNCTIONALY, not just if it starts running or not.
            delay: 6000,                    // How long between slide transitions in AutoPlay mode
            startStopped: false,            // If autoPlay is on, this can force it to start stopped
            animationTime: 600,             // How long the slide transition takes
            hashTags: true,                 // Should links change the hashtag in the URL?
            buildNavigation: true,          // If true, builds and list of anchor links to link to each slide
            pauseOnHover: true,             // If true, and autoPlay is enabled, the show will pause on hover
            startText: "Go",                // Start text
            stopText: "Stop",               // Stop text
            navigationFormatter: null,      // Details at the top of the file on this use (advanced use)
			timeSlideshow: time_slideshow	// Array with time for each slide (useful for videos)
        });

    }
}

//funcao home slideshow agenda
function home_slideshow_agenda(){

		$('.anythingSliderHomeAgenda').height($('.anythingSliderHomeAgenda .wrapper ul').height());

        $('.anythingSliderHomeAgenda').anythingSlider({
            easing: "easeInQuad",        // Anything other than "linear" or "swing" requires the easing plugin
            autoPlay: true,                 // This turns off the entire FUNCTIONALY, not just if it starts running or not.
            delay: 6000,                    // How long between slide transitions in AutoPlay mode
            startStopped: false,            // If autoPlay is on, this can force it to start stopped
            animationTime: 600,             // How long the slide transition takes
            hashTags: true,                 // Should links change the hashtag in the URL?
            buildNavigation: true,          // If true, builds and list of anchor links to link to each slide
            pauseOnHover: true,             // If true, and autoPlay is enabled, the show will pause on hover
            startText: "Go",                // Start text
            stopText: "Stop",               // Stop text
            navigationFormatter: null       // Details at the top of the file on this use (advanced use)
        });

}


//home_slideshow_noticias
function home_slideshow_noticias(){

		$('.anythingSliderHomeNoticias').height($('.anythingSliderHomeNoticias .wrapper ul').height());

        $('.anythingSliderHomeNoticias').anythingSlider({
            easing: "easeInQuad",        // Anything other than "linear" or "swing" requires the easing plugin
            autoPlay: true,                 // This turns off the entire FUNCTIONALY, not just if it starts running or not.
            delay: 6000,                    // How long between slide transitions in AutoPlay mode
            startStopped: false,            // If autoPlay is on, this can force it to start stopped
            animationTime: 600,             // How long the slide transition takes
            hashTags: true,                 // Should links change the hashtag in the URL?
            buildNavigation: true,          // If true, builds and list of anchor links to link to each slide
            pauseOnHover: true,             // If true, and autoPlay is enabled, the show will pause on hover
            startText: "Go",                // Start text
            stopText: "Stop",               // Stop text
            navigationFormatter: null       // Details at the top of the file on this use (advanced use)
        });

}


// mudar o estilo das listagem em noticias/eventos
function hover_news(){
	$(".noticias_linhas_listagens").hover(
        function () {

            //alert($(this).height()+" "+$(this).outerHeight()+" "+$(this).innerHeight());


            if ($.browser.msie && $.browser.version<"8") {
                // todo...
            } else {
                noticias_linhas_listagens_height = $(this).height();
                $(this).children(".noticias_bloco_conteudo_listagens").height(noticias_linhas_listagens_height);
            }
			$(this).children(".noticias_bloco_conteudo_listagens").removeClass('noticias_bloco_conteudo_listagens').addClass('noticias_bloco_conteudo_listagens_hover');
		},
		function () {
			$(this).children(".noticias_bloco_conteudo_listagens_hover").removeClass('noticias_bloco_conteudo_listagens_hover').addClass('noticias_bloco_conteudo_listagens');
		}
	);
}

function make_datepicker() {

    this_class = ".datepicker";
	
	if ( ( $(this_class).length ) > 0 )
	{
		if($(this_class).attr('name') === undefined || $(this_class).attr('name') === false) {
			// todo...
		} else {
			this_attribute = $(this_class).attr('name');
		}

		if (this_attribute) {

			if((this_attribute.indexOf("f_data_nascimento"))>=0 || (this_attribute.indexOf("f_data_de_nascimento"))>=0) {

				var d = new Date();
				end_year = d.getFullYear();
				start_year = (end_year-120);

				$(this_class).datepicker({
							yearRange: start_year+':'+end_year,
							maxDate: '-5Y',
							dateFormat: 'yy-mm-dd',
							firstDay: 1,
							hideIfNoPrevNext: true,
							showButtonPanel: true,
							constrainInput: true,
							changeMonth: true,
							changeYear: true
						});
			} else {
				$(this_class).datepicker({
							dateFormat: 'yy-mm-dd',
							firstDay: 1,
							hideIfNoPrevNext: true,
							showButtonPanel: true,
							constrainInput: true,
							changeMonth: true,
							changeYear: true
						});
			}

		}

	}

}

function showHide_acordeao(self,who) {

    if ( $('#show_hide_acordeao_'+who).is(':hidden')) {
        $('.show_hide_acordeao_items').hide(0,function () {
            $('#show_hide_acordeao_'+who).show(0);

            $('.div_acordeao_titulo').removeClass('div_acordeao_titulo_aberto');
            $('.div_acordeao_titulo').addClass('div_acordeao_titulo_fechado');

            $(self).removeClass('div_acordeao_titulo_fechado');
            $(self).addClass('div_acordeao_titulo_aberto');

        });
    } else {
        $('.show_hide_acordeao_items').hide(0);
            $(self).removeClass('div_acordeao_titulo_aberto');
            $(self).addClass('div_acordeao_titulo_fechado');
    }
}



function showHide_projecto(self,who) {
	
	$('.show_hide_projecto_html').html('+');
	$('.show_hide_projecto_items_sep').show(0);

    if ( $('#show_hide_projecto_'+who).is(':hidden')) {
        $('.show_hide_projecto_items').hide(0,function () {
            $('#show_hide_projecto_'+who).show(0);
			$('#show_hide_projecto_html_'+who).html('-');
			$('#agenda_sep_menu_'+who).hide(0);
			$('#spacer_'+who).hide(0);
        });
    } else {
        $('.show_hide_projecto_items').hide(0);
		$('.show_hide_projecto_html').html('+');
    }
}



// Parceiros - Slider Home jcarousel
function mycarousel_initCallback(carousel)
{
    // Pause autoscrolling if the user moves with the cursor over the clip.
    carousel.clip.hover(function() {
        carousel.stopAuto();
    }, function() {
        carousel.startAuto();
    });
};

function mycarousel_assinaturas_rodape_itemVisibleInCallback(carousel, item, idx, state)
{
	parent_id = item.parentNode.id;
	
	this_title = $('#'+parent_id+' li[jcarouselindex|="' + idx + '"] a img').attr('title');	

	$('#'+parent_id+"_txt").html(this_title);
	
};



function open_flipbook(){

    $('.doc_folder').click(function() {

        var flip_url = $(this).attr('href');

        var ran_number=Math.floor(Math.random()*10000);

        var htmlStr = '<div id="box_'+ran_number+'" style="position:fixed;display:none;width:90%;height:90%;" ><a class="boxclose" id="boxclose"  href="javascript:void(close_overlay());"></a><iframe width="100%" height="100%" id="id_flipbook'+ran_number+'" name="frm_flipbook'+ran_number+'" src="'+flip_url+'" frameborder="0" scrolling="no" marginheight="0" marginwidth="0"></div>';

        $('#overlay').css('display', 'block');

        $('#overlay_box').html("");

        $(htmlStr).appendTo('#overlay_box');


        $('#overlay_box').css('display', 'block');
        $('#box_'+ran_number).css('display', 'block');


        window_height = $( window ).height();
        overlay_box_height = $('#box_'+ran_number).height();

        toMiddle =  ( ( window_height - overlay_box_height) / 2 );

        toMiddle = (toMiddle>0) ? toMiddle : 10;


        window_width = $( window ).width();
        overlay_box_width = $('#box_'+ran_number).width();

        toCenter =  ( ( window_width - overlay_box_width) / 2 );

        toCenter = (toCenter>0) ? toCenter : 10;

        $('#box_'+ran_number).css('left',toCenter);

        $('#box_'+ran_number).animate({'top': toMiddle},500);

        return false;
    });

}

function open_overlay(id){

    $('#overlay').css('display', 'block');
    var htmlStr = $('#box_'+id).html();
    $('#overlay_box').html(htmlStr);
    $('#overlay_box').css('display', 'block');
    $('#video_container_p_'+id).css('display', 'block');

    window_height = $( window ).height();
    overlay_box_height = $('#overlay_box').height();

    toCenter =  ( ( window_height - overlay_box_height) / 2 );

    toCenter = (toCenter>0) ? toCenter : 10;

    $('#overlay_box').animate({'top': toCenter},500);
}


function close_overlay(){
    $('#overlay').css('display', 'none');
    $('#overlay_box').css('display', 'none');
    $('#overlay_box').html('');
}



function choose_new_theme(id){
    //$('#temas').detach().appendTo($('#img_user_'+id));$('#temas').show();

    get_off = $('#'+id).offset();

    set_top = get_off.top+45;
    set_left = get_off.left+5;

    $('#temas').detach().appendTo($('body'));

    $('#temas').css({'top': set_top, 'left': set_left, 'z-index': '9'})

    $('#temas_id').html(id);

    $('#temas').show();
}

function select_new_theme(theme_id,theme_color,theme_text){

    //$('.imagem_div_choosed').hide();
    //$('.imagem_bucket').show();
    active = $('#temas_id').html();

    $('.imagem_div_choosed').not('.imagem_div_cor_selected').hide();
    $('.imagem_bucket').not('.imagem_div_cor_selected').show();

    $('#'+active).closest('.imagem_div').find('.imagem_div_choosed').show();
    $('#'+active).closest('.imagem_div').find('.imagem_bucket').hide();

    //$('.imagem_div_choosed .imagem_div_cor_selected').show();
    //$('.imagem_bucket .imagem_div_cor_selected').hide();

    //$('.imagem_div_choosed').hasClass('imagem_div_cor_selected').show('slow');
    //$('.imagem_bucket').hasClass('imagem_div_cor_selected').hide('slow');
    //$(who).closest('.imagem_div').find('.imagem_bucket .imagem_div_cor_selected').hide();

    //$('.imagem_div_cor').not('.imagem_div_cor_selected').css('background', '');



    $('#'+active).closest('.imagem_div').find('.imagem_div_cor').css('background', theme_color);
    $('#'+active).closest('.imagem_div').find('.imagem_div_txt').html(theme_text);
    $('#'+active).closest('.imagem_div').find('.imagem_div_id').html(theme_id);
    $('#temas').hide();
}


function apply_new_theme(logo_type,logo_id,div_id){

    theme_id = $('#'+div_id).closest('.imagem_div').find('.imagem_div_id').html();

    location.href="index.php?op=29&fenviar=1&logotipo_tipo="+logo_type+"&logotipo="+logo_id+"&tema="+theme_id;

    return false;
}

function mensagens_personalizacao() {

    msg_personalizacao_html = "";
    msg_personalizacao_html = $('#msg_personalizacao').html();

    if (msg_personalizacao_html) {
         setTimeout(function(){
             $('#msg_personalizacao').hide('slow');
         }, 3000);
    }
    
}


function custom_jconfirm_link(titulo, texto, link, btn_ok, btn_cancel){

    backup_okButton = $.alerts.okButton;
    backup_cancelButton = $.alerts.cancelButton;

    $.alerts.okButton=btn_ok;
    $.alerts.cancelButton=btn_cancel;

    jConfirm(texto, titulo,function(r) {
            if(r) {
                location.href=link;
            }
            return false;
        }
    );
    // repor valores originais
    $.alerts.okButton=backup_okButton;
    $.alerts.cancelButton=backup_cancelButton;

    $('#popup_ok').css('width','auto');
    $('#popup_cancel').css('width','auto');

    return false;

}


function custom_jconfirm_download(titulo, texto, btn_ok, btn_cancel, logo_type, logo_id, btn_print){

    backup_okButton = $.alerts.okButton;
    backup_cancelButton = $.alerts.cancelButton;
    backup_showPrintButton = $.alerts.showPrintButton;    

    $.alerts.okButton=btn_ok;
    $.alerts.cancelButton=btn_cancel;
    $.alerts.printButton=btn_print;    
    $.alerts.showPrintButton=true;

    jConfirm(texto, titulo,function(r) {
            if(r) {

                $.alerts.showPrintButton=true;
                $.alerts.okButton=$("#btn_send").html();
                $.alerts.cancelButton=$("#btn_cancel").html();

                jPrompt($("#motivo_txt").html(), '', '',function(rr) {

                        $.alerts.okButton=backup_okButton;
                        $.alerts.cancelButton=backup_cancelButton;
                        $.alerts.showPrintButton=backup_showPrintButton;                        
                        rr = $.trim(rr);

                        if(rr) {
                            
                            $.get("index.php", {fenviar: "1", op: "31", text: rr, logotipo: logo_id, logotipo_tipo: logo_type},
                                function(data){

                                     if((data.indexOf("index.php"))!=-1) {
                                         // todo ok
                                        if ( $.browser.msie && (parseInt($.browser.version, 10)<9) ) {

                                            str_link = $("#link_download").html();
                                            str_link = str_link.replace("#LINK#", data);

                                            $.alerts.okButton=$("#btn_cancel").html();
                                            jAlert(str_link, '');
                                        } else {
                                            location.href=data;
                                        }

                                     } else {
                                         // erro...
                                         jAlert(data, '');
                                     }

                            });



                        } else {
                            jAlert($("#motivo_erro").html(), '');
                        }
                        return false;
                    }
                );
                $('#popup_ok').css('width','auto');
                // esconder o botao de cancelar...
                $('#popup_cancel').css('display','none');

            }
            return false;
        }
    );
    // repor valores originais
    $.alerts.okButton=backup_okButton;
    $.alerts.cancelButton=backup_cancelButton;
    $.alerts.showPrintButton=backup_showPrintButton;     

    $('#popup_ok').css('width','auto');
    $('#popup_cancel').css('width','auto');
    $('#popup_print').css('width','auto');  

    return false;

}




function custom_jalert_checkbox(titulo, texto, id_cb, btn_ok, btn_cancel, btn_print){

    backup_okButton = $.alerts.okButton;
    backup_cancelButton = $.alerts.cancelButton;
    backup_showPrintButton = $.alerts.showPrintButton;    

    $.alerts.okButton=btn_ok;
    $.alerts.cancelButton=btn_cancel;
    $.alerts.printButton=btn_print;
	if (btn_print=="") {
		$.alerts.showPrintButton=null;
	} else {
		$.alerts.showPrintButton=true;
	}
    

    jConfirm(texto, titulo,function(r) {
            if(r) {
				$('#'+id_cb).attr('checked', true);
            } else {
				$('#'+id_cb).attr('checked', false);
			}
            return false;
        }
    );
    // repor valores originais
    $.alerts.okButton=backup_okButton;
    $.alerts.cancelButton=backup_cancelButton;
    $.alerts.showPrintButton=backup_showPrintButton;     

    $('#popup_ok').css('width','auto');
    $('#popup_cancel').css('width','auto');
    $('#popup_print').css('width','auto');  

    return false;

}


function form_files(fFile, fTxt) {
	var file="";
	var anexo = document.getElementById(fFile);
	var anexo_txt = document.getElementById(fTxt);
	file=anexo.value;
	anexo_txt.value=file;
}


function add_bookmark(title, txt_alternative){
    if (document.getElementsByTagName) {
        titleElement = document.getElementsByTagName('title')[0];
        if ( !!titleElement.childNodes.length ) {
            title = titleElement.firstChild.data;
        }
    }
    var url = location.href;
    if (document.all) { // Para o IE
        window.external.AddFavorite(url, title);
    } else if (window.sidebar) { // Para o Firefox
        window.sidebar.addPanel(title, url, "");
    } else if( window.opera && window.print ) {
        var mbm = document.createElement('a');
        mbm.setAttribute('rel','sidebar');
        mbm.setAttribute('href',url);
        mbm.setAttribute('title',title);
        mbm.click();
    } else { // Para outros browsers
        alert(txt_alternative);
    }
}

function printId(id) {
   $('#'+id+' > div').clone().appendTo('#'+id+' > div').css({'height': '100%','min-height': '100%','max-height': '100%', 'font-size': '9px'}).printElement({overrideElementCSS: true}).css({'display': 'none'});
}



function start_upload(who,text){

        var ran_number=Math.floor(Math.random()*10000);

        var htmlStr = '<div id="box_'+ran_number+'" style="position:fixed;display:none;z-index:11;" ><div style="width:380px; margin:20px 0px;"><div id="caixa_mensagem" class="msgBoxGreen"><div id="msg_cse" class="msgCSEGreen"></div><div id="msg_csd" class="msgCSDGreen"></div><div id="msg_cie" class="msgCIEGreen"></div><div id="msg_cid" class="msgCIDGreen"></div><table width="380" height="50" border="0" cellpadding="0" cellspacing="0"><tr><td width="80" class="msgUploadGreen">&nbsp;</td><td width="300" class="msgTextGreen" style="padding-left:15px;">'+text+'</td></tr></table></div></div></div>';


		$('#overlay').removeAttr('onclick');
		$('#overlay').css('display', 'block');


        $(htmlStr).appendTo('body');

        $('#box_'+ran_number).css('display', 'block');


        window_height = $( window ).height();
        overlay_box_height = $('#box_'+ran_number).height();

        toMiddle =  ( ( window_height - overlay_box_height) / 2 );

        toMiddle = (toMiddle>0) ? toMiddle : 10;


        window_width = $( window ).width();
        overlay_box_width = $('#box_'+ran_number).width();

        toCenter =  ( ( window_width - overlay_box_width) / 2 );

        toCenter = (toCenter>0) ? toCenter : 10;

        $('#box_'+ran_number).css('left',toCenter);
		
        $('#box_'+ran_number).css('top',toMiddle);		

		who.submit();

}


function autoSelect(selectTarget) {
 	if(selectTarget != null && ((selectTarget.childNodes.length == 1
      && selectTarget.childNodes[0].nodeName == "#text") || (selectTarget.tagName == "INPUT"
      && selectTarget.type == "text"))) {
  		if(selectTarget.tagName == 'TEXTAREA' || (selectTarget.tagName == "INPUT" && selectTarget.type == "text")) {
  			 selectTarget.select();
  		} else if(window.getSelection) { // FF, Safari, Opera
   			var sel = window.getSelection();
   			var range = document.createRange();
   			range.selectNode(selectTarget.firstChild);
   			sel.removeAllRanges();
   			sel.addRange(range);
  		} else { // IE
   			document.selection.empty();
   			var range = document.body.createTextRange();
   			range.moveToElementText(selectTarget);
   			range.select();
  		}
 	}
}

function custom_lightbox_finish() {
    $('#jquery-lightbox').remove();
    $('#jquery-overlay').fadeOut(function() {$('#jquery-overlay').remove();});
    $('embed, object, select').css({'visibility': 'visible'});
}

function linkShareMultimedia(linkShareArray) {

	for (key in linkShareArray) {
			eval(key+" = '"+linkShareArray[key]+"';")
	}

	
	windowLocation = window.location+"";
	
	// limpar codigo antigo
	windowLocation = windowLocation.replace( /#.*/, "");
	
	// adicionar o correcto
	windowLocation += "#"+item_id;
	
	// limpar parametros vazios
	windowLocation = windowLocation.replace( /&sup=\d+/, "");
	windowLocation = windowLocation.replace( /kword_cat=&/, "");
	windowLocation = windowLocation.replace( /&kword_cat=#/, "#");	
	
	windowLocationEscaped = escape(windowLocation);	
	
	if (box_type=="lightbox") {
		
		html = '<div style="padding:0 0 10px 10px;text-align:left;background-color:#ffffff;font-size:11px;" onClick="return false;" id="box-container-custom_links"><div><iframe src="//www.facebook.com/plugins/like.php?href='+windowLocationEscaped+'&amp;send=false&amp;layout=standard&amp;font=lucida+grande&amp;width=760&amp;show_faces=false&amp;action=like&amp;colorscheme=dark&amp;font&amp;height=35&amp;locale='+locale+'" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:760px; height:35px;" allowTransparency="true"></iframe></div><div style="background-color:#ffffff;color:gray;font-size:11px;">'+link_partilha_txt+': <span style="font-size:11px;background-color:#ffffff;color:gray;">'+windowLocation+'</span></div><div class="fclear"></div></div>';

		$('#lightbox-container-image-data').after(html);


		$('#box-container-custom_links span').bind('dblclick', function () {
			autoSelect(this);
		  });		  

		$('#box-container-custom_links').bind('mouseover', function () {
			$("#jquery-overlay").unbind('click');
			$("#jquery-lightbox").unbind('click');
		  });

		$('#box-container-custom_links').bind('mouseout', function () {
			$("#jquery-overlay").bind('click', function() {
					custom_lightbox_finish();
				});
			$("#jquery-lightbox").bind('click', function() {
					custom_lightbox_finish();
				});
		  });  
		  
		  
	  } else if (box_type=="overlaybox") {
		  
		  html='<div style="padding:0 0 10px 10px;text-align:left;background-color:#000000;font-size:11px;" id="box-container-custom_links"><div><iframe src="//www.facebook.com/plugins/like.php?href='+windowLocationEscaped+'&amp;send=false&amp;layout=standard&amp;font=lucida+grande&amp;width=760&amp;show_faces=false&amp;action=like&amp;colorscheme=dark&amp;font&amp;height=35&amp;locale='+locale+'" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:760px; height:35px;" allowTransparency="true"></iframe></div><div style="background-color:#000000;color:gray;font-size:11px;">'+link_partilha_txt+': <span style="font-size:11px;background-color:#000000;color:gray;">'+windowLocation+'</span></div><div class="fclear"></div></div>';
		  
		  $('#overlay_box').append(html);	  		  
	  }

	  $('#box-container-custom_links span').bind('dblclick', function () {
		autoSelect(this);
	  });


}



var BrowserDetect = {
	init: function () {
		this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
		this.version = this.searchVersion(navigator.userAgent)
			|| this.searchVersion(navigator.appVersion)
			|| "an unknown version";
		this.OS = this.searchString(this.dataOS) || "an unknown OS";
	},
	searchString: function (data) {
		for (var i=0;i<data.length;i++)	{
			var dataString = data[i].string;
			var dataProp = data[i].prop;
			this.versionSearchString = data[i].versionSearch || data[i].identity;
			if (dataString) {
				if (dataString.indexOf(data[i].subString) != -1)
					return data[i].identity;
			}
			else if (dataProp)
				return data[i].identity;
		}
	},
	searchVersion: function (dataString) {
		var index = dataString.indexOf(this.versionSearchString);
		if (index == -1) return;
		return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
	},
	dataBrowser: [
		{
			string: navigator.userAgent,
			subString: "Chrome",
			identity: "Chrome"
		},
		{string: navigator.userAgent,
			subString: "OmniWeb",
			versionSearch: "OmniWeb/",
			identity: "OmniWeb"
		},
		{
			string: navigator.vendor,
			subString: "Apple",
			identity: "Safari"
		},
		{
			prop: window.opera,
			identity: "Opera"
		},
		{
			string: navigator.vendor,
			subString: "iCab",
			identity: "iCab"
		},
		{
			string: navigator.vendor,
			subString: "KDE",
			identity: "Konqueror"
		},
		{
			string: navigator.userAgent,
			subString: "Firefox",
			identity: "Firefox"
		},
		{
			string: navigator.vendor,
			subString: "Camino",
			identity: "Camino"
		},
		{		// for newer Netscapes (6+)
			string: navigator.userAgent,
			subString: "Netscape",
			identity: "Netscape 6+"
		},
		{
			string: navigator.userAgent,
			subString: "MSIE",
			identity: "Internet Explorer",
			versionSearch: "MSIE"
		},
		{
			string: navigator.userAgent,
			subString: "Gecko",
			identity: "Mozilla",
			versionSearch: "rv"
		},
		{ 		// for older Netscapes (4-)
			string: navigator.userAgent,
			subString: "Mozilla",
			identity: "Netscape < 4.9",
			versionSearch: "Mozilla"
		}
	],
	dataOS : [
		{
			string: navigator.userAgent,
			subString: "Windows NT 6.1",
			identity: "Windows 7",
			versionSearch: "Windows NT 6.1"
		},		
		{
			string: navigator.userAgent,
			subString: "Windows NT 6.0",
			identity: "Windows Vista",
			versionSearch: "Windows NT 6.0"
		},		
		{
			string: navigator.userAgent,
			subString: "Windows NT 5.1",
			identity: "Windows XP",
			versionSearch: "Windows NT 5.1"
		},	
		{
			string: navigator.platform,
			subString: "Win",
			identity: "Windows"
		},
		{
			string: navigator.platform,
			subString: "Mac",
			identity: "Mac"
		},
		{
			string: navigator.platform,
			subString: "iPhone",
			identity: "iPhone/iPod"
		},
		{
			string: navigator.platform,
			subString: "Linux",
			identity: "Linux"
		}
	]

};
BrowserDetect.init();
//alert( BrowserDetect.browser );
//alert( BrowserDetect.version );
//alert( BrowserDetect.OS );




$(document).ready( function() {

	// esticar conteudos
	stretch_portal_content();
	//$(window).resize( stretch_portal_content );

	// id do submenu selecionado
	default_main_sub_menu();
    
	// Home links
	home_links();
    
	// Slideshow home
	home_slideshow();
	home_slideshow_agenda();
	home_slideshow_noticias();

	// mudar o estilo das listagem em noticias/eventos
	hover_news();

    // abre possiveis flipbooks numa iframe interna
    open_flipbook();

	// Substitui todos os inputs do tipo checkbox pela imagem pretendida
	$('input:checkbox').checkbox();
	$('input:radio').checkbox();

	// insere um calendario com a class "datepicker""
	make_datepicker();

    // Parceiros - Slider Home
    $('#mycarousel').jcarousel({
        auto: 3,
        animation:1,
        scroll:1,
        wrap: 'last',
        initCallback: mycarousel_initCallback
    });

    $('#temas').mouseleave(function() {
      $('#temas').hide();
    });
	
	$(".frmSelect.hidden, .frmSelectAgenda.hidden, .frmSelectBig.hidden").keypress(function(event) {
	  if ( event.which == 13 ) {
		 event.preventDefault();
		 $(this).hide();
	   }
	});
	$(".frmSelect.hidden, .frmSelectAgenda.hidden, .frmSelectBig.hidden").click(function() {
		 $(this).hide();
	});	
	$(".frmSelect.hidden, .frmSelectAgenda.hidden, .frmSelectBig.hidden").blur(function() {
		 $(this).hide();
	});		

	mensagens_personalizacao();

    // carregar fontes sifr
    loadsIFR('empty');


});

