/**
* Esse arquivo contém algumas ações que são padrões nos sites desenvolvidos 
* pela Fivecom para adicionar essas funcionalidades às páginas, siga as 
* instruções em cada uma das funções e/ou eventos abaixo
*/

$(document).ready(function(){

  $(".acesso_rapido").change(function(){
    window.open($(this).val());
  });

	var timeId = null;
/**
 *Acessibilidade
 */
  Acessibilidade.ini();
  $('.set_contraste').click(function(){
    Acessibilidade.toggleContraste();
  });

  $(".link_externo").click(function(){
    Apoio.link_externo(this);
  });
  
  $('#ds_busca').click(function(){
		$(this).val('');
  });

  /**
	* Botão Voltar
	* adicione id="voltar" no elemento que receberá a ação do clique
	*/
  $('#voltar').click(function(){
    window.history.go(-1);
  });
	
  /** ---------------------------------------------------------- */
	
  /**
	* Alterantiva ao target="_blank"
	* Abrir em nova Aba/Janela
	*/
  $('.target_blank').click(function(){
    var pag = $(this).attr('href');
    window.open(pag);
    return false;
  })
	
  /** ---------------------------------------------------------- */

  /**
	* Controle de Fonte
	*/
  var fonte;
  if($.cookie('tfont') != null) {
    fonte = parseInt($.cookie('tfont'));
    $('.tfonte').css({
      'font-size' : fonte+'px'
      });
  } else {
    fonte = 11;
  }
  $('.mais').click(function(){
    if (fonte<13){
      fonte = fonte+1;
      $('.tfonte').css({
	'font-size' : fonte+'px'
	});
      $.cookie('tfont', fonte);
    }
  });
  $('.menos').click(function(){
    if (fonte>10){
      fonte = fonte-1;
      $('.tfonte').css({
	'font-size' : fonte+'px'
	});
      $.cookie('tfont', fonte);
    }
  });
	
  /** ---------------------------------------------------------- */


  /**
	* IMPRIMIR PÁGINA	
	*/
  $('#imprimir').click(function(){
    //var pagina = $(this).attr('rel');
    //window.open(pagina);
    window.print();
    return false;
  });

  /** ---------------------------------------------------------- */
	
  /**
	* SUBMIT EM FORMULÁRIOS
	* parta executar o submit dos fomulários de um site, basta inserir 
	* a classe submit (class="submit") no elemento responsável por esse
	* evento e inserir um elemento para receber a infromação de sucesso
	* ou erro, colocando nesse elemento o id="loading"
	*/
  $('.submit').click(function(){
    var msg = new Array();
		
    var jqForm = $(this).parents("form");
    var jq = jqForm.find('.loading');
    var i = 0;

    var inputs = jqForm.find('input');
    i = inputs.size();
    while(i--){
      var input = inputs.get(i);
      if(input.type == 'text'){
	if(input.title != '' && input.value == ''){
	  msg.push("O campo "+input.title+" é obrigatório") ;
	}
      }
    }

    var inputs = jqForm.find('textarea');
    var i = inputs.size();
    while(i--){
      var input = inputs.get(i);
      if(input.title != '' && input.value == ''){
	msg.push("O campo "+input.title+" é obrigatório");
      }
    }
		
    var inputs = jqForm.find('select');
    var i = inputs.size();
    while(i--){
      var input = inputs.get(i);
      if(input.title != '' && input.value == ''){
	msg.push("O campo "+input.title+" é obrigatório");
      }
    }
		
		
    if (msg.length > 0) {
      var text = "";
      for(i=0;i<msg.length;i++)
	text += msg[i] + "<br />";
			
      if (text != "")
	jq.html(text);
    }
    else {
      var buttom = $(this);
      var params = jqForm.serialize();
      $.ajax({
	type: jqForm.attr("method"),
	url: jqForm.attr("action"),
	data: params,
	beforeSend: function(){
	  jq.show();
	  jq.html('Enviando...');
	  buttom.hide();
	},
	success: function(txt){
        var msg = "";
        data = new String(txt);
        var flag = data.match(/<return>1<\/return>/gi);
        if(flag)
        	jqForm.get(0).reset();
        else
        	buttom.show();
        
        var msgs = data.replace(/(.*<msgs>)|(<\/msgs>.*)|(<\/msg>)/gi, '').split('<msg>');
        var total = msgs.length;
        
        for(var i=1;i<total;i++)
            msg += msgs[i]+"<br />\n";
        
        jq.html(msg);
	},
	error: function(txt){
	  jq.html(txt);
	}
      })
    }
    return false;
  });
	
  /** ---------------------------------------------------------- */
	
  /**
	* LightBox da Galeria de Fotos
	*/
  $('.gallery a').lightBox();
  $('.openBox').lightBox();
	
  /** ---------------------------------------------------------- */
	
  /**
	* Carrossel da Galeria de Fotos
	*/
  $('#mycarousel').jcarousel({
    scroll: 1,
    time: 5000,
    auto: 4,
    wrap: 'last'
  });	
	
  /** ---------------------------------------------------------- */
	 
  /**
	* Banner Rotativo
	*/
  $('#Banner').before('<div id="nav">').cycle({
    fx:     'fade',
    speed:   600,
    timeout: 5000,
    pager:  '#nav'
  });
	
  /** ---------------------------------------------------------- */
   
  /**
	 * Menu
	 */	 
  $('.menu ul li').mouseover(function(){
    $(this).parents('ul').eq(0).find('ul').hide();
    var ul = $(this).find('ul').not($(this).find('ul').find('ul'));
    ul.fadeIn("fast");
    window.clearTimeout(timeId);
    return false;
  });
		

  $('.menu ul li ul').mouseover(function(){
    window.clearTimeout(timeId);
    return false;
  });
		
  $('.menu li').mouseleave(function(){
    var jq = $(this).parents('ul').find('ul');
    timeId = window.setTimeout(function() {
      jq.fadeOut();
    },1000);
    return false;
  });
		
  /** ---------------------------------------------------------- */
		
  /**
		* Calendário
		*/
  $(".cal_nav").click(function(){
    Calendario.change(this);
    return false;
  });
	
  $('.tooltip').tooltip({
    track: true,
    delay: 0,
    showURL: false,
    showBody: " - ",
    fade: 150
  });
  /** ---------------------------------------------------------- */
	
  /**
   * Exibe legenda da imagem da notícia
   */
	
  $('.legenda-NOTÍCIAS').each(
    function() {
      var legenda = $(this);
      if (legenda.parent().find('img').size()) {
        if (legenda.parent().find('img').attr('alt') != "") {
          legenda.html(legenda.parent().find('img').attr('alt'));
          legenda.css('width',legenda.parent().find('img').width()+1+'px');
          legenda.show();
        }
      }
    }
  );
  /** ---------------------------------------------------------- */
  
  // /**
	// * Controle de Contraste
	// */
  // if ( $.cookie('ASS') == "modify" ) {
    // setActiveStyleSheet('modify');
  // } else {
    // setActiveStyleSheet('padrao');
  // }
  // $('.contraste').click(function() {
    // if ( getActiveStyleSheet() == "padrao" ) {
      // setActiveStyleSheet('modify');
      // $.cookie('ASS', 'modify');
    // } else {
      // setActiveStyleSheet('padrao');
      // $.cookie('ASS', 'padrao');
    // }
  // });
	
  /** ---------------------------------------------------------- */
	
  /**
	* Link para a Capa
	*/
  $('#home').css('cursor','pointer');
  $('#home').click(function(){
    window.location='index.php?id=/capa/index.php';
  });
	
  /** ---------------------------------------------------------- */  
  
    /**
	* Banner Pop Up
	*/
  $('.banner-close').click(function() {
	$('.banner-popup').fadeOut(function() {
		$(this).remove();
	});
  });
  setTimeout(function() {
	if($('.banner-popup').size()) {
		$('.banner-popup').fadeOut(function() {
			$(this).remove();
		});
	}
  }, 8000);
  
  /** ---------------------------------------------------------- */  
  
    /**
	* PrettyPhoto
	*/
	$("a[rel^='prettyPhoto']").prettyPhoto();
	
	/** ---------------------------------------------------------- */  
	
    /**
	* Máscaras
	*/
	$(".date").mask("99/99/9999",{placeholder:"_"});
	/** ---------------------------------------------------------- */  
});	

/**
* Função de Geração do Calendário
*/
var Calendario = {
  change:function(elem){
    $(".cal_nav").unbind();
    //$(elem).parents('.calendar_box').prepend('<div class="loading">Carregando...</div>');
    var url = "?id=/includes/paginas/calendario.php";
    url += "&"+$(elem).attr('rel');
    $(elem).ajaxComplete(function(event,request, settings){
      var data = $.httpData(request,settings.dataType);
      $(this).parents('.calendar_box').html(data);
      Calendario.rebind();
    });
    $.post(url);
  },
  rebind:function(){
    $(".cal_nav").click(function(){
      Calendario.change(this);
      return false;
    });
    // refaz as tooltips
    $('.calendar_box .tooltip').tooltip({
      track: true,
      delay: 0,
      showURL: false,
      showBody: " - ",
      fade: 150
    });
  }
}

/** --------------------------------------------------------------------------------------- */

/**
 * Funções de acessibilidade
 */

var Acessibilidade = {
  ini:function(){
    if(Cookies.read("contraste") == 1){
      Acessibilidade.toggleContraste();
    }
  },
  toggleContraste:function(){
    var isContraste = $("head > #contraste").size();
    if(isContraste){//alert('marcelo1');
      $('#contraste').remove();
      Cookies.erase("contraste");
    }else{//alert('marcelo2');
      $('head').append('<link id="contraste" type="text/css" href="includes/css/contraste.css" rel="stylesheet" />');
      Cookies.create("contraste", 1);
    }
  }
};

var Cookies ={
  create:function(name,value,days){
    if (days){
      var date = new Date();
      date.setTime(date.getTime()+(days*24*60*60*1000));
      var expires = "; expires="+date.toGMTString();
    }
    else var expires = "";
    document.cookie = name+"="+value+expires+"; path=/";
  },
  read:function(name){
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++){
      var c = ca[i];
      while (c.charAt(0)==' ') c = c.substring(1,c.length);
      if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
  },
  erase:function(name){
    Cookies.create(name,"",-1);
  }
};

var Apoio = {
  link_externo:function(elem){
    $(elem).attr("target", "_blank");
  }
}
