/*
 * QTObject embed
 * http://blog.deconcept.com/2005/01/26/web-standards-compliant-javascript-quicktime-detect-and-embed/
 *
 * by Geoff Stearns (geoff@deconcept.com, http://www.deconcept.com/)
 *
 * v1.0.2 - 02-16-2005
 *
 * Embeds a quicktime movie to the page, includes plugin detection
 *
 * Usage:
 *
 *	myQTObject = new QTObject("path/to/mov.mov", "movid", "width", "height");
 *	myQTObject.altTxt = "Upgrade your Quicktime Player!";    // optional
 
 *  myQTObject.addParam("controller", "false");              // optional
 *	myQTObject.write();
 *
 */

QTObject = function(mov, id, w, h) {
	this.mov = mov;
	this.id = id;
	this.width = w;
	this.height = h;
	this.redirect = "http://www.finallyequal.com/trailer-flash.html";
	this.initialized = false;
	this.sq = document.location.search.split("?")[1] || "";
	this.altTxt = "This content requires the QuickTime Plugin. <a href='http://www.apple.com/quicktime/download/'>Download QuickTime Player</a>.";
	this.bypassTxt = "<p>Already have QuickTime Player? <a href='?detectqt=false&"+ this.sq +"'>Click here.</a></p>";
	this.params = new Object();
	this.doDetect = getQueryParamValue('detectqt');
}

QTObject.prototype.addParam = function(name, value) {
	this.params[name] = value;
}

QTObject.prototype.getParams = function() {
    return this.params;
}

QTObject.prototype.getParam = function(name) {
    return this.params[name];
}

QTObject.prototype.getParamTags = function() {
    var paramTags = "";
    for (var param in this.getParams()) {
        paramTags += '<param name="' + param + '" value="' + this.getParam(param) + '" />';
    }
    if (paramTags == "") {
        paramTags = null;
    }
    return paramTags;
}

QTObject.prototype.getHTML = function() {
    var qtHTML = "";
	if (navigator.plugins && navigator.plugins.length) { // not ie
        qtHTML += '<embed type="video/quicktime" src="' + this.mov + '" width="' + this.width + '" height="' + this.height + '" id="' + this.id + '"';
        for (var param in this.getParams()) {
            qtHTML += ' ' + param + '="' + this.getParam(param) + '"';
        }
        qtHTML += '></embed>';
    }
    else { // pc ie
        qtHTML += '<object classid="clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B" width="' + this.width + '" height="' + this.height + '" id="' + this.id + '">';
        this.addParam("src", this.mov);
        if (this.getParamTags() != null) {
            qtHTML += this.getParamTags();
        }
        qtHTML += '</object>';
    }
    return qtHTML;
}


QTObject.prototype.getVariablePairs = function() {
    var variablePairs = new Array();
    for (var name in this.getVariables()) {
        variablePairs.push(name + "=" + escape(this.getVariable(name)));
    }
    if (variablePairs.length > 0) {
        return variablePairs.join("&");
    }
    else {
        return null;
    }
}

QTObject.prototype.write = function(elementId) {
	if(isQTInstalled() || this.doDetect=='false') {
		if (elementId) {
			$(elementId).innerHTML = this.getHTML();
		} else {
			document.write(this.getHTML());
		}
	} else {
		if (this.redirect != "") {
			document.location.replace(this.redirect);
		} else {
			if (elementId) {
				$(elementId).innerHTML = this.altTxt +""+ this.bypassTxt;
			} else {
				document.write(this.altTxt +""+ this.bypassTxt);
			}
		}
	}		
}

function isQTInstalled() {
	var qtInstalled = false;
	qtObj = false;
	if (navigator.plugins && navigator.plugins.length) {
		for (var i=0; i < navigator.plugins.length; i++ ) {
         var plugin = navigator.plugins[i];
         if (plugin.name.indexOf("QuickTime") > -1) {
			qtInstalled = true;
         }
      }
	} else {
		execScript('on error resume next: qtObj = IsObject(CreateObject("QuickTimeCheckObject.QuickTimeCheck.1"))','VBScript');
		qtInstalled = qtObj;
	}
	return qtInstalled;
}

/* get value of querystring param */
function getQueryParamValue(param) {
	var q = document.location.search;
	var detectIndex = q.indexOf(param);
	var endIndex = (q.indexOf("&", detectIndex) != -1) ? q.indexOf("&", detectIndex) : q.length;
	if(q.length > 1 && detectIndex != -1) {
		return q.substring(q.indexOf("=", detectIndex)+1, endIndex);
	} else {
		return "";
	}
}

// Script stuff for QT Player:

QTPlayer = function(id,url,width,height,image_url) {
	testObject = new QTObject("zzz.mov","test_qt", 1, 1);
	testObject.addParam("enablejavascript", "true");
	testObject.write('movie_test');
	if (typeof($('test_qt').GetPluginStatus) == 'function' || (Prototype.Browser.IE && typeof($('test_qt').GetPluginStatus) == 'unknown')) {
		this.attach = true;
	} else {
		this.attach = false;
	}
	Element.remove($('movie_test'));
	this.clicktoplay = typeof(image_url) != "undefined";
	this.url = url;
	this.image_url = image_url;
	this.id=id;
	this.width=width;
	this.height= this.attach ? height : height+16;
	
	this.current_time = 0;
	this.scrubbing = false;
	this.stopped = true;
	this.playing = false;
	this.myQTObject = new QTObject(this.url,"movie_"+this.id,this.width,this.height);
	this.myQTObject.addParam("controller", this.attach ? 'false' : 'true');
	this.myQTObject.addParam("loop", "false");
	this.myQTObject.addParam("autoplay", "true");
	this.myQTObject.addParam("enablejavascript", "true");
	this.myQTObjectString = this.myQTObject.getHTML();
	this.movieContainer = $('movie_container_'+id);
}

QTPlayer.prototype.render = function() {
	if (this.clicktoplay) {
		this.writeImage();
	} else {
		this.writeMovie();	
	}
}

QTPlayer.prototype.writeImage = function() {
	this.image = document.createElement("img");
	this.image.src = this.image_url;
	this.image.onclick = this.writeMovie.bind(this);
	Element.addClassName(this.image, 'clicktoplay');
	this.movieContainer.appendChild(this.image);
	if (this.appendInfo) { 
		this.movieContainer.appendChild(this.appendInfo);
		//Element.removeClassName(this.appendInfo, "hidden");;
	}
}

QTPlayer.prototype.writeMovie = function() {
//	if (!Prototype.Browser.IE) {
	//if (this.appendInfo.innerHTML) $('add_to_movie').appendChild(this.appendInfo);
	
	//div = document.createElement('DIV');
	//div.innerHTML = this.myQTObjectString;
	//this.movieContainer.appendChild(div);
	
	this.movieContainer.innerHTML = "<div>" + this.myQTObjectString + "</div>";
	
	this.movie = $('movie_'+this.id);
	Element.addClassName(this.movieContainer, 'movie_container');
	//setTimeout(this.controlStatus.bind(this), 750);
	this.controlStatus();
	
//	} else {
//		this.movieContainer.innerHTML = '<object classid="clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B" width="400" height="316" id="movie_'+this.id+'"><param name="src" value="'+this.url+'" /><param name="controller" value="true" /><param name="loop" value="false" /></object>';
//	}
}

QTPlayer.prototype.controlStatus = function() {
	if (this.attach) {
		try {
			this.duration = this.movie.GetDuration();
		} catch(e) {
			setTimeout(this.controlStatus.bind(this), 100);
			return;
		}
		//alert(this.duration);
		if (this.duration == 0) {
			setTimeout(this.controlStatus.bind(this), 100);
			return;
		}
		this.createController();
	}
	
	//if (this.appendInfo) {
		//Element.removeClassName(this.appendInfo, "hidden");
	//	this.movieContainer.appendChild(this.appendInfo);
	//}
}

QTPlayer.prototype.createController = function() {
	try {
	this.movie.SetControllerVisible(false);
	} catch(e) {}
	this.controllerContainer = document.createElement('div');
	Element.addClassName(this.controllerContainer, "controller_container");

	this.playpauseControl = document.createElement('div');
	Element.addClassName(this.playpauseControl, "pause control");
	this.controllerContainer.appendChild(this.playpauseControl);
	
	this.playpauseControl.onclick = this.PlayPause.bind(this);
	this.trackContainer = document.createElement('div');
	Element.addClassName(this.trackContainer, "track_container");
	this.track = document.createElement('div');
	Element.addClassName(this.track, "track");

	this.playhead = document.createElement('div');
	Element.addClassName(this.playhead, "playhead");
	this.track.appendChild(this.playhead);
	
	this.trackContainer.appendChild(this.track);
	this.controllerContainer.appendChild(this.trackContainer);
	
	/*this.previousControl = document.createElement('div');
	Element.addClassName(this.previousControl, "previous_frame control");
	this.controllerContainer.appendChild(this.previousControl);
	Event.observe(this.previousControl, 'mousedown',this.PreviousDown.bind(this));
	
	this.nextControl = document.createElement('div');
	Element.addClassName(this.nextControl, "next_frame control");
	Event.observe(this.nextControl, 'mousedown', this.NextDown.bind(this));
	this.controllerContainer.appendChild(this.nextControl);
	*/
	this.muteControl = document.createElement('div');
	Element.addClassName(this.muteControl, "mute control");
	this.muteControl.onclick = this.toggleMute.bind(this);
	this.controllerContainer.appendChild(this.muteControl);
	
//	Event.observe(document, 'mouseup', this.ClearDowns.bind(this));

	this.attacher=window.setInterval(this.waitForMovie.bind(this),100);
	
	this.movieContainer.appendChild(this.controllerContainer);
	this.slider = new Control.Slider(this.playhead, this.track, {range:$R(0,this.duration),onSlide:this.onSliderSlides.bind(this), onChange:this.onSliderChanges.bind(this)});
}

QTPlayer.prototype.onSliderSlides = function(v) {
	if (!this.scrubbing) this.shouldPlay = this.movie.GetRate() == 1;
	this.scrubbing = true;
	this.Stop();
	this.SetFrame(v,true);
}

QTPlayer.prototype.onSliderChanges = function(v) {
	if (this.scrubbing) {
		this.SetFrame(v, true);
		this.scrubbing = false;
		if (this.shouldPlay) this.Play();
	} else if (Math.abs(v - this.current_time) > 20) {
		this.shouldPlay = this.playing;
		if (this.shouldPlay) this.Stop();
		this.SetFrame(v, true);
		if (this.shouldPlay) {
			this.Play();
			this.shouldPlay = false;
		}
	}
}

QTPlayer.prototype.showPlayPause = function (playing) {
	if (playing && !this.playing) {
		Element.addClassName(this.playpauseControl, "pause");
		Element.removeClassName(this.playpauseControl, "play");
		this.playing = true;
		//console.log(1);
	} else if (!this.scrubbing && (!playing && this.playing)) {
		Element.addClassName(this.playpauseControl, "play");
		Element.removeClassName(this.playpauseControl, "pause");
		this.playing = false;
		//console.log(2);
	} //else console.log(3);
}

QTPlayer.prototype.Play = function() {
	this.movie.Play();
	this.stopped = false;
}

QTPlayer.prototype.Stop = function() {
	this.movie.Stop();
	if (!this.scrubbing) this.stopped = true;
}

QTPlayer.prototype.PlayPause = function() {
	if (!this.playing) {
		this.Play();
	} else {
		this.Stop();
	}
}

QTPlayer.prototype.Next = function() {
	this.movie.Step(1);
	this.watch(true);
}
/*
QTPlayer.prototype.NextDown = function() {
	this.Next();
	this.nextWatcher = window.setInterval(this.Next.bind(this), 250);
}*/

QTPlayer.prototype.toggleMute = function() {
	if (this.movie.GetMute()) {
		this.movie.SetMute(false);
		Element.addClassName(this.muteControl, "mute");
		Element.removeClassName(this.muteControl, "unmute");
	} else {
		this.movie.SetMute(true);
		Element.addClassName(this.muteControl, "unmute");
		Element.removeClassName(this.muteControl, "mute");
	}
}
/*
QTPlayer.prototype.KeyDown = function(event) {
	theKey = event.charCode ? event.charCode : event.keyCode;
	if (this.accept_keys && !this.inputHasFocus) {
		if (theKey == 39 || theKey == 63235) {
			if (this.nextWatcher == false) {
				this.Next();
				this.nextWatcher = window.setInterval(this.Next.bind(this), 250);
			}
			Event.stop(event);
		} else if (theKey == 37 || theKey == 63234) {
			if (this.previousWatcher == false) {
				this.Previous();
				this.previousWatcher = window.setInterval(this.Previous.bind(this), 250);
			}
			Event.stop(event);
		}
//IF WE WANT SPACE TO PLAY/PAUSE	else if (theKey == 32) {
//			this.PlayPause();
//			Event.stop(event);
//		}
	}
}

QTPlayer.prototype.ClearDowns = function(event) {
	if (this.nextWatcher != false) {
		window.clearInterval(this.nextWatcher);
		this.nextWatcher = false;
	}
	if (this.previousWatcher != false) {
		window.clearInterval(this.previousWatcher);
		this.previousWatcher = false;
	}
}*/

QTPlayer.prototype.Previous = function() {
	this.movie.Step(-1);
	this.watch(true);
}
/*
QTPlayer.prototype.PreviousDown = function() {
	this.Previous();
	this.previousWatcher = window.setInterval(this.Previous.bind(this), 250);
}*/

QTPlayer.prototype.SetFrame = function(v,setMovie) {
	if (setMovie && v<=this.max_loaded) this.movie.SetTime(v);
}

QTPlayer.prototype.waitForMovie = function() {
	try {
		this.max_loaded = this.movie.GetMaxTimeLoaded();
	if (this.max_loaded>0) {
		if (!this.initialized) {
			this.initialized = true;
			this.watcher = window.setInterval(this.watch.bind(this),100);
		}
		this.percent_complete = Math.round(100*((this.max_loaded)/(this.duration)));
		this.track.style.width = this.percent_complete+'%';
	}
	if (this.percent_complete == 100) {
		window.clearInterval(this.attacher);
	}
	} catch (e) {
	}
}

QTPlayer.prototype.watch = function(update) {
	update = (update === true);
	this.showPlayPause(this.movie.GetRate() != 0);
	if (!(this.inputHasFocus || this.scrubbing)) {
		current_time = this.movie.GetTime();
		this.current_time = current_time;
		if (current_time == 0) return;
		if (this.playing || update || this.slider.value!=(this.current_time+60)) {
			this.slider.setValue(current_time);
		}
	}
}
