//biz section

var csDomain = 'http://comstock.foxnews.com';
var csPort = '80';
var smDomain = 'http://smartmoney.foxbusiness.com/';

function indexData (name, today, change, percentChange, percentWeekChange, percentYearChange)  { 
	this.name = name; 
	this.today = today; 
	this.change = change; 
	this.percentChange = percentChange;   
	this.percentWeekChange = percentWeekChange; 
	this.percentYearChage = percentYearChange; 
}

var content;
function loadRootBizScripts() {
	var i;
	var sc;
	var srcs = [ csDomain+':'+csPort+'/javascript/general.js?sSyms=TNX.X.OPI&arName=conInd&'+ranNum,
		 smDomain+'foxbusiness/js/fullfeed.js?u='+ranNum
		 ];
	
	for (i=0;i<srcs.length;i++) {
		sc = document.createElement("script");
		sc.setAttribute("src", srcs[i]);
		sc.setAttribute("type", "text/javascript");
		document.getElementsByTagName("head")[0].appendChild(sc);
	}
}

function msgBizData(s) {
	if (s == 'NaN' || s == '-') {
		var finalInt = '-';
	} else if (s == 'NA') {
		var finalInt = s;
	} else {
		var s = (""+s).replace(/,/g,"");
		var s = (""+s).replace(/\s/g,"");
		var s = (""+s).replace(/\+/g,"");
		var s = (Math.round(parseFloat(s)*100)/100).toString();
		if (s.indexOf('.') == "-1") var s = s+".00";
		if (s.charAt(s.length-2) == '.') var s = s+'0';
		if (s.charAt(0) == '.' || (s.charAt(1) == '.' && s.charAt(0) == '-')) {
			var s = s.charAt(0) == '-' ? "-0"+s.substring(1,(s.length)) : "0"+s;
		}
		var integer = s.split('.')[0];
		var decimal = s.split('.')[1];
		var newInt = "";
		var counter = 0;
		for (var i=integer.length; i>0; i--) {
			counter++;
			newInt = (counter % 3 == 0 && i > 1 && integer.charAt(i - 2) != '-') ? "," + integer.charAt(i - 1) + newInt : integer.charAt(i - 1) + newInt;
		}
		var finalInt = newInt +"."+decimal;
	}
	return finalInt;
}

function writeIndices() {
	var iNames = new Array(
		'DJIA',
		'NASDAQ',
		'S&amp;P 500');
	
	var i = '<table style="margin:0;padding:0;border:0;font:bold .75em Verdana;">';
	var price, change, perChange, arrow, iChange;
	var bgcolor = '#FFF';
	for (var c=0;c<iNames.length;c++) {
		i += '<tr>';
		    price = c < 3 ? msgBizData(indexdata["price"][c])    :msgBizData(conInd[0].today);
		   change = c < 3 ? msgBizData(indexdata["change"][c])   :msgBizData(conInd[0].change);
		perChange = c < 3 ? msgBizData(indexdata["pctchange"][c]):msgBizData(conInd[0].percentChange);
		if (c % 2 == 0) {
			//bgcolor = '#CCC';
			arrow = change.indexOf("-")==-1?'arrow_up_gray.gif':'arrow_down_gray.gif';
		} else {
			//bgcolor = '#FFF';
			arrow = change.indexOf("-")==-1?'arrow_up.gif':'arrow_down.gif';
		}
		iChange = change.replace(/\+/g, '');
		i += '<td style="width:24%;background:'+bgcolor+';">'+iNames[c]+'</td>';
		i += '<td style="width:24%;text-align:right;">'+price+'</td>';
		i += '<td style="width:23%;text-align:right;">'+iChange+'</td>';
		i += '<td style="width:8%;text-align:center;"><img src="/i/'+arrow+'" width="8" height="8" alt="" /></td>';
		i += '<td style="width:21%;text-align:right;">'+perChange+'%</td>';
		i += '</tr>';
	}
	i += '</table>';
	return i;
}
	
function writeIndices_hp() {
	var iNames = new Array(
		'DJIA',
		'NASDAQ',
		'S&amp;P 500');

	// parallel array mapped to the list of stock symbols above.	
	var iStockLink = new Array(
		'http://www.foxbusiness.com/research.html?referrer=fn&searchString=$i:dji&',
		'http://www.foxbusiness.com/research.html?referrer=fn&searchString=$i:comp',
		'http://www.foxbusiness.com/research.html?referrer=fn&searchString=$INX'		
	);
	
	var price, change, perChange, arrow, iChange;
	var bgcolor = '#FFF';
		
	var i = '<div class="nsponb">';
	for (var c=0;c<iNames.length;c++) {
		price = c < 3 ? msgBizData(indexdata["price"][c])		:msgBizData(conInd[0].today);
		change = c < 3 ? msgBizData(indexdata["change"][c])		:msgBizData(conInd[0].change);
		perChange = c < 3 ? msgBizData(indexdata["pctchange"][c]):msgBizData(conInd[0].percentChange);	
		
		iChange = change.replace(/\+/g, '');
		
		var classStyle = "positive";
		var directionArrow = "market-up-arrow.jpg";
		if ( iChange < 0 ) {		
			classStyle = "negative";
			directionArrow = "market-down-arrow.jpg";
		}

		i += '<div id="biz_indice">';
		i += '	<div class="arrows"><img width="44" height="45" border="0" alt="" src="/i/new/' + directionArrow + '"/></div>';
		  i += '	<span class="titles"><a href="' + iStockLink[c] + '">'+iNames[c]+'</a><br/><span class="previous"><a href="' + iStockLink[c] + '">'+price+'</a></span></span>';
		 i += '	<span class="' + classStyle + '"><a href="' + iStockLink[c] + '">'+iChange+'</a><br/><span class="percentage"><a href="' + iStockLink[c] + '">'+perChange+'%</a></span></span>';
		i += '</div>';
	}
	i += '</div>';
	return i;
}

function showSMHeads(){
	var maxLength = 5;
	var o = '';
	for(i=0;i<maxLength;i++){
		if(content[i]["title"] != "" && content[i]["title"].charAt(0) != "/") {
			o += '<li><a href="'+content[i]["link"]+'" onclick="window.open(this.href);return false;">'+content[i]["title"]+'</a></li>';
		} else {
			maxLength++;
		}
	}
	return o;
}

//behavior rules

var rr = {
	tabs : function(t,cls){

			var tabs_el = getParent(getParent(t));
			var tabs = tabs_el.id;
			var headerTabs = tabs_el.getElementsByTagName('LI');
			var id = t.id.substring(5); // if t is the anchor tag, then t's parent is the LI tag, which contains the relevant ID we want
			
			Element.show(cls+id);
			for(var cc=1;cc<=headerTabs.length;cc++)
			{
			  if(cc!=id)
	  		   Element.hide(cls+cc);
			}
			
			
			//expandContent2(id);
	
			for ( var i=1; i <= headerTabs.length; i++) {
				headerTabs[i-1].className= (i == id) ? "current" :"";
			}
			
	
			/*
			Element.show(cls+id);		
			while (e) {
				if (e!=id) {
					Element.hide(cls+e);
				}
				e--;
			}
			expandContent(t,tabs);
			
			*/
			return false;
	},
	poll_button : function(t){
			var ans = getParent(getParent(t)).getElementsByTagName('input');
			var i = ans.length;
			var x = false;
			while (i-->0) {
				if (ans[i].name=='answer'&&ans[i].checked==true) { x=true; }
			}
			if (!x) {
				alert("You must vote to submit this poll.");
			} else {
				var pp=window.open('about:blank','pp','width=550,height=400,top=100,left=100');
				getParent(getParent(t)).submit();
				//pp.focus();
				setTimeout(function(){pp.focus();},2000);
 window.location='/yourworld/index.html';
			}
			return false;
	},
	poll_view : function(t){
			var p = t.title.split('_')[0];
			var f = t.title.split('_')[1];
			var pp = pop('http://www2.foxnews.com/polls/poll_results/bg_results_'+f+'.jpg__basic_'+p+'.htm','pp',550,400,'no','no');
			pp.focus();
			return false;
	}
};
//root tabs
function root_tabs(t,cls,parent_id) {
  	//var tabs_el = parent_id;
	var tabs = $(parent_id);
	var headerTabs = tabs.getElementsByTagName('LI');
	var id = t.id.substring(5); // if t is the anchor tag, then t's parent is the LI tag, which contains the relevant ID we want
	
	if (tabs.id==='tabs_2' && id==4) { // live events on homepage - add this in the root_tabs function on this specified location
		liveEventsFeed.init();
	}

	Element.show(cls+id);
	for(var cc=1;cc<=headerTabs.length;cc++)
	{
	  if(cc!=id)
	   Element.hide(cls+cc);
	}
	for ( var i=1; i <= headerTabs.length; i++) {
	    headerTabs[i-1].className= (i == id) ? "current" :"";
	}
	return false;
}
var onload_root = function() {

	els = $A(document.getElementsByClassName('tabs','root'));
	els.each (function(el) {
		lnx = $A(el.getElementsByTagName("A"));
		lnx.each (function(ln) {
			ln.setAttribute('href', ln.getAttribute('href')+"?r="+ranNum);
		});
	});
};


function refresh() {
setTimeout("window.location.reload(true)",600000);
}
Event.observe(window,'load',function(){onload_root();renderBiz();},false);

// Follow Us Mouse Overs. Updated 10/07/2009
// Dependencies: prototype
Event.observe(window, 'load', function() {
	var observeMOvers = {
		obj: new Object(),
		ctr: 0,
		start: function() {
			this.observe();
		}, 
		observe: function() {
			var followUsLI = $$('.follow-us ul li');
			followUsLI = (followUsLI==undefined)?null:followUsLI;
			var thisObj = this;
			if (followUsLI.length>0) {
				for (x=0; x < followUsLI.length; x++) {
					var li = $(followUsLI[x]);
					li.onmouseover = function() { (this.getElementsByTagName('div'))[0].style.display='inline'; }
					li.onmouseout = function() { (this.getElementsByTagName('div'))[0].style.display='none'; }
				}
				clearTimeout(this.obj);
			} else {
				var c = this.ctr; c = c + 1; this.ctr = c;
				if (c>100) {
					clearTimeout(this.obj);
				} else { this.obj = setTimeout(function() { thisObj.observe(); }, 100); }
			}
		}
	};
	observeMOvers.start();
}); /* End Follow Us Mouse Overs */ 


// V5 Home Page Live Events Tab - Updated: 02/05/2010
// Dependencies: jQuery
// jQuery wrapped
(function($){
// carousel 
window.triggerCarousel = function(focusItem) {
	focusItem = focusItem || 1; // default to focus on first item if not defined
	
	$("#root_tab_content_4 ul:first").each(function(i) {
		var carousel = this;
		var config = {
			auto: { set:false,speed:3000 }, // auto scroll
			slide: 'horizontal', // horizontal or vertical
			scroll: 1, // number of items to scroll per event
			show: 1, // items shown
			speed: "slow", // scroll speed
			rotate: false, // rotate back to star if end
			focus: { item:focusItem,animate:false }, // where to focus on load
			eventCallback: function(obj) { // callback function for all carousel events

				$(".controls",carousel).each(function(){
					$(".prev",this).each(function(){
						if (obj.batch.current===1) {
							$(this).addClass("inactive-prev");
						} else {
							$(this).removeClass("inactive-prev");
						}
					});
					$(".next",this).each(function(){
						if (obj.batch.current===obj.batch.max) {
							$(this).addClass("inactive-next");
						} else {
							$(this).removeClass("inactive-next");
						}
					});
				});

			},
			controlsCallback: function(control) { // callback to set up controls

				$(".controls",carousel).each(function(){
					$(".prev",this).click(function(){ // previous link
						control.stopAutoScroll();
						control.slide('prev');
						return false;
					});
					$(".next",this).click(function(){ // next link
						control.stopAutoScroll();
						control.slide('next');
						return false;
					});
				});

			}
		};

		$(this).jfoxCarousel(config);
	});

};

})(jQuery);

// V5 Home Page Live Events Parser - Updated: 02/09/2010
// Dependencies: jQuery
// jQuery wrapped
(function($){

function LiveEventsFeed() {
	this.contentId = "root_tab_content_4"; // content holder id
	this.feed = {
		parsed: false,
		source: 'http://tools.foxnews.com/schedule/${channel}/',
		holder: false, // content holder object
		text: {
			//noshows: "There is no '${channelTxt}' airing today.",
			//endshow: "There is no '${channelTxt}' airing today."
			noshows: "There is no 'Strategy Room' airing today.",
			endshow: "There are no more 'Strategy Room' shows airing today."
		},
		today: {
			parsed: false,
			channel: 'the-strategy-room',
			channelText: "Strategy Room", // default text
			vars: { callback: "parseLiveEventsFeedToday" },
			sourceCall: "today",
			elm: [], // holder element jquery obj
			data: {} // holder for parsed data
		},
		upcoming: {
			parsed: false,
			channel: 'live-web-shows',
			channelText: '',
			sourceCall: "",
			vars: { callback: "parseLiveEventsFeedUpcoming",limit:2 },
			elm: [],
			data: {}
		}
	};
	this.parserInitialized = false; // parser script listener
	this.holderInitialized = false; // item holder listener
	this.currentTimeStamp = false; // time stamp - will come from the feed if exists
}

LiveEventsFeed.prototype = {
	init: function(config) {
		if (!this.parserInitialized) {
			if (config) {
				for (i in config) { this['_'+i] = config[i]; }
			}
			this.parseFeed.root = this;
		}
		
		if (this.feed.today.parsed && this.feed.upcoming.parsed) { return false; } // don't re-parse if all feeds have been parsed

		if (!this.holder && !this.holderInitialized) { // if holder not initialized
			this.setProperties();
			this.setHolder();
		}
		this.getFeed();
		this.parserInitialized = true;
	},
	setProperties: function() { 
		// set content Id
		if (this._contentId) { this.contentId = this._contentId; }
	},
	setHolder: function() {
		this.feed.holder = $("#"+this.contentId);
		if (!this.feed.holder) { showToConsole("[error] No id element found: " + this.contentId); return false; } // stop if no content element

		var children = this.feed.holder.children();
		this.feed.today.elm = $(children.get(1)).find("div.slideshow:first");
		this.feed.upcoming.elm = $(children.get(2));

		$(this.feed.today.elm, this.feed.upcoming.elm).css("opacity","0");

		this.feed.holder.css("position","relative").append($('<div id="loader-status">Loading...</div>').css({ margin:"0",padding:"2px 5px",position:"absolute",right:"10px",top:"10px",color:"#ff3333",backgroundColor:"#ccc" }));

		this.loaderHolder = this.feed.holder.find("#loader-status");
		this.noShowHolderOn = this.feed.holder.find(".no-show");
		
		var controls = this.feed.holder.find(".controls:first");
		controls.find(".prev").addClass("inactive-prev");
		controls.find(".next").addClass("inactive-next");
		controls.hide(); // hide controls on load
		
		this.holderInitialized = true;
	},

	getFeed: function() {
		
		// don't get feed if there are no defined element to hold it
		if (!this.feed.holder) { showToConsole("[error] No element holder set for feeds"); return false; }

		function ajaxCall(url,callback) {
			try {
				$.ajax({
					type: "GET",
					url: url,
					data: callback,
					dataType: "jsonp",
					error: function(xhr,status,err) {
						showToConsole("["+status+"]: " + err);
						showToConsole(xhr); // put xmlhttprequest object to console for reference
					}
				});
			} catch(err) {
				showToConsole("[error] External Error thrown on ajax request: " + err);
			}
		}
		
		// "today" feed
		if (!this.feed.today.parsed) {
			var url = this.feed.source.replace("${channel}",this.feed.today.channel);
			ajaxCall(url+this.feed.today.sourceCall,this.feed.today.vars);
		}
		
		// "upcoming" feed
		if (!this.feed.upcoming.parsed) {
			var url = this.feed.source.replace("${channel}",this.feed.upcoming.channel);
			ajaxCall(url+this.feed.upcoming.sourceCall,this.feed.upcoming.vars);
		}
	},

	parseFeed: { // feed parser

		today: function(data) {
			var thisObj = this;
			var root = this.root;
			var noFeed = false;
			root.loaderHolder.animate({ opacity:"0" },2000,"swing"); // hide loader
			
			if (typeof data==='undefined') { 
				showToConsole("[parse] Data undefined - returns foo()"); 
				noFeed = true;
			} else if (data.length<1) { noFeed = true; }
			
			if (noFeed) { // if no feed
				var noshows = root.feed.text.noshows.replace("${channelTxt}",root.feed.today.channelText);
				root.noShowHolderOn.text(noshows).show();
				return false;
			}
			
			root.feed.today.parsed = true; // set to parsed
			root.feed.today.data = data;
			
			if (!root.currentTimeStamp) { root.currentTimeStamp = data[0].now; } // save time stamp from feed
			this.insertContent("today",root.feed.today.elm,data);
		},

		upcoming: function(data) {
			var LF = this;
			var root = this.root;
			
			if (typeof data==='undefined') { 
				showToConsole("[parse] No data defined for upcoming feed"); return false;
			} else {
				if (data.length<1) { // no data, don't parse and show "no show" text
					showToConsole("[parse] No upcoming information");
					return false;
				}
			}
			root.feed.upcoming.parsed = true; // set to parsed
			root.feed.upcoming.data = data;
			
			this.insertContent("upcoming",root.feed.upcoming.elm,data);
		},

		insertContent: function(type,holder,data) {
			var LF = this;
			var root = this.root;
			var html = [];
			
			function getHtml() {
				var count = data.length;
				if (type==='upcoming') { count = (data.length > 2) ? 2 : data.length; } // only show 2 items for the right side

				if (type==='today') { html.push("<ul>"); }
				for (var x=0;x<count;x++) {
					var item = data[x];
					var isLast = (type==='upcoming' && x==count-1) ? true : false;
					html.push(LF.formats.feed(type,item,isLast));
				}
				if (type==='today') { html.push("</ul>"); }
				return html.join('');
			}
			
			var feedHolder = $(holder).html(getHtml());
			feedHolder.find("a").each(function(){ // format blank links 
				if ($(this).attr("href")==='#') { $(this).click(function(){ return false; }); }
			});

			if (type==='today') { // call carousel
				var focus = LF.getTodayFocusItem(data);
				if (!focus) {
					var endshow = root.feed.text.endshow.replace("${channelTxt}",data[0].show_channel_name);
					root.noShowHolderOn.text(endshow).show();
					return false;
				}
				holder.scrollLeft(0); // make sure scrollLeft is reset
				triggerCarousel(focus); // trigger carousel plugin
				root.feed.holder.find(".controls:first").show(); // show control buttons
			}
			feedHolder.animate({ opacity:"1" },"slow","swing");
		},
		
		getTodayFocusItem: function(data) { // this will return the current show time
			var LF = this;
			var root = this.root;
			var rawTimes, times = [];
			var current = root.timeStamp('military');
			var nextFocus = 0;
			
			for (var x=0;x<data.length;x++) {
				var item = data[x];
				
				var start = root.timeStamp('military',item.episode_start_time);
				var end = root.timeStamp('military',item.episode_end_time);
				
				if (start >= current) {
					return x+1;
				} else if (start < current && end >= current) {
					return x+1;
				}
				
			}
			return false;
		},

		formats: {

			feed: function(type,obj,last) {
				var html = [];
				var hosts = (typeof obj.show_hosts!=='undefined') ? obj.show_hosts : false;
				var addClass = (last) ? ' class="last"':'';

				var channel = {
					name: obj.show_channel_name,
					link: (obj.show_channel_link) ? obj.show_channel_link : '#'
				};

				var show = {
					title: (obj.episode_title) ? obj.episode_title : obj.show_title,
					link: (obj.show_url) ? obj.show_url : '#',
					day: (type==='upcoming') ? obj.show_day.substring(0,3) + ' ' : '',
					start: this.formatFeedTime(obj.show_start_time,obj.show_startminute,obj.show_time_meridiem),
					end: (type==='today') ? ((obj.show_end_time) ? ' - ' + this.formatFeedTime(obj.show_end_time,obj.show_endminute,obj.show_time_end_meridiem) : '') : '',
					img: (obj.show_image_filepath) ? obj.show_image_filepath : false,
					description: (type==='today') ? ((obj.episode_long_description) ? obj.episode_long_description : obj.show_long_description) : ((obj.episode_short_description) ? obj.episode_short_description : obj.show_short_description)
				};

				html.push('<li'+addClass+'>');
				html.push('<h2><span class="time">'+show.day+show.start+show.end+'</span> | <a href="'+channel.link+'">'+channel.name+'</a></h2>');
				if (show.img) {
					html.push('<div class="img"><img src="'+show.img+'" /></div>');
				}
				html.push('<div class="deck">');
				html.push('<h3><a href="'+show.link+'">'+show.title+'</a></h3>');

				if (hosts && type==='today') { // put hosts
					var hostArr = [];
					html.push('<p>');
					if (hosts.length>0) { html.push('<span class="host">Hosted by:</span>'); }
					for (var h=0;h<hosts.length;h++) { 
						var link = (hosts[h].bio!==null) ? hosts[h].bio : false;
						if (link) { 
							hostArr.push('<a href="'+link+'" target="_blank">' + hosts[h].name + '</a>'); 
						} else {
							hostArr.push(hosts[h].name);
						}
					}
					html.push(hostArr.join(', '));
					html.push('</p>');
					if (type==='today') { html.push('<div style="clear:both;"></div>'); }
				}

				html.push('<p style="padding-top:10px;">'+show.description+'</p>');
				html.push('</div>');
				html.push('</li>');

				return html.join('');
			},

			formatFeedTime: function(hr,min,mrd) {
				min = min || '00';
				return hr + ':' + min + ' ' + mrd;
			}
		}

	}
};

LiveEventsFeed.prototype.timeStamp = function(type,dateObj) {
	dateObj = dateObj || false;
	var months = ["January","February","March","April","May","June","July","August","September","October","November","December"];
	var days = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];
	
	var raw = (dateObj) ? (new Date(dateObj)) : (this.currentTimeStamp) ? (new Date(this.currentTimeStamp)) : (new Date());
	var time = {
		month: parseInt(raw.getUTCMonth(),10)+1,
		year: raw.getFullYear(),
		day: raw.getDate(),
		dow: raw.getDay(),
		hours: raw.getHours(),
		minutes: raw.getMinutes()
	};

	if (type==='feed') {
		return [time.year, ((time.month<10) ? '0'+time.month : time.month), time.day].join('/');  //return '2010/01/27';
	}
	else if (type==='raw') {
		return raw;
	}
	else if (type==='military') {
		
		var hr = time.hours+"";
		var min = (time.minutes<10) ? "0"+time.minutes : time.minutes;
		return parseInt(hr+min,10);
		
	} else {
		return days[time.dow] + ', ' + months[time.month-1] + ' ' + time.day;  
	}
};

function showToConsole(str) {
	if (typeof window.console==='object') { 
		if (typeof console.log!=='undefined') { console.log(str); }
	}
}

var liveEventsFeed = window.liveEventsFeed = new LiveEventsFeed();
window.parseLiveEventsFeedToday = function(data) {
	liveEventsFeed.parseFeed.today(data);
};
window.parseLiveEventsFeedUpcoming = function(data) {
	liveEventsFeed.parseFeed.upcoming(data);
};

})(jQuery);


function parseLoomiaRoot(data) {
	var mrContent="<ul>";
	jQuery.each(data.recs, function(i,item){
    //console.log(item.link);
		mrContent +=  '<li><a href="'+ item.link+'">' + item.title + '</li>'; //'<li><a href="'+ item.link +'" >' + item.title + '</a></li>';
		if ( i == 4 ){
			mrContent += '</ul><ul style="margin-left:1em">';
		} else if ( i == 10 ) {
			mrContent += "</ul>"
			return false;
		}
	});
	jQuery('#root_tab_content_2').html(mrContent);
}


