//http://outwestmedia.com/jquery-plugins/xmldom/
//jquery plugin to create an xmldom object from xml text
(function($) {
	// IE DOMParser wrapper
	if ( window['DOMParser'] == undefined && window.ActiveXObject ) {
		DOMParser = function() { };
		DOMParser.prototype.parseFromString = function( xmlString ) {
			var doc = new ActiveXObject('Microsoft.XMLDOM');
	        doc.async = 'false';
	        doc.loadXML( xmlString );
			return doc;
		};
	}
	
	$.xmlDOM = function(xml, onErrorFn) {
		try {
			var xmlDoc 	= ( new DOMParser() ).parseFromString( xml, 'text/xml' );
			if ( $.isXMLDoc( xmlDoc ) ) {
				var err = $('parsererror', xmlDoc);
				if ( err.length == 1 ) {
					throw('Error: ' + $(xmlDoc).text() );
				}
			} else {
				throw('Unable to parse XML');
			}
		} catch( e ) {
			var msg = ( e.name == undefined ? e : e.name + ': ' + e.message );
			if ( $.isFunction( onErrorFn ) ) {
				onErrorFn( msg );
			} else {
				$(document).trigger('xmlParseError', [ msg ]);
			}
			return $([]);
		}
		return $( xmlDoc );
	};
})(jQuery);


var iFlaggedComment = 0;
//var oVideoTabDivs = {};
var arrCategories = ['all', 'sports', 'entertainment', 'business', 'life', 'advertising'];

//removes all links from items matching the specified path, this was previously needed but no longer needed as of 10/11/09
//example removeLinks("ul li.signin a");
function removeLinks(szPath)
{
	$(szPath).each(function(i) {
		$(this).replaceWith($(this).text() );
	});
}
/**
* Makes comments tab active
*/
function showCommentsTab()
{	
	$('#descriptionWrapper').css("display", "none");
	$("#nav_tab_featured_video").removeClass('nav_tab_active');
	$("#nav_tab_featured_video").addClass('nav_tab');
	$("#nav_tab_comments").addClass('nav_tab_active');
	$('#moduleTabbedContent').fadeIn('fast');

	
}

/**
* Makes description tab active
*/
function showDescriptionTab()
{
	$('#moduleTabbedContent').css("display", "none");
	$("#nav_tab_comments").removeClass('nav_tab_active');
	$("#nav_tab_comments").addClass('nav_tab');
	$("#nav_tab_featured_video").addClass('nav_tab_active');
	$('#descriptionWrapper').fadeIn('fast');
}

/**
* Hides add comment section
*/
function hideAddComment()
{
	$('div.comments div.module div.content div.body fieldset').css("display", "none");
	$('div.comments div.module div.content div.body div.input').css("display", "none");
}

/**
* Shows add comment section with text area and input
*/
function showAddComment()
{
	$('div.comments div.module div.content div.body fieldset').css("display", "block");
	$('div.comments div.module div.content div.body div.input').css("display", "block");
    $('div.comments div.module div.content div.body fieldset').css("visibility", "visible");
	$('div.comments div.module div.content div.body div.input').css("visibility", "visible");
}

/**
* inserts add comment button link which shows comment input section
*/
function insertAddCommentButton()
{		
	//$('div.comments div.module div.content ul:eq(0)').append('<a id="add_comment_link" href="javascript:showAddComment();">Add Comment</a>');
	$('div#moduleTabbedContent').append('<a id="add_comment_link" href="javascript:showAddComment();">Add Comment</a>');
}

/**
* function to check if a new comment was added and if so it flags it so that an admin can review it
*/
function watchForNewComments()
{
	//get all the first comment in the listing and check if it has text that it was recently added.
	//if it was recently added check if we've already flagged it, if not then try to auto flag it	
	var szNewCommentToken = '(A moment ago )';
	var oFirstComment = $('div.comments div.module div.content div.body ul li:eq(0)');
	if (oFirstComment)
	{		
		var oTxt = oFirstComment.children('div.txt:eq(0)');
		var oDate = oTxt.children('div.date:eq(0)');
						
		if (szNewCommentToken == $.trim(oDate.text() ) && !(iFlaggedComment > 0) )
		{					
			//flag the comment!
			iFlaggedComment = oFirstComment.attr('id');
			//set the reason to other in the flagging options.
			$('#cmsgData\\[flagReasonId\\]').val('5');
			$('#cmsgData\\[flagReasonId\\] :selected').text()			
			confirmFlag(iFlaggedComment, 'comment');
		}		
	}
}

/**
* helper function to remove # of items since category by default lists # of items
*/
function formatCategoryHeaderString(szText)
{
	var arrTmp = szText.split('(');	
	return $.trim(arrTmp[0]).toLowerCase();
}

/**
* function to display the active tab in the video gallery for the video page
* this is separate than the normal function because the video thumbnail/category list module combination from EOS
* displays differently on the video detail page so we hard code the category header
*/
function showVideoPageVideoGalleryTab(szIndex)
{        			
	if ($.inArray(szIndex, arrCategories) != -1)
	{
		//set the nav states
		for (var i = 0; i < arrCategories.length; i++)
		{
			//remove class for active
			$('#nav_gallery_' + arrCategories[i] + ':eq(0)').removeClass('video_gallery_active');
		}		
		$('#nav_gallery_' + szIndex).addClass('video_gallery_active');				
				
		$('div#moduleVideoPageVideoGallery div.video_thumbnail').each (function(i) {
			$(this).css({'visibility':'hidden'});
			}
		);

		//get all the header category names we are doing this because EOS ajax paging resets divs
		var arrCategoryHeaders = $('div#moduleVideoPageVideoGallery div.video_thumbnail > div.module > div.content > div.head > div.title > h3');
		
		// place all divs for video gallery into the oVideoTabDivs object we can access by category name
		var oVideoTabDivs = new Object();
		$('div#moduleVideoPageVideoGallery div.video_thumbnail').each ( function(i) {
				oVideoTabDivs[formatCategoryHeaderString($(arrCategoryHeaders[i]).text() )] = $(this);
			}
		);
		
		oVideoTabDivs[szIndex].css({'visibility':'visible'});
	}
}

/**
* default function to display the active tab in the video gallery for the home page and video category page
*/
function showVideoGalleryTab(szIndex)
{        
	if ($.inArray(szIndex, arrCategories) != -1)
	{
	
		$('div#moduleVideoGallery div.video_thumbnail').each (function(i) {
			$(this).css({'visibility':'hidden'});
			}
		);
		
		//get all the header category names we are doing this because EOS ajax paging resets divs
		var arrCategoryHeaders = $('div#moduleVideoGallery div.video_thumbnail > div.module > div.content > div.head > div.title > h3');
		
		// place all divs for video gallery into the oVideoTabDivs object we can access by category name
		var oVideoTabDivs = new Object();
		$('div#moduleVideoGallery div.video_thumbnail').each ( function(i) {
				oVideoTabDivs[formatCategoryHeaderString($(arrCategoryHeaders[i]).text() )] = $(this);
			}
		);
		
		oVideoTabDivs[szIndex].css({'visibility':'visible'});				
		
		//set the nav states
		for (var i = 0; i < arrCategories.length; i++)
		{
			//remove class for active
			$('#nav_gallery_' + arrCategories[i] + ':eq(0)').removeClass('video_gallery_active');
		}
		
		$('#nav_gallery_' + szIndex).addClass('video_gallery_active');		
	}	
}

/**
* Parses string and replace BBCode-type elements with html entities.  This is needed because the 
* description field for movies in EOS does not natively support HTML attributes.  This is called
* only on the video detail page description
* credit for source, modified from http://www.dreamincode.net/code/snippet304.htm of parseBBCode 
*/
function parseBBCode(szText)
{	
	
	szText = szText.replace(/\.\.\.less/gi, "");
	szText = szText.replace(/\[br\]/g, '<br />');
	szText = szText.replace(/\[b\]/g, '<b>');
	szText = szText.replace(/\[\/b\]/g, '</b>');
	szText = szText.replace(/\[\/url\]/g, '</a>');
	szText = szText.replace(/\[\/urlsmall\]/g, '</a>');
	szText = szText.replace(/\[url=\"/g, '<a target="_blank" href="');
	szText = szText.replace(/\[urlsmall=\"/g, '<a class="urlsmall" target="_blank" href="');
	szText = szText.replace(/\]/g, '>');	
	
	/*
	arrSearch = new Array(                    
		  /\[url=(.+?)\](.+?)\[\/url\]/g,
		  /\[urlsmall=(.+?)\](.+?)\[\/urlsmall\]/g,
          /\[b\](.*?)\[\/b\]/g,          
		  /\[br\]/g		  
		  );

	arrReplace = new Array(                              
		  "<a href=$1 target=\"blank\">$2</a>",
          "<a class=\"urlsmall\" href=$1 target=\"blank\">$2</a>",
          "<b>$1</b>",          
		  "<br />"		  
		  );
	  
	for(i = 0; i < arrSearch.length; i++)
	{
		 szText = szText.replace(arrSearch[i], arrReplace[i]);		 
	}
	*/	
	return szText;
}

/**
* Timer functions that get called to make sure effects/events stay alive even during ajax section refreshes
* for video category page
*/
function videoGalleryTimerFunctions()
{
	var oTestVideoGallery = $('#moduleVideoGallery .video_thumbnail li.video:eq(0)');
	if (oTestVideoGallery.data('events') === undefined)
	{
		//setVideoGalleryRollovers();
		setVideoGalleryRatingRollovers();
		//override the default links for categories for the video gallery module to act dhtml tab links instead or redircting to a new page.
 $('div#moduleVideoGallery form div.categories div.module div.content div.body ul li.division ul li div.title a').click(function(e) {
  e.preventDefault();
  //do ajax form
  showVideoGalleryTab($.trim($(this).text().toLowerCase() ) );
  return false; // preventDefault and stopPropagation
  });


	}
}

/**
* Timer functions that get called to make sure effects/events stay alive even during ajax section refreshes
* for video detail page
*/
function videoDetailTimerFunctions()
{
	//used for auto flagging new coments
	if(!$('li.signin').length)
	{//only if someone is already logged in, if the signin div exists, then don't 				  
		watchForNewComments();
	}
	
	/*
	check if we hit a new page for related videos by checking if there is a rollover event handler
	for the first video, if not we need to reset the rollovers
	*/
	var oTestRelatedVideos = $('#moduleMainVideoDetailContent .video_thumbnail li.video:eq(0)');
	if (oTestRelatedVideos.data('events') === undefined)
	{
		setVideoDetailRelatedVideoRollovers();
	}
	
	/*
	check if we need to reset rollovers for video gallery
	*/
	var oTestVideoGallery = $('#moduleVideoPageVideoGallery .videos li:eq(0)');
    if (oTestVideoGallery.data('events') === undefined )
    {//set video gallery rollovers again
		setVideoPageVideoGalleryRollovers();
   	}
}

/**
* sets rollover effect for video detail page video gallery thumbnails
*/
function setVideoPageVideoGalleryRollovers()
{
	//assign rollovers for all thumbnails in the video gallery tabs	
	$("#moduleVideoPageVideoGallery .video_thumbnail li.video").hover(
		function()
		{		
			$(this).find('div.rating').fadeIn('slow');
			$(this).find('div.title h4 a').css({'color':'#ffffff'});
			$(this).find('div.img a').css({'border':'solid #ffffff 1px'});
		},
		function()
		{
			$(this).find('div.rating').fadeOut('slow');
			$(this).find('div.title h4 a').css({'color':'#47baeb'});
			$(this).find('div.img a').css({'border':'0px'});
		}
	);
}

/**
* main function to setup video detail page video gallery module
*/
function doVideoPageVideoModuleGallery()
{
	/*get all the header category names
	var arrCategoryHeaders = $('div#moduleVideoPageVideoGallery div.video_thumbnail > div.module > div.content > div.head > div.title > h3');
	//place all divs for video gallery into the oVideoTabDivs global object we can access by category name
	$('div#moduleVideoPageVideoGallery div.video_thumbnail').each ( function(i) {
			oVideoTabDivs[formatCategoryHeaderString($(arrCategoryHeaders[i]).text() )] = $(this);
		}
	);	
	*/
	
	setVideoPageVideoGalleryRollovers();
	

	var	szLoc = $.trim($('div#moduleMainVideoDetailContent .video_thumbnail .videos .txt .category a:eq(0)').text().toLowerCase() );		
	showVideoPageVideoGalleryTab(szLoc);
}

/**
* sets rollover effect for home and video category page video gallery thumbnails
*/
function setVideoGalleryRatingRollovers()
{	
	//assign rollovers for all thumbnails in the video gallery tabs	
	$("#moduleVideoGallery .video_thumbnail li.video").hover(
		function()
		{		
			$(this).find('div.rating').fadeIn('slow');
			$(this).find('div.title h4 a').css({'color':'#ffffff'});
			$(this).find('div.img a').css({'border':'solid #ffffff 1px'});
		},
		function()
		{
			$(this).find('div.rating').fadeOut('slow');
			$(this).find('div.title h4 a').css({'color':'#47baeb'});
			$(this).find('div.img a').css({'border':'0px'});
		}
	);
}

/**
* handles the event handling for the video gallery module for the home and video category pages
*/
function doVideoModuleGallery()
{	
	//get all the header category names
	var arrCategoryHeaders = $('div#moduleVideoGallery div.video_thumbnail > div.module > div.content > div.head > div.title > h3');

	/*
	place all divs for video gallery into the oVideoTabDivs global object we can access by category name
	$('div#moduleVideoGallery div.video_thumbnail').each ( function(i) {
			oVideoTabDivs[formatCategoryHeaderString($(arrCategoryHeaders[i]).text() )] = $(this);
		}
	);  
	*/
	
	//override the default links for categories for the video gallery module to act dhtml tab links instead or redircting to a new page.
	/* no longer needed since we're not using EOS categories anymore
	$('div#moduleVideoGallery form div.categories div.module div.content div.body ul li.division ul li div.title a').click(function(e) {
		e.preventDefault();
		//do ajax form		
		showVideoGalleryTab($.trim($(this).text().toLowerCase() ) );
		return false; // preventDefault and stopPropagation
		});
	*/
		
	//setVideoGalleryRollovers();
	setVideoGalleryRatingRollovers();
	
	var szLoc = document.location; 
	var arrPath = szLoc.toString().split('/');
	 			
	if (arrPath.length == 4) //if we're on home page
	{
		
		szLoc = 'all';
	}
	else
	{
		szLoc = arrPath[arrPath.length - 2].replace('/', '');	
		szLoc = $.trim(szLoc.toLowerCase() );	
	}

	//szLoc = szLoc.substring(0,1).toUpperCase() + szLoc.substring(1, szLoc.length).toLowerCase();	
	
	showVideoGalleryTab(szLoc);
}

/**
* just sets the name of the related video module for category pages and sets callback timer functions
*/
function doVideoCategoryPage()
{
	//set the correct title for the video category module by appending the category name and changing capitalization
	//var oCategoryModuleTitle = $('div#moduleMainContent div.video_thumbnail > div.module > div.content > div.head > div.title > h3:eq(0)');	
	var oCategoryModuleTitle = $('div#moduleMainContent > h3:eq(0)');	
	var szVideoCount = $('div#moduleMainContent div.video_thumbnail > div.module > div.content > div.head > div.title > h3 span.total:eq(0)').text();	
	
	
	var szLoc = document.location;  
	var arrPath = szLoc.toString().split('/');  
	szLoc = arrPath[arrPath.length - 2].replace('/', '');	
	szLoc = szLoc.substring(0,1).toUpperCase() + szLoc.substring(1, szLoc.length).toLowerCase();	
	
	//var szHeaderText = szLoc + " " + formatCategoryHeaderString(oCategoryModuleTitle.text() );	
	oCategoryModuleTitle.text(szLoc + ' Videos ' + szVideoCount);	
}

/**
* sets the main styles for the main nav as well as active/passive states based on url
*/
function setMainNavRollovers()
{
	$('div.nav_main li').each(function(i) {		
		var oTmp = $(this);
		var oTmpAnchor = oTmp.children('a:eq(0)');
		
		var szCategory = $.trim($(this).text().toLowerCase() );		
		var szLoc = document.location;
		var arrPath = szLoc.toString().split('/');
				
		if (arrPath.length == 4) //if we're on home page
		{
			
			szLoc = 'home';
		}
		
		//if we're on a vid category page
		if ( $('div#moduleMainContent div.video_thumbnail').length )
		{  			  		
			szLoc = arrPath[arrPath.length - 2].replace('/', '');		
		
			//in case we have page anchors in the location remove them
			var arrAnchor = szLoc.split('#');
			szLoc = arrAnchor[0];
		}
		
		//if we're on a video page.  
		if ( $('div#moduleMainVideoDetailContent').length )
		{
			szLoc = $.trim($('div#moduleMainVideoDetailContent .video_thumbnail .videos .txt .category a:eq(0)').text().toLowerCase() );
		}
		
		/* tried just setting the class to set background position instead of new id names, but it wasn't working
		if (szLoc == szCategory)
		{
			oTmpAnchor.addClass('active_rollover');
		}		
		*/
		if (szLoc == szCategory)
		{
			oTmpAnchor.attr('id', 'nav_main_' + szCategory + '_active' );
		}
		else
		{
			oTmpAnchor.attr('id', 'nav_main_' + szCategory );
		}
				
		oTmpAnchor.wrapInner('<span class="alt_text">' + '</span>');		
	}
  );
}

/**
*sets the rollover for the video gallery menu
*/
function setVideoGalleryRollovers()
{

	//alert('test');
	$('div#moduleVideoGallery div.categories li.category div.title').each(function(i) {		
		var oTmp = $(this);
		var oTmpAnchor = oTmp.children('a:eq(0)');
		oTmpAnchor.attr('id', 'nav_gallery_' + $.trim($(this).text().toLowerCase() ) );
		oTmpAnchor.wrapInner('<span class="alt_text">' + '</span>');
	}
  );
}

function setVideoDetailRelatedVideoRollovers()
{
	//handleRollovers for video thumbnails
	$("#moduleMainVideoDetailContent .video_thumbnail li.video").hover(
		function()
		{		
			$(this).find('div.title').fadeIn('slow');			
		},
		function()
		{
			//$(this).find('div.title').fadeOut('fast');			
			$(this).find('div.title').css({'display':'none'});			
		}
	);
}

function doVideoDetailPage()
{
	doVideoPageVideoModuleGallery();
	
	//default add nba link
	//$('<li id="partner_ads"><a href="http://www.nba.com" target="_blank"><img src="http://extranet.the1stmovement.com/Cisco/HNE/partner_logos/img_logo_NBA.png" /></a></li>').insertBefore('#moduleMainVideoDetailContent li.sharelink:eq(0)');
	
	//add the dim lights button to video page if page is not rendered in IE
	 var browserName=navigator.appName; 
	  
	 if (browserName!="Microsoft Internet Explorer"){
	{
$('<li><a href="javascript:dimLights();" id="dim_lights"><span class="alt_text">dim lights</span></a></li>').insertAfter('#moduleMainVideoDetailContent li.sharelink:eq(0)');
	 }
}
	//remove share text
	//no longer needed, just using text-indent css property of sharelink.  enable this only if needed for browser compatibility
	//$('div.tools > ul > li.sharelink > a.sharelink:eq(0)').wrapInner('<span class="alt_text">' + '</span>');
	
	//handle new comments auto flagging 
	if ( $('div.comments').length )
	{
		/*
		set number of comments in tab.  we don't currently do this because if a user adds a comment this does not automatically update.  With a newer jquery version we could probably do this
		*/
		var iNumComments = $('div.comment h3 span.count:eq(0)').text();	
			if (iNumComments>0){
		$('#nav_tab_comments').text('Comments (' + iNumComments + ')');
		} else {
		$('#nav_tab_comments').text('Post a Comment');
		}
		
	if(!$('li.signin').length)
		{//only if someone is already logged in, if the signin div exists, then don't 				  
			//moving this out of condition per request of client
			//insertAddCommentButton();			
		}
		insertAddCommentButton();			
	}
	
	//set event handlers for dim lights/show lights
	$("#show_lights").bind("click", showLights);
	
	//remove number of videos from related videos title
	var oRelatedVideosTitle = $('#moduleMainVideoDetailContent .video_thumbnail .title h3');	
	var arrTmp = oRelatedVideosTitle.text().split('(');		
	oRelatedVideosTitle.text($.trim(arrTmp[0]) );		
	
	setVideoDetailRelatedVideoRollovers();
			
	$('<a href="javascript:showDescriptionTab();">Featured Video</a><div id="tab_header">&nbsp;</div><div id="tab_description"></div>').insertBefore('#moduleMainVideoDetailContent form:eq(2)');
	$('<div id="tab_footer">&nbsp;</div>').insertAfter('#moduleMainVideoDetailContent form:eq(2)');
	
	//add description to our custom div and unencode it
	var szVideoDescription = $('#moduleMainVideoDetailContent .video > .description:eq(0)').text();	
	var szParsedText = parseBBCode(szVideoDescription.toString() );				
	$('#videoDescriptionContent p').html(szParsedText);
	
	
	/*move the title div before ratings.  so far this doesn't really help anything so disabling it.
	$('#moduleMainVideoDetailContent div.video_player div.title:eq(0)').insertAfter('#moduleMainVideoDetailContent div.video_player div.author');		
	*/
	
	setInterval('videoDetailTimerFunctions()', 2500);
	
	//get video slug
	var szLoc = document.location;  
	var arrPath = szLoc.toString().split('/');  
	szLoc = arrPath[arrPath.length - 2].replace('/', '');
	setXMLData(szLoc, szPartnerXML);
	
	
	var linkSize = $('li#partner_ads').length;
	//alert (linkSize);
	// attempt to check if href has a value, and if not, do not display..need to get this right
	if(linkSize==0){
	$("#partner_ads").css({'display':"none"}); 
	}
}	

function dimLights(e)
{
	$("#dim_overlay").fadeIn("slow");
	restoreShowLights();
}

function showLights(e)
{
	$("#dim_overlay").fadeOut("slow");
	restoreDimLights();
}

/* Restoration function for dimming/showing lights - function calls added to the two above functions RJM */

function restoreDimLights () {
	$("a#dim_lights").attr('href', 'javascript:dimLights();');
	$("a#dim_lights").css({'background-image':"url('http://lln.ciscoeos.com/zipupload/227/c8a/40227fe7e74ebe4b44ea51a055/images/dimlights_btn.gif')"}); 

}

function restoreShowLights() {
	$("a#dim_lights").attr('href', 'javascript:showLights();');
	$("a#dim_lights").css({'background-image':"url('http://lln.ciscoeos.com/zipupload/227/c8a/40227fe7e74ebe4b44ea51a055/images/undim_btn.gif')"}); 

	
}

$(document).ready(function() {
  //custom jquery goes here! BEE
  //removeLinks("li.hello a"); uncomment to remove profile link at top of page
  //removeLinks(" div.txt div.author a");
  
  //set the main menu set for css rollovers
  setMainNavRollovers();
  
  //set the video gallery for css rollovers
  setVideoGalleryRollovers();
  
  //override default join message based on cisco folder
  
  
$("signup.thickbox.a").html('Join the Cisco Video Lounge');
  
  /*
  if we have video section we should set the appropriate event handlers/styles
  this should be for most pages
  */
  if ( $('div#moduleVideoGallery').length )
  {	  
		doVideoModuleGallery();
		setInterval('videoGalleryTimerFunctions()', 2500);
  }
  
  //if we're on a category page  set the appropriate handler/styles
  if ( $('div#moduleMainContent div.video_thumbnail').length )
  {
		doVideoCategoryPage();	
  }
  
  //if we're on a video detail page
  if ( $('div#moduleMainVideoDetailContent').length )
  {
	doVideoDetailPage();	
  }
  
  //create a clickable div to emulate a link over the cisco logo
  $("#nav_main-567790").append("<div id='cisco_link' onclick='window.open(\"http://www.cisco.com\");' ></div>")
});