/*
 * This script takes a div containing an indeterminate number of links
 * and converts it to a circular filmstrip based on the parameters specified.
 * Uses hoverIntent for hover function - http://cherne.net/brian/resources/jquery.hoverIntent.minified.js  
 */

var cwFilmstrip = {
  
    // set options
    slideTime: 2500, // time one cell takes to move
    waitTime: 1500, // time filmstrip pauses between cells
    cellWidth: 316,
    initialCells: 3, // number of static images placed on page to start
    firstVisibleCell: 0,
    totalCells: $("#ss_inner a").size(), 
    cellLoaded: new Array(this.totalCells), // hold boolean value for each image
    totalCellsLoaded: this.initialCells,
    allCellsLoaded: false,
    hasMoved: false,
    leftMargin: 0, // used for alignment
    interval: null, // used for autoflow
    timer: null, // used to synchronize image loading with filmstrip movement
    isPaused: false, // auto-start setting
    show_title: true,
    
      
  init: function() {
    
    // detect IE6
    var isIE6 = /msie|MSIE 6/.test(navigator.userAgent);
    
    // add jQuery function to load image instead of content in element     
    $.fn.loadImage = function(src, callback){
    	return this.each(function(){
    	var i = new Image();
    	i.src = src;
      i.onload = callback;
    	this.content=''; // clear existing content
    	this.appendChild(i);
    	});
    }     
     
    $.fn.setHover = function() {
      return this.each(function() {         
        // set hover behavior
        $(this).hoverIntent(function(){ 
            // show highlighter (doesn't work in IE6)
            if(!isIE6) { $(this).children("img.highlighter").fadeIn(1000); }
            cwFilmstrip.pause() 
          }, function() { 
            if(!isIE6) { $(this).children("img.highlighter").fadeOut(1000); }
            if(!$("div.ppt").is(":visible")) {
              cwFilmstrip.play();
          }
        })
      });
    }
    
    $.fn.addHighlighter = function() {
      return this.each(function() {
      // create highlighter image
        var i = new Image();
        i.src = "assets/images_pres/slideshow_overlay.png";
        $(i).addClass("highlighter").hide();
        this.appendChild(i);
      });
    }
    
    // initial load of lightbox & hover behavior, and hidden highlighter image 
    // the first two must be called again after each new link is created
    this.loadLightbox();
    $("#ss_inner a").setHover();
    $("#ss_inner a:has(img)").addHighlighter();
        
    // enlarge container to appropriate size
    var totalWidth = this.totalCells * this.cellWidth;
    $("#ss_inner").css({'width': totalWidth}); 
    
    // load cells
        
    // select all anchor elements within filmstrip that don't already have an image child
    $("#ss_inner a").not("a:has(img)").each(function(i) {
      // set timer to delay move if image loads quickly, but only if there isn't another one there already 
      if(!cwFilmstrip.timer) {
        var functionCall = "cwFilmstrip.moveIfLoaded(" + i + ")";
        cwFilmstrip.timer = setTimeout(functionCall,this.waitTime);
      }
      
      // get image source from link target by replacing text
      // pass move function as callback
      $(this).loadImage(this.href.replace("_zoom","_preview"),
        function() { 
          cwFilmstrip.cellLoaded[i] = true;
          // move cell onlf if slideshow hasn't begun and if there's not already a timer waiting
          if(!cwFilmstrip.timer && !cwFilmstrip.allCellsLoaded) {
            cwFilmstrip.move(1);
          }
        }).
        addHighlighter();
      });
            
    // after loading, begin auto-flow
    this.allCellsLoaded = true;
    this.waitToStart();	
      
  },
	
	waitToStart: function() {
    // as long as there is a timer, wait for it to finish
    if(this.timer) {
      setTimeout("cwFilmstrip.waitToStart()",100);
    }
    else {
      this.start();
    }
  },
	
	moveIfLoaded: function(index) {
    // if cell at index has loaded, move filmstrip
    if(this.cellLoaded[index]) {
      this.move(1);
    }
    else {
      clearTimeout(this.timer);
    }
    this.timer = null; // destroy timer so callback won't find it  
  },
	
	pause: function() {
    this.isPaused = true;
  },
  
  play: function() {
    this.isPaused = false;
  },
	
	stop: function() {
    clearInterval(this.interval);
  },
  
  start: function() {
    this.interval = setInterval("cwFilmstrip.move(1)",(this.slideTime + this.waitTime));  
  },
	
  move: function(increment) {
    
    if(!this.isPaused) {
      /* if this function is called without an image present, it will display blanks
       * increment is int argument: positive is forward, negative is reverse
    	 */
              	
    	if(!this.allCellsLoaded || !this.hasMoved) {
    		// filmstrip not fully loaded or has not moved at all.
        this.leftMargin -= this.cellWidth * increment;
        this.hasMoved = true;
    		}
    	else {
        // fully loaded; must wrap          
    		var tempLeftMargin = this.leftMargin + (this.cellWidth * increment); 
    		if(increment > 0 ) {
          // forward
          $("#ss_inner a:first").remove().insertAfter($("#ss_inner a:last")).setHover();
    		  }
        else {
          // reverse
          $("#ss_inner a:last").remove().insertBefore($("#ss_inner a:first")).setHover();
        }
        // lightbox and hover events are not copied, so we have to recreate them
        this.loadLightbox();
        // set temporary left margin to hold strip in place until animation starts
        $("#ss_inner").css({'margin-left': tempLeftMargin});         
    	}
    	// slide
      $("#ss_inner").animate(
    	   { 'margin-left': this.leftMargin },
    		 this.slideTime
      );
    }
    
  },
  
  loadLightbox: function() {
    $("a[rel='prettyPhoto[filmStrip]']").prettyPhoto({
      theme: 'light_square', 
      overlay_gallery: false,
      counter_separator_label: " of ", 
      // on close
      callback: function() { 
        if(cwFilmstrip.isPaused) {
          cwFilmstrip.play();
        }
      }
    });  
  }

}

// begin function only after all images are loaded
$(window).load(function() {
   cwFilmstrip.init()
});


