//jquery leftnav plugin
(function($)
{	
	// constructor
	function VideoLeftNav(root, conf)
	{	
		// Private fields ------------------------------------------------------------------
		var _root = $(root),
			_domElement = _root[0],
			_self = this,
			
			_curPage, //1-based, just to avoid confusion (video links are 1-based; e.g., /video/36673755001/40264834001/page/1)
			_totalPages,
			_pageNavHolders = $("table.module-footer-pagination"),
			_pageNavItems = $("table.module-footer-pagination div.pagination-video"), //divs inside the top/bottom pagination tables
			_pageNavItemHtml = '<a href="{p}" class="pgNum:{pn}">{dispP}</a>', //HTML used for each link in pagination (event handlers attached in setPageCount())
			
			_loadingMsgHtml = '<li id="video-status-msg"><span class="loadingMsg">Loading videos...</span><br/><img src="/assets/img/ajax_loader_circle_gow.gif" width="24" height="24" /></li>',
			_errorMsgHtml = '<li id="video-status-msg">Sorry. We seem to be having technical difficulties.<br/><br/>Please <a href="#" onclick="window.reload();">reload the page</a> or try again later.</li>',
			
			_contentTitleHolder = $("div.module-header.video h4"), //page title element (updated when playlist changes)
			_ajaxPageContainer = $("ul.video-index"), //the DOM element the returned AJAX HTML gets loaded into
			_curMenu, //currently selected top-level section UL (e.g., NHL)
			_curLink, //currently selected leftnav A element
			_curPlaylist, //single ("36625012001/") or multiple ("36625012001/40223742001/") - parsed from HREF of currently selected leftnav item 
			_opts = {
				debug: false,
				animSpeed: 200 //milliseconds
			}
			;
			$.extend(_opts, conf);
	
		// Public methods ------------------------------------------------------------------
//		$.extend(_self, {
			
//		});
	
		// Private methods -----------------------------------------------------------------
		//content
		function setPlaylist(wLink, doAjaxLoad){
			_curPlaylist = getPlaylistPath(wLink.attr("href"));
			setPageCount(wLink);
			if (doAjaxLoad) {
				_ajaxPageContainer.html(_loadingMsgHtml);
				setContentTitle(wLink.html());
				setTimeout(function() {
						loadPlaylist(_curPlaylist);
					}, (_opts.animSpeed));
			} else {
				debug("initial page load - setting page to initialPageNum (see dynamic_video_listing_inc): " + initialPageNum);
				setPageNum(initialPageNum);
				testForEmptyPage();
			}
		}
		
		function setContentTitle(wStr){
			_contentTitleHolder.html(wStr);
		}
		
		//navigation
		function setPageNum(wNum){
			_curPage = parseInt(wNum);
			debug("setPageNum; _curPage: " + _curPage);
			
			var re = new RegExp(/\pgNum:\s*(\S+)\b/);
			_pageNavItems.each(function(){
				_this = $(this);
				_this.find("a").each(function() {
					_this = $(this);
					
					var m = re.exec(_this[0].className);
					if (m != null) {
						var myPgNum = parseInt(m[1]);
						debug("myPgNum: " + myPgNum);
						
						if (myPgNum == wNum) {
							_this.addClass("on");
						}
						else {
							_this.removeClass("on");
						}
					}
				});
			})
			if (_curPage > 1){
				$('.previous').html('<img src="/assets/img/pagination_previous_active.gif"/>');
				$('.previous').attr({href: '#'});
			} else {
				$('.previous').html('<img src="/assets/img/pagination_previous.gif"/>');
				$('.previous').removeAttr('href');
			}
			if (_curPage < _totalPages){
				$('.next').html('<img src="/assets/img/pagination_next_active.gif"/>');
				$('.next').attr({href: '#'});
			} else {
				$('.next').html('<img src="/assets/img/pagination_next.gif"/>');
				$('.next').removeAttr('href');
				
			}
		}
		
		function setPageCount(wLink){
			_totalPages = 1; //defaults to 1 (will hide page nav) in case the conditions below
			
			var re = new RegExp(/\bpgCnt:\s*(\S+)\b/);
			var m = re.exec(wLink[0].className);
			if (m != null) {
				_totalPages = parseInt(m[1]);
			}
			debug("_totalPages: " + _totalPages);
			
			_pageNavHolders.hide(); //shown after the page loads - see onLoadPageSuccess()
			_pageNavItems.each(function(){
				_this = $(this);
				_this.html("");
				var baseUrl = wLink[0].href;
				var pHtml = "";
				for(var i=1; i<=_totalPages; i++) {
					var itemHtml = _pageNavItemHtml;
					itemHtml = itemHtml.replace("{pn}", i); 
					itemHtml = itemHtml.replace("{p}", baseUrl + "/page/" + i);
					itemHtml = itemHtml.replace("{dispP}", i);
					
					pHtml += itemHtml;
				}
				_this.html(pHtml);
				_this.find("a").click(function() {
						 onPageNumberClick(this);
						 return false;
					}
				);
				
				if (_totalPages <= 1) {
					$("table.module-footer-pagination a.previous").hide();
					$("table.module-footer-pagination a.next").hide();
				} else {
					$("table.module-footer-pagination a.previous").show();
					$("table.module-footer-pagination a.next").show();
				}
			})
		}
		
		//AJAX
		function loadPlaylist(playList){
			setPageNum(1); //defaults back to first page when loading new playlist
			debug("loadPlaylist: " + playList + " (_curPage: " + _curPage + ")");
			doAjaxCall(playList, _curPage);
		};
		
		function loadPage(pageNum){
			debug("loadPage: " + pageNum + " (_curPlaylist: " + _curPlaylist + ")");
			_ajaxPageContainer.html(_loadingMsgHtml);
			doAjaxCall(_curPlaylist, pageNum);
		};
		
		function doAjaxCall(playlistId, pageNum) {
			var baseUrl = "/videolisting";
			if (playlistId != "")
				baseUrl += "/" + playlistId;
			if (pageNum != "")
				baseUrl += "/page/" + pageNum;
			
			debug("** loading-ajax: " + baseUrl);
			
			$.ajax({
				url: baseUrl, //script to return the HTML
				async: false, //just one request at a time - comment this out if you want stacked 
				type: 'GET',
				dataType: 'html',
				timeout: 1000,
				error: function(XMLHttpRequest, textStatus, errorThrown){
					onLoadPageError(XMLHttpRequest, textStatus, errorThrown);
				},
				success: function(responseXml){
					onLoadPageSuccess(responseXml);
				}
			});
		};
	
		function onLoadPageError(XMLHttpRequest, textStatus, errorThrown) {
			debug("onLoadPageError; textStatus: " + textStatus + "; errorThrown: " + errorThrown); //responseText, textStatus, XMLHttpRequest
			_ajaxPageContainer.html(_errorMsgHtml);
		};
	
		function onLoadPageSuccess(responseXml) {
			debug("onLoadPageComplete");
			_ajaxPageContainer.html(responseXml);
			
			testForEmptyPage();
		};
	
		function testForEmptyPage(){
			//determines if the page came back with no thumbnails by testing for the empty LI
			if ($("#video-status-msg")[0] == undefined) {
				_pageNavHolders.show();
			} else {
				debug("### pageIsEmpty");
			}
		}
				
		//utility
		function getMenu(sectionLink) {
			var myMenu;
			var isMenuLink = !(sectionLink.parent().parent().hasClass("link-list"));
			if (isMenuLink) {
				myMenu = sectionLink.parent();
			} else {
				myMenu = sectionLink.parent().parent().parent();
			}
			return myMenu;
		}
	
		function getMenuLabel(wMenu){
			return $(wMenu.find('> a')[0]).attr("href");
		}
	
		function getPlaylistPath(href){
			//parse the href to just the playlist/video
			//returns values with no preceding slash; e.g., "36625012001/" or "36625012001/40223742001/"
			var path = "";
			var re = new RegExp(/\/video[^\/]*\/(\S+)/gi);
			var m = re.exec(href);
			if (m != null) {
				path = m[1];
			}
			debug("getPlaylistPath: " + path);
			return path;
		}
		
		//events
		function onSectionClick(wLink)
		{
			var wMenu = getMenu(wLink);
			var sameMenu = getMenuLabel(wMenu) == getMenuLabel(_curMenu);
			debug("onSectionClick; sameMenu: " + sameMenu);
			if (!sameMenu) {
				closeMenu(_curMenu);
				_curMenu = wMenu;
				openMenu(_curMenu);
			}
			
			var samePlaylist = wLink.attr("href") == _curLink.attr("href");
			if (!samePlaylist) {
				_curLink.removeClass("on");
				_curLink = wLink;
				_curLink.addClass("on");
				
				setPlaylist(_curLink, true);
			}
		};
		
		function onPageNumberClick(wLink)
		{
			_wLink = $(wLink);
			//var clickPageNum = _wLink.attr("href");
			var clickPageNum = 1;
			
			var re = new RegExp(/\pgNum:\s*(\S+)\b/);
			var m = re.exec(_wLink[0].className);
			if (m != null) {
				clickPageNum = parseInt(m[1]);
			}
			
			debug("onPageNumberClick; clickPageNum: " + clickPageNum + "; _curPage: " + _curPage);
			if (clickPageNum != _curPage) {
				setPageNum(clickPageNum);
				loadPage(_curPage);
			}
		};
		
		function closeMenu(wMenu) {
			wMenu.removeClass("on");
			wMenu.addClass("default");
			var wList = wMenu.find(">ul.link-list");
			if (wList) {
				wList.show();
				wList.slideUp(_opts.animSpeed);
			}
		}
		
		function openMenu(wMenu) {
			wMenu.removeClass("default");
			wMenu.addClass("on");
			var wList = wMenu.find(">ul.link-list");
			if (wList) {
				wList.hide();
				wList.slideDown(_opts.animSpeed);
			}
		}
		
		function debug(str)
		{
			if (_opts.debug == true) {
				try {
					trace(str);
				} 
				catch (e) {
					try {
						console.log(str);
					} 
					catch (er) {
						alert("debug: " + str);
					}
				}
			}
		};
		// Initialization ------------------------------------------------------------------
		function init()
		{
			_curMenu = $(_root.find('> li.on')[0]);
			_curLink = $(_curMenu.find('> ul a.on')[0] || _curMenu.find('> a')[0]); //looks for a nested item first, otherwise menu title
			
			initLinks();
			
			setPlaylist(_curLink, false);
		};

		function initLinks()
		{
			debug("initLinks");
				
			//leftnav
			var initFunc = function() {
				var $this = $(this);
				$this.click(function() {
					onSectionClick($this);
					return false;
				});
			};
			_root.find("> li > a").each(initFunc); //section links
			_root.find("> li > ul.link-list > li > a").each(initFunc); //sub-section links
			
			//pagination numbers
			_pageNavItems.find("a").click(function() {
					 onPageNumberClick(this);
					 return false;
				}
			);
			
			//pagination prev/next
			$("table.module-footer-pagination a.previous").click(function() {
				debug("prev");
				if (_curPage > 1) {
					setPageNum(_curPage-1);
					loadPage(_curPage);
				} else {
					debug("already on first page");
				}
				return false;
			});
			$("table.module-footer-pagination a.next").click(function() {
				debug("next");
				if (_curPage < _totalPages) {
					setPageNum(_curPage + 1);
					loadPage(_curPage);
				} else {
					debug("already on last page");
				}
				return false;
			});
		};
		
		init();
	};
	
	// jQuery plugin implementation
	$.fn.videoLeftNav = function(conf)
	{
		var opts = { };
		$.extend(opts, conf);
		
		this.each(function()
		{
			var $instance = new VideoLeftNav($(this), opts);
		});
		
		return this;
	};
})(jQuery);



//misc functions
jQuery(document).ready(function()
{
	if(jQuery("#next_up").length > 0) NextUp.init();
});

//| Clear the search box default input
function bcp_clearInput(pEl) {
	if(pEl.value == "Search Videos") {
		pEl.value = "";
	}
}

//| Clear the search box default input
function bcp_replaceInput(pEl) {
	if(pEl.value.length == 0) {
		pEl.value = "Search Videos";
	}
}

var NextUp = 
{
	playlist: new Array(),
	currentVideo: -1, //keeps track of where we are in the playlist
	
	init: function()
	{
		jQuery("#next_up li").each(function(pItem)
		{
			NextUp.playlist.push({
				videoID: jQuery(this).attr("id").split("-")[1],
				url: jQuery(this).children("a").attr("href"),
				videoName: jQuery(this).children("a").children(".video-info").children(".video-name").text(),
				description: jQuery(this).children("a").children(".video-info").children(".ellipsis").text()
			});
		})
	},
	
	getNextVideo: function()
	{
		if(NextUp.currentVideo <= NextUp.playlist.length) 
		{
			jQuery("#next_up li:first").remove();
			jQuery("#next_up li:eq(2)").show();
			
			if( jQuery("#next_up li").size() ==0 )
			{
				jQuery("#nextup-section").remove();
			}
			NextUp.currentVideo++;
			jQuery("#video-description").text(NextUp.playlist[NextUp.currentVideo].description);
			
			
			jQuery("#video-name").text(NextUp.playlist[NextUp.currentVideo].videoName);
			return NextUp.playlist[NextUp.currentVideo].videoID;
		}
		else 
		{
			return;
		}
	},
	
	getCurrentVideoURL: function()
	{
		return NextUp.playlist[NextUp.currentVideo].url;
	},
	
	getCurrentVideoName: function()
	{
		return NextUp.playlist[NextUp.currentVideo].videoName;
	},
	
	updateSharingLinks: function()
	{
		jQuery(".Video-Share a").each(function(pItem)
		{
			var url = jQuery(this).attr("href");
			var urlSplit;
			var newURL;
			
			if(url.indexOf("facebook.com") !== -1)
			{
				//http://www.facebook.com/sharer.php?u=http://dev.video.citytv.com/video/25195089001/Perfect-Patio-Furniture-Makeover/&t=Perfect+Patio+Furniture+Makeover
				urlSplit = url.split("?u=");
				newURL = urlSplit[0] + 
						"?u=" + NextUp.getCurrentVideoURL() + 
						"&t=" + NextUp.getCurrentVideoName();
			}
			if(url.indexOf("digg.com") !== -1)
			{
				//http://digg.com/submit?url=http://dev.video.citytv.com/video/25195089001/Perfect-Patio-Furniture-Makeover/&title=Perfect+Patio+Furniture+Makeover&bodytext=Perfect+Patio+Furniture+Makeover&media=&topic=
				urlSplit = url.split("?url=");
				newURL = urlSplit[0] + 
						"?url=" + NextUp.getCurrentVideoURL() + 
						"&title=" + NextUp.getCurrentVideoName() + 
						"&bodytext=" + NextUp.getCurrentVideoName() + 
						"&media=&topic=";
			}
			if(url.indexOf("stumbleupon.com") !== -1)
			{
				//http://www.stumbleupon.com/submit?url=http://dev.video.citytv.com/video/25195089001/Perfect-Patio-Furniture-Makeover/&title=Perfect+Patio+Furniture+Makeover
				urlSplit = url.split("?url=");
				newURL = urlSplit[0] + 
						"?url=" + NextUp.getCurrentVideoURL() + 
						"&title=" + NextUp.getCurrentVideoName();
			}
			if(url.indexOf("del.icio.us") !== -1)
			{
				//http://del.icio.us/post?url=http://dev.video.citytv.com/video/25195089001/Perfect-Patio-Furniture-Makeover/&title=Perfect+Patio+Furniture+Makeover&notes=Perfect+Patio+Furniture+Makeover
				urlSplit = url.split("?url=");
				newURL = urlSplit[0] + 
						"?url=" + NextUp.getCurrentVideoURL() + 
						"&title=" + NextUp.getCurrentVideoName();
			}
			if(url.indexOf("newsvine.com") !== -1)
			{
				//http://www.newsvine.com/_tools/seed?popoff=0&u=http://dev.video.citytv.com/video/25195089001/Perfect-Patio-Furniture-Makeover/
				urlSplit = url.split("&u=");
				newURL = urlSplit[0] + "&u=" + NextUp.getCurrentVideoURL();
			}
			if(url.indexOf("reddit.com") !== -1)
			{
				//http://www.reddit.com/submit?url=http://dev.video.citytv.com/video/25195089001/Perfect-Patio-Furniture-Makeover/
				urlSplit = url.split("?url=");
				newURL = urlSplit[0] + "?url=" + NextUp.getCurrentVideoURL();
			}
			
			jQuery(this).attr("href", newURL);
		});
	}
}
