/* GLOBAL VARS */
var active_video_object_id = "";
var video_object_ids = new Array();
var pluginUpdate;
var scroll_position;


/* BEGIN TUBEFEED */

(function ($) {
	"use strict";
	var obj = this,
		playerObj,								
		thumbsObj,
		dataUrl,
		updated,
		viewCount = 0,
		searchMethod = 0,
		showRelated,
		autoPlay,
		enableJS,
		disableKB,
		enableEGM,
		fullScreen,
		enableHD,
		showSearch,
		showInfo,
		maxResults,
		matchArray = new Array(),
		videoArray = new Array(),
		data = new Object(),
		responseTags = new Object(),
		totalResults,
		firstRun = true,
		totalLoaded;
	
	$.fn.tubefeed = function (options) {		
		var defaults = {
			autoPlay : true,						// autoplay the video
			startIndex : 1,							// index of video to start with
			maxResults : 50,						// maximum results to receive	
			playerID : 'ytPlayer',					// id of the div that gets replaced with the flash object
			playlistID : 'ytPlaylist',				// id of the div that gets populated with thumbnails
			mainID : 'video',						// component container
			playerOptions : {						
				disableKB : false,					// disable keyboard controls on player
				enableHD : true,					// enable hd option on player
				fullScreen : true,					// enable fullscreen option on player
				jsAPI : {
					enabled : true,				// allow javascript access to the player
					nextID : 'nextBtn',				// id of the link for "next" functionality
					prevID : 'prevBtn'				// id of the link for "previous" functionality
				},
				playerWidth : 640,					// width of the player
				playerHeight : 390,					// height of the player
				showRelated : true,					// show related videos at the end of a video
				useEGM : true,						// use enhanced genie mode (genie mode appears during playback when the video is moused over
				showSearch : false,					// show search bar at the end of a video
				showInfo : false,					// show info at the end of a video
				showTitle : false,					// show the title at the end of the video
				showDescription : false				// show the description at the end of the video
			},
			ids : [ ],								// specific id's of videos to receive
			tags : [ ],								// tags to search for within a user's feed
			playQueue : false,						// play the next video after the current video has finished
			userName : '',							// set the username of the user's feed you want	
			onComplete: function(userFunction) {
				if(userFunction !== undefined) {
					userFunction();
				}
			}
		};
		//this applies the user's settings (options) to the default value object (defaults)
		options = $.extend(defaults, options);
		playerObj = $('#' + options.playerID);										
		thumbsObj = $('#' + options.playlistID);
		
		showRelated = (options.playerOptions.showRelated === true) ? 1 : 0;
		autoPlay = (options.autoPlay === true) ? 1 : 0;
		enableJS = (options.playerOptions.jsAPI.enabled === true) ? 1 : 0;
		disableKB = (options.playerOptions.disableKB === true) ? 1 : 0;
		enableEGM = (options.playerOptions.useEGM === true) ? 1 : 0;
		fullScreen = (options.playerOptions.fullScreen === true) ? 1 : 0;
		enableHD = (options.playerOptions.enableHD === true) ? 1 : 0;
		showSearch = (options.playerOptions.showSearch === true) ? 1 : 0;
		showInfo = (options.playerOptions.showInfo === true) ? 1 : 0;
		maxResults = (options.maxResults > 50) ? 50 : options.maxResults;
		// Set global ref to update()
		pluginUpdate = update;
		
		// set height and width of video on video wrapping div
		$('#' + options.playerID).css("height", options.playerOptions.playerHeight);
		$('#' + options.playerID).css("width", options.playerOptions.playerWidth);
		
		// if no thumbnail div exists, create one
		if (thumbsObj.length === 0) { appendThumbDiv(this) };
		
		
		function getFeed() {
			switch(searchMethod) {
				case "username" :
					dataUrl = "https://gdata.youtube.com/feeds/api/users/" 
						+ options.userName + "/uploads?v=2&alt=jsonc&start-index=" 
						+ options.startIndex + "&max-results="
						+ options.maxResults + "&callback=?";
						
					prepareBatchSearch(dataUrl);
					break;
				case "id" : 
					for(i = 0; i < options.ids.length; i++) {
						dataUrl = "https://gdata.youtube.com/feeds/api/videos?v=2&alt=jsonc&q=" 
							+ options.ids[i] + "&callback=?";	
							prepareBatchSearch(dataUrl);
					}
					
					break;
				case "tag" :
					dataUrl = "";
					prepareBatchSearch(dataUrl);
					break;
				case "multiple" :
					dataUrl = "https://gdata.youtube.com/feeds/api/users/" 
						+ options.userName + "/uploads?v=2&alt=jsonc&start-index="
						+ options.startIndex + "&max-results="
						+ options.maxResults + "&callback=?";
					prepareBatchSearch(dataUrl);
					break;
				case "none" :
					dataUrl = "";
					break;
			}
			
			$('div.ytVideo').live('click', function() {
				// alert($(this).attr('id'));
				update($(this).attr('id'));
			});
			
			$('div.ytVideo').live('mouseover', function() {
				// Check to see if element is currently active
				if ($(this).hasClass("active")) return;
				$(this).find('div.bg').stop().animate({
					opacity : '1'
				});
			});
			
			$('div.ytVideo').live('mouseout', function() {
				if ($(this).hasClass("active")) return;
				$(this).find('div.bg').stop().animate({
					opacity : '0'
				});
			});
		}
		
		setSearchMethod();
		getFeed();
		
		$("#ytPlaylist").scroll(function() {
   			// Check if at the bottom of scroll container
   			if ($(this)[0].scrollHeight - $(this).scrollTop() == $(this).outerHeight()) {
   				// Check to see if there are anymore videos to load
				// alert(totalLoaded + "/" + totalResults);
				if (totalLoaded >= totalResults) return;
     			// Rerun script, add additional videos
     			// Make sure the number vids to load doesn't exceed totalResults
     			options.startIndex = totalLoaded + 1;
     			var n = options.startIndex + maxResults;
     			// alert(n + "/" + totalResults);
     			if (n > totalResults) {
     				maxResults = (options.startIndex + maxResults) - totalResults; 
     			}
     			// Reset props
				matchArray = new Array();
     			// Build ytLoader
      			$("#" + options.mainID).append('<div id="ytLoader"><div id="ytLoaderBg"></div></div>');
      			$("#ytLoader").css("top", $("#" + options.playlistID).position().top);
      			$("#ytLoader").css("left", $("#" + options.playlistID).position().left);
      			// Load
      			setSearchMethod();
     			getFeed();
   			}
		});
		
		function setSearchMethod() {
			if(options.userName === '' && options.ids.length === 0 && options.tags.length === 0) {
				searchMethod = "none";
			} else if(options.userName !== '' && options.ids.length === 0 && options.tags.length === 0) {
				searchMethod = "username";
			} else if(options.ids.length > 0 && options.userName === '' && options.tags.length === 0) {
				searchMethod = "id";
			} else if(options.tags.length > 0 && options.userName === '' && options.ids.length === 0) {
				searchMethod = "tag";
			} else {
				searchMethod = "multiple";
			}
		}
		
		function appendThumbDiv(target) {
			target.append('<div id="' + options.playlistID + '"></div>');
		}
		
		function prepareBatchSearch(url) {
			loadSWFObject();
			$.getJSON(url, function(data){
				processJSON(data.data);
			});
		}
		
		function loadSWFObject() {
			if(typeof(swfobject) === 'undefined') {
				var head = document.getElementsByTagName('head')[0];
				var script = document.createElement('script');
				script.type = "text/javascript";
				script.src = "https://ajax.googleapis.com/ajax/libs/swfobject/2.2/swfobject.js";
				head.appendChild(script);
			}
		}
		
		function processJSON(data) {
			var idMatchPoints = 0;
			// Set number of total 
			totalResults = data.totalItems;
			$.each(data.items, function(i, item) {
				if(searchMethod === "username") {
					matchArray.push(this);
				} else if(searchMethod === "id") {
						matchArray.push(this);
				} else if(searchMethod === "tag") {
				} else if(searchMethod === "multiple") {
					if(options.tags.length > 0) {
						var responseTags = this.tags;
						var tagMatchPoints = 0;
						
						for(y = 0; y < options.tags.length; y++) {	
							if($.inArray(options.tags[y], responseTags) > -1) {
								tagMatchPoints++;
							} 
						}
						
						if(tagMatchPoints === options.tags.length) {
							matchArray.push(this);
						}
					} else {
						matchArray.push(this);	
					}
				} else if(searchMethod === "none") { }
			});
			
			for(var x = 0; x < matchArray.length; x++) {
				getVideoData(matchArray[x]);
			}
			
			// Set object ids global to local videoArray... for now
			video_object_ids = videoArray;
			// Update total videos loaded
			totalLoaded = videoArray.length;
			// alert("totalLoaded: " + totalLoaded);
			
			if (firstRun) {
				update(videoArray[0]);
				firstRun = false;
			}
			
			// Remove loader if exists
			$("#ytLoader").remove();
			
			options.onComplete();
		}
		
		
		function getVideoData(obj) {
			updated = (obj.updated === undefined) ? "Unknown" : jQuery.timeago(obj.updated);
			var thumbUrl = obj.thumbnail.hqDefault;
			responseTags = obj.tags;
			
			if(obj.accessControl !== undefined && obj.accessControl.embed === 'denied') {
				// do nothing
			} else {
				$("#" + options.playlistID).append(
					'<div class="ytVideo" id="' + obj.id + '"><div class="bg"></div>' +
					'<div class="imgWrap"><img src="' + thumbUrl.replace('http', 'https') + '" height="35" width="62" alt="" /></div>' +
					'<div class="videoInfo"><p class="title">' + obj.title + '</p><p class="viewCount">Uploaded ' + updated + '</p></div>' +
					'</div.ytVideo>'
				);
			}
			// Update video array
			videoArray.push(obj.id);
		}
		
		
		function loadYouTubeVideo(videoID) {
			// Remove existing swf object
			if (active_video_object_id != "") $('#' + active_video_object_id).remove();
			// Append new div to load object
			$('#' + options.playerID).append('<div id="ytObject"></div>');
			// Set active object global
			active_video_object_id = "_" + videoID;
			// Build URL string
			var url = "http://www.youtube.com/v/" + videoID + "?f=user_uploads&app=youtube_data"
				+ "&enablejsapi=" + enableJS
				+ "&rel=" + showRelated
				+ "&fs=" + fullScreen
				+ "&hd=" + enableHD
				+ "&showsearch=" + showSearch
				+ "&showinfo=" + showInfo
				+ "&disablekb=" + disableKB
				+ "&autoplay=" + autoPlay
				;
			// Embed SWF	
			swfobject.embedSWF
    		(
      			url,
      			"ytObject",
      			options.playerOptions.playerWidth,
      			options.playerOptions.playerHeight,
      			'9.0.0',
      			null,
      			null,
      			{
        			allowScriptAccess: 'always',
        			allowFullScreen: 'true',
        			wmode : 'transparent'
      			},
      			{
        			id: active_video_object_id
      			}
    		);
		}
		
				
		function update(active) {
			loadYouTubeVideo(active);
			// Change properties
			for (var i=0; i <= videoArray.length; i++) {
				var s = videoArray[i];
				if (s == active) {
					$("#" + active).addClass("active");
					$("#" + active).find('div.bg').addClass("active").css("opacity", "1");;
					$("#" + active).find('p').addClass("active");
				} else {
					$("#" + s).removeClass("active");
					$("#" + s).find('div.bg').removeClass("active").css("opacity", "0");
					$("#" + s).find('p').removeClass("active");
				}
			}
		}
		
		
	};
})(jQuery);


function onYouTubePlayerReady(playerId) {
	var o = document.getElementById(active_video_object_id);
    if (o) o.addEventListener("onStateChange", "onPlayerStateChange");
}


function onPlayerStateChange(newState) {
	// If 0, need to advance to next video, switch states in playlist
	if (newState == "0") {
		pluginUpdate(getNextVideo());
		// Need to advance scrollbar
		// alert("scroll_position: " + scroll_position);
		$("#ytPlaylist").animate({
			scrollTop : scroll_position
		});
	}
}


function getNextVideo() {
	for (var i=0; i <= video_object_ids.length; i++) {
		if (video_object_ids[i] == active_video_object_id.substr(1)) {
			var j = (i >= video_object_ids.length - 1) ? 0 : i + 1;
			// Set scroll position global
			setScrollPosition(j);
			return video_object_ids[j]
		}
	}
	// Return first item id as default
	return video_object_ids[0];
}


function setScrollPosition(n) {
	scroll_position = 54 * n;
}


function ytInit() {
	// calls the tubefeed plugin
	$("#video").tubefeed({
		userName : 'ChicagoChevyLMA',
		maxResults : 10,
		playerID : 'ytPlayer',
		playlistID : 'ytPlaylist',
		mainID : 'video',
		playerOptions : {						
			disableKB : false,					// disable keyboard controls on player
			enableHD : false,					// enable hd option on player
			fullScreen : false,					// enable fullscreen option on player
			jsAPI : {
				enabled : true,					// allow javascript access to the player
				nextID : 'nextBtn',				// id of the link for "next" functionality
				prevID : 'prevBtn'				// id of the link for "previous" functionality
			},
			playerWidth : 303,					// width of the player
			playerHeight : 195					// height of the player	
		},
		onComplete: function() {}
	});
}



