
// Use javascriptcompressor.com to compress this
//   v2.0 2009/02/15 : ajax version to read in values from server

// TODO: Preload images as you go, don't preload the array with 60*15, keep loading 15 in advance as they are completed.


var   all_products = new Array();
var   all_products_count = 0;

var   xxxxxxshows = 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 ( xxxxxxshows[product] ) {
              xxxxxxshows[product].stopshow();
	}
}


function run_start_obj_post(product) {

      global_stop  = 0;

      if ( ! xxxxxxshows[product] ) {

/* 
{"still_pattern":"http://s3.footagesearch.com/preview/HH/HH01/Images/HH01_028/frame--XXXXXX.jpg",
"still_fps":15,
"product":"HH01_028",
"still_numstills":"171",
"still":"http://www.oceanfootage.com/stillimage/HH01_028",
"still_number":105}
*/

//  $product =~ /([A-Z]+)([0-9]+[0-9A-Za-z]*)_.*/;
//    my $a1 = $1;
//    my $a2 = $1.$2;
//
//    my $url_location = '/export/dvf/preview/'.$a1.'/'.$a2.'/Stills/'.$product.'-%06d.jpg';
        
         a1 = product.match(/^[A-Z]+/g);
         a2 = product.match(/^[A-Z]+[0-9a-zA-Z]+/g);

	 //	 alert('product = ' + product);
	 //	 alert('a1 = ' + a1);
	 //	 alert('a2 = ' + a2);

        still_pattern = 'http://s3.footagesearch.com/preview/' + a1 + '/' + a2 + '/Images/' + product + '/frame--XXXXXX.jpg';

        // alert('still_pattern' + still_pattern);

        still = jQuery('img[name=' + product + ']' ).attr("src");

	//	alert('The original still was:' + still + ' for product ' + product );

//	still = '/stillimage/' + product;

	if ( (still !== undefined) && ( still != "" ) ) {
	    var tmp_obj = new SlideShowSimple(  product, // data[0].product,
						product, // data[0].product,
						0,     // data[0].still_number, 
						still_pattern, //	  data[0].still_pattern,
						60*15,   //      data[0].still_numstills,
						15,      //      data[0].still_fps,
						still //      data[0].still );
						); 
	    
	    xxxxxxshows[ product ] =  tmp_obj;
	} else {
	    //	    alert('The original still was blank, just return');
	    return;
	}


      }

           xxxxxxshows[product].startshow();
}

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 );
        xxxxxxshows[ data[0].product ] =  tmp_obj;

	tmp_obj.startshow();
}


$(document).ready(function(){

    //	http://docs.jquery.com/Manipulation/wrap

	//    $(".info_ro").wrap($('<div class="wrapper"></div>'));
	//    $(".info_ro").before('<div class="t"></div>&nbsp;<BR>');
	//    $(".wrapper").wrap($('<div class="content"></div>'));
	//    $(".wrapper").after('<div class="b"><div></div></div>');
	//    $(".dialog_dvf").wrap($('<div class="dialog_container" style="padding-bottom:0px;width:75%;position:relative;left:30px;top:10px;"></div>'));
	//    $(".info_ro").show();
	



    // Fix the pricing calculator icons
    $(".pc_link").each(function(){
       this.href =  "javascript:openWindow('" + this.href + "', 'popupWin');";  
    });

    $(".video_link").each(function(){
       this.href =  "javascript:openWindow('" + this.href + "', 'popupWin');";  


       appstring = '<a href="javascript:fsjs_startshow(\'' + this.name +'\',3);" >                    <img name="'+this.name+'_3xbutton" title="3x QuickView Playback" alt="3x Playback" src="/images/global/controllers/3x_sm.gif" border="0"                 onmouseover="movepic(\''+this.name+'_3xbutton\',\'/images/global/controllers/3x_selected_sm.gif\');"                 onmouseout= "movepic(\''+this.name+'_3xbutton\',\'/images/global/controllers/3x_sm.gif\');                             fsjs_stopshow(\''+this.name+'\');"                 style="margin-left:2px; margin-right:2px;"                 /></a>';

       // Add 3x speed
       jQuery(this).after(appstring);


       // Add 2x speed
       appstring = '<a href="javascript:fsjs_startshow(\'' + this.name +'\',2);" >                    <img name="'+this.name+'_2xbutton" title="2x QuickView Playback" alt="2x Playback" src="/images/global/controllers/2x_sm.gif" border="0"                 onmouseover="movepic(\''+this.name+'_2xbutton\',\'/images/global/controllers/2x_selected_sm.gif\');"                 onmouseout= "movepic(\''+this.name+'_2xbutton\',\'/images/global/controllers/2x_sm.gif\');                             fsjs_stopshow(\''+this.name+'\');"                 style="margin-left:2px; margin-right:2px;"                 /></a>';

       // Add 2x speed
       jQuery(this).after(appstring);


    });



    $(".video_link").append("");


    $(".simple_roll_over_playback").mouseover(function(event){

//    alert("mouseover");

      global_stop  = 0;
      global_speed = 1;

      //      alert('Rollover start: Id: ' + this.id + "name:" + this.name);

	if ( this.name == "" ){

	     // src should be of the form: http://www.oceanfootage.com/stillimage/AG01_001
	     //                        or: http://www.oceanfootage.com/preview/ST/ST05/Images/ST05_040/frame--000015.jpg
             //                        or: /stillimage/AG01_001
	     //                        or: http://s3.footagesearch.com/stills/NZ21b_027.jpg
	
              var srcurl = this.src;

	      //	      alert('URL:' + srcurl);

	      srcurl = srcurl.replace(/\/frame(.*).jpg/,"")

	     // src should be of the form: http://www.oceanfootage.com/stillimage/AG01_001
	     //                        or: http://www.oceanfootage.com/preview/ST/ST05/Images/ST05_040
             //                        or: /stillimage/AG01_001
	     //                        or: http://s3.footagesearch.com/stills/NZ21b_027.jpg


	      srcurl = srcurl.replace(/.jpg/,"")

	     // src should be of the form: http://www.oceanfootage.com/stillimage/AG01_001
	     //                        or: http://www.oceanfootage.com/preview/ST/ST05/Images/ST05_040
             //                        or: /stillimage/AG01_001
	     //                        or: http://s3.footagesearch.com/stills/NZ21b_027

	      var last_slash_pos = srcurl.lastIndexOf('/')

	      srcurl = srcurl.substring(last_slash_pos+1);

	      //	      alert('URL:' + srcurl);

	      this.name = srcurl;

	      //	      alert('Set the NAME to:' + this.name);

	     // src should be of the form: AG01_001
	     //                        or: ST05_040
             //                        or: AG01_001
	     //                        or: NZ21b_027

	      // Set the ID to flip_flip_PRODUCT

	      this.id = 'flip_flip_' + srcurl;

	      //	      alert('Set the ID to:' + this.id);






	}

//      alert("mouseover before post");
	if ( this.name != "" ) {
	        run_start_obj_post(this.name);
        }
      
    });



    

    $(".simple_roll_over_playback").mouseout(function(){
//	alert("mouseout"+this.name);

	   if ( xxxxxxshows[this.name] ) {
              xxxxxxshows[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 = 'xxxxxxshows[\''+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.set_last_image = set_last_image;
 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 xxxxxxshows is a full list, go through and reset the rest, but not this one */
  if ( typeof xxxxxxshows != "undefined" ) {
      for(var i in xxxxxxshows) {
  	if( xxxxxxshows[i] != this ) {
              	xxxxxxshows[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;
  preload_before_start = 20*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);

 }


 // This get's called when an image wont load, so we know we hit the end.
 // do some bookeeping.

 function set_last_image(i){


   if ( numstills > i )  {
//	   alert("Setting last image for this sequence to be  " + i);
	   numstills = i;
           totalImages = i;

           imageArray.length = i;
           image_urls.length = i;

	   if ( preload_before_start >= numstills ) {
	    preload_before_start = numstills - 1;
	   }
   }

 }

 /* Called when mouse leaves picture, reset to the picked 'start' image in sequence */
 function stopshow() {
//  alert("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];
      // Just leave it alone
        //       document[place].src = initial_url;
      alert("startURL was blank");
  }

//  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];
       imageArray[i].onerror = function(){ xxxxxxshows[product].set_last_image(i-5);};

//       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);
  
  if ( imageArray[num].complete ) {
        document[place].src = imageArray[num].src;
  }
 }

}


