enlarged_height = 420;
enlarged_width = 500;
debug = false;

expanded_or_selection_interrupted = false;
var aytube_setInterval = false;

dojo.addOnLoad(function() {
	
	// Set the arguments			
	var aytube_args = {
		outer_id: "aytube_outer_container",
		display_id: "mod_aytube_youtube",
		prev_id: "aytube_prev",
		next_id: "aytube_next",
		enlarge_id: "aytube_enlarge",
		url: base_url + "index2.php?option=com_aytube",
		debug: debug
	};
	// Create a new instance of aytube.cycle
	aytube_youtube = new aytube.cycle(aytube_args);
	
	// Get the POST data
	dojo.xhrPost( {
		url: aytube_args.url,
		handleAs: "json-comment-filtered",
		load: function (response, ioArgs) { 
			// Process the response and populate aytube_data_array with the youtube objects
			successful_process = aytube_youtube.process_youtube_information(response, ioArgs);
			if (successful_process) { // means no errors
				// Set the dimensions
				aytube_youtube.set_dimensions();
				// Display the first video
				aytube_youtube.display_video(0);
				// Set up the event handlers
				dojo.connect(aytube_youtube._prev_node, 'onclick', function(evt) { aytube_youtube._prev_next_handler("prev"); } );
				dojo.connect(aytube_youtube._next_node, 'onclick', function(evt) { aytube_youtube._prev_next_handler("next"); } );
				// Display the selection button only if more than 1 video
				if (response.data.length > 1) {
					dojo.style("aytube_select_outer", "display", "block");
					dojo.connect(dojo.byId("aytube_select_outer"), "onclick", function(evt) {
						// assume each image takes up 40 px
						var height = response.data.length * 40;
						// maximum height for the Shadowbox that we allow is 300 (6 images)
						if (height > 300) {
							height = 300;
						}
						// Pause the player if it's playing. Resuming of the player after shadowbox is closed will have to be manually done.						
					  	pause_player();
						Shadowbox.open({
					       	title:      'Select Video',
					       	type:       'html',
					       	content:    response.table,
					   	 	height:     height,
					  	  	width:      350
   						 });
					});
					
				}
			}
			return response;
		},
		content: {
			no_html: "1",
			format: "raw"
		}
	});	
	
});

dojo.declare("aytube.cycle", null, {

	_aytube_data_array: null,
	dimensions: null,
	_error_output_node: null,
	_display_node: null,
	_prev_node: null,
	_next_node: null,
	_enlarge_node: null,
	_url: "",
	_debug: false,
	_enlarge_text: "",
		
	//constructor : function(display_node, error_output_node, prev_node, next_node) {
	constructor : function(aytube_args) {
		this._error_output_node = dojo.byId(aytube_args.outer_id);	
		this._display_node = dojo.byId(aytube_args.display_id);
		this._prev_node = dojo.byId(aytube_args.prev_id);
		this._next_node = dojo.byId(aytube_args.next_id);
		this._enlarge_node = dojo.byId(aytube_args.enlarge_id);
		this._enlarge_text = dojo.byId(aytube_args.enlarge_id).innerHTML;
		this._url = aytube_args.url;
		this._debug = aytube_args.debug;
		
		// Get and set dimensions
		this.set_dimensions(this._error_output_node, this._display_node);
		// Initialize shadowbox
		Shadowbox.init({listenOverlay:	false});
	},
	
	
	// Get the width of the containing div (reference_container), and then sets the width and height of the internal (displaying) div accordingly, and returns 
	// the set width and height
	set_dimensions : function() { // example "aytube_outer_container", "mod_aytube_youtube"
		// Get the width and height of the containing(external) div
		var div_width = dojo.coords(this._error_output_node).w;
		var div_height = 0.84 * div_width;
		if(this._debug) console.log("width and height: " + div_width + div_height);	
		// Set the height of the displaying div so it's not collapsed, so we can see the ajax-loading.gif
		this._display_node.style.height = div_height + "px";
		
		this.dimensions = {width: div_width, height: div_height};
	},
	
	// This function will process the information that is retrieved via ajax.
	// It will also populate the global array aytube_data_array with the youtube data objects.
	// This function returns true if there are youtube information, and false if none.
	process_youtube_information : function(response, ioArgs) {
		if (response.error != 0) {
			this._error_output_node.innerHTML = response.error_msg;
			return false;
		}
		var data = response.data;
		for (i=0; i<data.length; i++) {
			if(this.debug) console.log(data[i].url);
		}
		
		// Show the Prev and Next if data.length > 1
		if (data.length > 1) {
			dojo.style(this._prev_node.parentNode, "display", "block");
		}
	
		// Place the youtube data (which are objects) inside a global array 
		this._aytube_data_array = data;
		
		return true;
	},
	
	// This function will display the first video in the global array aytube_data_array initially.
	// It also sets up aytube_enlarge.
	// It also sets up the Prev and Next hrefs to enable cycling
	display_video : function(video_number_to_show) {
		
		video_number_to_show = parseInt(video_number_to_show);
		var video_to_be_shown = this._aytube_data_array[video_number_to_show];
		if(this._debug) console.log("video number to show: " + video_number_to_show);
		var div_width = this.dimensions.width;
		var div_height = this.dimensions.height;
		var video_html = '<object aytube_video_number="' + video_number_to_show + '" id="aytube_myytplayer" type="application/x-shockwave-flash" style="width:' + div_width + 'px; height:' + div_height + 'px;" data="' + video_to_be_shown.url + '&enablejsapi=1' + '&playerapiid=aytube_ytplayer' + '"><param name="movie" value="' + video_to_be_shown.url + '&enablejsapi=1' + '&playerapiid=aytube_ytplayer' + '" /><param name="allowScriptAccess" value="always"/></object>'
		
		// Write out the youtube video html
		this._display_node.innerHTML = video_html;
		// Write out the html for the Enlarge link
		this._enlarge_node.innerHTML = '<a class="enlarge" id="aytube_enlarge_click" href="' + video_to_be_shown.url + '" title="' + video_to_be_shown.title + '">' + this._enlarge_text + '</a>';
		// Set up shadowbox for the enlarge link
		Shadowbox.setup(	dojo.byId("aytube_enlarge_click"), 
			{						
				height:     enlarged_height,
     			width:      enlarged_width,
       			onOpen:		function() {pause_player();}
       		}
		);
		// Show the enlarge link.
	
		if(this._debug) console.log("number: " + video_number_to_show);
	},
	
	// Stub: Event handler when Prev is clicked
	_prev_handler : function() {
		this._prev_next_handler("prev");
	},
	
	// Stub: Event handler when Next is clicked
	_next_handler : function() {
		this._prev_next_handler("next");
	},
	
	// Actual Event handler for Prev and Next 
	_prev_next_handler : function(prev_or_next) {
		if ( (prev_or_next != "prev") && (prev_or_next != "next") ) {
			if(this._debug) console.log("Neither prev or next");
			return false;
		}
		// Get current video number
		var current_video_number = dojo.attr(dojo.byId("aytube_myytplayer"), "aytube_video_number");
		if(this._debug) console.log("Current video showing: " + current_video_number);
		// Increment by 1 to get next video number
		if (prev_or_next == "prev") {
			video_number_to_show = parseInt(current_video_number) - 1;
			// Check if it's out of range 
			// If out of range, show the last video (aytube_data_array.length)
			if (video_number_to_show < 0) {
				video_number_to_show = this._aytube_data_array.length - 1;
			}
		}
		else {
			video_number_to_show = parseInt(current_video_number) + 1;
			// Check if it's out of range (compare against aytube_data_array.length)
			// If out of range, show the first video
			if (video_number_to_show > (this._aytube_data_array.length - 1)) {
				video_number_to_show = 0;
			}
		}
		
		// Call aytube_display_video
		this.display_video(video_number_to_show);	
	}
	
});


// function that is called when the player is ready
function onYouTubePlayerReady(playerId) {
	if(debug) console.log("in onYouTubePlayerReady");
	aytube_ytplayer = dojo.byId("aytube_myytplayer");
}

// function that is called when user chooses and clicks on a video in shadowbox
function switch_video(video_number) {
	aytube_youtube.display_video(video_number);
	Shadowbox.close();
}

// after buffering is over, the player is paused and the interval timer is cleared.
function _pause_player_after_buffering() {
	if (window.aytube_ytplayer === undefined) {
		return;
	}
	else if (aytube_ytplayer.getPlayerState() != "2") { // we keep trying to pause if it's not in paused mode
		aytube_ytplayer.pauseVideo();
		return;
	}
	else if (aytube_ytplayer.getPlayerState() == "2") { // we clear the interval once it's paused
		clearInterval(aytube_setInterval);
	}
	return;
}

// pauses the player, taking into account the fact that the player may be buffering.
function pause_player() {
	if (window.aytube_ytplayer === undefined) {
		// Use "window.aytube_ytplayer === undefined" instead of just "aytube_ytplayer === undefined". 
		// This is because all variables are also defined as properties of the window object.
		// "aytube_ytplayer === undefined" will only work if the aytube_ytplayer has actually been declared with "var aytube_ytplayer"
		// regardless of whether it has been assigned a value. Therefore it is safer to use "window.aytube_ytplayer" which will not result 
		// in an error if the variable hasn't been declared. 
		// Use the === compare operator to check whether the variable is really boolean false.
		// The == operator is not reliable as a value of 0 will also evaluate to false.
		// (Basically, the === asks whether variable are of same value AND datatype!) 
		aytube_setInterval = setInterval("_pause_player_after_buffering()", 1000);
	}
	else if (aytube_setInterval != null && typeof(aytube_ytplayer.getPlayerState) == "function") {
		if (aytube_ytplayer.getPlayerState() == "3") //buffering
		{
			aytube_setInterval = setInterval("_pause_player_after_buffering()", 1000);
		}
		else {
			aytube_ytplayer.pauseVideo();
		}
	}
	else {
		aytube_setInterval = setInterval("_pause_player_after_buffering()", 1000);
	} 
}