/*  ===========================
	VERSION INFO:
	-------------------
	Revision: v 1.4.1
	Last Updated: 2008-04-11 @ 15:35 EST
	Last Author: Jade Rauenzahn (jade.rauenzahn@foxnews.com)

	Addition: Thomas Kim's Singleton for the Markets Overview Tabs (2008-04-08)
	=========================== */
// Experiment
// $('a[id^="regionBug"]').css({position: "absolute",backgroundColor: "#fff"});
// ###########################
// Loading JavaScript Functions per template
// THIS IS THE NEW AND IMPROVED WAY OF DETECTING / ACTIVATING JS. FOOLPROOF!
// ...reverse engineering complete!!
// ###########################
function loadJS(template) {
	// NOTE: param 'template' is depreciated and not used in this new code.

	// oFoxContrAd.initAds(); // Ads

	// rounded corner classes
	// if($(".round5").length != 0) { $(".round5").corner("5px"); }
	//
	if($(".roundT5").length != 0) { $(".roundT5").corner("5px top"); }
	if($(".roundB5").length != 0) { $(".roundB5").corner("5px bottom"); }
	if($(".round7").length != 0) { $(".round7").corner("7px"); }
	if($(".roundT7").length != 0) { $(".roundT7").corner("7px top"); }
	if($(".roundB7").length != 0) { $(".roundB7").corner("7px bottom"); }
	if($(".roundTRB7").length != 0) { $(".roundTRB7").corner("7px tr br bl"); }
	if($(".round10").length != 0) { $(".round10").corner("10px"); }
	if($(".roundTLBR10").length != 0) { $(".roundTLBR10").corner("10px tl br"); }
	if($('.submitBtn').length != 0) { $('.submitBtn').corner('3px'); }
	if($('.loginSubmit').length != 0) { $('.loginSubmit').corner('5px'); }
	if($('.forgotLogin').length != 0) { $('.forgotLogin').corner('5px'); }
	//if($('.relatedContent').length != 0) { $('.relatedContent').corner('10px'); }
    
	if($('.homeSideCol .translatorBox').length != 0) { $('.homeSideCol .translatorBox').corner('7px'); }
//	if($('.latestNav li').length != 0) { $('.latestNav li').corner('5px bottom'); }
	//if($('.partnerNav li').length != 0) { $('.partnerNav li').corner('5px bottom'); }
	if($('.headerSnapshot').length != 0) { $('.headerSnapshot').corner('5px top'); }
	if($('.mostNav li').length != 0) { $('.mostNav li').corner('5px bottom'); }
	if($('.subchannel h3').length != 0) { $('.subchannel h3').corner('5px'); }
	if($(".redHeadline, .blueHeadline").length != 0) { $(".redHeadline, .blueHeadline").corner("5px"); }
	if($(".redHeadline, .round5").length != 0) { $(".redHeadline, .round5").corner("5px"); }

	// special customized corners
//	if($(".mainHeadlines").length != 0) { $(".mainHeadlines").corner("10px bl #db6700"); }
	//if($(".sideHeadlines").length != 0) { $(".sideHeadlines").corner("10px tr #700701"); }

	// dynamically detect if nav is 2nd level nest - will add class for arrow styling
	$("#primaryNav > li > ul li:has(ul)").addClass('nestNav');

	// Nav Height Changer - b/c we had to take the nav out of layout for z-indexing....
	// $("#primaryNav > li").hover( function(){ expandMenu(); }, function(){ collapseMenu(); } );

	// Search Target filtering
	$('#searchQuotes').click(function() { $('#topSearchForm').attr('action','/portal/site/fb/menuitem.53f7ee27bd7d192570efce1008a68a0c/?vgnextoid=a5886baebb158110VgnVCM100000806aa8c0RCRD') });
	$('#searchNews').click(function() { $('#topSearchForm').attr('action','/portal/site/fb/menuitem.53f7ee27bd7d192570efce1008a68a0c/?vgnextoid=211892d7c4c38110VgnVCM100000806aa8c0RCRD') });

	// translator slider
	var isExpand = false;
	if($('#transTrigger').length != 0) { $("#transTrigger > a").click(function() {
		$("#transSlide").slideToggle("fast");
		$("#transArrow").rotateLeft("180");
		if(!isExpand){
												isExpand=true;
			if(document.getElementById('fbtoolapplet')!=null)
													document.getElementById('fbtoolapplet').style.display = 'none';
								}else{
												isExpand=false;
			if(document.getElementById('fbtoolapplet')!=null)
												document.getElementById('fbtoolapplet').style.display = 'block';
								}
		toggleDetach();
		return false; });

	}

	// js column equalizations throughout site
	if($('.searchResults').length != 0) { $(".searchResults .videos, .searchResults .news").equalizeCols(); }
	if($(".subchannel").length != 0) { $(".subchannel").equalizeCols(); }

	// translator accordion
	if($('.translator').length != 0) {
		// init jCord
		jCordInit("#accord",".trigger",true,'#transIndices');

		if((typeof(pageType)!="undefined")&&(pageType== 'translator')) {
		document.getElementById("transDetach").style.visibility="hidden";
		aResizeFunction();
		$("#trigger1 a ").click(function() { jCord("#accord","#trigger1",true); setTimeout("aResizeFunction()",500);return false; });
		$("#trigger2 a ").click(function() { jCord("#accord","#trigger2",true); setTimeout("aResizeFunction()",500);return false; });
		$("#trigger3 a ").click(function() { jCord("#accord","#trigger3",true); setTimeout("aResizeFunction()",500);return false; });
		$("#trigger4 a ").click(function() { jCord("#accord","#trigger4",true); setTimeout("aResizeFunction()",500);return false; });
		$("#trigger5 a ").click(function() { jCord("#accord","#trigger5",true); setTimeout("aResizeFunction()",500);return false; });
		}
		else {
		// manually set triggers (wouldn't it be nice if jCordInit() did this? maybe one day i'll be that smart.)
		$("#trigger1 a ").click(function() { jCord("#accord","#trigger1",true); return false; });
		$("#trigger2 a ").click(function() { jCord("#accord","#trigger2",true); return false; });
		$("#trigger3 a ").click(function() { jCord("#accord","#trigger3",true); return false; });
		$("#trigger4 a ").click(function() { jCord("#accord","#trigger4",true); return false; });
		$("#trigger5 a ").click(function() { jCord("#accord","#trigger5",true); return false; });
		}

		// fill that translator's belly!
		writeIndices("#transIndices");
		stockGainers("#transGainers");
	}

	
	
	
	
	
	
	
	
	
	   
	// the market snapshot feed
	if($('.marketWindow').length != 0) {
		loadSnapshot('home');
		$("#indexRow0").mouseover(function() { changeMarker('#indexRow0'); });
		$("#indexRow1").mouseover(function() { changeMarker('#indexRow1'); });
		$("#indexRow2").mouseover(function() { changeMarker('#indexRow2'); });
		$("#indexRow3").mouseover(function() { changeMarker('#indexRow3'); });

		document.getElementById('marketmover').style.display='none';

		// market snapshot slider
		$("#triggerIndices > a").click(function() {
			document.getElementById('stockmarketindices').style.display= 'block';
			if(document.getElementById('loancenter') !=null){
				document.getElementById('loancenter').style.display='none';
			}
			document.getElementById('marketmover').style.display='none';

			jumpSlide(".marketIndices",".marketWindowContent","#triggerIndices",".sideHeadlines ul",true); return false; });
		$("#triggerMovers > a").click(function() {
			document.getElementById('stockmarketindices').style.display= 'none';
			if(document.getElementById('loancenter') !=null){
				document.getElementById('loancenter').style.display='none';
			}
			document.getElementById('marketmover').style.display='block';
												jumpSlide(".marketMovers",".marketWindowContent","#triggerMovers",".sideHeadlines ul",true); return false; });
		$("#triggerLoans > a").click(function() {
			document.getElementById('stockmarketindices').style.display= 'none';
			document.getElementById('marketmover').style.display='none';
			if(document.getElementById('loancenter') !=null){
				document.getElementById('loancenter').style.display='block';
			}
			jumpSlide(".marketLoans",".marketWindowContent","#triggerLoans",".sideHeadlines ul",true); return false; });
		$("#triggerIndices_ > a").click(function() {
			if(document.getElementById('marketmover') !=null){
				document.getElementById('marketmover').style.display='none';
			}
			if(document.getElementById('loancenter') !=null){
				document.getElementById('loancenter').style.display='none';
			}

			document.getElementById('futuremarketindices').style.display='block';
			if(document.getElementById('futureindices')){
				document.getElementById('futureindices').style.display='block';
			}

			if(document.getElementById('marketClock') !=null){
																document.getElementById('marketClock').style.visiblity='visible';
				document.getElementById('marketClock').style.position = 'relative';
				document.getElementById('marketClock').style.left = '1px';
												 }
			jumpSlide("#futuremarketindices.marketIndices",".marketWindowContent","#triggerIndices_",".sideHeadlines ul",true);

			return false; });

		$("#triggerMovers_ > a").click(function() {
			if(document.getElementById('futuremarketindices') !=null){
                                document.getElementById('futuremarketindices').style.display= 'none';
                        }

                        if(document.getElementById('futureindices') !=null){
                                document.getElementById('futureindices').style.display= 'none';
                        }

			if(document.getElementById('marketmover') !=null){
				document.getElementById('marketmover').style.display='block';
			}
			if(document.getElementById('loancenter') !=null){
				document.getElementById('loancenter').style.display='none';
			}
			if(document.getElementById('marketClock') !=null){
			 	document.getElementById('marketClock').style.visiblity='hidden';
				document.getElementById('marketClock').style.position = 'relative';
				document.getElementById('marketClock').style.left = '-100000px';
				document.getElementById('marketClock').style.height = '0px';
			 }
			jumpSlide(".marketMovers",".marketWindowContent","#triggerMovers_",".sideHeadlines ul",true);
			 return false;
			 });
	}

		$("#triggerLoans_ > a").click(function() {
			if(document.getElementById('futureindices') !=null){
				document.getElementById('futureindices').style.display= 'none';
			}
			/*
			document.getElementById('futuremarketindices').style.visiblity= 'hidden';
			document.getElementById('futuremarketindices').style.position = 'relative';
			document.getElementById('futuremarketindices').style.left = '-100000px';
			*/

			if(document.getElementById('marketClock') !=null){
				document.getElementById('marketClock').style.visiblity='hidden';
				document.getElementById('marketClock').style.position = 'relative';
				document.getElementById('marketClock').style.left = '-100000px';
				document.getElementById('marketClock').style.height = '0px';
			}
			document.getElementById('marketmover').style.display='none';
			if(document.getElementById('loancenter') !=null){
				document.getElementById('loancenter').style.display='block';
			}
			jumpSlide(".marketLoans",".marketWindowContent","#triggerLoans_",".sideHeadlines ul",true);
			return false;
			});

	// slider - latest news
	if($('.boxLatest').length != 0) {
		$("#triggerNews a").click(function() { jumpSlide(".slideNews","#latestSlideBox","#triggerNews",".latestNav"); return false; });
		$("#triggerRead a").click(function() { jumpSlide(".slideRead","#latestSlideBox","#triggerRead",".latestNav"); return false; });
		$("#triggerEmailed a").click(function() { jumpSlide(".slideEmailed","#latestSlideBox","#triggerEmailed",".latestNav"); return false; });
	}

	// slider - partners
	if($('#partnerSlideBox').length != 0) {
		$("#triggerSmartmoney > a").click(function() { jumpSlide(".slideSmartmoney","#partnerSlideBox","#triggerSmartmoney",".partnerNav"); return false; });
		$("#triggerForbes > a").click(function() { jumpSlide(".slideForbes","#partnerSlideBox","#triggerForbes",".partnerNav"); return false; });
		$("#triggerMinyanville > a").click(function() { jumpSlide(".slideMinyanville","#partnerSlideBox","#triggerMinyanville",".partnerNav"); return false; });
	}
		$("#triggerBankrate > a").click(function() { jumpSlide(".slideBankrate","#partnerSlideBox","#triggerBankrate",".partnerNav"); return false; });

	// sidebar Market Snapshot
	if($('.sideSnapshot').length != 0) {
		loadSnapshot('internal');
		$("#triggerIndices > a").click(function() { jumpSlide("#snapshotIndex",".snapshotWindow","#triggerIndices",".headerSnapshot > ul",true); return false; });
		$("#triggerMovers > a").click(function() { jumpSlide("#snapshotMovers",".snapshotWindow","#triggerMovers",".headerSnapshot > ul",true); return false; });
	}

	// slider - latest news
	if($('.sideMost').length != 0) {
		$("#triggerRead > a").click(function() { jumpSlide(".slideRead","#mostSlideBox","#triggerRead",".mostNav"); return false; });
		$("#triggerEmailed > a").click(function() { jumpSlide(".slideEmailed","#mostSlideBox","#triggerEmailed",".mostNav"); return false; });
		$("#triggerBlogs > a").click(function() { jumpSlide(".slideBlogs","#mostSlideBox","#triggerBlogs",".mostNav"); return false; });
	}

	// bank rate slider
	if($('.bankRates').length != 0) {
		$("#triggerMortgages > a").click(function() { jumpSlide("#slideMortgages",".bankRatesWindow","#triggerMortgages",".bankRates ul"); return false; });
		$("#triggerHomeEq > a").click(function() { jumpSlide("#slideHomeEq",".bankRatesWindow","#triggerHomeEq",".bankRates ul"); return false; });
		$("#triggerCDRates > a").click(function() { jumpSlide("#slideCDRates",".bankRatesWindow","#triggerCDRates",".bankRates ul"); return false; });
	}


	// Singleton for Markets Overview Tabs
	// Author: Thomas Kim
	// Date: 4/8/2008
	if($('.marketsWindow').length != 0) {
		var MarketOverviewTabs = (function() {
			/*private members. Note: Protect the integrity of the active tab's index.. with your life!*/
			var triggerIndex = 0;
			var blockBase = ".marketsSlideBox";   //div blocks that are toggled by tabs
			var triggerBase = ".marketsNav li";   //the list items / tabs
			function hideTab() {
				$(blockBase)[triggerIndex].className="marketsSlideBox hidden";
				$(triggerBase)[triggerIndex].className="";
				return this;
			}
			function setTab(tab) {
				triggerIndex = tab.parentNode.getAttribute("id").split("b")[1];
				$(blockBase)[triggerIndex].className="marketsSlideBox shown";
				$(triggerBase)[triggerIndex].className="active";
			}
			//constructor
			$(blockBase)[0].className="marketsSlideBox shown";
			for(var i=1; i<$(blockBase).length; i++) {
				$(blockBase)[i].className="marketsSlideBox hidden";
			}
			/*public members: Use these two public methods to change tabs*/
			return {
				init: function() {
					$(blockBase)[0].className="marketsSlideBox shown";
					for(var i=1; i<$(blockBase).length; i++) {
						$(blockBase)[i].className="marketsSlideBox hidden";
					}
				},
				tabClick: function(tab) {
					hideTab();
					setTab(tab);
					return this;    //enable chainability
				}
			};
		})();
		$(".marketsNav a").click(function() {MarketOverviewTabs.tabClick(this);return false;});
	}

	if($('.emailStoryBox').length != 0) {
		$('#emailStory').click(function() { $('.emailStoryBox').toggleFade({ speedIn : "normal"}); return false; });
		$('#emailStoryClose').click(function() { $('.emailStoryBox').fadeOut(); return false; });
	}

	if($('#quigo_story_right').length != 0) {
		if($('.authInfo > h6').html().toLowerCase() != "marketwatch pulse" && $('#articleCont').html().length > 1000) {
			$('#quigo_story_right').each(function(n){ document.getElementById('storyAd1').innerHTML = this.innerHTML; this.innerHTML = '&nbsp;'; });
			$('#storyAd1').css('display','block');
		}else{
			if ($('.storyAdPlace').length != 0 && $('.storyAdPlace').html().length < 187)
				$('.storyAdPlace').remove(); 
		}
	}else{
		if ($('.storyAdPlace').length != 0 && $('.storyAdPlace').html().length < 187)
			$('.storyAdPlace').remove(); 
	}
	// Video Player
	if($("#videoPlayerModule").length != 0 && vidObj) {
		renderVideoPlayer(vidObj.type, vidObj.w, vidObj.h, vidObj.playlistId, vidObj.videoId);
	}

	// Live Quotes
	// excluded comtex
	if($("#articleCont").length != 0){
		$("#articleCont").html($("#articleCont").html().replace(/\(<a href="http:\/\/quote.foxbusiness.com\/symbol\/([A-Z]+)\/snapshot" class="story_quote">([A-Z]+)<\/a>\)/g, '(<a href="javascript:stockSearch\(\'$1\'\);">$1</a>\)'));
	}
}


// ###############################
// Core Site Functionality
// ###############################

// menu height expand / collapse
function expandMenu() {
	$('#primaryNav').height(500);
}

function collapseMenu() {
	$('#primaryNav').height(40);
}


// #############################
// dynamic content filling for FOX
// Translator.... (fun accessibility crutch!)
var xmlDoc=null;
function loadXML(xmlFile,cb) {
	if (window.ActiveXObject) {
		xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
		xmlDoc.async=false;
		xmlDoc.onreadystatechange=function(){if(xmlDoc.readyState==4){eval(cb+'()');}};
		xmlDoc.load(xmlFile);
	} else if (document.implementation && document.implementation.createDocument) {
		xmlDoc = document.implementation.createDocument("","",null);
		xmlDoc.async=false;
		xmlDoc.load(xmlFile);
		eval(cb+'()');
	}
}

// #############################
// FOX Translator Aggregation

// resize window for the detached translator
function aResizeFunction()
{
	var winHeight;
	var winWidth;
	if (window.innerHeight && window.scrollMaxY) {// Firefox
		winHeight = window.innerHeight + window.scrollMaxY;
		//winWidth = window.innerWidth + window.scrollMaxX;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		winHeight = document.body.scrollHeight;
		//winWidth = document.body.scrollWidth;
	} else { // works in Explorer 6 Strict, Mozilla (not FF) and Safari
		winHeight = document.body.offsetHeight;
		//winWidth = document.body.offsetWidth;
		}
	window.resizeTo(306,winHeight+40);
}

// quote utility function
function quoteLink(s,n) {
	var name = n ? n : s, vOnclick="";
	var quoteUrl = "/research.html?searchString=";
	if(pageType=='translator'){vOnclick = 'onclick="window.opener.location.href=this.href;return false;"';}

	if("$I.FOX50" ==s){
		return '<a href="/markets/market-overview.html?marketview=foxgrades" ' + vOnclick+'>' + name + '</a>';
	}
	return '<a href="' + quoteUrl + s.replace('I.','') + '"' +vOnclick+'>' + name + '</a>';
}

// indices
function writeIndices(target) {
	var rstyle = '';
	var fox50 = 0;
	var output = '<table>';
	output += '<tr><th>Name</th><th>Price</th><th colspan="2">Change</th><th>%CHG</th><th>YTD</th></tr>';
	for(idxs=0;idxs<indexdata["name"].length;idxs++){
		// determine if value is up or down for record
		if(indexdata["name"][idxs]=='FOX 50') {
			fox50++;
			if(fox50>1) break;
		}
		if(indexdata["change"][idxs].indexOf("+") !=-1) {
			var marketMove = '<img src="/images/arrows_icons/icon_arrow_up.gif" alt="Positive Change" />';
		} else if(indexdata["change"][idxs].indexOf("-") !=-1 ) {
			var marketMove = '<img src="/images/arrows_icons/icon_arrow_dn.gif" alt="Negative Change" />';
		} else {
			var marketMove = '';
		}
		rstyle = idxs%2==0 ? ' class="odd"' : '';
		output += '<tr'+rstyle+'><td>'+quoteLink(indexdata["symbol"][idxs],indexdata["name"][idxs])+'</td><td>'+indexdata["price"][idxs]+'</td><td>'+indexdata["change"][idxs]+'</td><td>'+marketMove+'</td><td>'+indexdata["pctchange"][idxs]+'</td><td>';
		//output += indexdata["yearchange"][idxs] ? indexdata["yearchange"][idxs] : '-';
		output += '</td></tr>';
	}
	output += '</table>';
	if (target=='#transIndices') {
	  $(target).show();
	}
	$(target).html(output);
}

// stock gainers
function stockGainers(target) {
	var rstyle = '';
	var output = '<table>';
	output += '<tr><th>Symbol</th><th>Price</th><th>Change</th><th>%CHG</th><th>Vol</th></tr>';
	for(mkg=0;mkg<5;mkg++){
		rstyle = mkg%2==0?' class="alt"':'';
		output += ('<tr'+rstyle+'><td>'+quoteLink(marketgainers["symbol"][mkg])+'</td><td>'+marketgainers["lastprice"][mkg]+'</td><td>'+marketgainers["netchange"][mkg]+'</td><td>'+marketgainers["percentchange"][mkg]+'</td><td>'+marketgainers["volume"][mkg]+'</td></tr>');
	}
	output += '</table>';
	output += '<p><a href="#" onclick="changeGainers(\'#transGainers\'); return false;">See Next 5</a></p>';
	$(target).html(output);
}

function changeGainers(target) {
	var rstyle = '';
	var output = '<table>';
	output += '<tr><th>Symbol</th><th>Price</th><th>Change</th><th>%CHG</th><th>Vol</th></tr>';
	for(mkg=5;mkg<10;mkg++){
		rstyle = mkg%2!=0?' class="alt"':'';
		output += ('<tr'+rstyle+'><td>'+quoteLink(marketgainers["symbol"][mkg])+'</td><td>'+marketgainers["lastprice"][mkg]+'</td><td>'+marketgainers["netchange"][mkg]+'</td><td>'+marketgainers["percentchange"][mkg]+'</td><td>'+marketgainers["volume"][mkg]+'</td></tr>');
	}
	output += '</table>';
	output += '<p><a href="#" onclick="stockGainers(\'#transGainers\'); return false;">See Previous 5</a></p>';
	$(target).html(output);

}

// #############################
// Market Snapshot Feed Reading
function loadSnapshot(pageType) {
/* following commented-out code has been placed into homepage.js

	if(pageType == 'home') {
		///////////
		// placing indices
		var indicesTargets = $('.marketIndices > table tr');
		for(var i=0; i<4; i++) {
			$(indicesTargets[i+1]).attr('id','indexRow'+i);

			// place values: indices
			$('#indexRow'+i+' > th').html(quoteLink(indexdata.symbol[i],indexdata.name[i]));
			$('#indexRow'+i+' > .marketLast').html(indexdata.price[i]);
			$('#indexRow'+i+' > .marketPct').html(indexdata.pctchange[i]);

			// changing color if pos / neg change
			if(indexdata.pctchange[i] > 0) {
				// positive change
				$('#indexRow'+i).removeClass('noChange').addClass('posChange');
			} else if(indexdata.pctchange[i] < 0) {
				// negative change
				$('#indexRow'+i).removeClass('noChange').addClass('negChange');
			}
		}

// load chart for def (DJIA)
		$('#marketChart').attr('src','http://www.foxbusiness.idmanagedsolutions.com/charts/indices/quote.chart?ID_NOTATION=324977&HEIGHT=85&WIDTH=253');
		///////////
		// placing movers
		var moversTargets = $('.marketMovers > table tr');
		for(var z=0; z<10;z++) {
			// place values
			$(moversTargets[z+1]).html('<td>'+quoteLink(marketmovers.symbol[z])+'</td><td>'+marketmovers.lastprice[z]+'</td><td>'+marketmovers.netchange[z]+'</td><td>'+marketmovers.volume[z]+'</td>');
		}

	} else */
	if(pageType == 'internal') {
		//var indicesTargets = $('.snapshotSlide > div');
		var indicesLinks = $('.snapshotSlide > a');
		for(var i=0; i<4; i++) {
			//$(indicesTargets[i]).attr('id','indexRow'+i);
			$(indicesLinks[i]).attr('id','indexLink'+i);
			$(indicesLinks[i]).attr('href','/research.html?searchString='+indexdata.symbol[i].replace('I.',''));

			// place values: indices
			$('#indexLink'+i+ ' > div > h5').html(quoteLink(indexdata.symbol[i],indexdata.name[i]));
			$('#indexLink'+i+ ' > div > .marketChange').html(indexdata.change[i]);
			$('#indexLink'+i+ ' > div > .marketValue').html(indexdata.price[i]);

			// changing class if pos / neg change
			if(indexdata.change[i] > 0) {
				// positive change
				$('#indexLink'+i+' > div').removeClass('noChange').addClass('posChange');
			} else if(indexdata.change[i] < 0) {
				// negative change
				$('#indexLink'+i+' > div').removeClass('noChange').addClass('negChange');
			}
		}

		///////////
		// placing movers
		var moversTargets = $('.snapshotSlide > table tr');
		for(var z=0; z<5;z++) {
			// place values
			$(moversTargets[z+1]).html('<td>'+quoteLink(marketmovers.symbol[z])+'</td><td>'+marketmovers.lastprice[z]+'</td><td>'+marketmovers.netchange[z]+'</td><td>'+marketmovers.volume[z]+'</td>');
		}
	}
}
function changeMarker(row) {
	// find currently active td, replace with empty
	$('.activeRow .indicator').html('');
	$('.activeRow').removeClass('activeRow');

	// put new one in
	$(row+' > .indicator').html('<img src="/images/arrows_icons/arrow_marketPointer.gif" alt="Hilighted" />');
	$(row).addClass('activeRow');

	// get & place new chart (animated!)
	var ticker = $(row+' > th').parent().attr('id');
	var overRow = ticker.substring(8);
	if(indexdata !=null && "$i.dji" ==indexdata.symbol[overRow]){
		$('#marketChart').attr('src','http://www.foxbusiness.idmanagedsolutions.com/charts/indices/quote.chart?ID_NOTATION=324977&HEIGHT=85&WIDTH=253');
	}else if(indexdata !=null && "$I.COMPX" ==indexdata.symbol[overRow]){ 
	        $('#marketChart').attr('src','http://www.foxbusiness.idmanagedsolutions.com/charts/indices/quote.chart?ID_NOTATION=324985&HEIGHT=85&WIDTH=253');
        }else if(indexdata !=null && "$INX" ==indexdata.symbol[overRow]){
                $('#marketChart').attr('src','http://www.foxbusiness.idmanagedsolutions.com/charts/indices/quote.chart?ID_NOTATION=4359526&HEIGHT=85&WIDTH=253');
        }else if(indexdata !=null && ("$I.FOX50" ==indexdata.symbol[overRow] || "FOX50" ==indexdata.symbol[overRow])){
	        $('#marketChart').attr('src','http://www.foxbusiness.idmanagedsolutions.com/charts/indices/quote.chart?ID_NOTATION=19682584&HEIGHT=85&WIDTH=253');
        } 
}

function changeMovers(offset) {
	///////////
	// placing movers
	var moversTargets = $('.snapshotSlide > table tr');
	for(var z=0; z<5;z++) {
		// place values
		$(moversTargets[z+1]).html('<td>'+quoteLink(marketmovers.symbol[z+offset])+'</td><td>'+marketmovers.lastprice[z+offset]+'</td><td>'+marketmovers.netchange[z+offset]+'</td><td>'+marketmovers.volume[z+offset]+'</td>');

		// toggle trigger on offset
		if(offset == 5) {
			$('#moversLink').html('<a href="#" onclick="changeMovers(0); return false;">See Previous 5 &gt;</a>');
		} else {
			$('#moversLink').html('<a href="#" onclick="changeMovers(5); return false;">See Next 5 &gt;</a>');
		}
	}
}

function toggleDetach() {
	if($('#transDetach').length != 0) {
		$('#transDetach').toggleFade({ speedIn : "normal"});
	}
}

function renderVideoPlayer(id, w, h, playlist, videoId) {
	var mp = new MavenPlayer(id);
//	mp.setParameter('checkSystemId', 'videoSystemRequirements');
	mp.setParameter('playerWidth', w);
	mp.setParameter('playerHeight', h);
	mp.setVariable("fox_dartSite", 'fbnvideo');
	if(oFoxContrAd.getSValues() != undefined){
		mp.setVariable("fox_dartZone",oFoxContrAd.maven.dartSiteZone());
		//mp.setVariable("fox_baseKeyValue",oFoxContrAd.maven.baseKeyValue());
		mp.setVariable("revSciSegs", oFoxContrAd.maven.revenueScience());
	}
	mp.setParameter("backgroundColor", "#e1e1e1");
	mp.setVariable("maven_overridePlayerName","FOX BUSINESS VIDEO");
	mp.setVariable('referralPlaylistId', getQueryParamValue("referralPlaylistId"));
	mp.setVariable('referralParentPlaylistId', getQueryParamValue("referralParentPlaylistId"));
	mp.setWMode("transparent"); 
	if(videoId){
		mp.setVariable('referralObject', videoId);
	}else{	
		mp.setVariable('referralObject', getQueryParamValue("referralObject"));
	}
	if(getQueryParamValue("wmode") == "transparent") mp.setAllowFullScreen(false);

	//mp.setVariable("fox_dartSite", site_name);
	//mp.setVariable("fox_dartZone",s1);
	//mp.setVariable("fox_baseKeyValue","s1="+s1+";s2=;s3=;kw=;ptype="+ptype+";pageid=;col=;url=;age=;gend=;occ=;ind=;inc=;cosz=;pos=top;fbn=ad;test=;!c=;");

	if(playlist) mp.setVariable('overridePlaylistId', playlist);

	mp.write('videoPlayerModule');
}

function popSmallPlayer(id) {
	var newWin = window.open("/html/videoEmbedPopup.html?videoId=" + id, "videoSmallPlayer", "width=315,height=420");
	newWin.focus();
}

function popLargePlayer(id) {
	var newWin = window.open("/html/videoPopup.html?videoId=" + id, "videoLargePlayer", "width=750,height=600");
	newWin.focus();
} 

// legacy function used by smartmoney iframes
function showPopup(url) {
	if ((url.indexOf("external_login_smartmoney") != -1) ) {
		window.open(url.replace('http:','https:'), "pop", "width=750,height=500");
	} else if (url.indexOf("/foxbusiness/") != -1) {
		window.open(url, "pop", "width=600,height=500");
	} else if (url.indexOf("foxportfolio/") != -1) {
		window.open(url, "pop", "width=750,height=500");
	} else {
		window.open(url, "pop", "", "");
	}
}

function videoPlayer(vidFile,headline,format,hd,category,relID,channel,duration) {
	var category = category.replace(/'/g, "&#39;");
	var channel = typeof(channel) == "undefined" ? "" : channel.replace(/'/g, "&#39;");
	var duration = typeof(duration) == "undefined" ? 180 : duration;
	if(!hd || hd == "") {hd = "acc";}
	if(format == "Campaign_Carl" || format == "5_-_You_Decide") hd = "elec";
	if(vidUrlFile == "") {vidUrlFile = "resize05.html";}
//	var h = (screen.width > 1000 && BrowserDetect.browser != "Opera") ? 655 : 510;
	sLiveStream = vidFile.split("_::_");
	var h = (sLiveStream[0]=="liveSiteStream" && sLiveStream[2]=='chat') ? 700 : 325;
	var winState = (screen.width > 1000 && BrowserDetect.browser != "Opera") ? "exp" : "col";
	var vidUrl = "http://www.foxnews.com"+"/video2/"+vidUrlFile+"?"+vidFile+"&"+escape(format)+"&"+escape(headline)+"&"+escape(hd)+"&"+escape(category)+"&"+relID+"&"+escape(channel)+"&"+duration+"&"+winState;
	var winl = ((screen.width - 700) / 2) - 5;
	winprops = 'height='+h+',width=700,top=5,left='+winl;
	fncVidWin = window.open(vidUrl, 'fncVidPlayer', winprops);
	if (fncVidWin) {fncVidWin.focus();}
}

function siteStreamPlayer(n){
	if(typeof(n)=="undefined"){
			liveFile = 'liveSiteStream';
		} else{
			liveFile = 'liveSiteStream_::_'+n;//+'_::_'+sChat;
		}
		videoPlayer(liveFile,'Live%20Stream','Live_Site_Stream','acc','Live%20Stream','-1','News',180);
}

function siteStreamFlashPlayer(n) {
	var s = typeof(n) == "undefined" ? 1 : n;
	var w = 850;
	var h = 506;
	var winl = (screen.width-w)/2;
	var wint = (screen.height-h)/2;
	var settings  ='height='+h+',';
	settings +='width='+w+',';
	settings +='top='+wint+',';
	settings +='left='+winl+',';
	settings +='toolbar=no,';
	settings +='location=no,';
	settings +='scrollbars=no,';
	settings +='status=no,';
	settings +='resizable=no,';
	settings +='fullscreen=no';
	var win = window.open('http://interactive.foxbusiness.com/livestream/live.html?chanId='+s+'&openAIR=false','livePlayer',settings);
	win.focus();
}


/**
 * Adding queryString JavaScript Object to access query string values
 */
var queryString = {
	empty:function(){
		return window.location.search == "" ? true : false;
	},
	get:function(){
		return this.empty() ? null : window.location.search.substring(1);
	},
	param:{
		exists:function(p){
			return (!queryString.empty() && queryString.get().toLowerCase().indexOf(p.toLowerCase()+'=') > -1) ? true : false;
		},
		get:function(p){
			var value = null;
			if(this.exists(p)){
				var s = queryString.get().split('&');
				for(var i=0;i<s.length;i++){
					var e = s[i].split('=');
					if(e[0].toLowerCase() == p.toLowerCase() && e[1]) value = e[1];
				}
			}
			return value;
		}
	}
}

function parseLoomia(data) {
	var mrContent="";
	jQuery.each(data.recs, function(i,item){
		mrContent +=  '<li><a href="'+ item.link+'">' + item.title + '<a/></li>';
		if ( i == 10 ) return false;
	});

	jQuery('#link_list_most_read').html(mrContent);

}

function getSearch(){
	var qVars = window.location.search.substr(1).split('&');
	var s = '';
	for( var i=0; i < qVars.length; i++ ) 
	{
	    var q = qVars[i].split('=')[0].toLowerCase();
	    
	    if( q == "searchval" || q == "searchstring" )
	    {
	        if((qVars[i].split('=')[1]!="")&&(qVars[i].split('=')[1]!=null)) 
	        {
	            s = qVars[i].split('=')[1];
	            //console.log("get Search is : " + s);
	        }
	    }
	    return s;
	}
	return s; 
	}
	function latestNewsSearchResults(){  
	    //console.log("Latest News Search");
	    var s = getSearch();
	   // console.log("s is " + s);
	    $.ajax({
	            type: "GET",
	            url: "http://www.foxbusiness.com/search-results/rss",
	            data: ({q:s}),
	            dataType:"text",
	            success: function(data) {
	            //console.log("data is" + data);
	            var doc = ParseXML(data);
	           // console.log("doc " + doc);
	            if ((doc != null)&&(doc != "")) 
	            {
	                $('#resultsBox').html(doc);
	            }
	            else{
	                $('#resultsBox').html("No news has been returned from this search.");
	            }
	    },
	        error:function(XMLHttpRequest, message, errorThrown) {
	              //  console.log("Error", XMLHttpRequest, message, errorThrown);
	        $('#resultsBox').html('Error'+ '<br>' + message);
	        }
	    });
	};

	function ParseXML(text){
	    text=jQuery.trim(text);
	    if ( $.browser.msie ) {
	        xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
	        xmlDoc.async="false";
	        xmlDoc.loadXML(text);
	        return xmlDoc;
	    }else{
	        parser=new DOMParser();
	        xmlDoc=parser.parseFromString(text,"text/xml");  
	        return xmlDoc;
	    }
	} 


