/**
 * Advances HP video player play list
 **/
function advanceTo(playlist, index) {
	var doc = $('player0').contentWindow;
	doc.CNNPlaylistManager.getInstance().advanceTo(playlist, index);
}


/*Dropdown menu used for video categories + shows //uses jquery; foot.js, in the same directory, is a prototype version*/
var DDMenuController = function() {
  var that = this;
  var index = null;
  var mouseOverList = false;

  function setIndex(n){ index=n; }
  function showList(){
    if(jQuery('.cnnShowList').eq(index).hasClass('showList') && (mouseOverList==false)) {
	   document.body.onmousedown = null;
	   jQuery('.cnnShowList').eq(index).removeClass('showList');      //hide the list
       jQuery(".toggleList").eq(index).show();                        //enable the button
    }
    else {
  	   jQuery(".toggleList").eq(index).hide();					      //disable the button
	   jQuery('.cnnShowList').eq(index).addClass('showList');         //show the list
	   document.body.onmousedown = showList;
    }
  }
  function setMouseOvers(){
    jQuery('.cnnShowList').eq(index).mouseover(function(){ mouseOverList = true; });
    jQuery('.cnnShowList').eq(index).mouseout(function(){ mouseOverList = false; });
  }
  this.init = function(i,el) {
    setIndex(i);
    setMouseOvers();
    jQuery(el).click(function(){ showList(); return false; });
    return this;
  };
}
var DDmenu = function() {
  var ddMenus = [];
  this.init = function(){
    jQuery('.toggleList').each(function(index,value) {
      ddMenus[index] = new DDMenuController().init(index,value);
    });
    return ddMenus;
  };
  return this;
}

try{ var ddMenus = new DDmenu().init(); } catch(e){}
/*End of Dropdown menu used for video categories + shows //uses jquery; foot.js, in the same directory, has a prototype version*/

// live quotes
function runLQ(){
	if (typeof(LiveQuotesGateway) != 'undefined')
	{
		lqg = LiveQuotesGateway.setup();
		MWMarketBanner.tickerSetup(lqg);
		if (typeof(LiveNewsGateway) != 'undefined')
		{
			lng = new LiveNewsGateway();
			if (typeof(LiveNewsSetup) != 'undefined')
			LiveNewsSetup(lng, lqg);
		}
	}
}

// toggle tabs
function showNavTab(tabId,tabNo) {
	var tabCollection = document.getElementById(tabId);
	tabCollection.className='Tab'+tabNo+'Visible';
}
function linkBG(target)
{
	var targetDiv=document.getElementById(target);
	if(typeof targetDiv != 'undefined'){
		var elementLI=targetDiv.getElementsByTagName('li');
		for(var i=0; i<elementLI.length;i++)
		{
			elementLI[i].onmouseover = function() {	this.className=" over";	}
			elementLI[i].onmouseout = function() { this.className=" out"; }
		}
	}
}

// set up horizontal scroll
var setupFeaturedBoxes = function () {
	var buttons = {
		previous: {
			enabled: 'http://i.cdn.turner.com/money/.element/img/2.0/buttons/feature_left.gif',
			hover: 'http://i.cdn.turner.com/money/.element/img/2.0/buttons/feature_left_blue.gif'
		},
		next: {
			enabled: 'http://i.cdn.turner.com/money/.element/img/2.0/buttons/feature_right.gif',
			hover: 'http://i.cdn.turner.com/money/.element/img/2.0/buttons/feature_right_blue.gif'
		}
	};
	var featuredContentWidth = 190;		// 3 + 184 + 3
	var featuredContentScrollPrefs = {
		speed: 800,
		axis: 'x'
	};
	jQuery('.featuredBox').each( function (i) {
		var featuredBox = jQuery(this);
		featuredBox
			.find('.scrollArrow')
				.filter('.next')
					.hover(
						function () {
							jQuery(this)
								.attr( 'src', buttons.next.hover )
								.css( 'cursor', 'pointer' )
							;
						},
						function () {
							jQuery(this)
								.attr( 'src', buttons.next.enabled )
								.css( 'cursor', 'default' )
							;
						}
					)
					.click( function() {
						featuredBox.find('.featuredContent').scrollTo(
							'+=' + featuredContentWidth + 'px',
							featuredContentScrollPrefs
						);
						return false;
					})
				.end()
				.filter('.prev')
					.hover(
						function () {
							jQuery(this)
								.attr( 'src', buttons.previous.hover )
								.css( 'cursor', 'pointer' )
							;
						},
						function () {
							jQuery(this)
								.attr( 'src', buttons.previous.enabled )
								.css( 'cursor', 'default' )
							;
						}
					)
					.click( function() {
						featuredBox.find('.featuredContent').scrollTo(
							'-=' + featuredContentWidth + 'px',
							featuredContentScrollPrefs
						);
						return false;
					})
		;
	});
	jQuery('.featuredBox .featuredContent .featuredDisplayDiv').each( function (i) {
		jQuery(this).css( 'width', ( featuredContentWidth * jQuery(this).find('ul li').size() ) + 'px' );
	});
};


var MainPageUpdater = (function() {
	var self = this;
	var updated = 0;
	var executed = 0;
	var updatedTime = 0;
	var autoUpdateInterval = 5 * 60 * 1000;
	var autoUpdateTimer = null;

	this.init = function () {
		autoUpdateTimer = window.setTimeout( "MainPageUpdater.run()", autoUpdateInterval );
	};

	this.run = function () {
		executed++;
		if ( jQuery("#section_latestnews, #section_morenews").size() > 1 ) {
			jQuery.ajax({
				url: "/.element/ssi/main/2.0/content_ssi.exclude.html",
				dataType: "html",
// 				ifModified: true,
// 				cache: true,
				timeout: 1000,
				success: function(html){
					var now = new Date().getTime();
					if ( now > updatedTime + autoUpdateInterval ) {
						// Create a dummy div to hold the results
						var update = jQuery("<div/>")
							// inject the contents of the document in, removing the scripts
							// to avoid any 'Permission Denied' errors in IE
							.append(
								html
									.replace(/<script(.|\s)*?\/script>/g, "")
									.replace(/<iframe.+?\/iframe>/g, "")
							)
						;

						if ( update.find('#breakingNews_bar').contents().size() > 0 ) {
							jQuery("#breakingNews_bar").replaceWith( update.find('#breakingNews_bar') );
						}
						if ( update.find('#cnnTL1').contents().size() > 0 ) {
							jQuery("#cnnTL1").replaceWith( update.find('#cnnTL1') );
						}
						if ( update.find('#section_latestnews').contents().size() > 0 ) {
							jQuery("#section_latestnews").replaceWith( update.find('#section_latestnews') );
						}
						if ( update.find('#section_morenews').contents().size() > 0 ) {
							jQuery("#section_morenews").replaceWith( update.find('#section_morenews') );
						}
						updateLatestNewsTimestamp();
						update = null;
						updated++;
						updatedTime = now;
						pingOmniture();
					}
				}
			});
			autoUpdateTimer = window.setTimeout( "MainPageUpdater.run()", autoUpdateInterval );
		}
		updateLatestNewsTimestamp();
	};

	this.stop = function () {
		window.clearTimeout( autoUpdateTimer );
	};

	return {
		'init': init,
		'run': run,
		'stop': stop
	};

})();

var MarketRibbonUpdater = (function() {
	var self = this;
	var updated = 0;
	var executed = 0;
	var updatedTime = 0;
	var autoUpdateInterval = 60 * 1000;
	var autoUpdateTimer = null;

	this.init = function () {
		autoUpdateTimer = window.setTimeout( "MarketRibbonUpdater.run()", autoUpdateInterval );
	};

	this.run = function () {
		executed++;
		if ( jQuery("#marketRibbon, #marketTimeStamp").size() > 0 ) {
			jQuery.ajax({
				url: "/.element/ssi/data/2.0/market.ribbon.html",
				dataType: "html",
				ifModified: true,
				cache: true,
				timeout: 1000,
				success: function(html){
					var now = new Date().getTime();
					if ( now > updatedTime + autoUpdateInterval ) {
						// Create a dummy div to hold the results
						var update = jQuery("<div/>")
							// inject the contents of the document in, removing the scripts
							// to avoid any 'Permission Denied' errors in IE
							.append(
								html
									.replace(/<script(.|\s)*?\/script>/g, "")
									.replace(/<iframe.+?\/iframe>/g, "")
							)
						;

						if ( update.find('#marketRibbon').contents().size() > 0 ) {
							jQuery("#marketRibbon").replaceWith( update.find('#marketRibbon') );
						}
						if ( update.find('#marketTimeStamp').contents().size() > 0 ) {
							jQuery("#marketTimeStamp").replaceWith( update.find('#marketTimeStamp') );
						}
						updated++;
						updatedTime = now;
					}
				}
			});
			if ( updated > 0 || executed < 3 ) {
				autoUpdateTimer = window.setTimeout( "MarketRibbonUpdater.run()", autoUpdateInterval );
			}
		}
	};

	this.stop = function () {
		window.clearTimeout( autoUpdateTimer );
	};

	return {
		'init': init,
		'run': run,
		'stop': stop
	};

})();


var updateLatestNewsTimestamp = function () {
	var now = new Date().getTime();
	var SECOND = 1000;
	var MINUTE = 60 * SECOND;
	var HOUR = 60 * MINUTE;
	var DAY = 24 * HOUR;
	var latestTime = 0;

	jQuery( "#section_latestnews .HeadlineList li" ).each(function (i) {
		if ( jQuery(this).attr("time") ) {
			var time = new Number( jQuery(this).attr("time") );
			var date = new Date(time);
			if ( time && time > latestTime ) {
				latestTime = time;
			}
		}
	});

	if ( latestTime ) {
		var timestampString = '';
		var diff = now - latestTime;
		if ( diff > 0 && diff < ( 30 * MINUTE ) ) {
			var hours = Math.floor( diff / HOUR );
			var minutes = Math.floor( diff % HOUR / MINUTE );
			var seconds = Math.floor( diff % HOUR % MINUTE / SECOND );
			if ( diff < MINUTE ) {
				timestampString = ( "Last Updated " + seconds + " " + ( seconds == 1 ? "second" : "seconds" ) + " ago" );
			} else if ( diff < HOUR ) {
				timestampString = ( "Last Updated " + minutes + " " + ( minutes == 1 ? "minute" : "minutes" ) + " ago" );
			} else if ( diff < DAY ) {
				timestampString = ( "Last Updated " + hours + " " + ( hours == 1 ? "hour" : "hours" ) + " ago" );
			}
		}
		jQuery( "#section_latestnews .lastPublished" ).html( timestampString );
	}
};

var pingOmniture = function () {
	var iframeHref = '/.element/ssi/main/2.0/omniture.exclude.html';
	if ( jQuery('#omnitureIframe').size() > 0 ) {
		jQuery('#omnitureIframe').get(0).src = iframeHref;
	} else {
		// create iframe
		jQuery('body').eq(0).append( '<iframe id="omnitureIframe" width="0" height="0" align="right" style="visibility: hidden;" src="' + iframeHref + '"/>' );
	}
};
var CleanBCStockCookie = function () {
	var _domain = ".cnn.com";
	var _expiration = new Date("December 31, 2048 23:59:59");
	
	var Clean_Cookie_Value = function(string) {
		return string
			.replace( /[\n\r]/g, '' )
			.replace( /javascript:/gi, '' )
			.replace( /<\/?script\s*([^>]+)?>/gi, '' )
			.replace( /eval\s*\(.+?\)/g, '' )
			.replace( /[#&()\"'<>]/g, '' )
			.replace( /[^A-Za-z0-9+._$]/g, '' )
			.replace( /\+\++/g, '+' );
	};

	var Get_Cookie = function(name) {
		var start = document.cookie.indexOf(name+"=");
		var len = start+name.length+1;
		if ((!start) && (name != document.cookie.substring(0,name.length))) return null;
		if (start == -1) return null;
		var end = document.cookie.indexOf(";",len);
		if (end == -1) end = document.cookie.length;
		return Clean_Cookie_Value(decodeURIComponent(decodeURIComponent(document.cookie.substring(len,end))));
	}
	
	var Set_Cookie = function(name, value, expires, path, domain, secure) {
		document.cookie = name + "="
			+ encodeURIComponent(Clean_Cookie_Value(value)) +
			( (expires) ? ";expires=" + expires.toGMTString() : "") +
			( (path) ? ";path=" + path : "") + 
			( (domain) ? ";domain=" + domain : "") +
			( (secure) ? ";secure" : "");
	}
	
	var c = Get_Cookie('last5stocks');
	if(c != null) { // the cookie is present
		Set_Cookie("last5stocks", c, _expiration, "/", _domain , null);
	}

};

jQuery(document).ready(function(){

// update Latest News timestamp
	updateLatestNewsTimestamp();

// set up main page refresh
	MainPageUpdater.init();

// set up market ribbon refresh
//	MarketRibbonUpdater.init();

// set up horizontal scroll
	setupFeaturedBoxes();

// load live quotes
	runLQ();

// load CSIs
	cnnHandleCSIs();

// refresh ad after 8min
	setTimeout("cnnad_refreshAds();",60*1000*8);
	
// clean bad cookie
	CleanBCStockCookie();
	
// rollover on mostpop links
	linkBG('cnnTabsStatic');
	
});
