/**
 * Copyright 2006, Internet Broadcasting Systems. All Rights Reserved.
 * Version:   $Name: REL_2_39_0 $
 * ID:        $Id: base.js,v 1.76 2007/05/07 17:09:44 breisinger Exp $
*/

/* Define namespaces */
var ibsys = {};
var nbcsp = {};

/* Aliases for really long function names */
if(document.getElementsByClassName) {
	var $C = function(className,el) {
		return document.getElementsByClassName(className,el);
	}
}

/* Avoid namespace collisions by using this */
function using(namespace) {
	var parts = namespace.split(/\./);
	var context = window;
	while(parts.length != 0) {
		var obj = parts.shift();
		if(!(obj in context))
			context[obj] = {};
		context = context[obj];
	}
	return context;
}
/***************************************************************
*
* IBSYS.DomLoadedEvent
* 	ibsys.DomLoadedEvent.fire() happens in footer, just before </body></html>
***************************************************************/
ibsys.DomLoadedEvent = {
	add: function(func) {
		this.events.push(func);
		return true;
	},
	fire: function() {
		for(var i = 0; i < this.events.length; i++) {
			try { 
				this.events[i]();
			} catch (e) {};
		}
	},
	events: new Array()
}

/***************************************************************
*
* IBSYS.TABBOX
*
***************************************************************/
using("ibsys.tabbox");
ibsys.tabbox.build = function(sw)
{
	var tbars = document.getElementsByClassName('tbox tabs',sw)[0];
	var boxes = document.getElementsByClassName('tbox contents',sw)[0];
	var ctrls = tbars.getElementsByTagName('a');
	var contents = boxes.childNodes;
	var existingDefaultTab = false;
	for (var ii = 0; ii < ctrls.length; ii++) {
		ctrls[ii].onclick = ibsys.tabbox.display(ctrls,contents,ii);
		if (Element.hasClassName(ctrls[ii].parentNode,"tbox_tab_active"))
		  existingDefaultTab = true;
	}
	for (var ii = 0; ii < contents.length && contents[ii].nodeType != 1; ii++) {
		boxes.removeChild(contents[ii]);
	}
	if (! existingDefaultTab) {
		Element.addClassName(ctrls[0].parentNode,'tbox_tab_active');
		Element.addClassName(contents[0],'tbox_tab_active');
	}
}
ibsys.tabbox.display = function(ctrls,contents,ii)
{
	return function()
	{
		for (var n=0; n<ctrls.length; n++)
		{
			Element.removeClassName(ctrls[n].parentNode,'tbox_tab_active');
			Element.removeClassName(contents[n],'tbox_tab_active');
		}
		Element.addClassName(this.parentNode,'tbox_tab_active');
		Element.addClassName(contents[ii],'tbox_tab_active');
		this.blur();
		return false;
	}
}

/***************************************************************
*
* IBSYS.UTILS
*
***************************************************************/
using("ibsys.utils");

//fix png image alpha transparency, which is broken in <= IE6
ibsys.utils.fixPngImage = function(p) {
	var imgsrc;
	var trans = "http://nbcsports.nbcunifiles.com/spts/files/nbcsports/site/images/spacer.gif";   
	if(typeof p.tested != undefined && !p.tested &&  typeof p.runtimeStyle != 'undefined') {
		// retain image src
		imgsrc = p.src;
		// make sure the image is a PING
		if ( /\.png$/.test( imgsrc.toLowerCase() ) ) {
			// If it is set it to a transparent image
			p.src = trans;
			p.runtimeStyle.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + imgsrc + "',sizingMethod='scale')";
			p.tested = true;
		}
	}
}

// replace tildes with apostrophes
ibsys.utils.fixString = function(strText) {
	var newstr = strText.replace(/~/g, "&#39;");
	return newstr;
}

// Replace white space around tags in teaser
ibsys.utils.padTags = function(s){
	var tmp = s.replace(/(<\w)/ig, " $1");
	tmp = tmp.replace(/(<\/\w>)/ig, "$1 ");
	return tmp;
}

//Open window - pass URL and Attributes
ibsys.utils.popUp = function(URL, ATTRIBUTES)  {
	DEF_ATTRIB = 'width=200,height=200,top=100,left=100,resizable=yes,scrollbars';
	if (ATTRIBUTES == null) {
		ATTRIBUTES = DEF_ATTRIB;
	}
	child = window.open(URL, "spawn", ATTRIBUTES);
}

/***
* Use with pulldown display of index
* 	~ goes to url
* 	~ hides when nav is displaying (IE only)
*/
ibsys.utils.enableIndexPulldown = function(el) {
	Event.observe(el,'change',function() {
		ibsys.utils.redirectIndexPulldown(el);
	},false);
	if(window.navigator.userAgent.toLowerCase().indexOf("msie") != -1) {
		ibsys.DomLoadedEvent.add(function() {
			nbcsp.onNavsShowingEvent.push(function() {
			   el.style.visibility = 'hidden';
			});
			nbcsp.onNoNavsShowingEvent.push(function() {
			   el.style.visibility = 'visible';
			});
		});
	}
}
ibsys.utils.redirectIndexPulldown = function(el) {
	if(el[el.selectedIndex].value == '') {
		return false;
	} else if (el[el.selectedIndex].value.indexOf('NW:') == 0) {
		child = window.open(el[el.selectedIndex].value.substring(3));
	} else {
		window.location.href = el[el.selectedIndex].value;
	}
}


//manage survey form submits
//@type = "survey" 
//@id = coid
//@e = Object EVENT
ibsys.utils.submitFormWithPopupLaunch = function(type,id,e) {
	if (!e) return;
	this.thisForm = window.event ? window.event.srcElement.form : e ? e.currentTarget.form : null;
	if (!this.thisForm) return;
	
	var die = false; //if this is set to true, no submit will take place
	var errorMessage = false;
	var url, params;	
	
	this.isAtLeastOneRadioChecked = function() {
		var isAtLeastOneRadioCheckedFlag = false;
		for(var i=0; i<this.thisForm.length; i++) {
			var input = this.thisForm.elements[i];
			//insure at least one radio widget is checked
			if(input.type == "radio") {
				if(input.checked == true)
					isAtLeastOneRadioCheckedFlag = true;
			}
		}
		return isAtLeastOneRadioCheckedFlag;
	}
	
	//pop up
	if(type == "survey") {
		if(this.isAtLeastOneRadioChecked()) {
			//TODO: aff=?
			url = "/pollresults/" + id + "/detail.html?qs=t;st=" + ibsys.pageProps.sectiontag + ";pollresults=true;aff=";
			params = "toolbar=no,status=no,location=no,menubar=no,top=50,left=50,height=440,width=750,scrollbars=no";
			ibsys.utils.popUp(url,params);
		} else {
			errorMessage = "Please check at least one option."
		}
	}
	
	if(!errorMessage) {
		this.thisForm.submit();
	} else {
		alert(errorMessage);
	}
	return false;
}
/***
* Player profile split column lists
***/
ibsys.utils.profileListSplitCol = function()
{
	var profileListNumCols = 4;
	var profileLists = document.getElementsByClassName('profileList');
	for (var i=0; i < profileLists.length; i++)
	{
		var profileListItems = profileLists[i].getElementsByTagName('li');
		for (var ii=0; ii < profileListNumCols; ii++)
		{
			var newProfileListCol = document.createElement('div');
			newProfileListCol.className = 'profileListSplitCol';
			profileLists[i].appendChild(newProfileListCol);
		}
		for (var ii = 0; ii < profileListItems.length; ii++)
		{
			profileLists[i].getElementsByTagName('div')[Math.floor( (ii / profileListItems.length) * profileListNumCols )].appendChild(profileListItems[0]);
		}
	}
}
/* only load profile list if on players page */
if (window.location.href.match(/_players\/\d+\/feature.html/g)) {
	ibsys.DomLoadedEvent.add(ibsys.utils.profileListSplitCol);
}

// Get elements By Attribute Value  (attribute name, attribute value, tagname, parentElement)
ibsys.utils.getElementsByAttribute = function(att, val, tag, top) {
	var elemArray = new Array();
	if(top.length) {
		for(var e=0; e<top.length; e++){
			if(top[e].getAttribute(att) == val) elemArray.push(top[e]);
		}
	} else{
		if(att=='class' && isIE) var att='className';
		var tag=(tag)?tag:false;
		var top=(top)?top:document;
		if(tag){
			tlist = top.getElementsByTagName(tag);
			for(e=0; e<tlist.length; e++) {
				if (tlist[e].getAttribute(att) == val) {
					elemArray[elemArray.length] = tlist[e];
				}
			}
		}
	}
	return elemArray;
}

// Toggle focus of header search box class in header
ibsys.utils.toggleSearchFocus = function() {
	Event.observe($("searchInput"),'focus',function(){$("searchInput").className="searchInputTextOff";});
	Event.observe($("searchInput"),'blur', function(){if ($F("searchInput") == '') $("searchInput").className="searchInputText";});
};
ibsys.DomLoadedEvent.add(ibsys.utils.toggleSearchFocus);

/***************************************************************
*
* IBSYS.COOKIES
*
* TODO: Clean up coookies script
***************************************************************/
ibsys.Cookies = new Object();
ibsys.Cookies.cookies = new Object();
ibsys.Cookies.host = document.domain;
//Ritesh Changes Begin
 var __tmp = document.domain.split( '.');
 ibsys.Cookies.domain = __tmp[__tmp.length-2] + '.' + __tmp[__tmp.length-1];
// ibsys.Cookies.domain = document.domain ;
//Ritesh Changes End

var tmp = document.cookie.split( '; ');
for( var i=0; i < tmp.length; ++i) {
  try {
		var tmp1 = tmp[i].split( '=');
		if( tmp1[1] == null) tmp1[1] = '';
		ibsys.Cookies.cookies[tmp1[0].toLowerCase()] = tmp1[1];
	} catch( e) {}
}
ibsys.Cookies.get = function( name) {
	if( name == null) return null;
	name = name.toLowerCase();
	if( ibsys.Cookies.cookies && ibsys.Cookies.cookies[name] != null) return ibsys.Cookies.cookies[name];
	return null;
}
ibsys.Cookies.set = function( name, value, expires, domain, path, secure) {
	if( expires == null) {
		var exp = new Date();
		exp.setTime( exp.getTime() + 630720000000);
		expires = exp.toGMTString();
	} else if( expires.charAt( 0) == '+') {
		var exp = new Date();
		exp.setTime( exp.getTime() + (86400000 * expires)); // 10 days in the future
		expires = exp.toGMTString();
	}
	if( domain == null || domain == 'undefined' || domain == 'domain') domain = this.domain;
	else if( domain == 'host') domain = this.host;
	if( path == null) path = '/';
	ibsys.Cookies.cookies[name.toLowerCase()] = value; 
	document.cookie = name + '=' + value + '; expires=' + expires + '; domain=' + domain + '; path=' + path;
}
ibsys.Cookies.nuke = function( name) {
  if( name == null) return;
	name = name.toLowerCase();
	delete ibsys.Cookies.cookies[name];
	document.cookie = name + '=; expires=Sat, 1 Jan 2005 00:00:01 UTC; domain=' + ibsys.Cookies.host + '; path=/'
	document.cookie = name + '=; expires=Sat, 1 Jan 2005 00:00:01 UTC; domain=' + ibsys.Cookies.domain + '; path=/'
}


/***************************************************************
*
* NBCSP
*
***************************************************************/
using("nbcsp");
/**
* NBCSports Search Box 
* Routes Web search to google and SI.com search to SI.com and NBCSports search to internal site search 
**/
nbcsp.onSearch = function () {
	var queryText = $F('searchInput');
	/* Which search selected */
	var rbnWeb = $F('rbnWeb'); 
	var rbnNbc = $F('rbnNbc');
	var rbnSI = $F('rbnSI');
	var params = "fullscreen=yes,toolbar=yes,location=yes,directories=yes,status=yes,menubar=yes,scrollbars=yes,copyhistory=yes,resizable=yes";
	if(rbnNbc == 'n') {
		$('gs').submit();
	} else if(rbnSI == 's') {
		url = 'http://search.sportsillustrated.cnn.com/pages/search.jsp?query=' + queryText;
		ibsys.utils.popUp(url,params);
	} else if(rbnWeb == 'w') {
		url = 'http://www.google.com/search?q=' + queryText;
		ibsys.utils.popUp(url,params);
	}		
}
/**
* Attach onSearch as handler to submit of search form  
**/
ibsys.DomLoadedEvent.add(function() {
	Event.observe($('gs'),"submit",function(e) { 
		e = typeof window.event != "undefined" ? window.event : e;
		nbcsp.onSearch();
		Event.stop(e);
	},false);
});

/***
* Site navigation 
***/
nbcsp.pause = function(obj,delay,func) /* keep event bubbling, but limit how often a heavier-weight event is fired */
{
	return function()
	{
		if (delay) {
			obj.wait = setTimeout( function(){
				func();
				obj.mode = false;
			},delay);
		} else {
			clearTimeout(obj.wait);
			if (!obj.mode){func();obj.mode = true;}
		}
	}
}

nbcsp.zInt = 1001;
nbcsp.navsShowing = 0;
nbcsp.onNavsShowingEvent = new Array(); /* add a fct in this array if you want something to happen when navs are showing (e.g. hide a select element) */
nbcsp.onNoNavsShowingEvent = new Array(); /* add a fct in this array if you want something to happen when no more navs are showing */

/***
* element:hover alternative for <IE6 - basically adds and removes a classname that one can use in a stylesheet
* this is being called by a number of stylesheets, and only for IE
    USAGE: div {_behavior:expression(this.runtimeStyle.behavior=nbcsp.whateverHover(this,'hover',null,false));}
* to keep bubbling but limit how often a heavyweight operation is fired, param pauseTime should be an integer (say, 100)
* to stop bubbling, param pauseTime should be null
* affectWindowObjects param for determining whether or not effect should fire nbcsp.onNavsShowingEvent, which is presently used to hide <select> elements
***/
nbcsp.whateverHover = function(hoverObj, classValue, pauseTime, affectWindowObjects) {
	var doHover = function(obj, classValue, pauseTime, affectWindowObjects, state) {
		return function() {
			if (state) {
				Element.addClassName(obj,classValue);
				obj.style.zIndex = ++nbcsp.zInt;
				if(affectWindowObjects && ++nbcsp.navsShowing > 0 && nbcsp.navsShowing < 2) {
					$A(nbcsp.onNavsShowingEvent).each(function(value) {
						try { value(); } catch(e) {};
					});
				}
			} else {
				Element.removeClassName(obj,classValue);
				if(affectWindowObjects && --nbcsp.navsShowing < 1) {
					$A(nbcsp.onNoNavsShowingEvent).each(function(value) {
						try { value(); } catch(e) {};
					});
				}
			}
			if (pauseTime == null)
			{
				var e = window.event;
				Event.stop(e);
			}
		}
	}
	if (pauseTime != null) {
		hoverObj.onmouseover = nbcsp.pause( hoverObj, null, doHover(hoverObj, classValue, pauseTime, affectWindowObjects, true) );
		hoverObj.onmouseout = nbcsp.pause( hoverObj, pauseTime, doHover(hoverObj, classValue, pauseTime, affectWindowObjects, false) );
	} else {
		hoverObj.onmouseover = doHover(hoverObj, classValue, pauseTime, affectWindowObjects, true);
		hoverObj.onmouseout = doHover(hoverObj, classValue, pauseTime, affectWindowObjects, false);
	}
}

/***
* Function to launch nbc video pop-up window player
***/
nbcsp.launchVideo = function(pathid) { 
	/* this url is used for Most Popular video so if the parameter changes devs need to be notified */
	window.location = "http://video.nbcsports.com/player/?id=" + pathid;
	/*pop-up link deprecated 12-1-06 (#2002)
	/* site='http://video.nbcsports.com/player.html'; 
	param = '?dlid='; 
	newwindow=window.open(site+param+pathid,'sendtofriend','toolbar=no,scrollbars=no,location=no,statusbar=no,menubar=no,resizable=no,width=750,height=550');	
	if (window.focus) {
		newwindow.focus()
	} */
}

/***
* Collect the contents of the query string and define an array of name value pairs
***/
nbcsp.qsdata=[];
var currentWindowLocation= window.location.href ;
if (currentWindowLocation.indexOf('?') != -1){

			var querystringdata = currentWindowLocation.split('?')[1].split('&') ;
			
			for(var zz = 0; zz < querystringdata.length; zz++) {
                        	try {
			     		nbcsp.qsdata[querystringdata[zz].split('=')[0]]  = querystringdata[zz].split('=')[1];
							
                        	} catch (e) {};
			}		


}

/****
* Facebook link function
***/
nbcsp.fbs_click = function() {
	var u=location.href;
	var t=document.title;
	window.open('http://www.facebook.com/sharer.php?u='+encodeURIComponent(u)+'&t='+encodeURIComponent(t),'sharer','toolbar=0,status=0,width=626,height=436');
	return false;
}

/****
* Make an "empty" (i.e. ignored) http request of the current page...
****/
nbcsp.emptyHttpCall = function() {
	var url = window.location.href;
	var opts = {
		method: "get",
		/* cache-busting request headers for IE */
		requestHeaders: ["Cache-Control","no-cache, must-revalidate","Expires","Mon, 26 Jul 1997 05:00:00 GMT","If-Modified-Since","Sat, 29 Oct 1994 19:43:31 GMT"]
	}
	var t = new Ajax.Request(url, opts);
}
/****
* Do all the stuff required to make a page view
****/
nbcsp.firePageViewEvent = function(emptyHttp,omni,refreshAds) {
	emptyHttp = typeof emptyHttp != "undefined" ? emptyHttp : true;
	omni = typeof omni != "undefined" ? omni : true;
	refreshAds = typeof refreshAds != "undefined" ? refreshAds : true;
	/* grab page source  */
	if(emptyHttp) nbcsp.emptyHttpCall();
	/* omni page view event */
	if(omni) {
		try {
			s.t();
		} catch(e) {};
	}
	/* refresh ads */
	if(refreshAds) {
		try {
			/* position 1 */
			window.setTimeout(function() {
				ibsys.AdObj.elements[1].refresh()
			},100);
			
			/* position 7 */
			window.setTimeout(function() {
				if (ibsys.AdObj.elements[7])
				{
					ibsys.AdObj.elements[7].refresh()
				}				
			},200);
		} catch(e) {};
	}
}

/**
* get epoch time from timestamp on page
***/
nbcsp.getCurrentEpochTime = function() {
	var pageDate = ibsys.pageProps.dtString;	
	var tmpArr = pageDate.split(" ");
	var tmpDate = tmpArr[0].split("/");
	var tmpTime = tmpArr[1].split(":");
	/* months are 0-start for Date.UTC input params */
	tmpDate[0] = parseInt(tmpDate[0]) - 1;
	return Date.UTC(tmpDate[2],tmpDate[0],tmpDate[1],tmpTime[0],tmpTime[1],tmpTime[2],'00');
}
nbcsp.epochCurrent = null;

/**
* Convert string of numbers yyyymmddhhmmss into time since last update, based 
* on comparison with timestamp on page
*
* @param {string} elementId: id of element with above string in it, or string itself
* @returns {string} string representing time since last update. If elementId is id, it updates element, otherwise
*	just returns value. 
***/
nbcsp.storyUpdateTime = function (elementId) {
	this.parseNodeDateString = function(str) {
		/* #3621 use Math.round to force numeric type (parseInt will force numbers starting with 0 to parse as octal numbers, 
		which leads to a bug) */
		return {
			y: Math.round(str.substring(0,4)),
			mo: Math.round(str.substring(4,6)) - 1,
			d: Math.round(str.substring(6,8)),
			h: Math.round(str.substring(8,10)),
			mi: Math.round(str.substring(10,12))
		}
	}
	this.getEpochFromElement = function(nodeDate) {
		return parseInt(Date.UTC(nodeDate.y,nodeDate.mo,nodeDate.d,nodeDate.h,nodeDate.mi,'00','00'));
	}
	this.getDifferenceBetweenNowAndThen = function(now,then) {
		return (now/1000) - (then/1000);
	}
	this.convertEpochSecondsToDateString = function(epochTime) {
		var timeUpdate,timeType;
		/* seconds */
		if(epochTime < 60) {
			timeUpdate = epochTime;
			timeType = "sec";
		/* minutes */
		} else if(epochTime >= 60 && epochTime < 3600) {
			timeUpdate = Math.floor(epochTime / 60);
			timeType = "min";
		/* hours */
		} else if(epochTime >= 3600 && epochTime < 86400) {
			timeUpdate = Math.floor(epochTime / 3600);
			timeType = "hr";
		/* days */
		} else if(epochTime >= 86400) {
			timeUpdate = Math.floor(epochTime / 86400);
			timeType = "day";
		}
		if(parseInt(timeUpdate) > 1) {
			timeType += "s";
		}
		return " " + timeUpdate.toString() + " " + timeType;
	}
	this.epochCurrent = !nbcsp.epochCurrent ? nbcsp.getCurrentEpochTime() : nbcsp.epochCurrent;
	this.nodeTime = $(elementId) ? $(elementId).innerHTML : elementId;
	this.epochTime = this.getDifferenceBetweenNowAndThen(this.epochCurrent,this.getEpochFromElement(this.parseNodeDateString(this.nodeTime)));
	var timeUpdate = this.convertEpochSecondsToDateString(this.epochTime);
	
	if(timeUpdate.indexOf("undefined") == -1) {
		if($(elementId)) {
			$(elementId).innerHTML = timeUpdate;
			$(elementId).style.display = "inline";
		} else {
			return timeUpdate;
		}
	}
	
}

nbcsp.addIeBullet = function(obj) /* this is absolutely crazy - adds a bullet via innerHTML in IE - called by contentarea.css */
{
	obj.innerHTML = "&#9679;<em></em>" + obj.innerHTML;
}

