/* 
  $LastChangedDate: 2007-12-19 14:40:42 -0500 (Wed, 19 Dec 2007) $
  $LastChangedRevision: 4535 $
  $LastChangedBy: raccettura $
*/

var bnTickerMaster = true; // Master switch
var bnTickerInterval = 60; // in seconds
var s=new Object;    //legacy omniture, needed to prevent errors in adConfig


/** 
 * On Load
 */
$(document).ready(function(){
	// If style is different, assume there is a big top image and make it clickable 
	if(typeof(cbsVar_style) != 'undefined' && cbsVar_style != 'cbsnews') {
		$('#header .horizontalNavItems').after( '<a href="' + cbsVar_url + '"><img src="http://'+news_host+'.cbsnews.com/common/images/transp.gif" width="983" height="90" alt="Section Home" /></a>' );
	}

	// Get comments for home or section
	if( typeof(cbsVar_tmpl) != 'undefined' && cbsVar_tmpl != 'campaign2008' && (cbsVar_tmpl == 'section' || cbsVar_tmpl == 'home' || cbsVar_tmpl == 'watch_video' || cbsVar_tmpl == 'blogsection' || cbsVar_tmpl == 'videosection') ){
		getCommentCounts();
	}
	
	if(cbsVar_tmpl == 'home'){
		checkCbsNewsLocal();
	}
	
	if(navigator.userAgent.toLowerCase().indexOf('iphone') != -1){
		$('#leftNavSections').prepend('<li class="navExpandable"><img alt="" class="navIcon navEmpty" src="http://wwwimage.cbsnews.com/common/images/v3/icon_nav_empty.gif"/> <a onclick="return linkTo(this)" class="linksmall" href="http://www.cbsnews.com/iphone.php?qwr_=iphone">iPhone Site</a></li>');
	}

	// hide adsliver if blank
	var $adsliver = $("#adsliver");
	if($adsliver.height() < 20){
		$adsliver.hide();
	}

	//dbg
	//$("#ee").dblclick( function() {  
	//	$('#ee').append('<img id="ei" src="http://wwwimage.cbsnews.com/images/2002/08/06/image517703m.jpg" />');
	//	$('#ei').fadeIn('slow', function(){ setTimeout(function(){$('#ei').fadeOut('slow', function(){$('#ei').remove();});}, 3000);  });
	//} );
});


function onPermalinkLoad(){
	$(document).ready(function(){ pre_loadMonth();load(); });
}


function onStoryLoad(){
	/*if(status){
		$(document).ready(function(){myCount(); load(); });
	}
	else{
		$(document).ready(function(){ });
	}*/
	$(document).ready(function(){ /*add functions here*/});
}


function onBlogLoad(){
	$(document).ready(function(){ pre_loadMonth(); });
}

/* 
 *Get locale information so we can localize content
 */
var cbsNewsLocal = Array();

function checkCbsNewsLocal(){

	// Do we have a cookie?	
	var cookieVal = getCookieValue('localCbsNews');

	if(cookieVal != null){
		cookieVal = unescape(cookieVal);
		cookieVal = cookieVal.split(';');

		var val;

		// Load it up			
		for(i=0; i<cookieVal.length; i++){
			val = cookieVal[i].split('=');
			cbsNewsLocal[val[0]] = val[1];
		}
		if(typeof window.cbsGeoDataLoaded != 'undefined'){ cbsGeoDataLoaded(); }
		if(typeof window.cbsGeoDataLoaded2 != 'undefined'){ cbsGeoDataLoaded2(); }
	} else {

		// Request local info
		$.getJSON('/localize/localize.php', 
			function(result){
				
				var val = '';
				for (var key in result.locale) {
					val += key + '=' + result.locale[key] + ';';
					cbsNewsLocal[key] = result.locale[key];
				}				
				val = val.slice(0, -1);

				// Set Cookie
				document.cookie = 'localCbsNews='+escape(val)+'; expires=0; path=/';
				if(typeof window.cbsGeoDataLoaded != 'undefined'){ cbsGeoDataLoaded(); }
				if(typeof window.cbsGeoDataLoaded2 != 'undefined'){ cbsGeoDataLoaded2(); }
			}
		);
	}
}



/*
functions that handle auto refresh
*/
var pageRefresh;

function enableRefresh(){
	if(document.location.href.toLowerCase().indexOf('disablerefresh') == -1){
		pageRefresh = window.setTimeout(function(){
			document.location.href = 'http://' + news_host + '.cbsnews.com/?source=homepage_refresh';
		}, 180000);
	}
}

function disableRefresh(){
	clearTimeout(pageRefresh);
}

// Param to disable refresh
	disableRefresh();


/**
 * Adjust small fonts for Mac users
 * Note: happens before load complete since is's safari/firefox only.
 */
if($.cbsOsDetect.mac){
	$('head').append('<style type="text/css"> div.smallTabsBox .tabs ul li { font-size: 0.82em; padding: 0 3px 0 4px; } span.smallhead_black, div.moreLink, p.sectionCommentCount, body .headsmall_underline, body .smallhead_blue { font-size: 9px; } .toolbox_divider { margin:0 12px; } </style>');
}


// Global Ad;
var gAds = Array();


/**
 * Generates Ad ads
 * @param aParam {JS Obj} The object containing ad params
 */
function genAd(aParam){
	var extra = 'abr=!webtv;';
	aParam.adserver = 'CBSNews/';
	
	if(document.location.href.match("stories")){
		aParam.vtag = aParam.vtag.replace(/;page=index/ig, "");
	}
	
	if(aParam.secid != 100 && aParam.adsize == '300x250'){
		extra += 'dcopt=ist;';
	}
	
	 if (typeof(adv) == "undefined") {
           adv = getCookieValue("adv");
           if (!adv) {
                    var letters = new Array('a', 'b');
                   adv = letters[Math.floor(Math.random() * 2)];
			}	
			document.cookie = "adv=" + adv + ";Path=/;";   
    }
     
	
	//var adUrl = 'http://ad.doubleclick.net/adj/'+ aParam.adserver + aParam.vtag + ';'+extra+'sec=' + aParam.secid + ';tile=' + aParam.tile + ';sz=' + aParam.adsize + ';ord='+ aParam.ord;
	var adUrl = 'http://ad.doubleclick.net/adj/'+ aParam.adserver + aParam.vtag + ';adv=' + adv +';' +extra+'sec=' + aParam.secid + ';tile=' + aParam.tile + ';sz=' + aParam.adsize + ';ord='+ aParam.ord;
	var tag = '<script type="text/javascript" src="' + adUrl + '"></script>';
	gAds[gAds.length] = adUrl;

	if (aParam.secid == 100 && aParam.adsize == '300x250'){
		if ((!document.getElementById('iSliver')) || (typeof(window['toSeenX']) == 'undefined') || (toSeenX > toShowX)){
			return tag;
		}
		return null;
	}
	return tag;
}


/**
 * Serves ads
 * @param obj {JS Obj} The object containing ad params
 */
function serveAd(obj){
	var ad = genAd(obj);
	if(ad != null){
		document.write(ad);
	}
	
	if(obj.collapseIfEmpty){
		$(window).ready(function(){
			controlAdBoxSize(obj.collapseIfEmpty);
		});
	}
}


/**
 * Control Ad Box Size to minimize if no ad
 * @param aId {String} The Id of the adbox
 */
function controlAdBoxSize(aId){
	if(document.getElementById(aId)!=null){
		var adDiv = document.getElementById(aId);
		var adtop = adDiv.offsetHeight;
		var campaign08html = '<a href="http://www.cbsnews.com/sections/politics/main250.shtml"><img border="0" src="http://wwwimage.cbsnews.com/images/2007/09/14/image3260677.gif"/></a>';
		var endofyearhtml = '<a href="http://www.cbsnews.com/sections/2007/main502483.shtml"><img border="0" src="http://www.cbsnews.com//images/2007/12/12/image3610115.gif"/></a>';
		if(adtop < 18){
			/*		
			if(cbsVar_sectName == 'HOME' && aId == 'ad-88x31'){
				$(adDiv).html(campaign08html);
			}
			else{
				$(adDiv).css('display', 'none');
			}
			*/
		  $(adDiv).css('display', 'none');	
		}
		return adtop;
	}
/*	if($('#'+aId) && $('#'+aId).height() < 50){
		$('#'+aId).hide();
	} 
*/
}


/**
 * Generates Ad ads for specific 88x31 size
 * @author cnevers   DEPRECATED, Delete during launch
 */
 function gen88Ad(){
	//document.write('');
}


/**
 * Used for PopZoom Boxes
 * @param aObj {DOM Obj} The object to apply effect to
 */
function popZoom(obj){
	$obj = $(obj);
	$img = $("img", $obj);
	$link = $("a", $obj);
	
	// On Hover
	if(!$img.attr('a')){
		$img.attr('a', 1);

		// General
		$img.css('border-color', '#68C');
		if($obj.attr('class').indexOf('vidMO2') != -1 || $obj.attr('class').indexOf('tabItem') != -1 ){
			$img.css('border-style', 'solid');
			$img.css('border-width', '3px');
			$img.css('border-color', '#9CF');
			$img.css('margin', '0');
			$link.css('text-decoration', 'underline');
			if($obj.attr('class').indexOf('vidMO') != -1){
				$img.attr('src', 'http://'+news_image_host+'.cbsnews.com/common/images/v3/button_play_s.png');
				return;
			}
		}
		else if($obj.attr('class').indexOf('vidMO') != -1){
			$img.attr('src', 'http://'+news_image_host+'.cbsnews.com/common/images/v3/button_play_s.png');
			$link.css('text-decoration', 'underline');
			return;
		} else {
			$img.attr('src', 'http://'+news_image_host+'.cbsnews.com/common/images/transp.gif');
		}
		return;
	}
	
	// On Blur
	$img.removeAttr("a");
	$link.css('text-decoration', 'none');
	// Stick with png to keep IE 6 from going nuts
	if($obj.attr('class').indexOf('vidMO2') != -1 || $obj.attr('class').indexOf('tabItem') != -1 ){
		$img.css('border-width', '0px');
		$img.css('margin', '3px');
		if($obj.attr('class').indexOf('vidMO2') != -1){
			$img.attr('src', 'http://'+news_image_host+'.cbsnews.com/common/images/v3/button_play_s.png');
		} else {
			$img.attr('src', 'http://'+news_image_host+'.cbsnews.com/common/images/v3/transp.png');
		}
		return;
	}
	$img.css('border-color', '#fff');
	$img.attr('src', 'http://'+news_image_host+'.cbsnews.com/common/images/v3/transp.png');
	return;
}



/**
 * Used to keep jquery off of pages themselves
 * @param aObj {DOM Obj} The object to apply effect to
 */
function ref(aObj){
	return $(aObj);
}


/**
 * Used to keep jquery off of pages themselves
 */
function jqO(){
	return $;
}


/**
 * Toggles Sub-Navigation for menu
 * @param aSelf {DOM Obj} The image being clicked on
 * @param aSubNav {String} The id of the subnav dom element to manage
 */
function toggleNavSub(aSelf, aSubNav){

	$aSubNav = $('#'+aSubNav);
	$aSelf = $(aSelf);

	$('#leftNavSections div.subnav, #leftNavServices div.subnav, #leftNavSubSections div.subnav').each(function(i){
		$this = $(this);
		if($this.css('display') != 'none' && $this.attr('id') != $aSubNav.attr('id')){
			toggleNavSubClose($('img.navIcon', $this.parent()), $this);
			$('#closeAllNav').hide();
			return  false;
		}
	});

	if($aSubNav.css('display') == 'none'){
		toggleNavSubOpen($aSelf, $aSubNav);
		$('#closeAllNav').show();
		return;
	}
	toggleNavSubClose($aSelf, $aSubNav);
	$('#closeAllNav').hide();
	return false;
}


/**
 * Closes navigation element
 * @param aSelf {DOM Obj} The image being clicked on
 * @param aSubNav {String} The id of the subnav dom element to manage
 */
function toggleNavSubClose(aSelf, aSubNav){
	// On home make nav opaque when opened
	//if(cbsVar_tmpl == 'home'){
	//	$("#leftRail").fadeTo("fast", 1);
	//}

	aSelf.attr('src', 'http://'+news_image_host+'.cbsnews.com/common/images/v3/icon_nav_expand.gif');
	aSelf.attr('alt', 'Open');
	aSubNav.slideUp("fast");
}


/**
 * Opens navigation element
 * @param aSelf {DOM Obj} The image being clicked on
 * @param aSubNav {String} The id of the subnav dom element to manage
 */
function toggleNavSubOpen(aSelf, aSubNav){
	// On home make nav transparent when opened
	//if(cbsVar_tmpl == 'home'){
	//	$("#leftRailWrapper").fadeTo("fast", 0.85);
	//}

	aSelf.attr('src', 'http://'+news_image_host+'.cbsnews.com/common/images/v3/icon_nav_collapse.gif');
	aSelf.attr('alt', 'Close');
	aSubNav.slideDown("fast");
}


var loadingTab = false;

/**
 * Show Tab
 * @param aTab {String} Name of the Tab being clicked on.
 * @param aTabContainer {String} Id of the tab container element
 * @param aContentContainer {String} Id of the content container element
 * @param aActiveTabClass {String} Class name of active tab class
 * @param aInActiveTabClass {String} Class name of inactive tab class
 */
function showTab(aTab, aTabContainer, aContentContainer, aActiveTabClass, aInActiveTabClass){
	if(loadingTab){ return; }
	loading = true;

	// Tabs
	$.each( $("li", "ul#" + aTabContainer), function(obj){
		var $this = $(this);
		if($this.attr('class').indexOf('label') == -1){
			if($this.css('display') != 'none' && $this.attr('id') != aTab + '-tab') {
				$this.removeClass(aActiveTabClass);
				$this.addClass(aInActiveTabClass);
				$.each( $(".hideWhenInactive", $this), function(obj){
					$(this).css('display', 'none');
				});
			} else {
				$this.removeClass(aInActiveTabClass);
				$this.addClass(aActiveTabClass);
				$.each( $(".hideWhenInactive", $this), function(obj){
					$(this).css('display', '');
				});
			}
		}
	});

	$.each( $("#" + aContentContainer + " > *[@class*=tabPanel]"), function(obj){
		var $this = $(this);
		if($this.css('display') != 'none' && $this.attr('id') != aTab) {
			$this.hide();
		}
	});

	if($("#"+aTab).css('display') == 'none'){
		$("#"+aTab).fadeIn("fast", function(){ 
			$('#'+aTab).css('position', 'relative'); // WebKit fix
			loadingTab = false; 
		});
	}
	return false;
}



/**
 * The current image
 */
var cbsCurrentImage = 1;


/**
 * Toggles direction of image sequence based on param
 * @param aDir {String} The direction ('previous', 'next')
 */
function toggleImage(dir){
	if(dir == 'next' && (cbsCurrentImage) < cbsPhotos.length){
		goToImage(cbsCurrentImage+1);
	}
	else if(dir == 'previous' && (cbsCurrentImage) > 1){
		goToImage(cbsCurrentImage-1);
	}
	else if(dir == 'previous' && (cbsCurrentImage) == 1){
		goToImage(cbsPhotos.length);
	} else {
		goToImage(1);
	}
	return false;
}


/**
 * Loads the image/text for aNum
 * @param aNum {Integer} The index of the image to load
 */
function goToImage(aNum){
	cbsCurrentImage = aNum;
	imageLinks(aNum);
	aNum--;
	var img = cbsPhotos[aNum];
	if(img.alt){ 
		alt = img.alt; 
	} else { 
		alt = ''; 
	}
	return changeImage(img.url, alt, img.text);
}


/**
 * Changes Image/Text to the specified image and Text
 * @param aCurr {Integer} The current Image Number
 */
function changeImage(aImg, aAlt, aTxt){
	var $imgTag = $('#photoImg');
	var $imgDiv = $('#photoBox');
	$imgDiv.width( $imgTag.width() );
	$imgDiv.height( $imgTag.height() );

	$imgTag.hide();
	$imgTag.attr('src', aImg);
	$imgTag.attr('width', 244);
	//$imgTag.attr('height', 183);
	$imgDiv.height('');

	$imgTag.attr('alt', aAlt);
	$imgTag.attr('title', aAlt); // Firefox shows title per html4 sec 13.8.

	$('#photoTxt').html(aTxt);
	$imgTag.fadeIn("medium");
}


/**
 * Generates a string of html image links to a particular image and inserts to id=photoLinks
 * @param aCurr {Integer} The current Image Number
 */
function imageLinks(aCurr){
	var linkml = '';

	for(var i=1; i < cbsPhotos.length+1; i++){
		if(i == aCurr){
			linkml += '<strong class="bodysmall" style="color: #99A;">'+ i +'</strong>';
		} else {
				linkml += ' <a class="linksmall" href="#" onclick="goToImage(' + i + '); return false;">'+ i +'</a>';
		}
		if(i < cbsPhotos.length){
			linkml += ' | ';
		}
	}
	$("#photoLinks").html(linkml);
}


/* lock variable */
var mediaStripLock = false;


/**
 * Media Strip - Next Prev
 * Increments, decrements as appropriate for the object
 * @param aObj {DOM Object} The controller (this)
 * @param aDir {Integer} The direction you wish to go [1 = forward, <1 = backwards]
 */
function mediaStripNextPrev(aObj, aDir){
	$mediaStrip = $(aObj).parent().parent();
	var total = $('.scroller a.mediaScrollPage ', $mediaStrip).size();
	$mediaStrip = $('div.mediaContentFrame' , $mediaStrip);
	var pos = mediaStripCPos($mediaStrip);
	var nPos;
	
	// nPos = new position
	if(aDir > 0){ nPos = pos+1; } else { nPos = pos-1; }
	
	if(nPos < 1 && aDir < 1){
		mediaStripScroll(aObj, total);
		return false;
	}
	else if(nPos > total && aDir > 0){
		mediaStripScroll(aObj, 1);
		return false;
	}
	mediaStripScroll(aObj, nPos);
	return false;
}


/**
 * Media Strip - Current Position
 * Gets the current position (integer page #)
 * @param aObj {jQuery Object} The media strip set
 */
function mediaStripCPos(aObj){
	if(!aObj.attr('rel')){
		return 1;
	}
	return parseInt(aObj.attr('rel'));
}


/**
 * Media Strip - Update Scroller
 * Updates scroller controls
 * @param aObj {DOM Object} The controller (this)
 * @param aPos {Integer} The position you wish to go to (1-x)
 */
function mediaStripUpdateScroller(aMediaStrip, aPos){
	var on = 'on.gif';
	var off = 'off.gif';
	var url = 'http://'+news_image_host+'.cbsnews.com/common/images/v3/misc_multimedia_';
	var j = 1;
	$('.scroller a.mediaScrollPage ', aMediaStrip).each(function(i){
		var $this = $(this);
		if(j == aPos){
			$('img', $this).attr('src', url + on);
		} else {
			$('img', $this).attr('src', url + off);
		}
		j++;
	})
}


/**
 * Media Strip - Scroll
 * Handles scrolling of 1 page at a time, with locking mechanism
 * @param aObj {DOM Object} The controller (this)
 * @param aPos {Integer} The position you wish to go to (1-x)
 */
function mediaStripScroll(aObj, aPos){
	// Locking
	if(mediaStripLock){ return false; }
	mediaStripLock = true;

	$mediaStrip = $(aObj).parent().parent();
	$ms = $mediaStrip;
	$mediaStrip = $('div.mediaContentFrame' , $mediaStrip);
	$mediaStripMedia = $('div.mediaContentStrip', $mediaStrip);
	
	// Calculate frame width
	$fItem = $('li:first', $mediaStripMedia);
	var newPos = 0;
	do{
		newPos = newPos + $fItem.width();
	} while (newPos < $mediaStrip.width() - $fItem.width());
	
	// Fix drifting
	newPos -= 2;
	
	// Add the margin/padding back in
	var buff = cssToInt($mediaStrip.css('margin-left'))
				+ cssToInt($mediaStrip.css('margin-right'))
				+ cssToInt($mediaStrip.css('padding-left'))
				+ cssToInt($mediaStrip.css('padding-right'));
	newPos += buff;
	
	// Save Position for future reference
	$mediaStrip.attr('rel', aPos);
	mediaStripUpdateScroller($ms, aPos)
	
	if(aPos <= 1){
		scrollToPos($mediaStripMedia, 0);
	} else {
		scrollToPos($mediaStripMedia, newPos * (aPos-1));
	}
	return false;
}


/**
 * CSS to Integer
 * converts a css value to an integer
 * @param aVal {String} The pixel length string (ex. 3px)
 */
function cssToInt(aVal){
	return parseInt(aVal.replace('px', ''));
}


/**
 * Scroll to position
 * Scrolls to the new position
 * @param $obj {jQuery Object} The object to scroll
 * @param aNewPos {Integer} The new position (px)
 */
function scrollToPos($aObj, aNewPos){
	var speed = 400;
	var interval = 12;
	var cPos = $aObj.scrollLeft();
	var dir = 1; // default to 1 (rtl)

	if(cPos == aNewPos){
		return false;
	}
	else if(cPos > aNewPos){
		dir = 0;
	}
	var move = setInterval(function(){
		cPos = $aObj.scrollLeft();
		if(cPos < aNewPos && dir == 1){
			newPos = cPos + (speed/interval);
			if(newPos > aNewPos){
				newPos = aNewPos;
			}
			$aObj.scrollLeft(newPos);
		} else if(cPos > aNewPos && dir == 0){
			newPos = cPos - (speed/interval);
			if(newPos < aNewPos){
				newPos = aNewPos;
			}
			$aObj.scrollLeft(newPos);
		} else {
			mediaStripLock = false;
			clearInterval(move);
		}
	}, speed/interval);
}


/**
 * Get Comment Counts
 * @req cbsVar_tmpl must be set
 */
function getCommentCounts(){
	var commentCountsTags = new Array();
	var commentCountsRequest = '';
	var $this;
	var id; var requestId; var $span; var val; var now; var entryDate; var open;

	var commentIcon = '<img src="http://' +news_image_host+ '.cbsnews.com/common/images/v3/icon_comment.gif" alt="Comments" class="commentIcon inlineIcon">';

	$.each( $('.commentCount'), function(obj){
		$this = $(this);
		id = $this.attr('id');
		//console.log('the id', id);
		if(!id.indexOf('-')){
			requestId =  id;
		} else {
			requestId = ( id.substr(id.indexOf('-')+1, id.length) );
		}
		commentCountsRequest += requestId +  ',';
		commentCountsTags.push( Array(id, requestId) );
		return;
	});
	commentCountsRequest = commentCountsRequest.substr(0,commentCountsRequest.length-1);
	
	$.getJSON("/msgboard/htmlc/content/comment_count.sphp",
		{ assets: commentCountsRequest, type: cbsVar_tmpl},
		function(json){
 			for(var i=0; i<commentCountsTags.length; i++){

				$span = $('#'+commentCountsTags[i][0]);
				//console.debug(commentCountsTags[i][1], $span.attr('class'));
				if( typeof(json[ commentCountsTags[i][1] ]) == 'undefined'){
					val = 0;
				} else {
					val = json[ commentCountsTags[i][1] ];
				}

				// If a blog, Is it open?
				if(cbsVar_tmpl == 'blogsection'){
					now = new Date();
					entryDate = new Date($span.attr('rel'));
					if (entryDate.getTime() > now.getTime()-3*24*60*60*1000) {open = true}
					else{open = false}
				}
				
				// Comments Txt
				if( $span.attr('class').indexOf('commentCountText') != -1 && val > 0){
					//console.debug('comments text');
					$span.html ( 'Comments ' + commentIcon + ' ' + val );

				// Blog Txt
				} else if( $span.attr('class').indexOf('commentCountBlogText') != -1 ){
					//console.debug('blog comments text', open, val);
					if(open && val == 0) {
						$span.html ( commentIcon + " Comment On This Post" );
					} else {
						$span.html ( 'Comments  ' + commentIcon + '<em>' + val + '</em>');
					}
				// Blog Std
				} else if( $span.attr('class').indexOf('commentCountBlog') != -1 ){
					//console.debug('blog comments std', open, val);
					if(open && val == 0) {
						$span.html ( "Comment On This Post" );
					} else {
						$span.html ( commentIcon + ' <em>' + val + '</em>');
					}
					
				} else if( $span.attr('class').indexOf('commentCountVideoText') != -1 ){
					if(val > 0) {
						$span.html ( 'Comments: <strong class="linksmall" title="Read Comments">' + val + '</strong>' );
					}
				// Comments
				} else {
					//console.debug('comments std');
					if(val > 0) {
						$span.html ('&nbsp;|&nbsp;' + commentIcon + '<span class="smallhead_black">' +  val + '</span>');
					}
				}
			}
		}
	);
}


var gVideoInPlay;
var gPlayerName = 'rcpHolder';
var gPopUrl = 'http://' + news_host + '.cbsnews.com/sections/i_video/main500251.shtml?id=';
var gNextVid = false;
var gPlayerInMotion = false;


function getVideo(aVid){
	for (var i in embeddedVideos) {
		if(i == aVid){
			return embeddedVideos[i];
		}
	}
	alert("Sorry, this video is unavailable right now.");
	return false;
}


function playNewEmbeddedVideo(aVid){
	gVideoInPlay = getVideo(aVid);
	return playerLoadEmbedObj(gVideoInPlay, true);
}

/**
 * Play Flash Video 
 * @param aObj {Object} Video Object
 * @global gVideoInPlay Video Object
 */
function playEmbeddedVideo(aVid){
	gVideoInPlay = getVideo(aVid);
	return playerLoadEmbedObj(gVideoInPlay, true);
}


/**
 * Set Active Video
 * @param aObj {Object} Video Object
 */
function videoSetActiveVideo(aVidCont, aVid){
	$(document).ready(function(){
		playerMakeClickable(aVidCont, aVid);
	});
}

function restartVideoPlayer(){
	// When video is in background tab in non-ie video stops.  When brought back to front it will need to have
	// video ID passed back in.
	setTimeout(function(){
		if(!$.browser.msie && gVideoInPlay){
			playerLoadEmbedObj(gVideoInPlay, false);
		}
	}, 300);
	return false;
}


/**
 * Load Flash Video - internal
 * @param aObj {Object} Video Object
 * @param aPlayback {Boolean} Play imediately
 */
function playerLoadEmbedObj(aObj, aPlayback){
			
	gNextVid = true;

	$('#videoAd').html('');
	
	// Update metadata
	playerUpdateMetadata(aObj.title, aObj.description);
	
	// Show Video Image
	playerSwapThumb(aObj.videoContainerId, aObj.videoImage, aObj.cropClass);
	
	$vm = $('#' + aObj.videoContainerId + ' .videoMask');
	playerMakeClickable(aObj.videoContainerId, aObj.videoId);
	
	// If no media id, or defined to pop only, we can pop the player and leave.
	if(!aObj.flashId || aObj.flashId == '' || gVideoInPlay.popOnly == true){

		if(document.getElementById(gPlayerName) && $('#'+aObj.videoObjectContainer).css('display') != 'none'){

			// If a video is playing, pause it
			videoPlayerObj(gPlayerName).pause();

			gNextVid = false;

			// Hide Player in this case
			showPlayerObject(aObj.videoContainerId, false);
			$('#'+aObj.videoObjectContainer).html('');
			
			// if an companion ad is showing, hide it
			if($('#videoAd').css('display') != 'none'){
				closeVideoCompanionAd();
			}
		}

		// Pop and leave
		if(aPlayback){
			linkTo({'href': gPopUrl + aObj.videoId});
		}
		return false;
	}

	// Show Object / Hide Controls & Image
	showPlayerObject(aObj.videoContainerId, true);

	// If a player is already loaded, reuse it
	//COMMENTING OUT FOR TESTING
	/*if(document.getElementById(gPlayerName) && $('#'+aObj.videoObjectContainer).css('display') != 'none'){
		var playParam = playerBuildFlashVar(aObj.flashId);

		// Delay slightly in non-ie to ensure it's loaded all the way
		setTimeout(function(){
			gPlayerInMotion = true;
			videoPlayerObj(gPlayerName).extPlay(playParam);
		}, 400);
		return false;

	}*/
	
	// Otherwise create a new flash player
	//var so = new SWFObject("http://www.cbs.com/thunder/swf/rcpHolderCbs-News.swf", gPlayerName, "244", "216", "9", "#000000");   /*old player rcpHolderCbs-3.swf*/
	var so = new SWFObject("http://www.cbs.com/thunder/swf/rcpHolderCbs-Newsv2a.swf", gPlayerName, "243", "222", "9", "#000000");

	$('#'+aObj.videoContainerId).css('background-image', 'none');
	
	// In case of a situation with no flash player or it's ancient
	if(so.installedVer.major <6){ 
		showFlashNotValidError(aObj.videoContainerId);
		return false;
	}
	
	// Use Express Install for more recent, but still old versions
	if(!aObj.expressInstall || aObj.expressInstall == false){
		so.useExpressInstall('/common/embedplayer/swf/expressinstall.swf');
	}

	// Flash params
	so.addParam("name", gPlayerName);
	so.addParam("quality", "high");
	so.addParam("wmode", "opaque");
	so.addParam("scale", "noorder");
	so.addParam("autoplay", "false");
	so.addParam("allowScriptAccess", "always");
	so.addParam("allowFullScreen", true);
	//so.addParam('FlashVars', 'autoPlayVid=false');
	so.addParam('FlashVars', 'releaseURL=' + playerBuildFlashVar(aObj.flashId));

	so.write(aObj.videoObjectContainer);

	gPlayerInMotion = true;
	
	// Delay slightly in non-ie to ensure it's loaded all the way
/*
	setTimeout(function(){
		if(!videoPlayerObj(gPlayerName)){

			// no recursion since we will only have 1 retry
			setTimeout(function(){
				videoPlayerObj(gPlayerName).extPlay( playerBuildFlashVar(aObj.flashId) );
			}, 3000);
		}
		videoPlayerObj(gPlayerName).extPlay( playerBuildFlashVar(aObj.flashId) );
	}, 300);

*/

	//videoPlayerObj(gPlayerName).extPlay();
	return false;
}

function hello(){
	if(!$.browser.msie){
		$('#'+gPlayerName).attr('FlashVars', 'autoPlayVid=false');
	}
}


function onVideoStop(object) {
	gPlayerInMotion = false;
}

/**
 * Makes video click-and-play-able
 * @param aVm {DOM ID} object to add event to 
 * @param aVid {Video ID} video ID
 */
function playerMakeClickable(aVm, aVid){
	$aVm = $('#' + aVm + ' .videoMask')
	$aVm.unbind();
	$aVm.css('cursor', 'pointer');
	$aVm.click(function(){ playEmbeddedVideo( 'v' + aVid ) });

}


/**
 * Replace Thumbnail on player
 * @param aDiv {String} id of player
 * @param aImage {String} image url
 * @param aClass {String} class to apply to div
 */
function playerSwapThumb(aDiv, aImage, aClass){
	$div = $('#'+aDiv + ' .videoImage');

	$div.css('background-image', 'url(' + aImage + ')');
	if(aClass){
		$div.addClass(aClass);
	} else {
		$div.removeClass('resize');
	}
}


function showFlashNotValidError(aDiv){
	$div = $('#'+aDiv + ' .videoObject');
	$div.css('background-color', '#000');
	$.ajax({
		type: "POST",
		url: "/common/embedplayer/flashError.html",
		success: function(msg){
			$div.html( msg );
		}
	});

	showPlayerObject(aDiv, true);
}


/**
 * Shows actual player
 * @param aShow {Boolean} true= show player / hide video mask, false = hide player / show video mask
 */
function showPlayerObject(aPlayer, aShow){
	$videoMask = $('.videoMask', '#' + aPlayer);
	$videoObject = $('.videoObject', '#' + aPlayer);
	if(aShow){
		$videoMask.hide();
		$videoObject.show();
		return true;
	}
	$videoMask.show();
	$videoObject.hide();
//	$videoObject.html('');
	$('#'+aPlayer).attr('position', 'relative'); // webkit fix
	return true;
}


/**
 * playerUpdateMetadata
 * @param aTitle {String} A title to populate
 * @param aDescription {String} A description to populate
 */
function playerUpdateMetadata(aTitle, aDescription){
	$('#videoBox .subhead').html(aTitle);
	$('#videoBox .caption').html(aDescription);
}


/**
 * Build Flash Var 
 * @param aPid {String} Video PID
 */
function playerBuildFlashVar(aPid){
	var base = 'http://release.theplatform.com/content.select?pid=%PID%&amp;Tracking=true&amp;Embedded=True&partner=news&Portal=Cypress%20Feed&playerName=cbsNewsStoryEmbed&Tracking=True';//&autoPlayVid=false
	var re = new RegExp('%PID%', 'gi');
	return base.replace(re, aPid);
}



/**
 * Video Player Object
 * @param movieName {String} Name of video Object
 */
function videoPlayerObj(movieName) {
	if (navigator.appName.indexOf("Microsoft") != -1) {
		return window[movieName];
	}
	return document[movieName];
}

	
/**
 * On Ad Start 
 * @param aSrc {String} src for img
 * @param aUrl {String} url for link
 * @author raccettura
 */
function setExternalAd(aSrc, aUrl){
	$videoAd = $('#videoAd');
	$videoAd.html('<a href="' + aUrl + '" target="_blank"><img src="' + aSrc + '" alt="Advertisement" /></a>');
	if($videoAd.css('display') == 'none'){
		$videoAd.slideDown("slow");
	}
	//  Note: closed in onVideoEnded()
}


function onVideoStart(){
	gNextVid = false;
}


/**
 * On Video Ended 
 * @global gVideoInPlay {Object} Video Object
 */
function onVideoEnded(){
	if(!gNextVid){

		// Don't do this in the actual callback or you'll crash browsers
		setTimeout(function(){ 
			showPlayerObject(gVideoInPlay.videoContainerId, false);
			
			gPlayerInMotion = false;

			closeVideoCompanionAd();
	
		}, 10)	
	}
}


/**
 * Close Video Companion Ad
 */
function closeVideoCompanionAd(){
	$('#videoAd').slideUp("slow", 
		function(){
			$('#videoAd').html('');
		}
	);
}


/*
function playNextVideo(aVid){
	var nextVid = nextVideo(aVid);
	return playNewEmbeddedVideo(nextVid);
}


function nextVideo(aVid){
	var next = false;
	for (var i in embeddedVideos) {

		// If this is the next one
		if(next){
			return i;
		}

		// If this is the current one
		if(i == aVid){
			next = true;
		}
	}

	// Return the first one
	for (var i in embeddedVideos) {
		return i;
	}
}
*/

/**
 * Wildcard
 * @param aWidth {Integer} The desired width
 * @param aHeight {Integer} The desired height
 * @param aColor {String} The desired color
 * @author cnevers
 */
function wildcard(aWidth, aHeight, aColor){
	document.write('<table width="'+ aWidth +'" height="'+ aHeight +'" bgcolor="'+ aColor +'"><tr>');
	document.write('<td>wildcard</td>');
	document.write('</tr>');
	document.write('</table>');
}


/************************* Legacy ************************/

/**
 * Return current time
 */
function currentTime(){
	var the_date = new Date();
	var the_minutes = the_date.getMinutes();
	var the_hour = the_date.getHours();

	// Fix Hour
	if (the_hour >12) {
		the_hour = eval(the_hour - 12);
	}
	else if(the_hour == 0) {
		the_hour = eval(the_hour+12)
	}

	// Fix Time
	if ((the_minutes <10) && (the_date.getHours()<=11)) {
		the_minutes = "0" + the_minutes + "am";
	}
	else if ((the_minutes >=10) && (the_date.getHours()<=11)) {
		the_minutes = the_minutes + "am";
	}
	else if ((the_minutes >=10) && (the_date.getHours() >= 12)) {
		the_minutes = the_minutes + "pm";
	}
	else if ((the_minutes <10) && (the_date.getHours() >= 12)) {
		the_minutes = "0" + the_minutes + "pm";
	}
	return the_hour + ":" + the_minutes;
}


/**
 * Return current Date
 */
 function day()
{
	if(the_day < 10)
	{
		return "0"+the_day;
	}
	return the_day;
}
 
 	var month;
	var the_date = new Date();
	var the_day = the_date.getDate();
	var the_month = the_date.getMonth();
	var the_year = the_date.getFullYear();
function currentDate(){
	month = new Array('Jan.','Feb.','March','April','May','June','July','August','Sept.','Oct.','Nov.','Dec.');
	return month[the_month]+" " +the_day +", " + the_year;
}


/**
 * Return current Time
 */
function printCurrentDateTime(){
	document.write(currentDate() + " " + currentTime());
}


/**
 * Launch url in popup
 */
function launch(pageTitle,w,h,address) {
	newWin = window.open("",pageTitle,'width='+w+',height='+h+',status=no,toolbar=no,scrollbars=no')
	newWin.location = address;
	return false;
}


/*this will be our primary cookie function to be used to story all types of interesting stuff*/
var cookieString = document.cookie;
var today = new Date(); 
var cookieExpires = new Date(today.getTime() + 712 * 24 * 60 * 60 * 1000); // plus 30 day
var deletecookieExp = new Date(today.getTime() - 72 * 60 * 60 * 1000);  //
var cookiePath = ";Path=/"; 
  
  
/**
 * Get cookie value
 * @param name {String} Name of the cookie
 */
function getCookieValue(name) { 
	var index = cookieString.indexOf(name + "="); 
	if (index == -1) return null; 
		index = cookieString.indexOf("=", index) + 1; 
	var endstr = cookieString.indexOf(";", index); 
	if (endstr == -1) endstr = cookieString.length; 
		return unescape(cookieString.substring(index, endstr)); 
}


 
/**
 * Delete cookie value
 * @param {String} name Name of the cookie
 */
function deleteCookie(name){
	value = escape(name); 
	document.cookie=name + "=null; expires=" + deletecookieExp.toGMTString();
	cookieString = document.cookie;
}


/**
 * Set Cookie Value
 * @param {String} cookieName Name of the cookie
 * @param {String} cookieValue Value of the cookie
 */
function setCookie(cookieName, cookieValue){ 
	if (cookieValue != null && cookieValue != "")
		cookieValue = escape(cookieValue); 
	document.cookie=cookieName + "=" + cookieValue + "; expires=" + cookieExpires.toGMTString() + cookiePath;
	cookieString = document.cookie;
}


/** 
 * OutBound Link
 * @param tag {dom object} The href tag
 */
function OutBound(tag){
	var pos = tag.indexOf("story="); 
	var pos2 = tag.indexOf("&h=");
	var l = tag.substring(pos2, pos+12);/*sendToOmniture(tag.substring(l));*/
	var newWin = window.open(tag);
	return false;
	newWin.focus();
}


/**
 * The amazing linkTo
 * @param tag {DOM Object} The href tag (normally 'this')
 */
function linkTo(tag) {
	/*****************check link tag and determine output of file*****************/

	//if tag structure has javascript launch the javascript
	if (tag.href.indexOf("javascript:") !=-1) {//filter out url from javascript if index of showbuzz. this way it will open new window instead of popup window
		if(tag.href.indexOf('PopUp') > 0){
		var i = tag.href.split("'");
		var iUrl = i[1].split("'");
		var newWin = launch('CBSNewsInteractive', 740, 570, iUrl[0]);
		return false;
		newWin.focus();
		}else{
		return true;
		}

	}

/*
change cchamberlain: 
chande line 1244: from indexOf("/video") to just indexOf("500251"))
05052008
*/
	if((tag.href.indexOf("500251") > 0) && (tag.href.indexOf('/videoarchive') < 0) && (tag.href.indexOf('/video/main') < 0) && (tag.href.indexOf('/i_video/main') < 0) && (tag.href.indexOf('/videoplayer_email') < 0)){
	tag.target="_top";
	return true;				
	}
	else if (tag.href.indexOf(".mp3") > 0) {
		// Audios can be either site
		tag.href = tag.href.replace(news_host+".cbsnews.com/media", "audio.cbsnews.com");
		tag.href = tag.href.replace(buzz_host+".showbuzz.cbsnews.com/media", "audio.cbsnews.com");
		tag.href = tag.href.replace(buzz_host+"showbuzz.cbsnews.com/media", "audio.cbsnews.com");
		tag.target = "_new"; 
		return true;
	}
	
	else if(tag.href.indexOf("/external/story.php?story=") > 0 ){	
			var pos = tag.href.indexOf("destination="); 
			var pos2 = tag.href.indexOf("&h=");
			var l = tag.href.substring(pos2, pos+12);sendToOmniture(tag.href.substring(l));
			tag.target = "_new";
			return true			
	}
	else if(tag.href.indexOf("/link/") > 0 ){	
			tag.href = tag.href.replace(news_host+".cbsnews.com/", news_host+".cbsnews.com/external/story.php?story=");
			if(tag.href.indexOf("/link/blog") > 0){
			tag.target = "_top";
			return true
			}
			tag.target = "_new";
			return true			
	}
	/*else if (tag.href.indexOf("/videoarchive") > 0) {
		var pos = tag.href.indexOf(".shtml");
		var pos2 = tag.href.indexOf("_1_");
		var archiveStr = tag.href.substring(pos+15, pos2);
		tag.href = tag.href.substring(0, pos) + "_1_videosection_page.shtml";//http://www.cbsnews.com/sections/i_video/main500251_1_videosections_page.shtml
		tag.href = tag.href.replace("cbsnews.com", "cbsnews.com/sections/i_video/main500251.shtml?channel=");
		
		return true;
		//http://www.cbsnews.com/sections/i_video/main500251.shtml?channel=/elements/2006/05/22/world/videoarchive1639012_1_videosection_page.shtml
		http://www.cbsnews.com/elements/2006/05/22/world/videoarchive1639012_1_videosection_page.shtml
	}*/
	else if (tag.href.indexOf("/elements") > 0){
		if (tag.href.indexOf("showbuzz.cbsnews") < 0 && document.location.href.indexOf("/elements") > 0){
			if(tag.href.indexOf('videoarchive') > 0){
				tag.href = tag.href.replace(".shtml", "_1_videosection_page.shtml");
				tag.href = tag.href.replace(news_host+".cbsnews.com", news_host+".cbsnews.com/sections/i_video/main500251.shtml?channel=");
				
				/*var newWin = launch('CBSNewsVideo', 995, 685, tag.href);
				return false;
				newWin.focus();*/
				tag.target = "_top";					
			}else{
			var newWin = launch('CBSNewsInteractive', 740, 570, tag.href);
			return false;
			newWin.focus();				
			}
		}
		else if(tag.href.indexOf("showbuzz.cbsnews") > 0  && document.location.href.indexOf("/elements") < 0){
			var newWin = launch('CBSNewsInteractive', 740, 570, tag.href);
			return false;
			newWin.focus();	
		}
		else if( tag.href.indexOf("videoarchive") > 0 && tag.href.indexOf("i_video") > 0 ){
			/*var newWin = launch("CBSNewsVideo", 995, 685, tag.href);
			return false;
			newWin.focus();*/
			tag.target = "_top";
		}
		else if( tag.href.indexOf("videoarchive") > 0 && tag.href.indexOf("i_video") < 0 ){
			tag.href = tag.href.replace(".shtml", "_1_videosection_page.shtml");
			tag.href = tag.href.replace(news_host+".cbsnews.com", news_host+".cbsnews.com/sections/i_video/main500251.shtml?channel=");
			
			/*var newWin = launch('CBSNewsVideo',995, 685, tag.href);
			return false;
			newWin.focus();*/
			tag.target = "_top";				
		}
		else 
		{
			var newWin = launch('CBSNewsInteractive', 740, 570, tag.href);
			return false;
			newWin.focus();
		}

	}
	else if (tag.href.indexOf("showbuzz.cbsnews") > 0){
		tag.target = "_new";
		return true;
	}
	else if (tag.href.indexOf(news_host+".cbsnews") > 0 && document.location.href.indexOf("/elements") < 0){
		if( tag.href.indexOf("/i_video") > 0)
		{
			/*var newWin = launch('CBSNewsVideo',995, 685, tag.href);
			return false;
			newWin.focus();*/
			tag.target = "_top";
		}
		else
		{
		tag.target = "_top";
		return true;
		}
	}
	else if(tag.href.indexOf("/video") > 0  && (tag.href.indexOf('/videoplayer_email') < 0))
	{
		/*var newWin = launch('CBSNewsVideo',995, 685, tag.href);
		return false;
		newWin.focus();*/
		tag.target = "_top";
		return true;
	}
	else
	{
		tag.target = "_new";
		return true
	}
	/*****************END check link tag and determine output of file*****************/
}


/**
 * Link To No Href (same as above, but for non-a elements)
*/
function linkToNoHref(tag){
	if(linkTo(tag) == true){
		document.location.href = tag.href;
	}
	return false;
}
	

/**
 * SendToOmniture
 * @param l {string} outbound url href
*/
function sendToOmniture(l){
	s.linkTrackVars='prop50';
	s.linkTrackEvents='None';
	s.prop50=l;
	s.tl(this,'o',l);
}

/* Popup code */
/* Generic popup implementation - jq interm version */
function cbsPopup(id){
	this.id = id; return false;
};

cbsPopup.prototype = {

	open: function(url){
		this.url = url;
		this.host = window.location.hostname;

		var xmlDocument;
		if(!document.getElementById(this.id)){
			document.popupId = this.id;
			$.ajax({
				url: 'http://' + this.host + '/common/popups/' + this.id + '.xml',
				type: 'GET',
				dataType: 'xml',
				timeout: 1000,
				error: function(e){
					alert('Sorry.  We can\'t process your request right now.');
				},
				success: function(xml){
					var supPop = new cbsPopup;
					supPop.url = url; 
					supPop.id = document.popupId;
					document.popupId = null;
					supPop.buildPopup(xml);
        		}
			});
		}
		return false;
	},

	close: function(obj){
		var $outerFrame = $(obj).parent().parent(); //.parent().parent();
		$('#' + $outerFrame.attr('id').replace(/_header/i, '_shim')).remove();
		$outerFrame.parent().parent().remove();
		return false;
	},

	buildPopup: function(response){
		var doc = response;
		var iframe = false;
		var footer = false;
		var type = 'L';
		var contentHeight = null;

		if(this.getNode('url', doc) && this.getNode('url', doc).firstChild){
			iframe = true;
		}

		if(this.getNode('footer', doc) && this.getNode('footer', doc).firstChild){
			footer = true;
		}

		if(this.getNode('type', doc) && this.getNode('type', doc).firstChild){
			type = this.getNode('type', doc).firstChild.data;
			if(type == 'L'){ type = ''; }
		}
		
		if(this.getNode('contentHeight', doc) && this.getNode('contentHeight', doc).firstChild){
			contentHeight = this.getNode('contentHeight', doc).firstChild.data;
		}
		
		var frame = this.genPopup(footer, iframe, type, contentHeight);

		// iFrame URL

		if(this.url){
			this.gebid(this.id+'_frame').src = this.url;
			//this.gebid(this.id+'_frame').contentWindow.document.body.style.border = 0;
		}
		else if(this.getNode('url', doc) && this.getNode('url', doc).firstChild){
			this.gebid(this.id+'_frame').src = this.getNode('url', doc).firstChild.data;
		} else {

			if(this.getNode('content', doc) && this.getNode('content', doc).firstChild){
				this.gebid(this.id+'_content').innerHTML = this.getNode('content', doc).firstChild.data;
			}
		}

		if(this.getNode('footer', doc) && this.getNode('footer', doc).firstChild){
			this.gebid(this.id+'_footer').innerHTML = this.getNode('footer', doc).firstChild.data;
		}

		if(this.getNode('header', doc) && this.getNode('header', doc).firstChild){
			this.gebid(this.id+'_header').innerHTML = this.getNode('header', doc).firstChild.data;
		} else {
			this.gebid(this.id+'_header').innerHTML = '&nbsp;'; // should be 1 char space if nothing
		}

		var scrollX = 0, scrollY = 0;
		if(document.body.scrollTop){
			scrollX = document.body.scrollLeft;
			scrollY = document.body.scrollTop;
		} else if (document.documentElement){
			scrollX = document.documentElement.scrollLeft;
			scrollY = document.documentElement.scrollTop;
		} else {
			scrollX = window.pageXOffset;
			scrollY = window.pageYOffset;
		}

		var wX =0,  wY = 0;
		if(document.all){
			wX = document.body.offsetWidth;
			wY = document.body.offsetHeight;
		} else {
			wX = window.innerWidth
			wY = window.innerHeight;
		}
		var y = scrollY + (wY/2) - (frame.clientHeight/2);
		var x = scrollX + (wX/2) - (frame.clientWidth/2);
		
		frame.style['position'] = 'absolute';
		
		// Move off center
		y =  scrollY + 150;
		x = scrollX + 125;

		frame.style.top = y + 'px';
		frame.style.left = x + 'px';
		frame.style.zIndex = 101;

		// IE fix
		if($.browser.msie &&  $.browser.version < 8){
			var shim = document.body.appendChild(document.createElement('iframe'));
			shim.setAttribute('id', frame.id + '_shim');
			shim.src = 'about:blank';
			shim.frameBorder = 0;
			shim.scrolling = 'no';
			shim.style.position = 'absolute';
			shim.style.top = frame.style.top;
			shim.style.left = frame.style.left;
			shim.style.height = frame.clientHeight+'px';
			shim.style.width = frame.clientWidth+'px';
			shim.style.zIndex = 0;
			shim.style.display = 'block';
			shim.style.filter='progid:DXImageTransform.Microsoft.Alpha(style=0,opacity=0)';
		}
	},

	gebid: function(el){
		return document.getElementById(el);
	},

	getNode: function(n, doc){
		return doc.getElementsByTagName(n)[0];
	},

	genPopup: function(footer, iframe, type, contentHeight){
		if(navigator.userAgent.indexOf("MSIE")!=-1){
			cname = 'className';
		} else {
			cname = 'class';
		}

		// Build out the dom, and assign classes
		var popupFrame = document.body.appendChild(document.createElement('div'));
		popupFrame.setAttribute(cname, 'popupFrame'+type);
		popupFrame.setAttribute('id', this.id);

		var popupHeader = popupFrame.appendChild(document.createElement('div'));
		popupHeader.setAttribute(cname, 'popupHeader');

		var popupHeaderInner = popupHeader.appendChild(document.createElement('div'));
		popupHeaderInner.setAttribute(cname, 'popupHeaderInner');
		popupHeaderInner.setAttribute('id', this.id+'_header');

		var popupContentFrame = popupHeader.appendChild(document.createElement('div'));
		if(iframe){
			var popupContent = popupContentFrame.appendChild(document.createElement('iframe'));
			popupContent.setAttribute('id', this.id+'_frame');
			popupContent.setAttribute('frameborder', '0');
		} else {
			var popupContent = popupContentFrame.appendChild(document.createElement('div'));
			popupContent.setAttribute('id', this.id+'_content');
		}
		popupContent.setAttribute(cname, 'popupContent');

		if(contentHeight != null){
			popupContent.style['height'] = contentHeight;
		}
		
		if(footer){
			// Set the class on content frame now
			popupContent.setAttribute(cname, 'popupContentFrame');

			var popupFooter = popupHeader.appendChild(document.createElement('div'));
			popupFooter.setAttribute(cname, 'popupFooter');
			popupFooter.setAttribute('id', this.id+'_footer');
		} else {
			popupContentFrame.setAttribute(cname, 'popupContentFrameNoFooter');
		}

		// also some css specific to IE to work around IE bugs
		if(document.all && navigator.userAgent.indexOf("Opera") ==-1){
			if (window.XMLHttpRequest) {
				if(type == 'S'){
					document.styleSheets[0].addRule('#'+this.id, "background-image: url(http://"+news_image_host+".cbsnews.com/common/images/v2/popq_shadow.png); background-repeat: no-repeat;");
				}
				else if(type == 'A'){
					document.styleSheets[0].addRule('#'+this.id, "background-image: url(http://"+news_image_host+".cbsnews.com/common/images/v2/answers_shadow.png); background-repeat: no-repeat;");
				} else {
					document.styleSheets[0].addRule('#'+this.id, "background-image: url(http://"+news_image_host+".cbsnews.com/common/images/v2/popup_shadow.png); background-repeat: no-repeat;");
				}
			}
			document.styleSheets[0].addRule('#'+this.id+'_header', "margin: 0px 8px 19px 8px; padding-top: 8px");

			if(footer){
				document.styleSheets[0].addRule('#'+this.id+'_footer', "margin-right: 4px");
			}
		}
		return popupFrame;
	}
};



/**
 * Check URL - debug
 */
function checkUrl() {
	//if(previous_url != story_url){document.location.href=story_url}
	if(previous_url != story_url){
		if(previous_url.match("www.cbsnews.com") && previous_url.match("_page")){
			return true;
		}
		else{
			document.location.href=story_url;
		}
	}

}

/* digg */
eval(function(p,a,c,k,e,d){e=function(c){return(c<a?"":e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--){d[e(c)]=k[c]||e(c)}k=[function(e){return d[e]}];e=function(){return'\\w+'};c=1};while(c--){if(k[c]){p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c])}}return p}('C={9:a(6,4,5,3){B(!6)A;4=4||\'\';5=5||\'\';3=3||\'\';z.y(\'x://w.v/u-t?s=2&6=\'+q(6)+\'&4=\'+7(4)+\'&5=\'+7(5)+\'&3=\'+7(3),k i().j(),\'m=0,n=1,f=0,e=1,r=0,b=1,l=o,8=c,g = p,d = h\')}}',39,39,'|||topic|title|bodytext|url|escape|height|remoteSubmit|function|resizable|400|top|statusbar|location|left|150|Date|getTime|new|width|toolbar|scrollbars|600|470|escape|menubar|phase|submit|remote|com|digg|http|open|window|return|if|Digg'.split('|'),0,{}))


function appendStoryButton(){
	document.write('Find Related: <a class="iconsphere" title="Sphere" onclick="return Sphere.Widget.search()" href="http://www.sphere.com/search?q=sphereit:' + escape(document.location.href) + '"><img src="http://'+news_image_host+'.cbsnews.com/images/2007/03/22/image2595849.gif" border="0" alt="Sphere" height="19" class="inlineIcon" /></a>');
}

/*used on blog, different style and image*/
function appendBlogSphereButton(){
	document.write('Find Related: <a class="blog_small" title="Sphere" onclick="return Sphere.Widget.search()" href="http://www.sphere.com/search?q=sphereit:' + escape(document.location.href) + '"><img src="http://'+news_image_host+'.cbsnews.com/images/2007/03/22/image2596828.gif" border="0" alt="Sphere" align="absmiddle" /> Sphere It</a>');
}

/*************************************************************
Return the offset to eastern time
**************************************************************/
        function getEasternOffset() {
                return 300;
        }

/*************************************************************
        Function for check omniture variables
**************************************************************/
function checkOmniture() {
	var string = "acct = " + s_account + "\n";
	string += "name = " + s.pageName + "\n";
	string += "p1 = " + s.prop1 + "\n";
	string += "p2 = " + s.prop2 + "\n";
	string += "p3 = " + s.prop3 + "\n";
	string += "p4 = " + s.prop4 + "\n";
	string += "p5 = " + s.prop5 + "\n";
	string += "p6 = " + s.prop6 + "\n";
	string += "p7 = " + s.prop7 + "\n";
	string += "p8 = " + s.prop8 + "\n";
	string += "p9 = " + s.prop9 + "\n";
	string += "p10 = " + s.prop10 + "\n";
	string += "p11 = " + s.prop11 + "\n";
	string += "p12 = " + s.prop12 + "\n";
	string += "p13 = " + s.prop13 + "\n";
	string += "p14 = " + s.prop14 + "\n";
	string += "p15 = " + s.prop15 + "\n";
	string += "p16 = " + s.prop16 + "\n";
	string += "p17 = " + s.prop17 + "\n";
	string += "p18 = " + s.prop18 + "\n";
	string += "p19 = " + s.prop19 + "\n";
	string += "p20 = " + s.prop20 + "\n";
	string += "p21 = " + s.prop21 + "\n";
	string += "p22 = " + s.prop22 + "\n";
	string += "p23 = " + s.prop23 + "\n";
	alert(string);
}

function consoleCheckOminture(){
	var string = "acct = " + s_account + "\n";
	for (var i in s) {
		if(typeof(s[i]) == 'string')
			//string += i + ' = ' + s[i] + "\n";
			console.log(i + ' = ' + s[i]);
	}	
	//alert(string);
}

function checkDART() {
	if (typeof(vtag) != "undefined") {
		alert(vtag);
	} else if (typeof(dcTag) != "undefined") {
		alert(dcTag);
	} else {
		alert("unknown");
	}
}

function checkAds(){
	var val = '';
	var i;
	for(i=0; i< gAds.length; i++){
		val += gAds[i] + "\n";
	}
	alert(val);
}


/*******************
 * search
 *******************/
function searchForm(frm, type, loc) {
	var action_web="http://www.cbsnews.com/htdocs/search/websearch.php";  	
	var action_cbs="http://search.cbsnews.com/";
	var action_go = action_cbs;
	var needed_web = new Array('searchString', 'x', 'y', 'num', 'offset', 'advanced', 'section', 'sort', 'type');
	var needed_cbs = new Array('x');
	var id = new String("search" + loc);

	// Web Selected Search
	if (type == "web") {
		pruneInputElements(needed_cbs, id, loc);
		frm.searchString.value = frm.q.value;
		frm.type.value = "all";
		action_go = action_web;		
	}

	// CBS Selected Search
	else // remove web params
	{
		pruneInputElements(needed_web, id, loc);
	}

	frm.action = action_go;
	return true;
}

function pruneInputElements(array, id, loc) {
	var str = "";
	for (var i = 0; i < array.length; i++) {
		elemName = new String(array[i] + loc);
		if (elemName != "") {
			str += elemName;
			//removeElement(id, elemName);
			$('#'+elemName).remove();
		}
		
	}
}

function removeElement(frmElement, inputElement) {
	var d = document.getElementById(frmElement);
	var rd = document.getElementById(inputElement);
	if (rd) { d.removeChild(rd); }
}

/**
 * Swap Powered By Logo
 * @param obj Drop down object
 */
function swapPoweredBy(obj){
	if(obj.value == 'web'){
		$('.searchPoweredBy').html('<a href="http://www.google.com" target="_blank"><img src="http://wwwimage.cbsnews.com/common/images/v3/google_powered.gif" alt="Web Search Powered By Google" vspace="2" class="searchPoweredBy" />');
	} else {
		$('.searchPoweredBy').html('');
	}
}


/**
 * Email Video used in story and pop player
 * @param id = video id, @param title = video title
 * @param section = video section
 * also found in new_video_section.js
 */
function emailVideo(id, title, section) {
	javascript:launch('ShareVideo', 650, 480, "/htdocs/emailtoafriend/videoplayer_share.html?id=" + id + "&section=" + section + "&title="+ title);
}

/**
 * Set Font size changes font size
 * @param obj Object
 * @param n new font size
 */
function setFontSize(o, n){
	setCookie('cbsFontSize', n);
	changeFontSize(n);
	return false;
}

/**
 * Get Font size pref
 */
function getFontSize(){
	var font = parseInt(getCookieValue('cbsFontSize'));
	if(!font || typeof(font) != 'number'){
		changeFontSelector(12)
		return;
	}
	changeFontSize(font);
}

/**
 * Changes font size
 * @param n New Font size
 */
function changeFontSize(n){
	$("#centerColumnContent").css('font-size', n+'px');

	// Make current font diff color		
	changeFontSelector(n);
}

/**
 * Change Font selector
 * @param n New font size
 */
function changeFontSelector(n){
	$('.textSizeSelector a').each(function(){
		$(this).removeClass('fssActive');
		if($(this).hasClass( 'fss'+n+'px' )){
			$(this).addClass('fssActive');
		}
	});
}

/**
 * Story Email
 */
function storyEmail(){
	var headline = $('h1').html();
	var href = '/htdocs/send_article/mostpopular.html?story_headline=' + headline + '$@$;story_url=' + document.location.href;
	new cbsPopup('most_popular_email').open(href); 
	return false;
}

$(document).ready(function(){
	if(typeof cbsVar_tmpl == null || cbsVar_tmpl != 'story'){
		return false;
	}
	
	// Adjust font if needed.  Keep on top.
	getFontSize();

	// Printable             /*Apply bug fix below*/
	/*$('.toolbox_print a').each(function(){
		$(this).attr('href', document.location.href.replace(/\main/, 'printable'));
	});           
	 */
	 
	 $('.toolbox_print a').each(function(){
		var theURL = document.location.href;
			if(theURL.match("_page")){
				theURL = theURL.split("_");
				theURL[0] = theURL[0].replace(/\main/, 'printable');
				$(this).attr('href', theURL[0] + '.shtml');
			}
			else{
				$(this).attr('href', theURL.replace(/\main/, 'printable'));
			}
		});
	 
	// Digg
	var headline = $('h1').html();
	var subHeadline = $('h2').html();
	$('.toolbox_digg a').each(function(){
		$(this).click(function(){
			Digg.remoteSubmit(" + escape(document.location.href) + "," + escape(headline) + "," + escape(subHeadline) + ", '');
			return false;
		});
	});
	
	// Sphere
	$('.toolbox_sphere a').each(function(){
		$(this).attr('href', 'http://www.sphere.com/search?q=sphereit:' + escape(document.location.href));
		$(this).click(function(){
			return Sphere.Widget.search();
		});
	});
});

// AddThis configurations
addthis_pub             = 'mprosellini'; 
addthis_logo            = 'http://wwwimage.cbsnews.com/common/images/v3/logo_cbsnews.gif';
addthis_logo_background = 'FFFFFF';
addthis_logo_color      = '336699';
addthis_brand           = 'CBSNews.com';
addthis_options         = 'favorites, digg, delicious, live, technorati, newsvine, google, facebook, myweb, myspace, more';
addthis_caption_share   = 'Bookmark / Share';
addthis_caption_email   = 'Tell a Friend';
addthis_offset_top      = 3;
addthis_offset_left     = 0;


/*************************
 * Breaking News Reloaded
 * v 3.6
 **************************/

var bnTicker = false;
var bnTickerIndex = 0;
var bnTickerNeedData = true;
var bnTickerAnimX;
var bnTickerAnimY;

/**
 * Check Breaking News
 * Initializes breaking news
 */
function bnCheckBreakingNews(){
	if(!bnTickerMaster) { return false; }
	
	// Don't show on search
	if(document.location.href.indexOf('search.cbsnews.com') == -1 && news_host){
		bnCheckBreakingNewsStart();
	}
}


function bnCheckBreakingNewsStart(){
	// Initial fetch data
	bnTickerGetData();

	// This signifies that it's acceptable to fetch data
	// No fetching is done here so it doesn't interupt a banner mid-cycle.
	// Fetches are done inline as necessary.
	setInterval(function(){ 
		bnTickerNeedData = true; 
	}, (bnTickerInterval * 1000));
}


function bnTickerClose(){
	// If the ticker is active, close it
	if(bnTicker){
		$('#breakingNewsBanner div').slideUp('fast', function(){
			$('#breakingNewsBanner').html('');
			bnTicker = false;
		});
	}
	setTimeout(bnTickerGetData, (bnTickerInterval * 1000) );
}

function bnTickerGetData(){
	if(typeof window.bnTickerGetDataCallback != 'undefined'){
		bnTickerGetDataCallback();
	}

	$.ajax({
		url: "/feedfiles/breakingnews.xml",
		dataType: 'xml',
		success: function(xml){
			var content;
			
			// If it's off, just bail
			if($('cbsNewsTicker', xml).attr('active') != '1'){
				bnTickerClose();
				return false;
			}
			
			// Does it apply to this page?
			var bnRank = $('rank', xml).text();
			if(bnRank != 'global' && !bnTickerRankCheck(bnRank)){
				bnTickerClose();
				return false;
			}

			// Is it on the page yet?  If not, load the skin
			if(!bnTicker){
				bnTicker = true;
				
				// Output skin
				var skin = $('cbsNewsTicker skin', xml).text();
				$('#breakingNewsBanner').html( skin );
			}

			// Content Selector
			var contentSelector = $('cbsNewsTicker refreshableContent', xml).text();
			
			// Inject latest content
			if($content = $(contentSelector)){
				$content.html( $('cbsNewsTicker content', xml).text() );
			}

			if(typeof window.bnTickerGetDataCompleteCallback != 'undefined'){
				bnTickerGetDataCompleteCallback();
			}

			if($('ul.fadingTicker li', $content).size() > 1){
				bnTickerAnimate($content);
			} else {
				$('ul li', $content).show();
				setTimeout(bnTickerGetData, (bnTickerInterval + 1)*1000 );
			}

			bnTickerNeedData = false;
		}
	});
}


function bnTickerRankCheck(aRank){

	// Not global
	if(aRank == 'global'){
		return true;
	}
	
	// Test Section
	if(aRank == 'test' && document.location.href.indexOf('testProduction') != -1){
		return true;
	}

	// Not home
	if(aRank == 'notHome' && 
		(document.location.href != 'http://www.cbsnews.com/' &&
		 document.location.href != 'http://www.cbsnews.com/?source=homepage_refresh' &&
		 document.location.href != 'http://oaktree.cbsnews.com/' &&
		 document.location.href != 'http://cbsnews.com/')
	){
		return true;
	}

	// Sections
	else if(document.location.href.indexOf(aRank + '/main') !== -1){
		return true;
	}
	return false;
}


function bnTickerAnimate($content){

	if(typeof window.bnTickerStartAnimateCallback != 'undefined'){
		bnTickerStartAnimateCallback();
	}
	
	$('ul li:first', $content).fadeIn('slow');
	bnTickerIndex++;

	// Interval between frames
	bnTickerAnimX = setInterval(function(){

		// Fade it all out
		$('ul li', $content).fadeOut('slow');

		// Delay between fade and next frame
		bnTickerAnimY = setTimeout(function(){

			if(typeof window.bnTickerNextItemCallback != 'undefined'){
				bnTickerNextItemCallback();
			}

			$('ul li:eq(' +  bnTickerIndex +')', $content).fadeIn('slow');
			bnTickerIndex++;

			// Reset
			if(bnTickerIndex > $('ul li', $content).size()-1){
				bnTickerIndex = 0;
				
				// Stop for reload
				if(bnTickerNeedData){
					bnTickerStopAnim();
					bnTickerGetData();
				}
			}
		}, 800) // How long between fade and start
	}, 10000); // Interval... make sure this is a bit larger than timeout interval!
}	


function bnTickerStopAnim(){
	clearInterval(bnTickerAnimX);
	clearTimeout(bnTickerAnimY);
}