// Video Sequence Object Constructor
// The videoSeq object will play a series of videos in sequence. The videos' urls and their particulars are ajaxed in from an xml file

function videoSeq(divID, url) { //divID is the tag we have to work with, url is the xml file
	this.divID = divID;
	this.video = new Array();
	this.vididx = -1;
	this.currentTimer = false;
	this.originalPlaceholder = $("#" + this.divID).html(); // Save the original image to use when videos aren't running
	var that = this; // "this" is going to have a different meaning for deferred operations
	$("#stop" + this.divID).hide().click(function() { that.stopVideo() });
	$("#next" + this.divID + ", #" + this.divID + " img").css('cursor', 'pointer').click(function() { that.nextVideo() });
	$.get(url, // Ajax the xml file of videos
		function(xmlData, textStatus, jqXHR) { // This executes on success
			$(xmlData).find('video').each(
				function() { // This executes for each video in the sequence
					var idx = that.video.length;
					that.video[idx] = new Array();
					that.video[idx]['src'] = $(this).find('src').text(); // The URL of the video
					that.video[idx]['time'] = eval($(this).find('secs').text()); // The number of seconds to allow the video to run before sequencing (eval allows for formulas)
				}
			);
		}
	);
}

// Start videos or advance to the next video in the sequence. If the end of the sequence is reached, start over with the first video.
videoSeq.prototype.nextVideo = function() {
	if (this.video.length) {
		this.stopVideo();
		this.vididx++;
		if (this.vididx == this.video.length) this.vididx = 0;
		$("#" + this.divID).html('<iframe src="' + this.video[this.vididx]['src'] + '"></iframe>');
		$("#stop" + this.divID).fadeIn(1000);
		$("#next" + this.divID).html("Next&nbsp;Video");
		var that = this;
		this.currentTimer = setTimeout(function() { that.nextVideo() }, (this.video[this.vididx]['time'] + 20) * 1000);
	}
}

// Stop playing video and go back to the placeholder image
videoSeq.prototype.stopVideo = function() {
	if (this.currentTimer) clearTimeout(this.currentTimer);
	this.currentTimer = false;
	var that = this;
	$("#" + this.divID).html(this.originalPlaceholder);
	$("#" + this.divID + ' img').css('cursor', 'pointer').click(function() { that.nextVideo() });
	$("#stop" + this.divID).fadeOut(1000);
	$("#next" + this.divID).html('Play&nbsp;Video');
}
