/* Jesse Ruderman
 * July 18, 2004
 *
 * Remaining problems:
 *   IE sometimes crashes on exit after using the this script.
 *   In IE, it is a little ugly because IE doesn't support border-radius.
 *   In IE, it does not work at standalone Flash URLs.
 */

(function () {

var waitInterval = setInterval(initFlashControls, 100);
var count = 0;
var nTries = 1200;
var isFlv = false;
var currentPosition = -1;
  
function initFlashControls()
{
  function tt(elem, scrubSpan)
  {
    try {
      if (typeof elem.TotalFrames != "undefined") /* do not coerce elem.StopPlay to bool, because that breaks IE */
      {
        isFlv = document.getElementById("isFlv");
        if (typeof isFlv != "undefined" && isFlv != null) {
      		isFlv = true;
      	}
      	else {
      		isFlv = false;
      	}
        addFlashControls(elem, scrubSpan);
        ++count;
	    clearInterval(waitInterval);
	  }
    }
    catch(e) {
    	//alert(e);
    }
  }

  var i, x, ii, xx;
 
   if (nTries > 0) {
	   for (ii = 0; xx = document.getElementsByTagName("span")[ii]; ++ii) { 
	      if (xx.className=='scrub') {
			   for (i = 0; x = document.getElementsByTagName("object")[i]; ++i)
			    tt(x, xx);
			 
			  for (i = 0; x = document.getElementsByTagName("embed")[i]; ++i)
			    tt(x, xx);
			    
			  break;
	      }
	   }
   }
   else {
      clearInterval(waitInterval);
   }

  if (!count) {
  	//alert ("No scriptable flash on this page.");
	nTries--;
  }
  else {
	clearInterval(waitInterval);
  }
  
  if (nTries < 0) {
	  clearInterval(waitInterval);
  }
}

function addFlashControls(flash, controlSpan)
{
  clearInterval(waitInterval);
  var controlsDiv = document.createElement("div");

  /* Put the controls under the Flash. 
   *
   * If the Flash is an <embed> in an <object>, we do not want to touch the <object>, because that would make
   * Mozilla re-test whether the <object> is broken and reset the <embed>.  So in that case, we put the controls
   * under the <object>.
   */
  var where = controlSpan;
  /* var where = flash;
   * while (where.parentNode.tagName.toLowerCase() == "object")
   * where = where.parentNode;
   * where.parentNode.insertBefore(controlsDiv, where);
   */
  where.parentNode.insertBefore(controlsDiv, where);

  /* Construct controls using DOM2 instead of innerHTML.
   * In Mozilla, innerHTML= is like innerText= at standalone flash URLs.
   */
  var table = document.createElement("table");
  controlsDiv.appendChild(table);
  
  var row = table.insertRow(-1);
  
  var pauseLink = document.createElement("a");
  pauseLink.href = 'javascript:void(0);';
  var pauseButton = document.createElement("img");
  pauseButton.src = 'images/homework/pause.gif';
  pauseButton.height='25';
  pauseButton.width='61';
  pauseButton.alt = 'Pause';
  pauseButton.id='pause';
  pauseButton.name= 'pause';
  pauseLink.appendChild(pauseButton);
  
  var playLink = document.createElement("a");
  playLink.href = 'javascript:void(0);';
  var playButton = document.createElement("img");
  playButton.src = 'images/homework/play2.gif';
  playButton.height='25';
  playButton.width='61';
  playButton.alt = 'Play';
  playButton.id='play';
  playButton.name= 'play';
  playLink.appendChild(playButton);
  
  var buttonCell = row.insertCell(-1);
  buttonCell.appendChild(pauseLink);
  buttonCell.appendChild(playLink);
  playButtonDisable(true);
  
  var slider = row.insertCell(-1);
  slider.width = "100%";
  
  var visibleSlider = document.createElement("div");
  visibleSlider.style.position = "relative";
  visibleSlider.style.height = "10px";
  visibleSlider.style.width = "100%";
  visibleSlider.style.MozBorderRadius = "4px";
  visibleSlider.style.background = "#aaa";
  slider.appendChild(visibleSlider);
  
  var thumb = document.createElement("div");
  thumb.style.position = "absolute";
  thumb.style.height = "20px";
  thumb.style.width = "10px";
  thumb.style.top = "-5px";
  thumb.style.left = "0px";
  thumb.style.MozBorderRadius = "4px";
  thumb.style.background = "#666";
  visibleSlider.appendChild(thumb);
  

  var sliderWidth;
  var paused = false;
  var dragging = false;
  
  // sleiber: for end of movie redirect
  var setToRedirect = false;

  table.width = Math.min(parseInt(flash.width) || 0, 300);
  
  addEvent(slider, "mousedown", drag);
  addEvent(slider, "drag", function() { return false; }); /* For IE */
  window.setInterval(update, 30);

  function pauseUnpause()
  {
    paused = !paused;

    playButtonDisable(paused ? false : true);

	if (isFlv) {
		flash.sendEvent('playpause');
	}
	else {
	    if (paused)
	    	{ flash.StopPlay(); }
	    else 
	    	{ flash.Play(); }
    }
  }
  
  function pauseOnly()
  {
    paused = true;
    playButtonDisable(false);
    if (isFlv) {
    	// play states: 0=paused,1=buffering,2=playing,3=completed
    	if (parseInt(document.getElementById('flvPlayState').value) != 0) {
    		flash.sendEvent('playpause');
    	}
    } 
    else {
    	flash.StopPlay();
    }
  }  

function pauseButtonOver() {
	changeImagesById('pause','images/homework/pause_over.gif'); return true;
}

function pauseButtonDisabledOver() {
	changeImagesById('pause','images/homework/pause2.gif'); return true;
}

function pauseButtonOut() {
	changeImagesById('pause','images/homework/pause.gif'); return true;
}

function playButtonOver() {
	changeImagesById('play','images/homework/play_over.gif'); return true;
}

function playButtonDisabledOver() {
	changeImagesById('play','images/homework/play2.gif'); return true;
}

function playButtonOut() {
	changeImagesById('play','images/homework/play.gif'); return true;
}

function pauseButtonDisable(doDisable) {
	removeEvent(pauseLink,"mouseover",pauseButtonDisabledOver);
	removeEvent(pauseLink,"mouseout",pauseButtonDisabledOver);		
	removeEvent(pauseLink,"mouseover",pauseButtonOver);
	removeEvent(pauseLink,"mouseout",pauseButtonOut);	
	removeEvent(pauseButton, "click", pauseUnpause);
	if (doDisable) {		
		pauseButton.src = 'images/homework/pause2.gif';	
		addEvent(pauseLink,"mouseover",pauseButtonDisabledOver);
		addEvent(pauseLink,"mouseout",pauseButtonDisabledOver);	
	}
	else {
		pauseButton.src = 'images/homework/pause.gif';
		addEvent(pauseLink,"mouseover",pauseButtonOver);
		addEvent(pauseLink,"mouseout",pauseButtonOut);	
		addEvent(pauseButton, "click", pauseUnpause);
	}
}

function playButtonDisable(doDisable) {
	removeEvent(playLink,"mouseover",playButtonOver);
	removeEvent(playLink,"mouseout",playButtonOut);	
	removeEvent(playLink,"mouseover",playButtonDisabledOver);
	removeEvent(playLink,"mouseout",playButtonDisabledOver);	
	removeEvent(playButton, "click", pauseUnpause);	
	if (doDisable) {
		playButton.src = 'images/homework/play2.gif';
		addEvent(playLink,"mouseover",playButtonDisabledOver);
		addEvent(playLink,"mouseout",playButtonDisabledOver);			
	}
	else {
		playButton.src = 'images/homework/play.gif';
		addEvent(playLink,"mouseover",playButtonOver);
		addEvent(playLink,"mouseout",playButtonOut);	
		addEvent(playButton, "click", pauseUnpause); 
	}
	pauseButtonDisable(!doDisable);
}

  function update()
  {
    sliderWidth = parseInt(getWidth(slider) - getWidth(thumb));

    if (!paused && !dragging) {
    	if (isFlv) {
    		thumb.style.left = parseInt(currentFrame() / totalFrames() * sliderWidth) + "px";
    	}
    	else {
        	thumb.style.left = parseInt(currentFrame() / totalFrames() * sliderWidth) + "px";
        }
    }
      
    // sleiber: detect end of movie
    if (isFlv) {
    	if (flvRemaining() <= 0) {
	    	if (!setToRedirect) {
	    		setToRedirect = true;
	    		setTimeout(goToNextMovie,1000);
	    	}
	   	}
    }
    else {
	    if (!setToRedirect && (currentFrame() >= totalFrames()-3)) {
	    	if (currentFrame() != -1 && totalFrames() != 0) {
	    	   setToRedirect = true;
	    	   setTimeout(goToNextMovie,1000);
	        }
	    }
    }
  }

  function goToNextMovie() {
  	 nextUrl = document.playlistform.redirectUrl.value;
  	 if (isFlv) {
	  	 if (nextUrl != '') {
	  	 	jumpToUrl(nextUrl);
	  	 }
	  	 else {
	  	 	setToRedirect = false;
	  	 }
  	 }
  	 else {
	  	 if (nextUrl != '' && !paused) {
	  	 	jumpToUrl(nextUrl);
	  	 }
	  	 else {
	  	 	setToRedirect = false;
	  	 }
  	 }
  }

  function dragMousemove(e)
  {
    var pageX = e.clientX + document.body.scrollLeft; /* cross-browser, unlike e.pageX, which IE does not support */
    var pos = bounds(0, pageX - getX(slider) - 5, sliderWidth);
    var frame = bounds(1, Math.ceil(totalFrames() * pos / sliderWidth), totalFrames() - 2);

    thumb.style.left = pos + "px";

	if (isFlv) {
		if(navigator.appName.indexOf("Microsoft") != -1) {
			window['mySWFa'].sendEvent('scrub', frame);
		} else {
			document['mySWFa'].sendEvent('scrub', frame);
		}
	}
	else {
	    flash.GotoFrame(frame);
	}
  }

  function release(e)
  {
    removeEvent(document, "mousemove", dragMousemove);
    removeEvent(document, "mouseup", release);
    pauseOnly();
    if (!paused) {
    	if (isFlv) {
    		flash.sendEvent('playpause');
    	}
    	else {
      		flash.Play();
      	}
    }
    dragging = false;
  }

  function drag(e)
  {
    pauseOnly();
    addEvent(document, "mousemove", dragMousemove);
    addEvent(document, "mouseup", release);
    dragging = true;
    dragMousemove(e);
  }



  /* Boring functions, some of which only exist to hide differences between IE and Mozilla. */

  function bounds(min, val, max)
  {
    return Math.min(Math.max(min, val), max);
  }

  function totalFrames()
  {
    /* This is weird.  TotalFrames differs between IE and Mozilla.  CurrentFrame does not. */
	if (isFlv) {
		return parseInt(document.getElementById('flvTime').value) + flvRemaining();
	}
	else {
		if (typeof flash.TotalFrames == "number")
	      return flash.TotalFrames; /* IE */
	    else if (typeof flash.TotalFrames == "function")
	      return flash.TotalFrames(); /* Mozilla */
	    else
	      return 100; /* Partially loaded Flash in IE? */	
	}
  }
  
  function flvRemaining() {
  	return parseInt(document.getElementById('flvRemaining').value);
  }
  
  function currentFrame() {
  	if (isFlv) {
  		return parseInt(document.getElementById('flvTime').value);
  	}
  	else {
  		return flash.CurrentFrame();
  	}
  }

  function getWidth(elem)
  {
    if (document.defaultView && document.defaultView.getComputedStyle)
      return parseFloat(document.defaultView.getComputedStyle(elem,null).getPropertyValue("width")); /* Mozilla */
    else
      return parseFloat(elem.offsetWidth); /* IE (currentStyle.width can be "auto" or "100%") */
  }

  function getX(elem)
  {
    if (!elem) return 0;
    return (elem.offsetLeft) + getX(elem.offsetParent);
  }

  function addEvent(elem, eventName, fun)
  {
    if (elem.addEventListener) /* Mozilla */
      elem.addEventListener(eventName, fun, false);
    else /* IE */
      elem.attachEvent("on" + eventName, fun);
  }

  function removeEvent(elem, eventName, fun)
  {
    if (elem.addEventListener)
      elem.removeEventListener(eventName, fun, false);
    else
      elem.detachEvent("on" + eventName, fun);
  }

}

})()