$(function(){

//search
var mainMenu = $('#menu');
var mainSubMenu = mainMenu.find('ul');
var search = $('#search');
var searchTip = $('#search').find('.tip');
var searchInput = search.find('.string');
search.delegate('#advancedSearch', 'click focus', function(e, first){
  e.preventDefault();
  var advancedSearchLabel = $(this);
  var advancedFields = $('#advancedFields');
  if(advancedSearchLabel.hasClass('opened') && first != true) {
    search.animate({'margin-top': '0'}, function(){
      searchTip.slideDown(300);
      mainMenu.fadeIn(function(){
        advancedSearchLabel.text('Pesquisa Avançada').removeClass('opened');
        search.find('.string').select();
      });
    });
  } else {
    searchTip.slideUp(800);
    mainMenu.fadeOut(function(){
      search.animate({'margin-top': '-140px'}, function(){
        advancedSearchLabel.text('Pesquisa Simples').addClass('opened');
        search.find('.string').select();
      });
    });
  }
});
if($('#advancedSearch').hasClass('opened')){ $('#advancedSearch').trigger('click', [true]); }
  

//best content highlights
$.fn.showBestContent = function(url){
  //declare main vars
  var bestContentHighlights = $('#bestContentHighlights').find('.highlightsArea'),
    bestContentSelection = $('#bestContentSelection'),
    defaultContentHighlight = 'destaque';
  window.slideShowTimeout = "";
  //show highlights of default area
  //function loadBestContent(selectedContent){
  $.fn.loadBestContent = function(selectedContent){
    //clear vars data
    var highlight = '',
        highlightLabel = '',
        highlightLabelHTML = '',
        thumbs = '',
        seeAll = '',
        thumbsList = '',
        tempPlaceholder = '',
        totalImgs = 0;
    bestContentHighlights.ajaxSend(function(e, xhr, settings){
      //only do this loading for the homepage slider json
      if (settings.url == url+'/'+selectedContent) {
        //remove extra info
        $('.highlightLabel, .seeAllHighlights, .thumbsContainer').remove();
        //force width auto to revert the calculation of the necessary width for all the images and show the load icon
        bestContentHighlights.html('<img src="'+window.GlobalFn.URL.basePath+'/assets/images/global/icon_loader.gif" alt="a carregar..." width="48" height="48" class="loader" />').width('auto');
      }
    });
    $.ajax({
      url: url+'/'+selectedContent,
      dataType: 'json',
      error: function(){
        bestContentHighlights.html('<p class="loader">Ocorreu uma anormalia ao chamar o serviço.<br/><strong>Por favor, tente novamente.</strong></p>').width('auto');
      },
      success: function(data){
        if(data[selectedContent] != undefined){

          thumbs = '<ul class="thumbsContainer">';
          //iterate through available items on the selected area
          for(i=0; i<data[selectedContent].content.length; i++){
            highlight += '<a href="'+data[selectedContent].content[i].url+'" title="'+data[selectedContent].content[i].title+'"><img src="'+data[selectedContent].content[i].image+'" alt="'+data[selectedContent].content[i].title+'" width="530" height="260" /></a>';
            thumbs += '<li><a href="' + data[selectedContent].content[i].url + '" title="' + data[selectedContent].content[i].title + '"><img src="' + data[selectedContent].content[i].thumbnail + '" alt="' + data[selectedContent].content[i].title + '" width="131" height="64" /></a></li>';
            totalImgs++;
          }
          thumbs += '</ul>';
          
          //set the view all link
          $('.seeAllHighlights').remove();
          seeAll = data[selectedContent].link;
          seeAll = '<a href="'+seeAll+'" title="Ver Todas" class="seeAllHighlights">Ver Todas</a>';
          $(seeAll).insertAfter(bestContentHighlights.parent()).hide();
          
          //create a temporary element and get images loaded into it
          $('<div class="temp_placeholder" style="position:absolute; top:-99999px; left:-99999px;">').insertAfter(bestContentHighlights.parent());
          tempPlaceholder = $('.temp_placeholder');
          tempPlaceholder.html(highlight);
          
          //set the item label
          $('.highlightLabelContainer').remove();
          highlightLabelHTML = '<div class="highlightLabelContainer">';
          highlightLabelHTML += '<a href="'+tempPlaceholder.children().eq(0).attr('href')+'" title="'+tempPlaceholder.children().eq(0).attr('title')+'" class="highlightLabel"><span>'+tempPlaceholder.children().eq(0).attr('title')+'</span></a>';
          highlightLabelHTML += '</div>';
          $(highlightLabelHTML).insertAfter(bestContentHighlights.parent()).hide();
          highlightLabel = $('.highlightLabel');
          
          //set the area thumbs
          $('.thumbsContainer').remove();
          $(thumbs).insertAfter(bestContentHighlights.parent()).hide();
          thumbsList = $('ul.thumbsContainer').find('li');
          thumbsList.first().css({'margin':'0'}).addClass('active');  
        }
      },
      complete: function(){
        //show highlight items and set the width necessary to the highlightsArea
        bestContentHighlights.html(tempPlaceholder.html()).width(bestContentHighlights.parent().width()*totalImgs).fadeIn();
        //delete temporary element
        tempPlaceholder.remove();
        
        //show higlight item label and see all link
        $('.highlightLabelContainer, .seeAllHighlights').fadeIn();
        
        //show higlightedd item and thumbs from the selected area
        $('.thumbsContainer').fadeIn();
        var thumbsOpacity = 0.7;
        thumbsList.not('.active').fadeTo(0, thumbsOpacity);
        
        
        //build slideshow
        (function bestContentSlideShow(){
          if($.type(window.slideShowTimeout)=="number"){clearInterval (window.slideShowTimeout);}
          window.slideShowTimeout = setInterval(function()
          {
            var $current = thumbsList.filter('.active'),
                $next = $current.next().length ? $current.next(): thumbsList.first();
            $current.removeClass('active').fadeTo(300, thumbsOpacity);
            $next.addClass('active').fadeTo(300, 1, function()
            {
              highlightLabel.parent().animate({'left': '-200px'});
              $('#bestContentHighlights').find('.slider').animate(
              {
                scrollLeft: $('#bestContentHighlights').width()
              }, 'slow', function(){
                bestContentHighlights.children().first().appendTo(bestContentHighlights);
                bestContentHighlights.parent().scrollLeft(0);
                highlightLabel.attr({
                  href: bestContentHighlights.children().eq(0).attr('href'),
                  title: bestContentHighlights.children().eq(0).attr('title')
                }).find('span').text(bestContentHighlights.children().eq(0).attr('title'));
                highlightLabel.parent().delay(100).animate({'left': '0'});
              });
            });
          }, 7000);
        })();
        
        //hovering thumbs
        thumbsList.hover(
          function(){
            $(this).fadeTo(300, 1); 
          }, function(){
            if(!$(this).is('.active')) $(this).fadeTo(300, thumbsOpacity); 
          }
        );
        
      }
    });
  }
  
  //fire on page load after getting the global vars
  window.GlobalFn.URL.init(function() {
    $.fn.loadBestContent(defaultContentHighlight);
  });
  
  //show highlights of selected area
  bestContentSelection.find('a[href=#'+defaultContentHighlight+']').addClass('active');
  $('#content').delegate('#bestContentSelection a', 'click focus', function(e){
    e.preventDefault();
    var selectedItem = $(this).attr('href');
    selectedItem = selectedItem.substr(1);
    if(defaultContentHighlight !== selectedItem){
      defaultContentHighlight = selectedItem;
      bestContentSelection.find('a.active').removeClass('active').end().find('a[href=#'+defaultContentHighlight+']').addClass('active');
      window.GlobalFn.URL.init(function() {
        $.fn.loadBestContent(defaultContentHighlight);
      });
    }
  }); 
};
  
  
  
});

