/*
 * Sizzle CSS Selector Engine - v0.9.3
 *  Copyright 2009, The Dojo Foundation
 *  Released under the MIT, BSD, and GPL Licenses.
 *  More information: http://sizzlejs.com/
 */

(function($){
  $.fn.animate2=function(css,speed,fn){
    fn=fn||function(){};
    if(speed===0){
      this.css(css);window.setTimeout(fn,0);
    }else{
      if($.browser.safari){
        var s=[];
        for(var i in css){s.push(i);}
        this.css({webkitTransitionProperty:s.join(", "),webkitTransitionDuration:speed+"ms"});
        window.setTimeout(function(x,y){x.css(y);},0,this,css);
        window.setTimeout(fn,speed);
      }else{
        this.animate(css,speed,fn);
      }
    }
  };

  $.heroFader={};
  $.fn.heroFader=function(controlsSelector,pagesClass){
    var duration=400,sleep=5000;
    
    $.heroFader.elem=this,$.heroFader.controls=this.find(controlsSelector).hide(),$.heroFader.blocks=this.find(pagesClass);
    
    if($.heroFader.blocks.length<1){
      return this;
    }
    
    if($.heroFader.blocks.length<2){
      $.heroFader.blocks.eq(0).showHero(0);
      return this;
    }
    
    $.heroFader.blocks.each(
      function(i){
        var block_id=($(this).attr("id").length>0)?$(this).attr("id"):"fader_block_"+i;
        $(this).attr("id",block_id);
        var class_name=(i==0)?"first":"";
        if(i==$.heroFader.blocks.length-1){
          class_name="last";
        }
        $.heroFader.controls.append('<a class="'+class_name+'" href="#'+block_id+'">&bull;</a>');
      }
    );
    
    $.heroFader.controls.css({"margin-left":parseInt(-$.heroFader.controls.width()/2)}).show();
    $.heroFader.controls.find("a").click(
      function(){
        var target_url=$(this).attr("href").split("#")[1];
        $("#"+target_url).showHero(duration);
        return false;
      }
    );
    
    var mouseOverFader=false;
    $.heroFader.elem.hover(
      function(){mouseOverFader=true;},function(){mouseOverFader=false;
      }
    );
      
    $.heroFader.blocks.eq(0).showHero(0);
    setInterval(function(){
      if(mouseOverFader){
        return false;
      }
      var current=$.heroFader.blocks.filter(":visible"),nextHero=current.next();
      if(nextHero.length<1){
        nextHero=$.heroFader.blocks.eq(0);
      }
      nextHero.showHero(duration);
    },sleep);
    return this;
  };
  $.heroFader.currentlyAnimating=false;
  $.fn.showHero=function(duration){
    if($.heroFader.currentlyAnimating){
      return;
    }
    var current=$.heroFader.blocks.filter(":visible").css({"z-index":1});
    if(current[0]===this[0]){
      return;
    }
    $.heroFader.controls.find("a.active").removeClass("active");
    $.heroFader.controls.find("a[href$="+this.attr("id")+"]").addClass("active");
    $.heroFader.currentlyAnimating=true;
    this.css({opacity:0}).show().animate2(
      {opacity:1},duration,function(){
        $.heroFader.currentlyAnimating=false;
        current.css({opacity:0,"z-index":5}).hide();
      }
    );
  };
})(jQuery);

