
	/* *
	 *
	 *		@function			Video Javascript
	 *
	 *		@website			MyWyoming.org
	 *		@owner				TCT West, Inc.
	 *
	 *		@author				Alan Ferguson
	 *		@company			Vision West, Inc.
	 *		@date					July 15, 2010
	 *
	 *		@description	
	 *
	 * */

	// Declare the video configuration array.
	// To be set in the page's header javascript.
	
	var video_unique_id = "";
	var video = new Array;
	
	/* *
	 * Execute when DOM Ready
	 * */

	$(document).ready(function() {

		// Bind the page control events to the
		// page controls. Must be called after
		// the video has been populated.
		
		BindPageControlEvents("browse");
		
		// Search
		
		$("input#search-input")
			.data('timeout', null)
			.keyup(function(){
				clearTimeout($(this).data('timeout'));
				$(this).data('timeout', setTimeout("VideoSearch('" + escape(this.value) + "');", 750));
			});

	});
	
	/* *
	 * Populate Video AJAX
	 *
	 *		Calls the PHP script to get video information
	 *		for the page. Supplies video type, limit, and page.
	 *
	 * */
	
	function PopulateVideoAJAX(div_id, type, limit, page, cols, page_range, owner, channel, similar)
	{
		
		// Lock the DIV height for the layer
		// containing video clips.
		
		VideoLockHeight(div_id);
		
		// Set loading message while video
		// content is loading.
		
		$("#" + div_id + " div.video-content").html("<div class=\"loading\"><img src=\"/assets/images/ajax-loader.gif\" alt=\"Loading...\" border=\"0\" /></div>");
		
		// The AJAX script to load video thumbnails.
		
		$.ajax({
			url: "/populate-videos",
			type: "POST",
			data: {"mode":"browse", "page":page, "limit":limit, "type":type, "owner":owner, "channel":channel, "similar":similar},
			dataType: "json",
			success: function(data) {
				PopulateVideo(div_id, data, cols, page_range, "browse");
			},
			error: function(obj, error) {
				alert(error);
			}
		});
		
		return true;
		
	}
	
	/* *
	 * Populate Video AJAX
	 *
	 *		Calls the PHP script to get video information
	 *		for the page. Supplies video type, limit, and page.
	 *
	 * */
	
	function SearchVideoAJAX(search_text, div_id, type, limit, page, cols, page_range)
	{
		
		// Lock the DIV height for the layer
		// containing video clips.
		
		VideoLockHeight(div_id);
		
		// Set loading message while video
		// content is loading.
		
		$("#" + div_id + " div.video-content").html("<div class=\"loading\"><img src=\"/assets/images/ajax-loader.gif\" alt=\"Loading...\" border=\"0\" /></div>");
		
		// The AJAX script to load video thumbnails.
		
		$.ajax({
			url: "/populate-videos",
			type: "POST",
			data: {"mode":"search", "search":search_text, "page":page, "limit":limit, "type":type},
			dataType: "json",
			success: function(data) {
				//alert(data);
				PopulateVideo(div_id, data, cols, page_range, "search");
			},
			error: function(obj, error) {
				alert(error);
			}
		});
		
		return true;
		
	}
	
	/* *
	 * Populate E-Commerce/Shopping Cart AJAX
	 *
	 *		Calls the PHP script to get shopping
	 *		cart information.
	 *
	 * */
	
	function EcommerceAJAX(action, field, value, authenticated, unique_id, qty)
	{
		
		// Redirect to sign in page if the user
		// is not authenticated.
		
		if (authenticated == false || authenticated == 'false')
		{
			$(document.location).attr("href","/sign-in?httpreferer=/video/" + unique_id + "/" + action + "/" + field + "/" + value);
		}

		// Show busy icon

		$("div#video-shopping-cart-wrapper").removeClass("hidden");
		$("<tr></tr>", {"class":"shopping-cart-busy"}).insertBefore("#video-shopping-cart-wrapper table tr.shopping-cart-footer");
		$("<td></td>", {"colspan":"4", "align":"center"}).html("<img src=\"/assets/images/ajax-loader.gif\" alt=\"Loading...\" border=\"0\" />").appendTo("tr.shopping-cart-busy");
		
		// If quantity field is specified, get the
		// quantity.
		
		if (qty !== null && qty !== false && qty !== 0) qty = $("#" + qty).val(); else qty = 0;
		
		// Remove contents if cart emptied.
		
		if (action == "EmptyCart") $("div#video-shopping-cart-wrapper table tr.shopping-cart-row").remove();

		// The AJAX script to perform e-commerce actions.
		
		$.ajax({
			url: "/populate-videos",
			type: "POST",
			data: {"action":action, "type":field, "id":value, "qty":qty},
			dataType: "json",
			success: function(data) {
				//alert(data);
				PopulateCart(data, data.misc);
			},
			error: function(obj, error) {
				//alert(error);
			}
		});
		
		return true;
		
	}

	/* *
	 * Populate Video
	 *
	 *		Fills a DIV with video thumbnails
	 *		and information.
	 *
	 * */
	
	function PopulateVideo(div_id, data, cols, page_range, mode)
	{
		
		// Set initial variables to false or empty.
		
		var i = 0;
		var str = '';
		var category = '';
		
		if (data.data.length > 0)
		{
			
			$("#video-set-wrapper div.video-set").removeClass("hidden");
			if (mode == "search") $("#picks").addClass("hidden");
			$("#video-set-message").html("");
			
			// Loop through the data provided by the AJAX
			// and output to the DIV provided in the parameters.
			
			$.each(data.data, function(key, value) {
				if (i >= cols) i = 1; else i++;
				if (i == 1) str += '<div class="video-row">';
				str += '<div class="video-cell">';
				str += '<a href="http://www.mywyoming.org/video/' + value.unique_id + category + '" title="' + value.video_title + '"><img src="/video-thumbs/' + value.unique_id + '_thumb.jpg" alt="' + value.video_title + '" /></a><br />';
				str += value.video_title + '<br />';
				str += addCommas(value.views) + ' view';
				if (value.views != 1) str += 's';
				str += '</div>';
				if (i >= cols) str += '<br class="clear" /></div>';
			});
			if (i > 0 && i < cols) str += '<br class="clear" /></div>';
			
			// Turn off loading message and fill the layer
			// with the video data (stored in string str).
			
			$("#" + div_id + " > div.video-content").html(str);
			
			// Rebuild the page controls for the video data.

			PopulatePageControl(div_id, data, page_range, mode);

		} else {
			
			$("#video-set-wrapper div.video-set").addClass("hidden");
			$("#video-set-message").html("<br />No videos found.");
			
		}
		
		// Release the DIV height to accommodate new content.
		
		VideoReleaseHeight(div_id);

		

		return true;
		
	}
	
	/* *
	 * Search
	 * */
	
	function VideoSearch(data)
	{
		
		if (data.length > 0)
		{
			
			$("#picks").addClass("hidden");
			$("#search-title").removeClass("hidden");
			$("#search-title").html("<div id=\"clear-search\"><a href=\"javascript:void(0);\" title=\"Clear search results\">X</a></div>Search results for <em>" + unescape(data) + "</em>");
			$("#clear-search").click(function() {
				$("#search-input").val("SEARCH");
				VideoSearch("");
			});
			
			$.each(video["search"], function(index, value){
				SearchVideoAJAX(data, value.div_id, value.type, value.limit, value.page, value.cells, value.page_range);
			});
			
		} else {
			
			$("#picks").removeClass("hidden");
			$("#search-title").addClass("hidden");
			$("#search-title").html("");
			
			$.each(video["browse"], function(index, value){
				PopulateVideoAJAX(value.div_id, value.type, value.limit, value.page, value.cells, value.page_range, value.owner, value.channel, value.similar);
			});
			
			$.each(video["search"], function(index, value){
				video["search"][index].page = 1;
				$.cookie("search_" + value.div_id, "1");
			});
			
		}
		
	}
	
	/* *
	 * Build Page Controls
	 *
	 *		Assembles page controls and decides
	 *		whether to have prev, page numbers, and
	 *		next options.
	 *
	 * */
	
	function PopulatePageControl(div_id, data, page_range, mode)
	{
		
		// Convert page_range to integer
		
		page_range = parseInt(page_range);
		
		// Get current page number and the total
		// pages from the data provided in the parameters.
		
		var current_page = parseInt(data.info.current_page);
		var total_pages = parseInt(data.info.total_pages);
		if (current_page < 1) current_page = 1;
		if (current_page > data.info.total_pages) current_page = data.info.total_pages;
		
		// Set the current page number into the video array
		// and into the cookie for later use.
		
		video[mode][div_id].page = current_page;
		$.cookie(mode + "_" + div_id, current_page);
		
		// Calculate page start and end range. If the
		// actual number of pages is less than the range,
		// then the page numbers are adjusted accordingly.
		
		var page_start = current_page - page_range;
		var page_end = current_page + page_range;
		if (page_start < 1) page_end = page_end + (1 + Math.abs(page_start));
		if (page_end > total_pages) page_start = page_start - (page_end - total_pages);
		if (page_start < 1) page_start = 1;
		if (page_end > total_pages) page_end = total_pages;
		
		// Build the page control HTML. First check if PREV
		// control should be output. Then output page numbers
		// and also output current page number. Then check if
		// NEXT control should be output.
		
		$("#" + div_id + " div.video-page-controls").html("");
		
		if (data.info.total_pages > 0)
		{
		
			$("<ul></ul>", {"class":"page-controls right"}).appendTo("#" + div_id + " div.video-page-controls");
			if (current_page != page_start) $("<li></li>", {"class":"prev"}).html("prev").appendTo("#" + div_id + " ul.page-controls");
			
			for (i = page_start; i < current_page; i++)
			{
				$("<li></li>", {"class":"page"}).html(String(i)).appendTo("#" + div_id + " ul.page-controls");
			}
			$("<li></li>", {"class":"page current-page"}).html(String(current_page)).appendTo("#" + div_id + " ul.page-controls");
			for (i = current_page + 1; i <= page_end; i++)
			{
				$("<li></li>", {"class":"page"}).html(String(i)).appendTo("#" + div_id + " ul.page-controls");
			}
			if (current_page != page_end) $("<li></li>", {"class":"next"}).html("next").appendTo("#" + div_id + " ul.page-controls");
			$("<br />", {"class":"clear"}).appendTo("#" + div_id + " ul.page-controls");
			$("<br />", {"class":"clear"}).appendTo("#" + div_id + " div.video-page-controls");
		
			// Bind click events to the new page controls.
			// Must be done every time HTML is changed by javascript.
			
			BindPageControlEvents(mode);
			
		}
		
		return true;
		
	}
	
	/* *
	 * Populate the Shopping Cart
	 * */
	
	function PopulateCart(data, misc)
	{
		
		if (data.info.rows > 0)
		{
			$("#video-shopping-cart-wrapper").removeClass("hidden");
			$("#video-shopping-cart-wrapper table tr.shopping-cart-row").remove();
		} else {
			$("#video-shopping-cart-wrapper").addClass("hidden");
			$("#video-shopping-cart-wrapper table tr.shopping-cart-busy").remove();
			return true;
		}

		var str = "";
		
		$.each(data.data, function(key, value) {
			$("<tr></tr>", {"class":"shopping-cart-row"}).insertBefore("#video-shopping-cart-wrapper table tr.shopping-cart-footer");
			str = value.title;
			if (value.use_schedule == 1) { str += "<br /><span class=\"smalltext-gray\">" + $.PHPDate("M j", new Date(value.date_start)) + " &ndash; " + $.PHPDate("g:i A", new Date(value.date_start)) + "</span>"; }
			if (value.video_id_ship != null) { str += '<br /><span class="smalltext-gray">Ship on DVD</span>'; }
			if (value.video_id_download != null) { str += '<br /><span class="smalltext-gray">Download</span>'; }
			$("<td></td>").html(str).appendTo("#video-shopping-cart-wrapper table tr.shopping-cart-row:last");
			if (value.video_id_ship != null) str = "<span class=\"cart-qty\">QTY&nbsp;<input type=\"text\" name=\"qty_" + value.id + "\" id=\"qty_" + value.id + "\" value=\"" + value.qty + "\" onchange=\"EcommerceAJAX('UpdateCart','item'," + value.id + "," + misc.authenticated + ",'" + video_unique_id + "','qty_" + value.id + "'); return false;\" /></span>"; else str = "&nbsp;";
			$("<td></td>", {"align":"center","width":"80px"}).html(str).appendTo("#video-shopping-cart-wrapper table tr.shopping-cart-row:last");
			str = "$" + value.price;
			$("<td></td>", {"align":"right"}).html(str).appendTo("#video-shopping-cart-wrapper table tr.shopping-cart-row:last");
			str = "<a href=\"" + misc.page_video + "/" + video_unique_id + "/RemoveFromCart/item/" + value.id + "\" title=\"Remove\" onclick=\"EcommerceAJAX('RemoveFromCart','item'," + value.id + "," + misc.authenticated + ",'" + video_unique_id + "'); return false;\" class=\"shopping-cart-remove\">X</a>";
			$("<td></td>", {"align":"right"}).html(str).appendTo("#video-shopping-cart-wrapper table tr.shopping-cart-row:last");
		});
		$("#shopping-cart-total-price").html(data.special["total-price"]);
		
		// Remove busy gif
		
		$("tr.shopping-cart-busy").remove();
		
	}

	/* *
	 * Lock Layer Height
	 *
	 *		Locks the height for a DIV
	 *		as provided in the parameter.
	 *
	 * */
	
	function VideoLockHeight(div_id)
	{
		
		$("#" + div_id + " div.video-content").height($("#" + div_id + " div.video-content").height());
		
	}
	
	/* *
	 * Unlock/Release Layer Height
	 *
	 *		Unlocks and releases the height
	 *		for a DIV as provided in the parameters.
	 *
	 * */
	
	function VideoReleaseHeight(div_id)
	{
		
		$("#" + div_id + " div.video-content").height("auto");
		
	}
		
	/* *
	 * Bind Page Control Events
	 *
	 *		Binds click events to the page controls
	 *		after they are output to the page by
	 *		javascript.
	 *
	 * */

	function BindPageControlEvents(mode)
	{
		
		// Next
		
		$("div.video-page-controls li.next").click(function() {
			var div_id = $(this).parents("div.video-set").attr('id');
			var limit = video[mode][div_id].limit;
			var page = parseInt($("#" + div_id + " li.current-page").html()) + 1;
			if (mode == "browse") PopulateVideoAJAX(div_id, div_id, limit, page, video[mode][div_id].cells, video[mode][div_id].page_range, video[mode][div_id].owner, video[mode][div_id].channel, video[mode][div_id].similar);
			if (mode == "search")
			{
				search_text = $("#search-input").val();
				SearchVideoAJAX(search_text, div_id, div_id, limit, page, video[mode][div_id].cells, video[mode][div_id].page_range);
			}
		});
		
		// Previous
				
		$("div.video-page-controls li.prev").click(function() {
			var div_id = $(this).parents("div.video-set").attr('id');
			var limit = video[mode][div_id].limit;
			var page = parseInt($("#" + div_id + " li.current-page").html()) - 1;
			if (mode == "browse") PopulateVideoAJAX(div_id, div_id, limit, page, video[mode][div_id].cells, video[mode][div_id].page_range, video[mode][div_id].owner, video[mode][div_id].channel, video[mode][div_id].similar);
			if (mode == "search")
			{
				search_text = $("#search-input").val();
				SearchVideoAJAX(search_text, div_id, div_id, limit, page, video[mode][div_id].cells, video[mode][div_id].page_range);
			}
		});
		
		// Page
		
		$("div.video-page-controls li.page").click(function() {
			var div_id = $(this).parents("div.video-set").attr('id');
			var limit = video[mode][div_id].limit;
			var page = parseInt($(this).html());
			if (mode == "browse") PopulateVideoAJAX(div_id, div_id, limit, page, video[mode][div_id].cells, video[mode][div_id].page_range, video[mode][div_id].owner, video[mode][div_id].channel, video[mode][div_id].similar);
			if (mode == "search")
			{
				search_text = $("#search-input").val();
				SearchVideoAJAX(search_text, div_id, div_id, limit, page, video[mode][div_id].cells, video[mode][div_id].page_range);
			}
		});
	
	}

