dartCalls = new Array; //To stop the JS error when debugging

//-- HEADER NAVBAR --//
function globalNavHover() {
	if (document.getElementById("globalNav")) {
		var navElements = document.getElementById("globalNav").getElementsByTagName("LI");
		
		for (var i=0; i<navElements.length; i++) {
			navElements[i].onmouseover = function() {
				var obj;
				
				//this covers the top level elements
				obj = this.getElementsByTagName("DIV");
				if (obj.length > 0) {
					if (obj[1].style.backgroundPosition.indexOf('bottom') == -1) {
						obj[1].style.backgroundPosition = 'center';
					}
				}
				
				//this covers sub elements
				else{
				   this.parentNode.parentNode.style.backgroundPosition = 'center';
				}

				obj = this.getElementsByTagName("UL");
				if (obj.length > 0) { obj[0].style.left = 'auto'; }
				if (this.getElementsByTagName("LI").length > 0) {
					checkInter("SELECT", false, this);
				}
			}
			navElements[i].onmouseout = function() {
				var obj;
				
				//this covers the top level elements
				obj = this.getElementsByTagName("DIV");
				if (obj.length > 0) { 
					obj[1].style.backgroundPosition = obj[0].className=='selected' ? 'center' : 'top';
				}
				
				obj = this.getElementsByTagName("UL");
				if (obj.length > 0) { obj[0].style.left = '-1000px'; }
				if (this.getElementsByTagName("LI").length > 0) {
					checkInter("SELECT", true, this);
				}
			}
		}
		navElements = document.getElementById("globalNav").getElementsByTagName("DIV");
		for (var i=0; i<navElements.length; i++) {
			navElements[i].onmouseover = function() {
				this.style.backgroundPosition = 'bottom';
			}
		}
	}
}

//checks if nav intersects select boxes
function checkInter(strTag, blnShow, objNav) {

	var sel = document.getElementsByTagName(strTag);
	
	//Create the intersection array if needed
	if (!objNav.smartIntersect) {
		var arrSel = new Array;
		var objDropR = new Recto(objNav.getElementsByTagName("UL")[0]);	//dropdown list rectangle
		for (var i=0; i<sel.length; i++) {
			var objSelR = new Recto(sel[i]);
			arrSel[i] = RectoInter(objDropR, objSelR)	//check select is under the nav
		}
		objNav.smartIntersect = arrSel;	//asign to DOM object for later access
	}

	//apply the styles to select dropdowns as needed
	for (var i=0; i<sel.length; i++) {
		if (objNav.smartIntersect[i]) {
			sel[i].style.visibility = blnShow ? "visible" : "hidden"; 
		}
	}
}


//Rectangle object constructor, takes any DOM object
function Recto(obj) {
	if (obj) {
		this.left = getParentOffLeft(obj);
		this.top = getParentOffTop(obj);
		this.width = obj.offsetWidth;
		this.height = obj.offsetHeight;
		this.bottom = this.top + this.height;
		this.right = this.left + this.width;
	}
}

//checks to see if two Recto objects intersect
function RectoInter(r1, r2) {
	var inter = false;
	//Find the leftmost etc rectangle. 
	var leftMost = r1.left < r2.left ? r1 : r2;
	var nonLeftMost = r1.left >= r2.left ? r1 : r2;
	var topMost = r1.top < r2.top ? r1 : r2;
	var nonTopMost = r1.top >= r2.top ? r1 : r2;
/*  If the left x co-ordinate of the non-leftmost rectangle is between the 
left and the right of the leftmost rectangle, you have the left cordinate of 
your intersection. If it is to the right you have no intersection, and the 
rectangles don't overlap. */
	if (nonLeftMost.left >= leftMost.left && nonLeftMost.left <= leftMost.right && nonTopMost.top >= topMost.top && nonTopMost.top <= topMost.bottom) inter = true;
	return inter;
}


//returns full offset value of an object on the page
function getParentOffTop(obj) {
	if (obj.offsetParent != null ) {
		return obj.offsetTop + getParentOffTop(obj.offsetParent);
	} else {
		return 0;
	}
}

function getParentOffLeft(obj) {
	if (obj.offsetParent != null ) {
		return obj.offsetLeft + getParentOffLeft(obj.offsetParent);
	} else {
		return 0;
	}
}

Event.observe(window, 'load', globalNavHover); //only for IE, FF uses classes

//-- RELOAD ASSETS --//
// This is how to register a hit (and refresh ads) in a JS call
var page = new Object();
var eventList = null;
page.reloadAssets = function() {
    adReloadAll();
    TrackingObject.setDomain(zagTopDomain);
    TrackingObject.setNodeId("zagTopHolder");
    TrackingObject.drawTracking();
    TrackingObject.setDomain(zagDomain);
    TrackingObject.setNodeId("zagHolder");
    TrackingObject.drawTracking();
    urchinTracker();
    if(eventList != null){ eventList.writeJavaScriptTags(); }
}
page.reloadAssetsNoEventTracking = function() {
	adReloadAll();
	TrackingObject.drawTracking();
}
var autoRefreshIterations = 0;
function AutoRefreshAssets(seconds, maxIterations) {
  setTimeout("TimedAssetsRefresh(" + seconds + ", " + maxIterations + ")",seconds * 1000);
}
function TimedAssetsRefresh(seconds, maxIterations){
  if (autoRefreshIterations < maxIterations) {
    page.reloadAssetsNoEventTracking();
    ++autoRefreshIterations;
    setTimeout("TimedAssetsRefresh(" + seconds + ", " + maxIterations + ")",seconds * 1000);
  }
}
//-- TRACK CHART COMPONENTS --//
// 
page.trackComponents = function() {
		var strUrl = '';
		for (var i=0; i < arguments.length; i++) {
			strUrl += arguments[i] + ((i == arguments.length-1) ? '' : '/');
		}
		if (strUrl.length != 0) {
			strUrl = 'charts/' + strUrl;
			strUrl = escape(strUrl);
		}
		TrackingObject.setComponentUrl(strUrl);
		TrackingObject.drawTracking();	
}

//Email a page launching function
function gotoEmailAFriend(qstring, popup) {
	var strURL = "/content/email/?referringPage="+escape('http://'+location.host)+escape(location.pathname)+qstring;
	if (popup) {
		window.open(strURL);
	} else {
		document.location = strURL;
	}
}

//-- SLIDESHOW POPUP --//
function popUpSlideshow(url) {
	window.open(url, 'portfolio_popup', 'toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=0,width=924,height=594');
}
function popUpInfographic(url) {
	window.open(url, 'portfolio_popup', 'toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=0,width=924,height=594');
}
function popUpVideo(url) {
	window.open(url, 'portfolio_popup', 'toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=0,width=924,height=634');
}
function popUpInteractiveFeature(url) {
	window.open(url, 'portfolio_popup', 'toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=0,width=924,height=594');
}
function popUpAudioSlideshow(url) {
	window.open(url, 'portfolio_popup', 'toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=0,width=924,height=594');
}

//-- SET BREADCRUMB --//
function setBreadcrumb(position, value) {
  document.getElementById('breadcrumb_' + position).innerHTML = value;
}
//-- SET BREADCRUMB --//
function setBreadcrumbTitle(position,value,titleid) {
	setBreadcrumb(position, value)
  document.getElementById(titleid).innerHTML = value;
}

//-- MISC UTILITY --//
function openInParent(url) {
    if (opener != null) {
    	opener.location.href = url;
        window.close();
	}
	else {
		window.location.href = url;
	}
}

//-- FONT SIZER --//
//Global text resizer for toolbar
//size is integer 0, 1, 2
function textSize(size) {
	var divs = document.getElementsByTagName('DIV');
	var ts = document.getElementById("smallimage");
	var tm = document.getElementById("mediumimage");
	var tl = document.getElementById("largeimage");
	var strClass;
	var div;
	
	if (size == 0) {
		ts.src="/images/site/icn/icon_textSize_small_bold.gif";
		tm.src = "/images/site/icn/icon_textSize_medium.gif";
		tl.src = "/images/site/icn/icon_textSize_large.gif";
	}
	
	if (size == 1) {
		ts.src = "/images/site/icn/icon_textSize_small.gif";
		tm.src = "/images/site/icn/icon_textSize_medium_bold.gif";
		tl.src = "/images/site/icn/icon_textSize_large.gif";
	}
	
	if (size == 2) {
		ts.src = "/images/site/icn/icon_textSize_small.gif";
		tm.src = "/images/site/icn/icon_textSize_medium.gif";
		tl.src = "/images/site/icn/icon_textSize_large_bold.gif";
	}
	for (var i=0; i<divs.length; i++) {
		div = divs[i];
		strClass = div.className;
		if (strClass && strClass.indexOf('bodyText') > -1) {
			
			strClass = strClass.replace(new RegExp("mediumText"), "");
			strClass = strClass.replace(new RegExp("largeText"), "");
			switch (size) {
				case 0:
					strClass = strClass.replace(new RegExp("bodyText"), "bodyText");
					break;
				case 1:
					strClass = strClass.replace(new RegExp("bodyText"), "bodyText mediumText");
					break;
				case 2:
					strClass = strClass.replace(new RegExp("bodyText"), "bodyText largeText");
					break;
			}
			div.className = strClass;
		
		}
	}
}



//-- PRINT FUNCTIONS --//
//Opens a popup for the print window
function doPrint() {
	var URL = document.location.href;
	if (URL.indexOf('#') > 0 ) {
		var cleanURL = URL.split("#");
		doPrintURL(cleanURL[0]);	
	}
	else {
		doPrintURL(URL);	
	}
	
}

function doPrintURL(URL) {
	if (URL.indexOf('?') > 0) {
		URL += '&print=true';
	} else {
		URL += '?print=true';
	}
	window.open(URL, 'print_popup', 'toolbar=0,scrollbars=1,location=0,statusbar=1,menubar=0,resizable=1');
}

//Makes the paper come out of the printer
function executePrint() {
	window.print();
}

function writePrintURL() {
	var strHTML = '<div class="printFooterBox"><div class="subHeader">Web address of this article</div>';
	var origURL = document.location.href.replace('#', '').replace('?print=true', '').replace('&print=true', '');
	strHTML += '<a href="' + origURL + '">' + origURL + '</a>';
	strHTML += '</div>';
	document.write(strHTML);
}

function writePrintLinks() {
	var strHTML = '';
	var objTxt = document.getElementById('bodyTextWrapper');
	var objLinks = objTxt.getElementsByTagName('A');
	if (objLinks) {
	  strHTML += '<div class="printFooterBox"><div class="subHeader">Links in this article</div>';
	  for (var i=0; i<objLinks.length; i++) {
	    if (objLinks[i].href) {
	      strHTML += '<div class="linkList"><img src="/images/site/bg/bullet-carved-arrow.gif" height="6" width="5" /><a href="' + objLinks[i].href + '">' + objLinks[i].href + '</a></div>';
	    }
	  }
	  strHTML += '</div>';
	}
	document.write(strHTML);
}


//////////
//Global Pause function
var objPause = new PauseManager();

//Pauses for a set number of milliseconds
//	after which it calls a specified function in the context of the Object passed
function pauseObjectMethod(objObject, objFunction, intMilliSec) {
	var id = objPause.StoreObject(objObject, objFunction);
	window.setTimeout('objPause.Finish(' + id + ');', intMilliSec);
}

//Pause Manager Constructor
function PauseManager() {
	//methods
	this.StoreObject = mtdStoreObject;
	this.Finish = mtdFinish;
	//locals
	var arrObjects = new Array;
	var arrFunctions = new Array;
	
//stores pause details
function mtdStoreObject(objObject, objFunction) {
	//save objects to array
	//we start at the beginning and reuuse first null array
	var next = arrObjects.length;
	OutLoop:
	for (i=0; i<arrObjects.length; i++) {
		if (arrObjects[i] == null) {
			next = i;
			break OutLoop;
		}
	}
	//window.status = 'TEST arrObjects[next] ' + next + '       ' + next;
	arrObjects[next] = objObject;
	arrFunctions[next] = objFunction;
	return next;
}

//finishes pause
function mtdFinish(id) {
	var fn = arrFunctions[id];
	var obj = arrObjects[id];
	//wipe values, but don't delete them or it'll screw up the indexes
	arrFunctions[id] = null;
	arrObjects[id] = null;
	//call function
	fn.apply(obj);
}

}


// Adds trim() function to String class
String.prototype.trim = function() { return this.replace(/^\s+|\s+$/, ''); };



function findExternalLinks(elmnt){
	//elmnt = DOM Object ref to element that needs to be parsed through for external links
	var linksArray = elmnt.getElementsByTagName("A");
	for(var idx=0;idx<linksArray.length;idx++){
		if(linksArray[idx].href.indexOf(window.location.host) < 0){
			if((linksArray[idx].href.indexOf("http://") > -1) || (linksArray[idx].href.indexOf("https://") > -1)){
				linksArray[idx].target = "_blank";
				linksArray[idx].setAttribute("target","_blank");
			}
		}
	}
}



var currentPage;
var pages;
var totalPages;
var topNav;
var botNav;
var aID;
var initPage;
function paginateArticle(page,aID,hist){
	pages.each(function(item,indx){
		item.hide();
	});
	pages[page].show();
	updateNav(page);
	currentPage = page;
	createCookie('articlePage'+ aID,page,1)
	if (hist != 'noHist') dhtmlHistory.add("page" + (page + 1), page);	
	return false;
} 

function updateNav(page){
	updateLinks(topNav,page)
	updateLinks(botNav,page)
	if (page != 0) {
		if ($('photo')) $('photo').hide();
		if ($('headDeck')) $('headDeck').hide();
	}
	else {
		if ($('photo')) $('photo').show();
		if ($('headDeck')) $('headDeck').show();
	}
} 
function changePage(lnk) {

	toggleArticleByline('hide');

	pageNumb = this.innerHTML;
	if (pageNumb.length != 1 && pageNumb.indexOf('Next') != -1) {
		pageNumb = currentPage + 1;
	}
	else if (pageNumb.length != 1 && pageNumb.indexOf('Prev') != -1) {
		pageNumb = currentPage - 1;
	}
	else {
		pageNumb = pageNumb-1
	}
	if (this.parentNode.id == 'bottomPagination') $('outerWrapper').scrollTo(); 
	page.reloadAssets();
	paginateArticle(pageNumb,aID);

	toggleArticleByline('show', pageNumb+1);
	
	return false;
}
function updateLinks(links,page){
	var currentSet = Math.ceil((page+1)/4)
	links.each(function(item,indx){
		item.removeClassName('currentPage')
		if ((links.length - 2) > 5) {
			if (  (indx > (currentSet*4) || indx <= ((currentSet-1)*4)) && indx != 1 && indx != links.length -2 ) {
				item.setStyle({display:'none'});
			}
			else {
				item.setStyle({display:'inline'});
			}
		}
		if (indx == 0 && page == 0) {
			item.setStyle({display:'none'});
		}
		else if (indx == 0 && page != 0) {
			item.setStyle({display:'inline'});
		}
		if ((indx + 1) == links.length && ((page + 1) == totalPages) ) {
			item.setStyle({display:'none'});
		}
		else if ((indx + 1) == links.length ) {
			item.setStyle({display:'inline'});
		}
		if ((indx + 1) != links.length && indx != 0 && ((page+1) == indx)) {
			item.addClassName('currentPage')
		}
	});
	var dots = $$('#'+ links[0].parentNode.id +' span')
	dots.each(function(dot,indx){
		dot.remove()
	});
	if ((links.length - 2) > 5 && page < 4 ) {
		new Insertion.After(links[links.length - 3], "<span> &hellip; </span>")
	}
	else if (((links.length - 2) > 5 && (links.length - 2) > 8 ) && page > 3 && page >= ((currentSet-1)*4) && page <= (links.length - 5)) {
		new Insertion.After(links[1], "<span> &hellip; </span>")
		new Insertion.After(links[links.length - 3], "<span> &hellip; </span>")
	}	
	else if ((links.length - 2) > 5 && page >= ((currentSet-1)*4) ) {
		new Insertion.After(links[1], "<span> &hellip; </span>")
	}	
	
} 
function showAll() {
	//handles the byline at the bottom of the page
	toggleArticleByline('show');	

	pages.each(function(item){
		item.show();
	});
	$('outerWrapper').scrollTo()
	$('toolPagination').hide();
	$('bottomPagination').hide();	
	return false
}
function setupPagination(articleID) {

	//handles the byline at the bottom of the page
	toggleArticleByline('hide');

	pages = $$('.articlePage');
	totalPages = pages.length;
	topNav = $$('#toolPagination a');
	botNav = $$('#bottomPagination a');	
	var topLinks = $$('#toolPagination a','#bottomPagination a');
	topLinks.each(function(item,indx){
		item.onclick = changePage;
	});
	pages.each(function(item,indx){
		item.id = 'pageNo'+ indx;
	});
	$('viewAll').onclick = showAll;
	dhtmlHistory.initialize();
	dhtmlHistory.addListener(historyChange);
	aID = articleID.substr(0, 20);
	var pageCookie = readCookie('articlePage'+ aID)
	if (window.location.hash != '' && window.location.hash.indexOf('page') != -1){
		var newPage = window.location.hash.substr(window.location.hash.length-1, 1);
		currentPage = newPage - 1;
		initPage =  newPage - 1;
		paginateArticle((newPage - 1), aID,'noHist');
		
		toggleArticleByline('show', newPage);
	}
	else if (pageCookie) {
		initPage = ((pageCookie - 1)+ 1);
		paginateArticle(((pageCookie - 1) + 1), aID,'noHist')
	}
	else {
		initPage = 0;
		paginateArticle(0, aID,'noHist')
	}
}
function historyChange(newLocation,historyData) {
	if (historyData == null && !initPage) {  
		var pageCookie = readCookie('articlePage'+ aID)
		historyData = ((pageCookie - 1) + 1)
	}
	else if (historyData == null ) { 
		historyData = initPage; 
	}
	paginateArticle( historyData, aID , 'noHist')
}

function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function countLetters(textObj, maxNum, divName, divName1){
	var currentCount = textObj.value.length;
	var currentCountMax = maxNum;
	if(currentCount > maxNum){
		textObj.value = textObj.value.substr(0,maxNum);
		currentCount = textObj.value.length;
	}	
	if (divName1) {
		currentCountMax = maxNum - currentCount;
		var outputDiv1 = document.getElementById(divName1);
		outputDiv1.innerHTML = currentCountMax;
	}
	
	var outputDiv = document.getElementById(divName);
	outputDiv.innerHTML = currentCount;
}

var socialShare = {
	initialize: function(){
		this.share = $('socialShare');
		this.caller = '';
		this.newTimer = null;
		if (this.share != null) {
			Event.observe('socialShare', 'mouseover', function(){ socialShare.showObj(); return false; },false);
			Event.observe('socialShare', 'mouseout', function(){ socialShare.initHide(); return false; },false);
		}
		this.showIt = function(){ socialShare.showObj(); return false; };
	},
	moveObject: function(target) {
		if (this.share != undefined) {
			this.caller = $(target.id);
			if (this.newTimer != null) { clearTimeout(this.newTimer) }
			var pos = Position.cumulativeOffset(this.caller);
			var xPos = pos[0];
			var yPos = pos[1] + this.caller.up(0).getHeight();
			if (this.caller.up(0).id == 'captionRight' || this.caller.up(1).hasClassName('marketEcom-toolbar')) xPos = xPos - 141;
			if (this.caller.hasClassName('share')) this.caller.addClassName('over');
			if (this.caller.up(0).hasClassName('toolShare')) this.caller.up(0).setStyle({ backgroundColor: '#f2f1ef'});
			this.share.setStyle({
			  left: xPos +'px',
			  top: yPos +'px'
			});
			this.share.setStyle( {
			 visibility:'visible'
			})
			Event.observe(this.caller.id, 'mouseover',  this.showIt ,false);
		}
	},
	initHide: function(target) {
		if ( target ) this.caller = $(target.id);
		this.newTimer = setTimeout("socialShare.hideObj()",250);
	},
	showObj:function() {
		if (this.share != undefined) {
			if (this.newTimer != null) { clearTimeout(this.newTimer) }
			this.share.setStyle( {
			 visibility:'visible'
			})
		}
	},
	hideObj: function(target) {
		if (this.share != undefined) {
			this.share.setStyle( {
			 visibility:'hidden'
			})
			this.caller.up(0).setStyle({
				backgroundColor: 'transparent' 
			});
		    if (this.caller.hasClassName('over')) this.caller.removeClassName('over');
			Event.stopObserving(this.caller.id, 'mouseover', this.showIt ,false);
		}
	},
	passURL: function (el){
		var nuURL = el.href + URLEncode(this.caller.href)
		if (this.caller.rel && el.href.indexOf('technorati') == -1) {
			if (el.href.indexOf('newsvine') != -1) {
				nuURL = nuURL +'&h='+ URLEncode(this.caller.rel)
			}
			else {
				nuURL = nuURL +'&title='+ URLEncode(this.caller.rel)
			}
		}
		window.open(nuURL);
		return false
	}

}
Event.observe(window, 'load', function(){ socialShare.initialize(); });
function URLEncode(plaintext)
{
	// The Javascript escape and unescape functions do not correspond
	// with what browsers actually do...
	var SAFECHARS = "0123456789" +					// Numeric
					"ABCDEFGHIJKLMNOPQRSTUVWXYZ" +	// Alphabetic
					"abcdefghijklmnopqrstuvwxyz" +
					"-_.!~*'()";					// RFC2396 Mark characters
	var HEX = "0123456789ABCDEF";


	var encoded = "";
	for (var i = 0; i < plaintext.length; i++ ) {
		var ch = plaintext.charAt(i);
	    if (ch == " ") {
		    encoded += "+";				// x-www-urlencoded, rather than %20
		} else if (SAFECHARS.indexOf(ch) != -1) {
		    encoded += ch;
		} else {
		    var charCode = ch.charCodeAt(0);
			if (charCode > 255) {
			    alert( "Unicode Character '" 
                        + ch 
                        + "' cannot be encoded using standard URL encoding.\n" +
				          "(URL encoding only supports 8-bit characters.)\n" +
						  "A space (+) will be substituted." );
				encoded += "+";
			} else {
				encoded += "%";
				encoded += HEX.charAt((charCode >> 4) & 0xF);
				encoded += HEX.charAt(charCode & 0xF);
			}
		}
	} // for

	return encoded;
};


function toggleArticleByline(toggle, curPage){
	var bottomByline = document.getElementById('articleBylineBottom');
	if(bottomByline != null){
		if(toggle == 'hide'){
			bottomByline.style.display = 'none';
		}else if(toggle == 'show'){
			if(curPage == totalPages || curPage == null){
				bottomByline.style.display = 'block';	
			}
		}
	}
}


