/*
anythingFader v1.0

By Chris Coyier: http://css-tricks.com

To use the navigationFormatter function, you must have a function that
accepts two paramaters, and returns a string of HTML text.

index = integer index (1 based);
panel = jQuery wrapped LI item this tab references
@return = Must return a string of HTML/Text

navigationFormatter: function(index, panel){
return index + " Panel"; // This would have each tab with the text 'X Panel' where X = index
}
*/

(function($){

  $.anythingFader = function(el, options){
    // To avoid scope issues, use 'basef' instead of 'this'
    // to reference this class from internal events and functions.
    var basef = this;

    // Access to jQuery and DOM versions of element
    basef.$el = $(el);
    basef.el = el; 

    // Set up a few defaults
    basef.currentPage = 1;
    basef.timer = null;
    basef.playing = false;

    // Add a reverse reference to the DOM object
    basef.$el.data("AnythingFader", basef);

    basef.init = function(){
      basef.options = $.extend({},$.anythingFader.defaults, options);

      // Cache existing DOM elements for later 
      basef.$wrapper = basef.$el.find('> div').css('overflow', 'hidden');
      basef.$slider  = basef.$wrapper.find('> ul');
      basef.$items   = basef.$slider.find('> li');
      basef.$single  = basef.$items.filter(':first');

      // Build the navigation if needed
      if(basef.options.buildNavigation) basef.buildNavigation();

      // Get the details
      basef.singleWidth = basef.$single.outerWidth();
      basef.pages = basef.$items.length;

      // Top and tail the list with 'visible' number of items, top has the last section, and tail has the first
      // This supports the "infinite" scrolling
      basef.$items.filter(':first').before(basef.$items.filter(':last').clone().addClass('cloned'));
      basef.$items.filter(':last' ).after(basef.$items.filter(':first').clone().addClass('cloned'));

      // We just added two items, time to re-cache the list
      basef.$items = basef.$slider.find('> li'); // reselect

      // Setup our forward/backward navigation
      //basef.buildNextBackButtons();

      // If autoPlay functionality is included, then initialize the settings
      if(basef.options.autoPlay) {
        basef.playing = !basef.options.startStopped; // Sets the playing variable to false if startStopped is true
        basef.buildAutoPlay();
      };

      // If pauseOnHover then add hover effects
      if(basef.options.pauseOnHover) {
        basef.$el.hover(function(){
          basef.clearTimer();
        }, function(){
          basef.startStop(basef.playing);
        });
		
		/*$("#topo, #logo, .materia_ler").hover(function(){
		  basef.clearTimer();
		}, function(){
		  basef.startStop(basef.playing);
		});*/
      }

      // If a hash can not be used to trigger the plugin, then go to page 1
      if((basef.options.hashTags == true && !basef.gotoHash()) || basef.options.hashTags == false){
        basef.setCurrentPage(1);
      };
    };

    basef.gotoPage = function(page, autoplay) {
      // When autoplay isn't passed, we stop the timer
      if(autoplay !== true) autoplay = false;
      if(!autoplay) basef.startStop(false);

      if(typeof(page) == "undefined" || page == null) {
        page = 1;
        basef.setCurrentPage(1);
      };

      // Just check for bounds
      if(page > basef.pages + 1) page = basef.pages;
      if(page < 0 ) page = 1;

      var dir = page < basef.currentPage ? -1 : 1,
      n = Math.abs(basef.currentPage - page),
      left = basef.singleWidth * dir * n;

      basef.$wrapper.filter(':not(:animated)').animate({
        opacity: '0'
      }, basef.options.animationTime, basef.options.easing, function () {
        if (page == 0) {
          basef.$wrapper.scrollLeft(basef.singleWidth * basef.pages);
          page = basef.pages;
        } else if (page > basef.pages) {
          basef.$wrapper.scrollLeft(basef.singleWidth);
          // reset back to start position
          page = 1;
        };
        basef.setCurrentPage(page);

      });

      basef.$wrapper.animate({
        opacity: '1'
        }, basef.options.animationTime, basef.options.easing);
      };

      basef.setCurrentPage = function(page, move){
        // Set visual
        if(basef.options.buildNavigation){
          basef.$nav.find('.cur').removeClass('cur');
          $(basef.$navLinks[page - 1]).addClass('cur');
		  
		  var contador_atual= parseInt($("#contador").val())+1;
		  
		  $("#item_lista_"+page).css("z-index", contador_atual);
		  
		  $("#contador").val(contador_atual);
		  
		  //alert($(basef.$navLinks[page - 1]).attr("style"));
		  
		  //if ($("body").is(".home")) {
		      //$(".materia_nav").find('.atual').removeClass('atual');
		  	  //$(".item"+page).addClass('atual');
			  
		//	alert(page);
		  //}
        };

        // Only change left if move does not equal false
        if(move !== false) basef.$wrapper.scrollLeft(basef.singleWidth * page);

        // Update local variable
        basef.currentPage = page;
      };

      basef.goForward = function(autoplay){
        if(autoplay !== true) autoplay = false;
        basef.gotoPage(basef.currentPage + 1, autoplay);
      };

      basef.goBack = function(){
        basef.gotoPage(basef.currentPage - 1);
      };

      // This method tries to find a hash that matches panel-X
      // If found, it tries to find a matching item
      // If that is found as well, then that item starts visible
      basef.gotoHash = function(){
        if(/^#?panel-\d+$/.test(window.location.hash)){
          var index = parseInt(window.location.hash.substr(7));
          var $item = basef.$items.filter(':eq(' + index + ')');
          if($item.length != 0){
            basef.setCurrentPage(index);
            return true;
          };
        };
        return false; // A item wasn't found;
      };

      // Creates the numbered navigation links
      basef.buildNavigation = function(){
        basef.$nav = $("<div id='thumbNav'></div>").appendTo(basef.$el);
        basef.$items.each(function(i,el){
          var index = i + 1;
          var $a = $("<a href='#'></a>");

          // If a formatter function is present, use it
          if( typeof(basef.options.navigationFormatter) == "function"){
            $a.html(basef.options.navigationFormatter(index, $(this)));
          } else {
            $a.text(index);
          }
          $a.click(function(e){
            basef.gotoPage(index);

            if (basef.options.hashTags)
            basef.setHash('panel-' + index);

            // console.log("click test");  passed

            e.preventDefault();
          });
          basef.$nav.append($a);
        });
        basef.$navLinks = basef.$nav.find('> a');
      };


      // Creates the Forward/Backward buttons
      /*basef.buildNextBackButtons = function(){
        var $forward = $('<a class="arrow forward">&gt;</a>'),
        $back    = $('<a class="arrow back">&lt;</a>');

        // Bind to the forward and back buttons
        $back.click(function(e){
          basef.goBack();
          e.preventDefault();
        });

        $forward.click(function(e){
          basef.goForward();
          e.preventDefault();
        });

        // Append elements to page
        basef.$wrapper.after($back).after($forward);
      };*/

      // Creates the Start/Stop button
      basef.buildAutoPlay = function(){
		//<a href='#' id='start-stop'></a>
        basef.$startStop = $("").html(basef.playing ? basef.options.stopText :  basef.options.startText);
        basef.$el.append(basef.$startStop);            
        basef.$startStop.click(function(e){
          basef.startStop(!basef.playing);
          e.preventDefault();
        });

        // Use the same setting, but trigger the start;
        basef.startStop(basef.playing);
      };
	  
	  /*$(".materia_nav ul li a.indexador").click( function() {
		basef.startStop(0);
        //e.preventDefault();
		
		$('.fader').anythingFader($(this).attr("tabindex"));
		
		return false;
	});*/

      // Handles stopping and playing the slideshow
      // Pass startStop(false) to stop and startStop(true) to play
      basef.startStop = function(playing){
        if(playing !== true) playing = false; // Default if not supplied is false
//playing=false;
        // Update variable
        basef.playing = playing;

        // Toggle playing and text
        if(basef.options.autoPlay) basef.$startStop.toggleClass("playing", playing).html( playing ? basef.options.stopText : basef.options.startText );

        if(playing){
          basef.clearTimer(); // Just in case this was triggered twice in a row
          basef.timer = window.setInterval(function(){
            basef.goForward(true);
            }, basef.options.delay);
          } else {
            basef.clearTimer();
          };
        };

        basef.clearTimer = function(){
          // Clear the timer only if it is set
          if(basef.timer) window.clearInterval(basef.timer);
        };

        // Taken from AJAXY jquery.history Plugin
        basef.setHash = function ( hash ) {
          // Write hash
          if ( typeof window.location.hash !== 'undefined' ) {
            if ( window.location.hash !== hash ) {
              window.location.hash = hash;
            };
          } else if ( location.hash !== hash ) {
            location.hash = hash;
          };

          // Done
          return hash;
        };
        // <-- End AJAXY code


        // Trigger the initialization
        basef.init();
      };


      $.anythingFader.defaults = {
        easing: "swing",                // 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
        startStopped: false,            // If autoPlay is on, this can force it to start stopped
        delay: 3000,                    // How long between slide transitions in AutoPlay mode
        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: "Start",             // Start text
        stopText: "Stop",               // Stop text
        navigationFormatter: null       // Details at the top of the file on this use (advanced use)
      };


      $.fn.anythingFader = function(options){
        if(typeof(options) == "object"){
          return this.each(function(i){			
            (new $.anythingFader(this, options));

            // This plugin supports multiple instances, but only one can support hash-tag support
            // This disables hash-tags on all items but the first one
            options.hashTags = false;
          });	
        } else if (typeof(options) == "number") {

          return this.each(function(i){
            var anySlide = $(this).data('AnythingFader');
            if(anySlide){
              anySlide.gotoPage(options);
            }
          });
        }
      };


      })(jQuery);
