// JavaScript Document
var aytube4js_enlarged_height = 420;
var aytube4js_enlarged_width = 500;

var aytube4js_enlarge_html = "";

dojo.require("dojo.parser"); 
dojo.require("dijit.layout.ContentPane");
dojo.require("dijit.layout.TabContainer");
dojo.require("dijit.layout.AccordionContainer");
dojo.require("dijit.form.Form");
dojo.require("dojo.io.iframe");
dojo.require("dijit.Tooltip"); 
dojo.require("dijit.TitlePane");

dojo.require("dijit.Dialog");

var aytube4js_setInterval = false;

dojo.addOnLoad(function() {
	
	dojo.query("body").addClass("tundra");
	
	// if the video is playing in the dialog box, and the dialog box is closed, we want the video to stop playing.
	dojo.connect(dijit.byId("aytube4js_enlarge"), "hide", function(e) {
		dijit.byId("aytube4js_enlarge").setContent(aytube4js_enlarge_html);
		if (dojo.isIE) {
			dojo.style(dojo.byId("mod_aytube4js_youtube"), "display", "block");			
		}
	});
	
	// for IE, when the dialog box is shown, the video in the background (not inside the dialog) always shows on top.
	// so when the dialog is shown, we set it to display: none. when the dialog is hidden, we want to set it back to show.
	dojo.connect(dijit.byId("aytube4js_selection_dialog"), "hide", function(e) {
		if (dojo.isIE) {
			dojo.style(dojo.byId("mod_aytube4js_youtube"), "display", "block");			
		}
	});
	
	if (dojo.byId("aytube4jsClickToSetup")) {
		// controls the hiding/display of the user setup section
		dojo.connect(dojo.byId("aytube4jsClickToSetup"), "click", function(e) {
			e.preventDefault();

			dojo.style("aytube4jsEditSettings", { 
			    display: "block"
			}); 

			dojo.style("aytube4jsClickToSetup", {
				display: "none"
			})		
			dojo.style("aytube4jsClickToHideSetup", {
				display: "block"
			})
		});
		dojo.connect(dojo.byId("aytube4jsClickToHideSetup"), "click", function(e) {
			e.preventDefault();

			dojo.style("aytube4jsEditSettings", { 
			    display: "none"
			}); 

			dojo.style("aytube4jsClickToSetup", {
				display: "block"
			})		
			dojo.style("aytube4jsClickToHideSetup", {
				display: "none"
			})
		});
		
		// set up the handler for the user settings submit button
		dojo.connect(dojo.byId("aytube4jsEditSettingsSubmit"), "click", function(e) {
			e.preventDefault();
			// TODO what do we do after saving? need to refresh? show a sign that it's been saved?			
			
			dojo.xhrPost( {
				url: base_url + "index2.php?option=com_aytube4js&no_html=1&format=raw",
				handleAs: "json",
				form: "aytube4jsEditSettingsForm",
				load: function (response, ioArgs) { 
					if (response.error == "1") {
						dojo.byId("aytube4js_outer_container").innerHTML = response.error_message;
						dojo.byId("aytube4js_select_link").innerHTML = "";

						return false;
					}
					else {
						aytube4jsDisplayToaster(response.message);
					}
				}
			
			
			
			});
		});
		
	}
	
	function aytube4jsDisplayToaster(message) 
	{
		dojo.byId("aytube4jsSubmitStatus").innerHTML = message;
		dojo.style(dojo.byId("aytube4jsSubmitStatus"), "display", "block");
		var aytube4js_manage_messages_status = dojo.animateProperty({ 
			node: dojo.byId("aytube4jsSubmitStatus"), 
			properties: { 
				opacity: { 
					start: 1,
					end: 0
				}	 
			},
			duration:	5000
		}).play(); 
		var on_end_connection = dojo.connect(aytube4js_manage_messages_status, "onEnd", function() {
			dojo.style(dojo.byId("aytube4jsSubmitStatus"), "display", "none");
			dojo.disconnect(on_end_connection);
		}); 
	}
	
	

	// Set the arguments			
	var aytube4js_args = {
		outer_id: "aytube4js_outer_container",
		display_id: "mod_aytube4js_youtube",
		prev_id: "aytube4js_prev",
		next_id: "aytube4js_next",
		enlarge_id: "aytube4js_enlarge",
		enlarge_label: "aytube4jsLarge",
		url: base_url + "index2.php?option=com_aytube4js&no_html=1&format=raw",
		debug: debug
	};

	// Create a new instance of aytube4js.cycle
	aytube4js_youtube = new aytube4js.cycle(aytube4js_args);
	// Get the POST data
	dojo.xhrPost( {
		url: aytube4js_args.url,
		handleAs: "json",
		content: {
			"userId": userId,
			"aytube4js_case": "getDisplayData"
		},
		load: function (response, ioArgs) { 
			if (response.error == "1") {
				dojo.byId("aytube4js_outer_container").innerHTML = response.error_message;
				dojo.byId("aytube4js_select_link").innerHTML = "";
				
				return false;
			}
			
			// Process the response and populate aytube4js_data_array with the youtube objects
			successful_process = aytube4js_youtube.process_youtube_information(response, ioArgs);
			if (successful_process) { // means no errors
				// Set the dimensions
				aytube4js_youtube.set_dimensions(response);
				// Display the first video
				aytube4js_youtube.display_video(0);
				// Display the selection button and set up the prev and next handlers only if more than 1 video
				if (response.data.length > 1) {
					// Set up the event handlers
					dojo.style("aytube4js_prevnext", "display", "block");
					dojo.connect(aytube4js_youtube._prev_node, 'onclick', function(evt) { aytube4js_youtube._prev_next_handler("prev"); } );
					dojo.connect(aytube4js_youtube._next_node, 'onclick', function(evt) { aytube4js_youtube._prev_next_handler("next"); } );
					
					dijit.byId("aytube4js_selection_dialog").setContent(response.selection);
					dojo.style("aytube4js_select_link", "display", "block");
					// set up the listener for the selection
					dojo.connect(dojo.byId("aytube4js_select_link"), "onclick", function(evt) {
						if (dojo.isIE) {
							dojo.style(dojo.byId("mod_aytube4js_youtube"), "display", "none");
						}
						pause_player();
						dijit.byId("aytube4js_selection_dialog").show();
					});

				}
			}
			return response;
		}
	});	

});

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

	_aytube4js_data_array: null,
	dimensions: null,
	_error_output_node: null,
	_display_node: null,
	_prev_node: null,
	_next_node: null,
	_enlarge_node: null,
	_enlarge_label: null,
	_url: "",
	_debug: false,
	_enlarge_text: "",
	_enlarge_connector: false,

	//constructor : function(display_node, error_output_node, prev_node, next_node) {
	constructor : function(aytube4js_args) {
		this._error_output_node = dojo.byId(aytube4js_args.outer_id);	
		this._display_node = dojo.byId(aytube4js_args.display_id);
		this._prev_node = dojo.byId(aytube4js_args.prev_id);
		this._next_node = dojo.byId(aytube4js_args.next_id);
		this._enlarge_node = dojo.byId(aytube4js_args.enlarge_id);
		this._enlarge_label = dojo.byId(aytube4js_args.enlarge_label);
		this._enlarge_text = dojo.byId(aytube4js_args.enlarge_id).innerHTML;
		this._url = aytube4js_args.url;
		this._debug = aytube4js_args.debug;
	},


	// 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(response) { // example "aytube4js_outer_container", "mod_aytube4js_youtube"		
		var div_width = response.width;
		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 aytube4js_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_message;
			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._aytube4js_data_array = data;

		return true;
	},

	// This function will display the first video in the global array aytube4js_data_array initially.
	// It also sets up aytube4js_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._aytube4js_data_array[video_number_to_show];
		if(this._debug) console.log("video number to show: " + video_number_to_show);
		var title = this._aytube4js_data_array[video_number_to_show].title;
		var div_width = this.dimensions.width;
		var div_height = this.dimensions.height;
		var video_html = '<object aytube4js_video_number="' + video_number_to_show + '" id="aytube4js_myytplayer" type="application/x-shockwave-flash" style="width:' + div_width + 'px; height:' + div_height + 'px;" data="' + video_to_be_shown.url + '&enablejsapi=1' + '&playerapiid=aytube4js_playerapiid' + '"><param name="movie" value="' + video_to_be_shown.url + '&enablejsapi=1' + '&playerapiid=aytube4js_playerapiid' + '" /><param name="allowScriptAccess" value="always"/></object>';
		var enlarged_video_html = '<object aytube4js_video_number="' + video_number_to_show + '" id="aytube4js_myytplayer_enlarged_player" type="application/x-shockwave-flash" style="display: none; width:' + aytube4js_enlarged_width + 'px; height:' + aytube4js_enlarged_width * 0.84 + 'px;" data="' + video_to_be_shown.url + '&enablejsapi=1' + '&playerapiid=aytube4js_playerapiid' + '"><param name="movie" value="' + video_to_be_shown.url + '&enablejsapi=1' + '&playerapiid=aytube4js_playerapiid' + '" /><param name="allowScriptAccess" value="always"/></object>';

		// we also set the global var aytube4js_enlarge_html to enlarged_video_html, because if the video is playing in the 
		// enlarged window, we want to be able to clobber it when we hide the dialog box
		aytube4js_enlarge_html = enlarged_video_html;

		// Write out the youtube video html
		this._display_node.innerHTML = video_html;

		// Show the enlarge link.
		dojo.style(this._enlarge_label, 'display', 'block');
		if(this._debug) console.log("number: " + video_number_to_show);
		
		// we cannot use this._enlarge_node as this._enlarge_node refers to dojo.by() and we need to use dijit.byId()
		dijit.byId("aytube4js_enlarge").setContent(enlarged_video_html);
		dijit.byId("aytube4js_enlarge").titleNode.innerHTML = title;
		
		// connect the Enlarge listener
		dojo.disconnect(this._enlarge_connector);
		this._enlarge_connector = dojo.connect(this._enlarge_label, "onclick", function(e) {
			pause_player();
			if (dojo.isIE) {
				dojo.style(dojo.byId("mod_aytube4js_youtube"), "display", "none");
			}
			dojo.style(dojo.byId("aytube4js_myytplayer_enlarged_player"), "display", "block");
			dijit.byId("aytube4js_enlarge").resize({w: aytube4js_enlarged_width + 30, h: aytube4js_enlarged_height + 50});
			dijit.byId("aytube4js_enlarge").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("aytube4js_myytplayer"), "aytube4js_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 (aytube4js_data_array.length)
			if (video_number_to_show < 0) {
				video_number_to_show = this._aytube4js_data_array.length - 1;
			}
		}
		else {
			video_number_to_show = parseInt(current_video_number) + 1;
			// Check if it's out of range (compare against aytube4js_data_array.length)
			// If out of range, show the first video
			if (video_number_to_show > (this._aytube4js_data_array.length - 1)) {
				video_number_to_show = 0;
			}
		}

		// Call aytube4js_display_video
		this.display_video(video_number_to_show);	
	}

});


// function that is called when the player is ready
function onYouTubePlayerReady(playerId) {
	// do nothing here.
}

// function that is called when user chooses and clicks on a video in shadowbox
function switch_video_aytube4js(video_number) {
	aytube4js_youtube.display_video(video_number);
	dijit.byId("aytube4js_selection_dialog").hide();
}

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

// pauses the player, taking into account the fact that the player may be buffering.
function pause_player() 
{		
	if (!dojo.byId("aytube4js_myytplayer")) 
	{
		aytube4js_setInterval = setInterval("_pause_player_after_buffering()", 1000);
	}
	else if (aytube4js_setInterval != null && typeof(dojo.byId("aytube4js_myytplayer").getPlayerState) == "function") 
	{		
		if (dojo.byId("aytube4js_myytplayer").getPlayerState() == "3") //buffering
		{				
			aytube4js_setInterval = setInterval("_pause_player_after_buffering()", 1000);
		}
		else 
		{				
			dojo.byId("aytube4js_myytplayer").pauseVideo();
		}
	}
	else 
	{			
		aytube4js_setInterval = setInterval("_pause_player_after_buffering()", 1000);
	} 
}

