/*!
 * jQuery YTQuery Plugin
 *
 * Copyright 2011, Sam Gluck
 * Follow me: @sdgluck
 * Email me: sdgluck@gmail.com
 * 
 * Version: 1.1.2
 * @requires SWFObject - http://code.google.com/p/swfobject/
 * ^ This plugin does not "yet" support HTML5 implementation of YT player.
 * 
 * All documentation can be found at: http://plugins.jquery.com/project/YTQuery
 *
 * Licensed under GPL:
 *   http://www.gnu.org/licenses/gpl.html 
 */

/*
	Global variables necessary so that I can access 
	them in the YouTube API functions: 
*/
var YTQuery = {};
	YTQuery["numVideos"] = 0;
	YTQuery["videos"] = {};

(function($){	
	var methods = {
		create: function(videoID, options, callback) {
			var settings = {
				'width': '642',
				'height': '362',
				'quality': 'medium', //small, medium, large, hd720, hd1080, highres, default
				'startMuted': false,
				'autoPlay': true,
				'swfVersion': '9',
                'wmode': 'opaque',
				'chromeless': false,
				'overwriteSWF': true,
				'forceRatio': '',
				'hidden': false,
				'performCallbackOnlyIfSuccessful': true
			};
			
			if(options) {
				// Merge the user-defined settings with the defaults:
				$.extend(settings, options);
			}

			if(settings.hidden === true) {
				swfobject.switchOffAutoHideShow();
				settings.width = '1';
				settings.height = '1';
			}
			
			var go = true;
			if(settings.overwriteSWF === false) {
				if($(this).is("object")) go = false;
			}
			
			if(settings.forceRatio !== '') {
				var ratio = settings.forceRatio.split(":");
				var width = parseInt(ratio[0]);
				var height = parseInt(ratio[1]);
				settings.height = (settings.width / width) * height;
			}
			
			if(go === true) {
				if(videoID) {
					// Increment YT videos counter:
					YTQuery.numVideos++;
					
					var ele = $(this).attr('id');
					var params = { allowScriptAccess: "always", wmode: "opaque" };
					var atts = { id: ele };
					
					if(settings.chromeless === true) {
						// Add videoID to the videoIDs array:
						YTQuery.videos[ele] = {};
						YTQuery.videos[ele]["videoID"] = videoID;
						if(settings.autoPlay === false) {
							YTQuery.videos[ele]["autoPlay"] = false;
						}
						
						swfobject.embedSWF("http://www.youtube.com/apiplayer?version=3&enablejsapi=1&showinfo=0&playerapiid=" + ele,
							ele, settings.width, settings.height, settings.swfVersion, null, null, params, atts, function(e) {
								if((e.success === true && settings.performCallbackOnlyIfSuccessful === true) || (settings.performCallbackOnlyIfSuccessful === false)) {
									if(typeof callback == "function"){
										callback();
									}
								}
							});
					} else {
						(settings.autoPlay === true) ? autoPlay = "&autoplay=1" : autoPlay = "&autoplay=0";
						swfobject.embedSWF("http://www.youtube.com/e/" + videoID + "?enablejsapi=1&wmode='opaque'&playerapiid=" + ele + autoPlay,
							ele, settings.width, settings.height, settings.swfVersion, null, null, params, atts, function(e) {
								if((e.success === true && settings.performCallbackOnlyIfSuccessful === true) || (settings.performCallbackOnlyIfSuccessful === false)) {
									if(typeof callback == "function"){
										callback();
									}
								}
							});
					}
				} else {   
					$.error("VideoID param not supplied in YTQuery 'create' method.");
				}
			}
			
			// Return the element to maintain chainability:
			return this;
		},
		remove: function(options) {
			var settings = {
				'restoreDiv': true // Creates an empty DIV ele that has the same ID as the player being removed.
			};
			
			if(options) {
				$.extend(settings, options);
			}
			
			var ele = $(this).attr("id");
			var parentEle = $(this).parent().get(0);
			var prevEle = $(this).prev();
			
			if(ele) {
				swfobject.removeSWF(ele);
			}
			
			if(settings.restoreDiv === true) {
				var string = "<div id='" + ele + "'></div>";
				if(prevEle.length != 0) {
					$(prevEle).after(string);
				} else {
					$(parentEle).prepend(string);
				}
			}
			return this;
		},
		play: function() {
			var ytplayer = document.getElementById($(this).attr("id"));
			if(ytplayer) {
				ytplayer.playVideo();
			}
			return this;
		},
		pause: function() {
			var ytplayer = document.getElementById($(this).attr("id"));
			if(ytplayer) {
				ytplayer.pauseVideo();
			}
			return this;
		},
		setVolume: function(volume) {
			var ytplayer = document.getElementById($(this).attr("id"));
			if(ytplayer) {
				if(volume) {
					if(volume >= 0 && volume <= 100) {
						ytplayer.setVolume(volume);
					} else if(volume > 100) {
						ytplayer.setVolume(100);
					} else if(volume < 0) {
						ytplayer.setVolume(0);
					}
				} else {
					$.error("Volume param not supplied in 'setVol' method");
				}
			}	
			return this;
		},
		mute: function() {
			var ytplayer = document.getElementById($(this).attr("id"));
			if(ytplayer) {
				ytplayer.mute();
			}
			return this;
		},
		unMute: function() {
			var ytplayer = document.getElementById($(this).attr("id"));
			if(ytplayer) {
				ytplayer.unMute();
			}
			return this;
		},
		state: function(returnText) {
			var ytplayer = document.getElementById($(this).attr("id"));
			if(ytplayer) {
				state = ytplayer.getPlayerState();
				if(returnText === true) {
					if(state === -1) {
						return "unstarted";
					} else if(state === 1) {
						return "playing";
					} else if(state === 2) {
						return "paused";
					} else if(state === 3) {
						return "buffering";
					} else if(state === 5) {
						return "video cued";
					} else if(state === 0) {
						return "ended";
					}
				} else {
					return state;
				}
			}
			return this;
		},
		bytesLoaded: function() {
			var ytplayer = document.getElementById($(this).attr("id"));
			if(ytplayer) {
				return ytplayer.getVideoBytesLoaded();
			}
			return this;
		},
		bytesTotal: function() {
			var ytplayer = document.getElementById($(this).attr("id"));
			if(ytplayer) {
				return ytplayer.getVideoBytesTotal();
			}
			return this;
		},
		elapsed: function() {
			var ytplayer = document.getElementById($(this).attr("id"));
			if(ytplayer) {
				return ytplayer.getCurrentTime();
			}
			return this;
		},
		duration: function() {
			var ytplayer = document.getElementById($(this).attr("id"));
			if(ytplayer) {
				return ytplayer.getDuration();
			}
			return this;
		},
		url: function() {
			var ytplayer = document.getElementById($(this).attr("id"));
			if(ytplayer) {
				return ytplayer.getVideoUrl();
			}
			return this;
		},
		lightbox: function(options) {
			var settings = {
				'opacity': '0.9',
				'color': "black",
				'width': ($(window).width() > $(document).width()) ? $(window).width() : $(document).width(),
				'height': ($(window).height() > $(document).height()) ? $(window).height() : $(document).height(),
				'zIndex': '-1000',
				'position': 'absolute',
				'top': '0',
				'left': '0',
				'fade': '',
				'addRemoveIcon': false,
				'removeText': 'Turn Lightbox Off'
			};
			
			if(options) {
				$.extend(settings, options);
			}
			
			if($(this).is("object")) {
				var width = "width: " + settings.width + ";";
				var height = "height: " + settings.height + ";";
				var opacity = "-moz-opacity: " + settings.opacity + "; opacity: " + settings.opacity + "; filter: alpha(opacity=" + settings.opacity * 100 + ");";
				var color = "background-color: " + settings.color + ";";
				var zIndex = "z-index: " + settings.zIndex + ";";
				var position = "position: " + settings.position + "; " + "left: " + settings.left + "px; top: " + settings.top + "px;";
				
				if(settings.fade !== '') {
					$("body").append("<div id='_ytqueryLightbox' style='display: none; " + width + height + opacity + color + position + "'></div>");
					$("#_ytqueryLightbox").fadeIn(parseInt(settings.fade));
				} else {
					$("body").append("<div id='_ytqueryLightbox' style='" + width + height + opacity + color + position + "'></div>");
				}
				
				if(settings.addRemoveIcon === true) {
					var style = "cursor: pointer; background-color: lightyellow; border: 1px solid black; width: auto; height: 17px; font-size: 12px; padding-left: 3px; padding-right: 3px; color: black; position: absolute;";
					$("body").append("<div id='_ytqueryRemoveLightbox' style='" + style + "'>" + settings.removeText + "</div>");
					var top = $(this).height() + $(this).offset().top + 2 + "px";
					var left = $(this).width() - $("#_ytqueryRemoveLightbox").width() + "px";
					$("#_ytqueryRemoveLightbox").css("top", top);
					$("#_ytqueryRemoveLightbox").css("left", left);
					
					$("#_ytqueryRemoveLightbox").click(function() {
						if(settings.fade !== '') {
							$("#_ytqueryLightbox").fadeOut(parseInt(settings.fade));
							$("#_ytqueryRemoveLightbox").fadeOut(parseInt(settings.fade));
							setTimeout(function() {
								$("#_ytqueryLightbox").remove();
								$("#_ytqueryRemoveLightbox").remove();
							}, parseInt(settings.fade) + 10);
						} else {
							$("#_ytqueryLightbox").remove();
							$("#_ytqueryRemoveLightbox").remove();
						}
					});
				}
				
				$(this).css("z-index", "1002");
			}
			return this;
		},
		seekTo: function(seconds) {
			if(seconds) {
				var ytplayer = document.getElementById($(this).attr("id"));
				if(ytplayer) {
					ytplayer.seekTo(seconds);
				}
			}
			return this;
		},
		stop: function() {
			var ytplayer = document.getElementById($(this).attr("id"));
			if(ytplayer) {
				ytplayer.stopVideo();
			}
			return this;
		},
		isMuted: function() {
			var ytplayer = document.getElementById($(this).attr("id"));
			if(ytplayer) {
				return ytplayer.isMuted();
			}
			return this;
		},
		isPlayer: function() {
			if($(this).is("object")) {
				return true;
			}
			return false;
		},
		loadVideo: function(videoId) {
			var ytplayer = document.getElementById($(this).attr("id"));
			if(ytplayer) {
				ytplayer.loadVideoById(videoId);
			}
			return this;
		}
	};
	
	// Create YTQuery namespace:
	jQuery.fn.YTQuery = function(method) {
		if(methods[method]) {
			return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
		} else if (typeof method === 'object' || !method) {
			return methods.init.apply(this, arguments);
		} else {
			$.error("Unknown method '" + method + "'.");
		}
	}
})(jQuery);

function onYouTubePlayerReady(playerId) {
	var ytplayer = document.getElementById(playerId);
	
	// Check if an array for this particular element exist in the YTQuery array:
	if(YTQuery.videos[playerId]) {		
		// Check if user wants video to play automatically:
		if(YTQuery.videos[playerId]["autoPlay"] === false) {
			// Load the video specified from the array:
			ytplayer.cueVideoById(YTQuery.videos[playerId]["videoID"]);
		} else {
			ytplayer.loadVideoById(YTQuery.videos[playerId]["videoID"]);
		}
	}
}
