	// Use javascriptcompressor.com to compress this
//   v2.0 2009/02/15 : ajax version to read in values from server

var   all_products = new Array();
var   all_products_count = 0;

var   named_slideshows = new Array();
var   global_stop;
var   global_speed;

function fsjs_startshow(product, speed) {
//	alert("startshow:" + product + " speed: " + speed);
        global_speed = speed;
        run_start_obj_post(product);
}
function fsjs_stopshow(product) {
        global_stop  = 1;
//	alert("stopshow:" + product);

        if ( named_slideshows[product] ) {
              named_slideshows[product].stopshow();
	}
}


function run_start_obj_post(product) {

      global_stop  = 0;

      if ( named_slideshows[product] ) {
           named_slideshows[product].startshow();
      } else {
           $.post("/action",
                  {screen:'get_slideshow_values' , product: product},
                  setup_playback_object,
                  "json"
                 );
      }
}

function setup_playback_object(data) {


       var tmp_obj = new SlideShowSimple(         data[0].product, 
                                                  data[0].product,
                                                  data[0].still_number, 
						  data[0].still_pattern,
                        	                  data[0].still_numstills,
                        	                  data[0].still_fps,
                        	                  data[0].still );
        named_slideshows[ data[0].product ] =  tmp_obj;

	tmp_obj.startshow();
}


$(document).ready(function(){
    $(".simple_roll_over_playback").mouseover(function(event){

//    alert("mouseover");

      global_stop  = 0;
      global_speed = 1;

	if ( this.name == "" ){

	     // src should be of the form: http://www.oceanfootage.com/stillimage/AG01_001
	     // src should be of the form: http://www.oceanfootage.com/preview/ST/ST05/Images/ST05_040/frame--000015.jpg
             //                        or: /stillimage/AG01_001
	
              var srcurl = this.src;
	      srcurl = srcurl.replace(/\/frame(.*).jpg/,"")
	      var last_slash_pos = srcurl.lastIndexOf('/')
	      this.name = srcurl.substring(last_slash_pos+1);

	}

//      alert("mouseover before post");
	if ( this.name != "" ) {
	        run_start_obj_post(this.name);
        }
      
    });



    

    $(".simple_roll_over_playback").mouseout(function(){
//	alert("mouseout"+this.name);

	   if ( named_slideshows[this.name] ) {
              named_slideshows[this.name].stopshow();
	}
    });

});

// Use javascriptcompressor.com to compress this
//   v1.1 2008/04/21 : fixed short film 3x problem

function debug(aMsg) {
}


 
function PadDigits(n, totalDigits) 
{ 
  n = n.toString(); 
  var pd = ''; 
  if (totalDigits > n.length) { 
    for (i=0; i < (totalDigits-n.length); i++) { 
       pd += '0'; 
    } 
  } 
  return pd + n.toString(); 
} 

// Note initial_url is option, may be derived from initial-frame if not set.
function SlideShowSimple(product, image_name, initial_frame, pattern_value, numstills, fps, initial_url )
{
  var imageNum = 0;
  var startFrame = initial_frame;
  var objname = 'named_slideshows[\''+product+'\']';
  var lastplace = product;
  var place = product;
 
  var startURL;

  if ( initial_url === undefined ) {
      startURL = "";
  } else {
      startURL = initial_url;
  }

  var imageArray = new Array();

  var num_advance_frames = 1;
  var interval = (1000/fps);
  var waiting_for_load = 0; 
  var preload_before_start = 45;
	

  var pattern = pattern_value;

  var image_urls =  new Array();

  var timerID;

  /* do not count the last image in the array, it is just a blank placeholder */
  var totalImages = 0;

 
 /* These are the public functions, called in mouse over/mouse exit, and the timer */
 this.startshow = startshow;
 this.stopshow = stopshow;
 this.switchImage = switchImage;
 this.reset_images = reset_images;


 /* Called externally when need images unloaded. */
 function reset_images() {
	var i;

	/* Start at the end and work back */
        for ( i = imageArray.length; i >=0 ; i--)	 {
		delete(imageArray[i]);
	}
	delete(imageArray);
	imageArray = new Array();

	/* Clear the timer if it had one */
        clearTimeout(timerID);
    
 }

 /* Called when mouse enters picture, reset to first image in sequence */
 function startshow() {

  
//  alert("startshow:" + objname);
 var place = lastplace;

//alert("place:" + place);

  // Start at images 0
  imageNum = 0;	



  /* Global named_slideshows is a full list, go through and reset the rest, but not this one */
  if ( typeof named_slideshows != "undefined" ) {
      for(var i in named_slideshows) {
  	if( named_slideshows[i] != this ) {
              	named_slideshows[i].reset_images();
	}
     }
  } 

  /* go stop the rest of the animations */


  var i;
  for ( i = 0; i < numstills; i++) {
	var tmpnum = PadDigits(i,6);
	image_urls[i] =  pattern.replace('XXXXXX',tmpnum);
  }
  totalImages = image_urls.length - 1 ;



//  debug("Starting show for " + objname);
  // Set the global for this object, called from mousing over a 2x 3x 4x, unset from others.
  num_advance_frames = 1;
  if ( typeof optional_speed != "undefined") {
    num_advance_frames = optional_speed;

    if (num_advance_frames < 1 ) {
      num_advance_frames = 1;
    }

  }

  // Minimum frame # to load before start playing animation.
  // will be checked in the image code later

  preload_before_start = 45*num_advance_frames;
  if ( preload_before_start >= numstills ) {
    preload_before_start = numstills - 1;
  }


//  debug("Starting showImage " + place);

  showImage(place,0);


  lastplace = place;
  var recur_call = objname + '.switchImage()';
//  alert("recur_call:" + recur_call);
  clearTimeout(timerID);
  timerID = setTimeout(recur_call, interval);

//  debug("Timer Set, exiting intrerval = " + interval);

 }



 /* Called when mouse leaves picture, reset to the picked 'start' image in sequence */
 function stopshow() {

//  debug("Stopping show for " + objname);


  // when the initial URL has not been set, use start frame instead
  if ( startURL != "" ) {

//     alert("X1:Setting image "+ place + " to " + startURL);
     document[place].src = startURL;
  } else {
     imageNum = startFrame;

//     alert("X2:Setting image "+ place + " to " + img_urls[startFrame]);
     document[place].src = image_urls[startFrame];
  }

//  showImage(place, startFrame);
//  display_speed(objname+"_speed_text","");

  clearTimeout(timerID);
 }


 /* Called from the timer. This function is queued */
 /* initially when the user mouses over picture    */
 /* then keeps getting queued up by itself         */

 function switchImage() {

// getTime() method returns the number of milliseconds since midnight
// of January 1, 1970

   if ( global_stop == 1) {
       stopshow();
   };

   num_advance_frames = global_speed;

 var today = new Date();
 var starttime = today.getTime();

  var nextImageNum = getNextImageNum();
//  alert("switchImage " + nextImageNum + "objname:" + objname) ;
//  debug("switchImage " + lastplace + " : " +   lastplace );
  var place = lastplace;

//  alert("objname = " + objname);
//  alert("place = " + place);

  // No longer want to loop, just run through one time.
  // nextImageNum will be -1 when animation should stop

  if ( nextImageNum != -1 ) {
    showImage(place, nextImageNum);

    clearTimeout(timerID);

//    alert("objname " + objname);	
    lastplace = place;	
    var recur_call = objname + '.switchImage()';
//    alert("recur_call:" + recur_call);
  

    // Determine how mcuh time to wait so total time is interval.
    var today2 = new Date();
    var nowtime = today2.getTime();
    var wait_time = interval - ( nowtime - starttime );
    timerID = setTimeout(recur_call, wait_time);
//    debug("Timer : " + wait_time);
  }
 }



//  --------------------
//  --------------------
//  -------------------- Support functions --------------------
//  --------------------
//  --------------------

 function getNextImageNum() {

  debug("getNextImageNum: " + imageNum + " : " +totalImages + " : " + totalImages);

  // No longer want to loop, just run through one time.
  // nextImageNum will be -1 when animation should stop

  if ( (imageNum+num_advance_frames) >=  totalImages ) {
    return(-1);
  }

  var nextNum = (imageNum+num_advance_frames) % totalImages;
  return(nextNum);
 }


 /* load up the images up to this point                                                    */
 /* set the imageNum variable so code knows what image is shown                            */

 function showImage(place, num) {
  var i;

  if ( totalImages  <= 0 ) { return; }

  var numcached = 0;
  var first_missed = totalImages;
  var loaded = "";

  //
  // Keep cashing new images, while
  //   images to cache (i < totalImages)
  //   have not cached more than 5 already (numcached < 5)
  //   
  //

  for ( i = 0;  (i < totalImages) && (numcached < 5); i += num_advance_frames) {
    if ( typeof(imageArray[i]) == 'undefined' ) {
       imageArray[i] = new Image();

//       alert("Good1:Setting image " + imageArray[i].src + " to " + image_urls[i]);
       imageArray[i].src = image_urls[i];

//       debug("attempting to load image #"+i);

       numcached = numcached + 1;
       if ( i < first_missed ) { first_missed = i; }

//       loaded = loaded + i +  "I";
    } else {
       if ( !imageArray[i].complete ) {
          numcached = numcached + 1;
	  if ( i < first_missed ) { first_missed = i; }
//          loaded = loaded + i +  "W";
       } else {
//          loaded = loaded + i +  "D";
       }


    }
  }

//  debug( imageNum + " -- " + first_missed + " / " + numstills );

//  debug(loaded);


   // Make sure it is loaded before moving forward
   waiting_for_load = 1; 
   if ( document[place].complete) {
      if (typeof(imageArray[num]) == 'undefined' ) {
//         debug( imageNum + " -- " + first_missed + " / " + numstills + 
//                " Frame #" + num + " not even started to be cached yet, so waiting." );
//       debug("Array still undefined...moving on....");
        return;
      } 

      if ( imageArray[num].complete ) {
      } else {
//         debug( imageNum + " -- " + first_missed + " / " + numstills + 
//                           " Frame #" + num + " not loaded yet, so waiting." );
         return;
      };

   } else {
//         debug( imageNum + " -- " + first_missed + " / " + numstills + 
//                           "Last image has not loaded ("+ document[place].src +"), do not move on to next.");
      return;
   };


//    debug(" Trying frame " + num + "." );       

  // Wait for the 1st <preload_before_start> to be preloaded before starting
  if ( first_missed < preload_before_start ) {
//         debug( imageNum + " -- " + first_missed + " / " + numstills + 
//                           "Waiting for first " + preload_before_start + " to start.");

      return;
  }

//       debug(" First 5 frames loaded! Starting Animation!" );
         

  waiting_for_load = 0; 



  imageNum = num;

//  alert("end of routine Setting image "+ place + " to " + num);
  document[place].src = imageArray[num].src;
 }

}

