$(function(){
   var max = -1;
   var mySection = new Array();
   mySection['empresa'] = 'Empresa';
   mySection['clientes'] = 'Clientes';
   mySection['home'] = 'Homepage';
   mySection['servicos'] = 'Serviços';
   mySection['infrastruturas'] = 'Infrastruturas';
   mySection['mercados'] = 'Mercados';
   mySection['qualidade_servicos'] = 'Qualidade Serviços';
   mySection['contactos'] = 'Contactos';
   mySection['noticias'] = 'Notícias';
   
    
  
  $('#viewport_container').removeClass('viewport_hidden');
     
    $.address.externalChange(function(event){

        var hash = $.address.path().substring(1);
        if(hash !== '' && $('#container>section[id='+hash+']').size()>0 && hash != 'pesquisa'){
            $('#container>section').hide();
            $('#container>section[id='+hash+']').css('top',0).show();
            $('#container').trigger('fixheight');
            $("a.nav-link").removeClass('active');
            $("a.nav-link[href=#"+hash+"]").addClass('active');
            
            Cufon.replace("a.nav-link-cufon");
            //Solução para o refresh da pagina qd esta em noticias
            if(hash == 'noticias'){
               var page = {'page':1};//OBject
                $.get('getNoticiasPagedAjax',page,function(data){
                    $('#noticias').html(data);
                    $('#noticias > article').hide();
                    Cufon.refresh('.cufon-replace');
                    //Calcular o novo height para as noticias
                    var section = $('#noticias').children();
                    var newHeight = 0;
                    section.each(function(){
                        newHeight += $(this).height();
                    });
                    $("#noticias").height(newHeight-150);
                    $('#noticias').css('top',0).trigger('fixheight');
                    $('#noticias > article').fadeIn('slow');

                    //Saber qual eh que tem o titulo maior
                    $('#noticias > article > ul > li').each(function() {
                        var h = $(this).height();
                        max = h > max ? h : max;
                    });
                    $('#noticias > article > ul > li').css('min-height', max+parseInt(10));
                },'html');
            }
        }
    });
    
    Cufon.replace('.cufon-replace');
	Cufon.replace('.cufon-replace-hover',{
		hover: true
	});


   
    /*MENU COLUMN*/
    //
    $('nav > ul > li > a').bind('mouseenter',function(e){
        e.preventDefault();
        e.stopPropagation();
      
        
        if(!$(this).hasClass('active')){
            var area = $(this).parent().attr('rel');
            var wrapper_height = $('#wrapper').height();
            var total_height = wrapper_height-27;//Acerto com o footer
            $('nav > ul > li[rel='+area+']').css('background','#0a718c');
            $('nav > ul > li[rel='+area+']').css('zIndex','2');
            $('nav > ul > li[rel='+area+']').height(total_height);
           
           
         }
        
    }).bind('mouseleave',function(e){
        e.preventDefault();
        e.stopPropagation();
        var area = $(this).parent().attr('rel');
        $('nav > ul > li[rel='+area+']').css('background','transparent');
        $('nav > ul > li[rel='+area+']').css('z-index','1');
        $('nav > ul > li[rel='+area+']').height(148);
    });
    
    
    $('.nav-left').hover(function(e){
        e.preventDefault();
        e.stopPropagation();
        $('.nav-left > img').attr('src',img_uri+'banner_nav_left_on.png');
    }, function(e){
        e.preventDefault();
        e.stopPropagation();
       $('.nav-left > img').attr('src',img_uri+'banner_nav_left_off.png');
    });
    
    $('.nav-right').hover(function(e){
        e.preventDefault();
        e.stopPropagation();
        $('.nav-right > img').attr('src',img_uri+'banner_nav_right_on.png');
    }, function(e){
        e.preventDefault();
        e.stopPropagation();
       $('.nav-right > img').attr('src',img_uri+'banner_nav_right_off.png');
    });
    
  
    /* NAVEGAÇÃO SITE*/
    
    $("#container").bind('fixheight',function(){
        $(this).height($("#container>section:visible").height());
    }).trigger('fixheight');
    
     
    $('a.nav-link').bind('click',function(event){
        event.stopPropagation();
        event.preventDefault();
   
        $.scrollTo(0, 200, {
			easing: "jswing"
        });
        
        var hash = $.address.path().substring(1)
        var link = $(this);
        var container = $("#container");
        var oldSection = $("#container>section:visible");
        var newSection = $(link.attr('href'));
        var oldSection_index = container.children().index(oldSection);
        var newSection_index = container.children().index(newSection);
        
        //$('title').html('Refertelecom - '+mySection[newSection.attr('id')]); 
     
        if(newSection.attr('id') === 'home'){
            $('#mycarousel').data('jcarousel').startAuto(2.3);
           
        }
        else{
            $('#mycarousel').data('jcarousel').stopAuto(0);
        }
        
        $('a.nav-link').removeClass('active');
       
        link.addClass('active').trigger('mouseleave');
        Cufon.replace('a.nav-link-cufon');
     

        if(newSection.attr('id') == 'noticias'){


            var page = {'page':1};//OBject
			//alert("antes");
			$.get('getNoticiasPagedAjax', page, function(data){
				$('#noticias').html(data);
				Cufon.refresh('.cufon-replace');
				/*
				//Calcular o novo height para as noticias
				var section = $('#noticias').children();
				var newHeight = 0;
				section.each(function(){
					newHeight += $(this).height();
				});
				$("#noticias").height(newHeight-150);
				$('#noticias').css('top',0).trigger('fixheight');
				$('#noticias > article').fadeIn('slow');

				//Saber qual eh que tem o titulo maior
				$('#noticias > article > ul > li').each(function() {
					var h = $(this).height();
					max = h > max ? h : max;
				});
				$('#noticias > article > ul > li').css('min-height', max+parseInt(10));
				*/
			},'html');
	
        }
       
     
        if(oldSection_index < newSection_index){
            $('#viewport_container').addClass('viewport_hidden'); 
            
            $('#wrapper').block({
                showOverlay:true,
                message:"",
                overlayCSS:  { 
                    backgroundColor: '#fff', 
                    opacity:0
                },
                css:{
                    zindex: '100px'
                }
            });

            newSection.css('top',$(window).height()).show();
            container.animate({top: -newSection.position().top},1000,'jswing',function(){
              
                oldSection.hide();
                $('#viewport_container').removeClass('viewport_hidden');
                newSection.css('top',0);
                container.css('top',0).trigger('fixheight');
                $('#wrapper').unblock();
            });
            
            $.address.path(newSection.attr('id'));
        
        } else if(oldSection_index > newSection_index){
            $('#viewport_container').addClass('viewport_hidden'); 
            
            $('#wrapper').block({
                showOverlay:true,
                message:"",
                overlayCSS:  { 
                    backgroundColor: '#fff', 
                    opacity:0
                },
                css:{
                    zindex: '100px'
                }
            });
            
            $("footer").css({
                position: 'fixed'
            });
            var originalHeight = newSection.height();
            var minHeight = Math.max($(window).height(), oldSection.height());
            newSection.height(minHeight);

            newSection.css('top',0 - newSection.height()).show();

            container.animate({top: -newSection.position().top},1000,'jswing',function(){
               
                oldSection.hide();
                $('#viewport_container').removeClass('viewport_hidden');
                newSection.css('top',0);
                newSection.height(originalHeight);
                container.css('top',0).trigger('fixheight');
                $("footer").css('position','relative');
                $('#wrapper').unblock();
            });
            $.address.path(newSection.attr('id'));
        }
      
    });

    /*EMPRESAS SUB NAV*/
    $('#empresa > .submenu > a').bind('click',function(e){
       e.preventDefault();
       e.stopPropagation();

       var subarea  = $(this).attr('rel');
       $('#empresa > article > section').hide();
       $('#empresa > article > section[rel='+subarea+']').fadeIn('slow');
       $('#empresa > .submenu > a').removeClass('active');
       $(this).addClass('active');
       Cufon.refresh('.cufon-replace-hover');
      
       var section = $('#empresa').children();
       var newHeight = 0;
       section.each(function(){
            newHeight += $(this).height();
       });
       
       if(subarea == 'organizacao'){
          $("#empresa").height(newHeight-203);
       }
       else{
         $("#empresa").height(newHeight-180);
       }
       $('#empresa').css('top',0).trigger('fixheight');
       
    });

    /* EMPRESAS > ORGANIZACAO*/
    $('#empresa .organizacao > ul > li.bg1 > a.administracao').bind('click',function(e){
        e.preventDefault();
        e.stopPropagation();
       
        $(this).css('display','none');
        $('#empresa .organizacao > ul > li.bg1 > a.organograma').css('display','block');
        $('#empresa .organizacao > ul > li.bg1').css('background','url('+img_uri+'organizacao_bg_administracao.jpg)');
        $('#empresa .organizacao > ul > li.bg1').css('height',803);
        $('#empresa .organizacao > ul > li.direccoes').hide();
        $('#empresa .organizacao > ul > li.conselho_administracao').fadeIn('slow');
        
        var section = $('#empresa').children();
        var newHeight = 0;
        section.each(function(){
            newHeight += $(this).height();
        });
        $("#empresa").height(newHeight-203);
        $('#empresa').css('top',0).trigger('fixheight');

    });
    $('#empresa .organizacao > ul > li.bg1 > a.organograma').bind('click',function(e){
        e.preventDefault();
        e.stopPropagation();
        
        $("#empresa").trigger('fixheight');
       
        $(this).css('display','none');
        $('#empresa .organizacao > ul > li.bg1 > a.administracao').css('display','block');
        $('#empresa .organizacao > ul > li.bg1').css('background','url('+img_uri+'organizacao_bg1.jpg)');
        $('#empresa .organizacao > ul > li.bg1').css('height',614);
        $('#empresa .organizacao > ul > li.conselho_administracao').hide();
        $('#empresa .organizacao > ul > li.direccoes').fadeIn('slow');
        
        var section = $('#empresa').children();
        var newHeight = 0;
        section.each(function(){
            newHeight += $(this).height();
        });
        $("#empresa").height(newHeight-203);
        $('#empresa').css('top',0).trigger('fixheight');
        

    });
    
    
    /*SERVICOS*/
    
   
     
    $('#servicos > .submenu > a').bind('click',function(e){
       e.preventDefault();
       e.stopPropagation();

       var subarea  = $(this).attr('rel');
       $('#servicos > article > section').hide();
       $('#servicos > article > section[rel='+subarea+']').fadeIn('slow');
       $('#servicos > .submenu > a').removeClass('active');
       $(this).addClass('active');
       Cufon.refresh('.cufon-replace-hover');
      
       var section = $('#servicos').children();
       var newHeight = 0;
       section.each(function(){
            newHeight += $(this).height();
       });
       
      
       $('#servicos').css('top',0).trigger('fixheight');
       
    });
   
    
    /* CONTACTOS*/

    //FOCUS & BLUR INPUT FORM
    $('#form_contacto > fieldset > input[name=nome]').bind("focus",function(){
		if ($(this).val() == "Insira o seu Nome") {
			$(this).val('');
		}
	});
	$('#form_contacto > fieldset > input[name=nome]').bind("blur", function(){
		if ($(this).val() == ""){
			$(this).val('Insira o seu Nome');
		}
	});


	$('#form_contacto > fieldset > input[name=email]').bind("focus",function(){
		if ($(this).val() == "Insira o seu E-mail") {
			$(this).val('');
		}
	});
	$('#form_contacto > fieldset > input[name=email]').bind("blur", function(){
		if ($(this).val() == ""){
			$(this).val('Insira o seu E-mail');
		}
	});
    
    
    $('#form_contacto > fieldset > input[name=assunto]').bind("focus",function(){
		if ($(this).val() == "Insira o Assunto da mensagem") {
			$(this).val('');
		}
	});
	$('#form_contacto > fieldset > input[name=assunto]').bind("blur", function(){
		if ($(this).val() == ""){
			$(this).val('Insira o Assunto da mensagem');
		}
	});


    $('#form_contacto > fieldset > textarea[name=mensagem]').bind("focus",function(){
		if ($(this).val() == "Mensagem") {
			$(this).val('');
		}
	});
	$('#form_contacto > fieldset > textarea[name=mensagem]').bind("blur", function(){
		if ($(this).val() == ""){
			$(this).val('Mensagem');
		}
	});

    $('#enviar').bind('click',function(e){
        e.preventDefault();
        e.stopPropagation();
        
        var nome_field = $('#form_contacto > fieldset > input[name=nome]');
        var email_field = $('#form_contacto > fieldset > input[name=email]');
        var assunto_field = $('#form_contacto > fieldset > input[name=assunto]');
        var mensagem_field = $('#form_contacto > fieldset > textarea[name=mensagem]');
        var label = '<label style="display:block;margin:0;padding:0;font:10px Arial,helvetica,sans-serif;color:#156b82;">Campo de preenchimento obrigatório</label>';


        //RESET PROP INPUTS
        nome_field.next('label').remove();
        email_field.next('label').remove();
        assunto_field.next('label').remove();
        mensagem_field.next('label').remove();

        nome_field.css('background','#ffffff');
        nome_field.css('border','none');
        nome_field.css('color','#666666');

        email_field.css('background','#ffffff');
        email_field.css('border','none');
        email_field.css('color','#666666');

        assunto_field.css('background','#ffffff');
        assunto_field.css('border','none');
        assunto_field.css('color','#666666');

        mensagem_field.css('background','#ffffff');
        mensagem_field.css('border','none');
        mensagem_field.css('color','#666666');

        //VALIDAR INPUTS
		if(nome_field.val() =="" || nome_field.val() =="Insira o seu Nome"){
			nome_field.css('background','#1a95b5');
			nome_field.css('border','1px solid #014e62');
			nome_field.css('color','#ffffff');
            nome_field.val('Insira o seu Nome');
            $('#form_contacto > fieldset > input[name=nome]').after(label);
			return false;
		} else if(email_field.val() == "" || email_field.val() == 'Insira o seu E-mail'){
			email_field.css('background','#1a95b5');
			email_field.css('border','1px solid #014e62');
			email_field.css('color','#ffffff');
            email_field.val('Insira o seu E-mail');
            $('#form_contacto > fieldset > input[name=email]').after(label);
			return false;
        } else if(assunto_field.val() == "" || assunto_field.val() == 'Insira o Assunto da mensagem'){
			assunto_field.css('background','#1a95b5');
			assunto_field.css('border','1px solid #014e62');
			assunto_field.css('color','#ffffff');
            assunto_field.val('Insira o Assunto da mensagem');
            $('#form_contacto > fieldset > input[name=assunto]').after(label);
			return false;
		} else if(mensagem_field.val() == "" || mensagem_field.val() == 'Mensagem'){
			mensagem_field.css('background','#1a95b5');
			mensagem_field.css('border','1px solid #014e62');
			mensagem_field.css('color','#ffffff');
            mensagem_field.val('Mensagem');
            $('#form_contacto > fieldset > textarea[name=mensagem]').after(label);
			return false;
        }
		else{
            $.blockUI({ css: { 
                border: 'none', 
                padding: '15px', 
                backgroundColor: '#000', 
                '-webkit-border-radius': '10px', 
                '-moz-border-radius': '10px', 
                opacity: .5, 
                color: '#fff',
                message:''
            } });
			
            $.post('form_contactos',$('#form_contacto').serialize(),function(data){
                if(data == 'post null'){
                    nome_field.css('background','#1a95b5');
                    nome_field.css('border','1px solid #014e62');
                    nome_field.css('color','#ffffff');
                    nome_field.val('Insira o seu Nome');
                    $('#form_contacto > fieldset > input[name=nome]').after(label);

                    email_field.css('background','#1a95b5');
                    email_field.css('border','1px solid #014e62');
                    email_field.css('color','#ffffff');
                    email_field.val('Insira o seu E-mail');
                    $('#form_contacto > fieldset > input[name=email]').after(label);

                    assunto_field.css('background','#1a95b5');
                    assunto_field.css('border','1px solid #014e62');
                    assunto_field.css('color','#ffffff');
                    assunto_field.val('Insira o Assunto da mensagem');
                    $('#form_contacto > fieldset > input[name=assunto]').after(label);

                    mensagem_field.css('background','#1a95b5');
                    mensagem_field.css('border','1px solid #014e62');
                    mensagem_field.css('color','#ffffff');
                    mensagem_field.val('Mensagem');
                    $('#form_contacto > fieldset > textarea[name=mensagem]').after(label);
                    
                } else if(data == 'nome' || data == 'email' || data == 'assunto' || data == 'mensagem'){
                    
                    $('#form_contacto > fieldset > input[name='+data+'').css('background','#1a95b5');
                    $('#form_contacto > fieldset > input[name='+data+'').css('border','1px solid #014e62');
                    $('#form_contacto > fieldset > input[name='+data+'').css('color','#ffffff');
                    $('#form_contacto > fieldset > input[name='+data+'').val('Insira o seu E-mail');
                    $('#form_contacto > fieldset > input[name='+data+'').after(label);
                    
                } else if(data == 'ok'){

                    $('#form_contacto > fieldset > input[name=enviar]').hide();
                    
                    nome_field.next('label').remove();
                    email_field.next('label').remove();
                    assunto_field.next('label').remove();
                    mensagem_field.next('label').remove();

                    nome_field.css('background','#e8f3fa');
                    nome_field.css('border','none');
                    nome_field.css('color','#666666');

                    email_field.css('background','#e8f3fa');
                    email_field.css('border','none');
                    email_field.css('color','#666666');

                    assunto_field.css('background','#e8f3fa');
                    assunto_field.css('border','none');
                    assunto_field.css('color','#666666');

                    mensagem_field.css('background','#e8f3fa');
                    mensagem_field.css('border','none');
                    mensagem_field.css('color','#666666');
                    
                    $('#form_contacto > fieldset > input[name=nome]').val('Insira o seu Nome');
                    $('#form_contacto > fieldset > input[name=email]').val('Insira o seu E-mail');
                    $('#form_contacto > fieldset > input[name=assunto]').val('Insira o Assunto da mensagem');
                    $('#form_contacto > fieldset > textarea[name=mensagem]').val('Mensagem');
                    $('#form_contacto > fieldset > input[name=enviar]').after('<p style="color:#333333;font:bold 13px Arial,helvetica,sans-serif;">Obrigado pelo seu contacto. A mensagem foi enviada com sucesso!</p>');
                   
                }
                $.unblockUI();
            },'html');
            
            return false;
		}
     });

     /*NOTICIAS THUMBS*/
     
     
      
     $('#noticias > article > ul > li').live("mouseover mouseout", function(e) {
        if ( e.type == "mouseover" ) {
            // do something on mouseover
            e.preventDefault();
            e.stopPropagation();
          
            $(this).css('background','#1a95b5');
            $(this).children('section').children('p.data').css('color','#ffffff');
            $(this).children('section').children('p.titulo').css('color','#ffffff');
            $(this).children('section').children('p.titulo').css('text-decoration','underline');
            $(this).children('section').children('p.descricao').css('color','#b3d9e4');
          
        } else {
            // do something on mouseout
            e.preventDefault();
            e.stopPropagation();
           
            $(this).css('background','transparent');
            $(this).children('section').children('p.data').css('color','#318298');
            $(this).children('section').children('p.titulo').css('color','#156b82');
            $(this).children('section').children('p.titulo').css('text-decoration','none');
            $(this).children('section').children('p.descricao').css('color','#666666');
        }
     });
  

    /*NOTICIAS - NAV*/
    
    $('#noticias  > .submenu > ul > li.prev').live({
        mouseenter:function(e){
            e.preventDefault();
            e.stopPropagation();
            $('#noticias  > .submenu > ul > li.prev > img').attr('src',img_uri+'nav_previous_noticias_on.png');
        },
        mouseleave:function(e){
            e.preventDefault();
            e.stopPropagation();
            $('#noticias  > .submenu > ul > li.prev > img').attr('src',img_uri+'nav_previous_noticias_off.png');
        }
    });
    
    $('#noticias  > .submenu > ul > li.next').live({
        mouseenter:function(e){
            e.preventDefault();
            e.stopPropagation();
            $('#noticias  > .submenu > ul > li.next > img').attr('src',img_uri+'nav_next_noticias_on.png');
        },
        mouseleave:function(e){
            e.preventDefault();
            e.stopPropagation();
            $('#noticias  > .submenu > ul > li.next > img').attr('src',img_uri+'nav_next_noticias_off.png');
        }
    });
    
    $('#noticias  > .submenu > .listar_noticias').live({
        mouseenter:function(e){
            e.preventDefault();
            e.stopPropagation();
            $('#noticias  > .submenu > .listar_noticias').attr('src',img_uri+'icon_listar_noticias_on.png');
        },
        mouseleave:function(e){
            e.preventDefault();
            e.stopPropagation();
            $('#noticias  > .submenu > .listar_noticias').attr('src',img_uri+'icon_listar_noticias_off.png');
        }
    });
    
    
    $('#noticias  > .submenu > ul > li.next').live('click',function(e){
        e.preventDefault();
        e.stopPropagation();
        
        var next_page = {'page':$(this).attr('rel')};//OBject
        if(next_page.page !== '0' && next_page.page !=='' && next_page.page !== null ){
            $.get('getNoticiasPagedAjax',next_page,function(data){
		
                $('#noticias').html(data);
                $('#noticias > article').hide();
                Cufon.refresh('.cufon-replace');
                
                var section = $('#noticias').children();
                var newHeight = 0;
                section.each(function(){
                    newHeight += $(this).height();
                });
                $("#noticias").height(newHeight-150);
                $('#noticias').css('top',0).trigger('fixheight');
                $('#noticias > article').fadeIn('slow');
                
                //Saber qual eh que tem o titulo maior
                $('#noticias > article > ul > li').each(function() {
                    var h = $(this).height();
                    max = h > max ? h : max;
                });
                $('#noticias > article > ul > li').css('min-height', max+parseInt(10));
                
                
            },'html');
        }
        return false;
    });

    $('#noticias  > .submenu > ul > li.prev').live('click',function(e){
        e.preventDefault();
        e.stopPropagation();
        
        var prev_page = {'page':$(this).attr('rel')};//OBject
        if( prev_page.page !== '0' && prev_page.page !=='' && prev_page.page !== null){
            $.get('getNoticiasPagedAjax',prev_page,function(data){
                $('#noticias').html(data);
                $('#noticias > article').hide();
               
                Cufon.refresh('.cufon-replace');
                
                var section = $('#noticias').children();
                var newHeight = 0;
                section.each(function(){
                    newHeight += $(this).height();
                });
                $("#noticias").height(newHeight-150);
                $('#noticias').css('top',0).trigger('fixheight');
                $('#noticias > article').fadeIn('slow');
                
                //Saber qual eh que tem o titulo maior
                $('#noticias > article > ul > li').each(function() {
                    var h = $(this).height();
                    max = h > max ? h : max;
                });
                $('#noticias > article > ul > li').css('min-height', max+parseInt(10));
                
            },'html');
        }
        return false
    });
    
    $('#noticias  > .submenu > .listar_noticias').live('click',function(e){
        e.preventDefault();
        e.stopPropagation();
        
        
        var page = {'page':1};//OBject

        $.get('getNoticiasPagedAjax',page,function(data){

	
            $('#noticias').html(data);
            $('#noticias > article').hide();
            Cufon.refresh('.cufon-replace');
            //Calcular o novo height para as noticias
            var section = $('#noticias').children();
            var newHeight = 0;
            section.each(function(){
                newHeight += $(this).height();
            });
            $("#noticias").height(newHeight-150);
            $('#noticias').css('top',0).trigger('fixheight');
            $('#noticias > article').fadeIn('slow');
            
            //Saber qual eh que tem o titulo maior
            $('#noticias > article > ul > li').each(function() {
                var h = $(this).height();
                max = h > max ? h : max;
            });
            $('#noticias > article > ul > li').css('min-height', max+parseInt(10));
        },'html');
        
        
        
       
        
    });
    
    /* NOTICIAS - CLICK DETALHE*/
    $('#noticias > article > ul > li').live('click',function(e){
        e.preventDefault();
        e.stopPropagation();
        
        var id_noticia = {'id_noticia':$(this).attr('rel')};//OBject
        if( id_noticia !== 0 || id_noticia !=='' || id_noticia !== null){
		
			
            $.get('getNoticiasDetalheAjax',id_noticia,function(data){
                $('#noticias').fadeOut();
                $('#noticias').html(data);
                Cufon.refresh('.cufon-replace');
                
                //Calcular o novo height para as noticias
                var section = $('#noticias').children();
                var newHeight = 0;
                section.each(function(){
                    newHeight += $(this).height();
                });
                $("#noticias").height(newHeight-150);
                $('#noticias').css('top',0).trigger('fixheight');
                $('#noticias').fadeIn('slow');
            },'html');
        }
    });
    
    
    
    /* NOTICIAS - HOME DETALHE*/
    $('#home > .noticias >  ul > li').bind('click',function(e){
        e.preventDefault();
        e.stopPropagation();
        
        $('#mycarousel').data('jcarousel').stopAuto(0);
        
        var id_noticia = {'id_noticia':$(this).attr('rel')};//OBject
        if( id_noticia !== 0 || id_noticia !=='' || id_noticia !== null){
            $.get('getNoticiasDetalheAjax',id_noticia,function(data){
                $('#noticias').html(data);
                Cufon.refresh('.cufon-replace');
                
                 /*ANIMação*/
                var hash = 'noticias'
                var container = $("#container");
                var oldSection = $("#container>section:visible");
                var newSection = $("#container>section#noticias");
                
                $('#viewport_container').addClass('viewport_hidden');
                
                var originalHeight = newSection.height();
                var minHeight = Math.max( $(window).height(), oldSection.height());
            
                newSection.height(minHeight);
                newSection.css('top',0 - newSection.height()).show();

                container.animate({top:  -newSection.position().top},1000,'jswing',function(){
                    oldSection.hide();
                     $('#viewport_container').removeClass('viewport_hidden');
                    newSection.css('top',0);
                    newSection.height(originalHeight);
                    container.css('top',0).trigger('fixheight');
                    $("footer").css('position','relative');

                });
                $.address.path(newSection.attr('id'));
                
            },'html');
        }
    });
    
   
   $('.logout').bind('click',function(e){
       $.get('fornecedores/logout',function(data){
            if(data == 'logout'){
                area = "";
                window.location = baseuri;
                
                $('#mycarousel').data('jcarousel').stopAuto(0);
                
                var container = $("#container");
                var oldSection = $("#container>section:visible");
                var newSection = $("#container>section#home");
                
                $('#viewport_container').addClass('viewport_hidden');
                
                if(oldSection.attr('id') != newSection.attr('id')){
                    var originalHeight = newSection.height();
                    var minHeight = Math.max( $(window).height(), oldSection.height());
                    newSection.height(minHeight);

                    newSection.css('top',0 - newSection.height()).show();

                    container.animate({top: -newSection.position().top},1000,'jswing',function(){
                        oldSection.hide();
                        $('#viewport_container').removeClass('viewport_hidden');
                        newSection.css('top',0);
                        newSection.height(originalHeight);
                        container.css('top',0).trigger('fixheight');
                        $("footer").css('position','relative');

                    });
                    $.address.path(newSection.attr('id'));

                }
            }
       },'html');
    });
    

    //FOCUS & BLUR INPUT FORM
    $('#form_login > fieldset > div > input[name=username]').bind("focus",function(){
		if ($(this).val() == "Insira o Username") {
			$(this).val('');
		}
	});
	$('#form_login > fieldset > div > input[name=username]').bind("blur", function(){
		if ($(this).val() == ""){
			$(this).val('Insira o Username');
		}
	});


	$('#form_login > fieldset > div > input[name=password]').bind("focus",function(){
		if ($(this).val() == "Insira a Password") {
			$(this).val('');
		}
	});
	$('#form_login > fieldset > div > input[name=password]').bind("blur", function(){
		if ($(this).val() == ""){
			$(this).val('Insira a Password');
		}
	});
    
   
    $('#enviar_login').bind('click',function(e){
        e.preventDefault();
        e.stopPropagation();

        var username_field = $('#form_login > fieldset > div > input[name=username]');
        var password_field = $('#form_login > fieldset > div > input[name=password]');
        var categoria_field = $('#form_login > fieldset > div > input[name=categoria]:checked');
        var label = '<label style="display:block;margin:0;padding:0;font:10px Arial,helvetica,sans-serif;color:#ffffff;">Campo de preenchimento obrigatório</label>';

        //RESET PROP INPUTS
        username_field.next('label').remove();
        password_field.next('label').remove();

        username_field.css('background','#ffffff');
        username_field.css('border','none');
        username_field.css('color','#666666');

        password_field.css('background','#ffffff');
        password_field.css('border','none');
        password_field.css('color','#666666');

        //VALIDAR INPUTS
        if(username_field.val() =="" || username_field.val() =="Insira o Username"){
            username_field.css('background','#1a95b5');
            username_field.css('border','1px solid #014e62');
            username_field.css('color','#ffffff');
            username_field.val('Insira o Username');
            $('#form_login > fieldset > div > input[name=username]').after(label);
            return false;
        } else if(password_field.val() == "" || password_field.val() == 'Insira a Password'){
            password_field.css('background','#1a95b5');
            password_field.css('border','1px solid #014e62');
            password_field.css('color','#ffffff');
            password_field.val('Insira a Password');
            $('#form_login > fieldset > div > input[name=password]').after(label);
            return false;
        } else{
            if(categoria_field.val() == 'prestadores'){
                //Só para login
                $.post('fornecedores/login',$('#form_login').serialize(),function(data){
                   if(data != 'error'){
                       //Afecta global
                       area = data;
                       //após login carrega os dados
                       $.get('fornecedores/',function(html){
                           $('#procedimentos').html(html);
                           $('.area_reservada > img').attr('src',img_uri+'button_area_reservada_off.png');
                           $('.area_reservada').css('background','#1fa0c2');
                           $('.login').fadeOut();
                           
                           $('#mycarousel').data('jcarousel').stopAuto(0);
                           
                           var hash = 'procedimentos';
                           var container = $("#container");
                           var oldSection = $("#container>section:visible");
                           var newSection = $("#container>section#procedimentos");
                           
                           $('#viewport_container').addClass('viewport_hidden');
                           
                           var originalHeight = newSection.height();
                           var minHeight = Math.max( $(window).height(), oldSection.height());
                           newSection.height(minHeight);

                           newSection.css('top',0 - newSection.height()).show();

                           container.animate({top:  -newSection.position().top},1000,'jswing',function(){
                               oldSection.hide();
                                $('#viewport_container').removeClass('viewport_hidden');
                               newSection.css('top',0);
                               newSection.height(originalHeight);
                               container.css('top',0).trigger('fixheight');
                               $("footer").css('position','relative');

                           });
                           $.address.path(newSection.attr('id'));
                       },'html');
                        
                   }
                   else{
                       alert('O utilizador não se encontra registado ou activo na base de dados');
                   }
                });
            }
            if(categoria_field.val() == 'clientes'){
               /*HACK */
               
               //Carregar o login para a iframe
                var element_iframe = $('#clientes > iframe');
                
                //Copiar dados login para o form da iframe
                element_iframe.squirt('<form action="login.php" method="POST" name="login_form" id="login_form"><input class="user" name="user" value="'+username_field.val()+'" type="text"><br><input class="pass" name="pass" value="'+password_field.val()+'" type="password"><input class="botao" type="submit" name="send_login" id="send_login" value=""><input type=hidden name=require value=login></form>');
                
                //Submit da iframe 
                var form = element_iframe.contents().find('#login_form');
                element_iframe.one('load',function(){
                   //Procurar se existe uma table para saber que estou logado
                   if(element_iframe.contents().find('table').size() > 0){
                       //estou logado
                       element_iframe.show();
                       
                       /* Animações , Links e afins*/
                       $('.area_reservada > img').attr('src',img_uri+'button_area_reservada_off.png');
                       $('.area_reservada').css('background','#1fa0c2');
                       $('.login').fadeOut();
                       area ='clientes';
                       
                        $('#mycarousel').data('jcarousel').stopAuto(0);
                        
                        var container = $("#container");
                        var oldSection = $("#container>section:visible");
                        var newSection = $("#container>section#clientes");
                        
                        $('#viewport_container').addClass('viewport_hidden');
                        
                        if(oldSection.attr('id') != newSection.attr('id')){
                            var originalHeight = newSection.height();
                            var minHeight = Math.max( $(window).height(), oldSection.height());
                            newSection.height(minHeight);

                            newSection.css('top',0 - newSection.height()).show();

                            container.animate({top: -newSection.position().top},1000,'jswing',function(){
                                oldSection.hide();
                                 $('#viewport_container').removeClass('viewport_hidden');
                                newSection.css('top',0);
                                newSection.height(originalHeight);
                                container.css('top',0).trigger('fixheight');
                                $("footer").css('position','relative');
                            });
                        }

                        $.address.path(newSection.attr('id'));
                       
                   } 
                });
                form.get(0).submit();
               
            }
        }
     });
    
    
    /* AREA RESERVADA LOGIN*/
    var janelaLoginAberta = true;
    $('.area_reservada > img').bind('click',function(e){
        e.preventDefault();
        e.stopPropagation();
        
        if (janelaLoginAberta){
            //show
            janelaLoginAberta = false;
            
            $('.area_reservada > img').attr('src',img_uri+'button_area_reservada_on.png');
            $('.area_reservada').css('background','#156b82');
            if(area == ""){
                $('.login').fadeIn();
            }
            else{
                $('.logout').fadeIn();
            }
           
        }else{
            //hide
            janelaLoginAberta = true;
           
            $('.area_reservada > img').attr('src',img_uri+'button_area_reservada_off.png');
            $('.area_reservada').css('background','#1fa0c2');
            if(area == ""){
                $('.login').fadeOut();
            }
            else{
                $('.logout').fadeOut();
            }
            
        }
    });
    
    
    
     //*FORM PESQUISA - // PESQUISA REAL TIME */
     
     $('#form_pesquisa > input[name=query]').bind("focus",function(){
		if ($(this).val() == "Pesquisa") {
			$(this).val('');
		}
	});
	$('#form_pesquisa > input[name=query]').bind("blur", function(){
		if ($(this).val() == ""){
			$(this).val('Pesquisa');
		}
	});
     
     
     
     $('#form_pesquisa').bind('submit',function(e){
        e.preventDefault();
        e.stopPropagation();
       
        $('#viewport_container').removeClass('viewport_hidden');
        
        $.blockUI({ css: { 
            border: 'none', 
            padding: '15px', 
            backgroundColor: '#000', 
            '-webkit-border-radius': '10px', 
            '-moz-border-radius': '10px', 
            opacity: .5, 
            color: '#fff',
            message:'Aguarde um momento...'
        } });  
            
        var query_field = $('#form_pesquisa > input[name=query]');
        
        if(query_field.val() =="" || query_field.val() =="Pesquisa"){
            query_field.css('background','#1a95b5');
			query_field.css('border','1px solid #014e62');
			query_field.css('color','#ffffff');
            query_field.val('Pesquisa');
            $.unblockUI();
            return false;
        }
        else{
            var html = '';
            var resultados ='';
            var results = [];
            var result = '';
            var flag = false;
            
            $("a.nav-link").removeClass('active');
            Cufon.refresh('.cufon-replace');
             $('#pesquisa').children().hide();
            //procura no ficheiro   
            $("#container>section *:contains('"+query_field.val()+"')").each(function(){
                result = {
                    section: $(this).parents('section[id]'),
                    text: $.trim($(this).parent().text())
                }
                results.push(result);
              
                resultados = '';
                var last_section;
                $.each(results,function(index,data){
                    if((data.section.attr('id') != undefined)&&(data.section.attr('id') != 'pesquisa')&&(data.section.attr('id') != 'noticias')){
                        if(data.section.attr('id') != last_section){
                            last_section = data.section.attr('id'); 
                            var text_lenght = data.text.indexOf(query_field.val()); 
                            var text_tras = parseInt(text_lenght)-100;
                            var text_frente = parseInt(text_lenght)+100;
                            resultados +='<section class="resultados"><h3 class="cufon-replace"><a rel="0" style="cursor:pointer;cursor:hand;" data-link="#'+data.section.attr('id')+'">Refer Telecom - '+mySection[data.section.attr('id')]+'</a></h3><p>...'+data.text.substring(text_tras,text_frente)+'...</p></section>';
                            
                        }
                    }
                });
                flag = true;
            });
           
            //procura nas noticias
            var word = {'query':query_field.val()};
            $.get('getSearchNoticiasAjax',word,function(data){
                if(data != 'error'){    
                    resultados += data;
                    flag = true;
                }
                
                if(flag === false){
                   
                   html +='<figure>'
                        html +='<img src="'+img_uri+'header_pesquisa.jpg" border="0" width="795" height="200" alt="">';
                    html +='</figure>';
                    html +='<article>';
                        html +='<h1 class="cufon-replace">Resultados de pesquisa por:</h1>';
                        html +='<h2>'+query_field.val()+'</h2>';
                        html +='<br style="clear:both;">';
                        html +='<div>';
                            html +='<p>A sua pesquisa não devolveu resultados</p>';
                        html +='</div>';   
                    html +='</article>';
                }
                else{
                   
                    html +='<figure>'
                        html +='<img src="'+img_uri+'header_pesquisa.jpg" border="0" width="795" height="200" alt="">';
                    html +='</figure>';
                    html +='<article>';
                        html +='<h1 class="cufon-replace">Resultados de pesquisa por:</h1>';
                        html +='<h2>'+query_field.val()+'</h2>';
                        html +='<br style="clear:both;">';
                        html +='<div>';
                            html +='<p>A sua pesquisa devolveu os seguintes resultados</p>';
                        html +='</div>';   
                        html +=resultados;
                    html +='</article>';
                }
                
                $('#pesquisa').html(html);
                $.unblockUI();
                
                $('#mycarousel').data('jcarousel').stopAuto(0);
                
                var container = $("#container");
                var oldSection = $("#container>section:visible");
                var newSection = $("#container>section#pesquisa");
                
                 $('#viewport_container').addClass('viewport_hidden');

                if(oldSection.attr('id') != newSection.attr('id')){
                    var originalHeight = newSection.height();
                    var minHeight = Math.max( $(window).height(), oldSection.height());

                    newSection.height(minHeight);

                    newSection.css('top',0 - newSection.height()).show();

                    container.animate({top: -newSection.position().top},1000,'jswing',function(){
                        oldSection.hide();
                         $('#viewport_container').removeClass('viewport_hidden');
                        newSection.css('top',0);
                        newSection.height(originalHeight);
                        container.css('top',0).trigger('fixheight');
                        $("footer").css('position','relative');
                        
                    });
                    $('#pesquisa').show();
                }
                else{
                   
                    var section = newSection.children();
                    
                    var newHeight = 0;
                    section.each(function(){
                        newHeight += $(this).height();
                    });
                   
                    if(flag === false){
                        newSection.height(newHeight);
                    }
                    else{
                        newSection.height(newHeight+25);
                    }
                    
                    newSection.css('top',0).trigger('fixheight');
                    $("footer").css('position','relative');
                    section.fadeIn('slow');
                    
                }
                
                $.address.path(newSection.attr('id'));
            },'html');
        }
        return false;
     });
     
     
    
     
     
     //VER DETALHE DA NOTICIA e fazer animacao no link QD FAZEMOS PESQUISA
    $('#pesquisa > article > section.resultados > h3 > a').live('click',function(e){
        e.preventDefault();
        e.stopPropagation();
     
        var id_noticia = {'id_noticia':$(this).attr('rel')};//OBject
        var link = $(this).data('link');
        var section = $(link);
        
        
        $('#pesquisa').hide();
        $("a.nav-link[href="+link+"]").addClass('active');        
        Cufon.replace("a.nav-link-cufon");
        
        if($(this).attr('rel') != 0 && $(this).attr('rel') !='' && $(this).attr('rel') != null){
            $.get('getNoticiasDetalheAjax',id_noticia,function(data){
                $('#noticias').html(data);
                Cufon.refresh('.cufon-replace');
                
                var section_children = section.children();
                var newHeight = 0;
                
                section_children.each(function(){
                    newHeight += $(this).height();
                });
                section.height(newHeight-150);
                section.css('top',0).trigger('fixheight');
            },'html');
        }
        
        section.fadeIn();
        section.css('top',0).trigger('fixheight');
        $("footer").css('position','relative');
                  
        $.address.path(section.attr('id'));
    });
     
});

function mycarousel_initCallback(carousel) {
    
    $('.jcarousel-control a').live('click', function() {
        carousel.scroll($.jcarousel.intval($(this).attr('rel')));
     
        return false;
    });

   $('#mycarousel-next').live('click', function(e) {
        e.preventDefault();
        e.stopPropagation();
        
        $('.images').block({
            showOverlay:true,
            message:"",
            timeout: 1200,
            overlayCSS:  { 
                backgroundColor: '#FFFFFF', 
                opacity:0 
            },
            css:{
                zindex: '100px'
            }
        });
        
        carousel.next();
       
        $('.images').unblock(); 
        return false;
       
    });

    $('#mycarousel-prev').live('click', function(e) {
         e.preventDefault();
         e.stopPropagation();
      
       $('.images').block({
            showOverlay:true,
            message:"",
            timeout:1200,
            overlayCSS:  { 
                backgroundColor: '#FFFFFF', 
                opacity:0 
            },
            css:{
                zindex: '100px'
            }
        });
     
       carousel.prev();
       
       $('.images').unblock(); 
       return false;
    });
}


$(document).ready(function() {
    
    Cufon.now();
    
    $('#mycarousel').jcarousel({
    	wrap: 'circular',
        animation: 1500,
        easing:'jswing',
        scroll: 1,
        size: 6,
		auto: 3,
		start: 1,
        buttonNextEvent: 'mycarousel-next',
        buttonPrevEvent: 'mycarousel-prev',
        initCallback: mycarousel_initCallback,
        itemFirstInCallback: {
            onBeforeAnimation: function(carousel_object,li,idx,state){
                var pos = $(li).attr('rel');

                $('a[class$="_active"]').removeClass();
                $('.numeros > a[rel="'+pos+'"]').addClass('btn'+pos+'_active');
                    
                if(pos == 1){
                    $('#mycarousel-next').attr('rel',2);
                    $('#mycarousel-prev').attr('rel',6);
                }
                else if(pos == 6){
                    $('#mycarousel-next').attr('rel',1);
                    $('#mycarousel-prev').attr('rel',5);
                }
                else{
                    $('#mycarousel-next').attr('rel',parseInt(pos)+1);
                    $('#mycarousel-prev').attr('rel',parseInt(pos)-1);
                }    
            }
        }
       
    });
    
    $('#viewport_container').css('overflow','none');   
    
    if(area == 'fornecedores'){
        $.get('fornecedores/',function(html){
            $('#procedimentos').html(html);
            $('#procedimentos').css('top',0).trigger('fixheight');
        },'html');
    }
    if($.browser.msie){
        var ie =  $.browser.version.substr(0,1);
        if(ie == 7){
            $('header').css('z-index','110');
            $('nav').css('z-index','100');
            $('#container').css('z-index','100');
            $('#container > section').css('z-index','110');
            $('#container > section > figure').css('z-index','120');
            /*
            $('#container > section > #banner').css('z-index','90');
            $('#container > section > #banner > .viewport').css('z-index','100');
            $('#container > section > #banner > .viewport > ul').css('z-index','110');
            $('#container > section > #banner > .viewport > ul > li').css('z-index','120');
            $('#container > section > #banner > .viewport > ul > li > img').css('z-index','130');
            */
            $('.login').css('z-index','100');
        }
    }
   

});

