/*------------------------------------------------------------------------------

BusinessWeek
Common jQuery Scripts
Copyright (c) by The McGraw-Hill Companies Inc. All Rights Reserved
--------------------------------------------------------------------------------
Revision Authors:
DHS: David Sleight
TTM: Thomas Mroczkowski
------------------------------------------------------------------------------*/

/*- jQuery Document Ready ----------------------------------------------------*/

// Register functions with jQuery document ready event here

$(document).ready(function(){
	setGatewaySWF();
	initTabControls();
	initRandomContentDisplay();
	initEmbeddedVideo();
	initAnnotations();
	initCoverBrowser();
	initLinkedInWidget();
	initTableStripes();
});

/*- SWF Data Gateway ---------------------------------------------------------*/

var gatewaySWF;
var gatewayIsLoaded = false;
var gatewayCheckInterval;
var gatewayQueue = new Array();

function setGatewaySWF() {
	gatewaySWF = $('#gatewaySWF');
	gatewaySWF = gatewaySWF[0];
	gatewayCheckInterval = setInterval(gatewayCheck, 10);
}

function gatewayCheck() {
	if (gatewayIsLoaded) {		
		clearInterval(gatewayCheckInterval);	
		//
		// go through array to see if any requests were waiting...
		if (gatewayQueue.length != 0) {
			for (var i = 0; i < gatewayQueue.length; i++) {
				var storedRequest = gatewayQueue.shift();
				gatewayRequest(storedRequest.source, storedRequest.handler);
			}
		}
	}
}

function gatewayRequest(dataSource, dataHandler) {
	if (gatewayIsLoaded) {	
		gatewaySWF.getData(dataSource, dataHandler);
	} else {
		var request = new Object();
		request.source = dataSource;
		request.handler = dataHandler;
		gatewayQueue.push(request);
	}
}

function setGatewayStatus(status) {
	gatewayIsLoaded = status;
}

/*- Tab Controls -------------------------------------------------------------*/

function initTabControls() {
	if (!document.getElementById) return false;
	if (!document.createElement) return false;
	var tabControls = $('.tabControl');
	if (tabControls == 0) return false;
	for (var i = 0; i < tabControls.length; i++) {
		var tabControl = tabControls[i];
		var tabSections = $(tabControl).find('.tabSection');
		$(tabSections).css('display', 'none');
		$(tabSections[0]).css('display', 'block');
		$(tabControl).prepend('<ul class="tabs"></ul>');
		var tabs = $(tabControl).find('ul')[0];
		for (var j = 0; j < tabSections.length; j++) {
			var tabTitle = $(tabSections[j]).find('.tabTitle').html();	
			$(tabSections[j]).find('.tabTitle').remove();
			$(tabs).append('<li><a href="#">' + tabTitle + '</a></li>');
		}
		var tabLinks = $(tabs).find('li');
		for (var k = 0; k < tabLinks.length; k++) {
			var tabLink = tabLinks[k];
			tabLink.onclick = updateTabControl(k, tabLinks, tabSections);
		}
		var tabItems = $(tabs).find("li");
		$(tabItems[0]).addClass('active');
	}
}

function updateTabControl(index, tabSet, contentSet) {
	return function() {
		$(tabSet).removeClass('active');
		$(tabSet[index]).addClass('active');
		$(contentSet).css('display', 'none');
		$(contentSet[index]).css('display', 'block');
		return false;
	}
}

/*- Random Content Display ---------------------------------------------------*/

function initRandomContentDisplay() {
	if (!document.getElementById) return false;
	if (!document.createElement) return false;
	var randomDisplayAreas = $('.randomDisplay');
	if (randomDisplayAreas == 0) return false;
	for (var i = 0; i < randomDisplayAreas.length; i++) {
		var randomDisplayArea = randomDisplayAreas[i];
		var sections = $(randomDisplayArea).find('.default, .alternate').remove();
		var randomIndex = Math.floor(Math.random() * sections.length);
		var randomContent = sections[randomIndex];
		$(randomContent).removeClass('alternate');
		$(randomDisplayArea).append(randomContent);
	}
}

/*- Inline Video -------------------------------------------------------------*/

function initEmbeddedVideo() {
	if (!document.getElementById) return false;
	if (!document.createElement) return false;
	var videoLink = document.getElementById("videoLink");
	if (!videoLink) return false;
	videoLink = videoLink.childNodes[0].href;
	var videoDisplay = '<p id="videoDisplay"><iframe src="' + videoLink + '&amp;rf=ev&amp;hl=true&amp;skin=twoclip" width="302" height="262" scrolling="no" frameborder="0" marginwidth="0" marginheight="0" ></iframe><p>';
	$("#videoLink").before(videoDisplay);
	$("#videoLink").remove();
}


/*- Story Annotations --------------------------------------------------------*/

function initAnnotations() {
	if (!document.getElementById) return false;
	if (!document.createElement) return false;
	var storyBody = document.getElementById("storyBody");
	if (!storyBody) return false;
	var annotations = $(storyBody).find(".annotation");
	for (var i = 0; i < annotations.length; i++) {
		var text = $(annotations[i]).text();
		$(annotations[i]).text("");
		$(annotations[i]).append('<a href="#" class="calloutLink"></a><span class="callout off"><span class="content">' + text + '</span><a class="closeBtn" href="#"></a><span class="calloutBottom"></span></span>');
		$(annotations[i]).addClass('active');
		annotations[i].onclick = function() {
			var calloutClass = $(this).find('.callout').attr('class');		
			if (calloutClass == "callout off") {
				$(this).find('.callout').removeClass('off');
			} else {
				$(this).find('.callout').addClass('off');
			}
			return false;
		}
	}
}

/*- Zebra Stripe Tables ------------------------------------------------------*/

function initTableStripes() {
	if (!document.getElementById) return false;
	if (!document.createElement) return false;
	$('.zebraStripe tr:even').addClass('alternate');
}

/*- LinkedIn Company Insider Widget ------------------------------------------*/

function initLinkedInWidget() {

	var companyName, tickers, ticker, dataSource;
	
	if (!document.getElementById) return false;
	if (!document.createElement) return false;
	var storyTools = document.getElementById("storyTools");
	if (!storyTools) return false;
	var meta = document.getElementsByTagName("meta");
	
	//TTM:Process for company name meta
	companyName = getLinkedInMeta(meta, 'company_primary'); //Get company_primary meta data
	if (companyName) { 
		buildLinkedInWidget('', companyName);
		return;
	}
	
	//TTM:Process for tickers meta
	tickers = getLinkedInMeta(meta, 'tickers_primary'); //Get tickers_primary meta data
	if (!tickers) { //tickers_primary does not exist try tickers
		tickers = getLinkedInMeta(meta, 'tickers'); //Get tickers meta data
		if (!tickers) { 
			return null; //Neither tickers variation exists, exit with error
		}
	}
	ticker = tickers.split(',')[0];
	dataSource = 'http://investing.businessweek.com/services/indices/marketdata.asp?symbols=' + ticker;
	gatewayRequest(dataSource, 'buildLinkedInWidget');

	
	/*TTM: Commented out old code. OK to delete.
	for (var i = 0; i < meta.length; i++) {
		var name = meta[i].getAttribute("name");
		if (name == "tickers_primary") {
			var tickers = meta[i].getAttribute("content");
			var ticker = tickers.split(",")[0];
			//
			var dataSource = "http://investing.businessweek.com/services/indices/marketdata.asp?symbols=" + ticker;
			// var dataSource = "marketdata.xml";
			//
			gatewayRequest(dataSource, "buildLinkedInWidget");
			break;
		} 	
	}
	if (!ticker) {
		for (var i = 0; i < meta.length; i++) {
			var name = meta[i].getAttribute("name");
			if (name == "tickers") {
				var tickers = meta[i].getAttribute("content");
				var ticker = tickers.split(",")[0];
				//
				var dataSource = "http://investing.businessweek.com/services/indices/marketdata.asp?symbols=" + ticker;
				// var dataSource = "marketdata.xml";
				//
				gatewayRequest(dataSource, "buildLinkedInWidget");
				break;
			} 	
		}
	}
	*/
	//
	// if no tickers, script reaches here and stops
	// "share this article" functionality to be added here for those cases
	//
}

//==============================================================================
// Function:     getLinkedInMeta
// Purpose:      Get the content value for a specific meta data element
// Arguments:    array Meta, string Meta Name
// Return:       Meta content as string data type or null on error
//------------------------------------------------------------------------------
// Arguments Detail:
// * aMeta (Required): This is an array of meta elements. This array must be provided outside of this function.
// * sMetaName (Required): The name of the meta data you are requesting. This is the value of the name attribute for the meta element.
//
// Notes: 
// * This function currently only looks up meta elements with a name attribute. Meta elements with http-equiv are ignored.
// * It is possible this function can return an empty string if content attribute has no value.
// * Only the first meta element that matches the meta name provided will return data.
//==============================================================================

function getLinkedInMeta(aMeta, sMetaName) {
	
	sMetaName = sMetaName.toLowerCase();
	if (!aMeta || !sMetaName) {
		return null; //Required args do not exist, return error
	}
	for (var i in aMeta) { 
		if (aMeta[i]['name'] && aMeta[i]['name'].toLowerCase() == sMetaName) {
			if (aMeta[i]['content']) {
				return aMeta[i].content;
			} else {
				return null;
			}
		}
	}
}

function buildLinkedInWidget(data, companyName) { //TTM: Added companyName argument
	
	var rSuffix = (/(\s\&\s?|\,\s?)?(\s(Corporation|Company|Corp|Co|Incorporated|Inc|llc|llp))?$/i); //TTM:Pattern to identify keyword suffix within company name
	
	if (data) {
		var sourceXML = parseXML(data);
		companyName = sourceXML && $(sourceXML).find('quote').attr('name'); //If sourceXML exists then retrieve name attribute
		//companyName = companyName.split(" ")[0]; TTM:Commented out code to keep all companyName data
	}
		
	if (companyName) { 
		companyName = companyName.replace(rSuffix, '').replace(rSuffix, ''); //TTM:Remove Suffix pattern from companyName, twice
		var storyTools = document.getElementById("storyTools");
		var storyToolsCode = ''
			+ '<div id="storyToolsCallouts">'
			+ '<div id="linkedInCallout" class="off">'
			+ '<span id="linkedInFrame"></span>'
			+ '<a class="shareLink" ></a>'
			+ '<!-- BW Ad Code -->'
			+ '<div id="linkedInAd" class="ad"></div>'
			+ '<a class="closeBtn" href="#"></a>'
			+ '<span id="linkedInCalloutBottom"></span>'
			+ '</div></div>'; //TTM: Updated code string for Story Tools Callout
		$(storyTools).find('ul').append('<li id="stLinkedIn" class="active"><a href="#">linkedin connections</a></li>');
		//$(storyTools).append('<div id="storyToolsCallouts"><div id="linkedInCallout" class="off"><span id="linkedInFrame"></span><a class="shareLink" ></a><a class="closeBtn" href="#"></a><span id="linkedInCalloutBottom"></span></div></div>'); //TTM: original story tools code block. OK to delete.
		$(storyTools).append(storyToolsCode); //TTM: recoded story tools callout code above
		var stLinkedIn = document.getElementById("stLinkedIn");
		var link = stLinkedIn.getElementsByTagName("a")[0];
		link.onclick = function() {
			var linkedInFrame = document.getElementById("linkedInFrame");
			var iframe = linkedInFrame.getElementsByTagName("iframe");
			if (iframe.length == 0) { 
				new LinkedIn.CompanyInsiderBox(linkedInFrame, companyName);
				
				//TTM: BEGIN: linkedIn Ad code
				if (window.BW_adsys) { //Ad framework exists
					var linkedInAd = document.getElementById('linkedInAd');
					var linkedInAdCode = BW_adsys('bottomright', '', '', 'basic'); //Return ad code
					linkedInAd.innerHTML = linkedInAdCode;
				}
				//END: linkedIn Ad code
			}
			var linkedInCallout = document.getElementById("linkedInCallout");
			if (linkedInCallout.className == "off") {
				linkedInCallout.className = "";
			} else {
				linkedInCallout.className = "off";
			}
			return false;
		};
		var closeBtn = $('#linkedInCallout .closeBtn');
		closeBtn = closeBtn[0];
		closeBtn.onclick = function() {
			var linkedInCallout = document.getElementById("linkedInCallout");
			linkedInCallout.className = "off";
			return false;
		};	
	}
}

/*- Cover Browser ------------------------------------------------------------*/

var coverBrowserRequestObject;
var coverBrowserData;
var coverBrowserInitIndex;
var coverBrowserCurrentIndex;
var coverBrowserNextBtn;
var coverBrowserPreviousBtn;

function initCoverBrowser() {
	if (!document.getElementById) return false;
	if (!document.createElement) return false;
	var coverBrowser = document.getElementById("coverBrowser");
	if (!coverBrowser) return false;
	coverBrowserRequestObject = getHTTPObject();
	var baseURL = String(location);
	baseURL = baseURL.match(/http:\/\/([^\/]+).*/);
	baseURL = baseURL[1];
	var cacheKiller = new Date();
	var dataSource = "http://" + baseURL + "/magazine/cover_browser.xml?cacheKiller=" + cacheKiller.getTime();
	getCoverBrowserFeed(dataSource);
}

function getCoverBrowserFeed(source) {
	if (!coverBrowserRequestObject) return false;
	coverBrowserRequestObject.open("GET", source, true);
	coverBrowserRequestObject.onreadystatechange = processCoverFeed;
	coverBrowserRequestObject.send(null);
}
	
function processCoverFeed() {
	if (coverBrowserRequestObject.readyState == 4) {
		var rawSource = coverBrowserRequestObject.responseText;
		rawSource = rawSource.replace(/<title>/g, "<itemtitle>");
		rawSource = rawSource.replace(/<\/title>/g, "</itemtitle>");
		rawSource = rawSource.replace(/<link>/g, "<itemlink>");
		rawSource = rawSource.replace(/<\/link>/g, "</itemlink>");
		var sourceXML = parseXML(rawSource);
		coverBrowserData = $(sourceXML).find('issue');
		//
		// Determine issue key from URL, set coverBrowserCurrentIndex
		//
		var fullURL = location.href;
		var keys = fullURL.match(/\d{2}_\d{2}/);

		if (keys != null) {
			var key = keys[0];
			for (var i = 0; i < coverBrowserData.length; i++) {
				var sourceKey = coverBrowserData[i].getAttribute("key");
				if (sourceKey == key) {
					coverBrowserInitIndex = coverBrowserCurrentIndex = i;
					break;
				} else {
					// Couldn't determine order from data
					// Use default value
					coverBrowserCurrentIndex = 0;
				}
			}
			buildCoverBrowser();
		} else {
			// Couldn't determine key from URL
			// Use default value
			coverBrowserInitIndex = coverBrowserCurrentIndex = 0;
			buildCoverBrowser();
		}
	}
}

function buildCoverBrowser() {
	$('#coverBrowser *').remove();
	var title = $('#coverBrowser').append('<h2>' + getCoverBrowserHeading() + '</h2>');
	var link = $(coverBrowserData[coverBrowserCurrentIndex]).find('itemlink').text();
	var coverImage = $(coverBrowserData[coverBrowserCurrentIndex]).find('image').text();;
	var date = $(coverBrowserData[coverBrowserCurrentIndex]).find('date').text();
	var title = $(coverBrowserData[coverBrowserCurrentIndex]).find('itemtitle').text();
	$('#coverBrowser').append('<a href="'+link+'"><img class="coverArt" src="'+coverImage+'" alt="magazine cover" /></a><p class="dateStamp"><a href="'+link+'">'+date+'</a></p><h3><a href="'+link+'">'+title+'</a></h3><ul><li class="previous"><a href="#">Previous Issue</a></li><li class="next"><a href="#">Next Issue</a></li></ul><div class="clearFloat">&nbsp;</div>');
	coverBrowserNextBtn = $('#coverBrowser .next');
	coverBrowserNextBtn[0].onclick = function() {
		if (coverBrowserCurrentIndex > 0) {
			coverBrowserCurrentIndex--;
			updateCoverBrowser();
		}
		return false;
	};
	coverBrowserPreviousBtn = $('#coverBrowser .previous');
	coverBrowserPreviousBtn[0].onclick = function() {
		if (coverBrowserCurrentIndex < (coverBrowserData.length - 1)) {
			coverBrowserCurrentIndex++;
			updateCoverBrowser();
		}
		return false;
	};
	evalCoverBrowserNav();
}

function updateCoverBrowser() {
	$('#coverBrowser h2').text(getCoverBrowserHeading());
	var link = $(coverBrowserData[coverBrowserCurrentIndex]).find('itemlink').text();
	var coverImage = $(coverBrowserData[coverBrowserCurrentIndex]).find('image').text();;
	var date = $(coverBrowserData[coverBrowserCurrentIndex]).find('date').text();
	var title = $(coverBrowserData[coverBrowserCurrentIndex]).find('itemtitle').text();	
	$('#coverBrowser > a').attr('href', link);
	$('#coverBrowser .dateStamp a').attr('href', link);
	$('#coverBrowser h3 a').attr('href', link);
	$('#coverBrowser .coverArt').attr('src', coverImage)
	$('#coverBrowser .dateStamp a').text(date);
	$('#coverBrowser h3 a').text(title);
	evalCoverBrowserNav();
}

function getCoverBrowserHeading() {
	var heading;
	if (coverBrowserCurrentIndex == coverBrowserInitIndex) {
		heading = "This Issue";
	} else if (coverBrowserCurrentIndex == 0) {
		heading = "This Week";
	} else if (coverBrowserCurrentIndex == 1) {
		heading = "Last Week";
	} else {
		heading = coverBrowserCurrentIndex + " Weeks Ago";
	}	
	return heading;
}

function evalCoverBrowserNav() {
	
	if (coverBrowserCurrentIndex <= 0) {
		$(coverBrowserNextBtn).addClass('disabled');
	} else {
		$(coverBrowserNextBtn).removeClass('disabled');
	}
	
	if (coverBrowserCurrentIndex == (coverBrowserData.length - 1)) { 
		$(coverBrowserPreviousBtn).addClass('disabled');
	} else {
		$(coverBrowserPreviousBtn).removeClass('disabled');
	}
}

