var ua = navigator.userAgent;

function makeFalse(ignored) {
	return false;
}

function browserAcceptsCookies() {
	var b_acceptsCookies = false;
	if ( document.cookie == '' ) {
		document.cookie = 'b_acceptsCookies=yes'; // Try to set a cookie.
		if ( document.cookie.indexOf( 'b_acceptsCookies=yes' ) != -1 ) {
			b_acceptsCookies = true; // If it succeeds, set variable
		}
	} else { // there was already a cookie
		b_acceptsCookies = true;
	}
	
	return ( b_acceptsCookies );
}

thisdomain = location.host;
// I don't know why this NS test is done, but it was done previously, so to be compatible with older scripts' expectations we do it anyway *shrug*
if (navigator.appName != "Netscape") thisdomain = thisdomain.substring(thisdomain.indexOf('.') + 1, thisdomain.length);

function getSLD (domain) { // "GET Second Level Domain" -- i.e. turner.com, cnn.com, si.com, etc.
	var tld = (domain ? domain : location.host);
	tld = tld.substring(tld.lastIndexOf(".", tld.lastIndexOf(".") - 1), tld.length);
	return tld;
}

function getDomain (domainparts, hostname) {
	var jscmd = 'host.lastIndexOf(".")';
	domainparts = (domainparts > 0 ? domainparts : 2);
	host = (hostname ? hostname : location.host);
	var hostendswithdot = (host.lastIndexOf(".") == host.length - 1) ? true : false;
	if (hostendswithdot) { domainparts++ }; // need to grab one more segment, if domain name is absolute (i.e. ends in '.'; e.g. 'turner.com.')
	for (dotcount = 1; dotcount < domainparts; dotcount++) {
		jscmd = 'host.lastIndexOf(".", ' + jscmd + ' - 1)';
	}
	jscmd = 'host.substring(' + jscmd + ', host.length)';
	return eval(jscmd);
}

function SetCookie (name,value,expires,path,domain,secure) {
	var tld = (domain) ? domain : getSLD();
	document.cookie = name + "=" + escape (value) +
		((expires) ? "; expires=" + expires.toGMTString() : "") +
		((path) ? "; path=" + path : "") +
		("; domain=" + tld) +
		((secure) ? "; secure" : "");
}

function GetCookie (name) {
	var arg = name + "=";
	var alen = arg.length;
	var clen = document.cookie.length;
	var i = 0;
	
	while (i < clen) {
		var j = i + alen;
		if (document.cookie.substring(i, j) == arg) return getCookieVal (j);
		i = document.cookie.indexOf(" ", i) + 1;
		if (i == 0) break;
	}
	return null;
}

function getCookieVal (offset) {
	var endstr = document.cookie.indexOf (";", offset);
	if (endstr == -1) endstr = document.cookie.length;
	return unescape(document.cookie.substring(offset, endstr));
}

function DeleteCookie (name) {
	var exp = new Date();
	exp.setTime (exp.getTime() - 1);
	var cval = GetCookie (name);
	document.cookie = name + "=" + cval + "; expires=" + exp.toGMTString() + "; path=/";
}

function FixCookieDate (date) {
	var base = new Date(0);
	var skew = base.getTime();
	if(skew > 0) date.setTime (date.getTime() - skew);
}


/*
	We had to change the name of some functions because Clickability is using  generic names!
	And that means that at least one of their variables was conflicting with one of my functions.
	It's MY site, dang it!! I should be able to use the generic var/function names! - *sigh*
	Anyway... Remove the ones without 'si_' some time in... *shrug* ... 2003(?) I suppose.
*/

// popWin is actually the only one that I *know* conflicts, but I made the others 'si_' named too, in case of other conflicts down the road
function popWin (url, name, opts, focus) { // Remove in 2003(?)
	si_popWin(url, name, opts, focus);
}

function si_popWin (url, name, opts, focus) {
	si_popupWin = window.open(url, name, opts);
	if (focus) {
		if (focus == "opener") {
			si_popupWin.opener.focus();
		} else if (focus == "popup") {
			si_popupWin.focus();
		}
	}
	return si_popupWin;
}

function popUp (url, name, opts) { // Remove in 2003(?)
	si_popUp (url, name, opts);
}

function si_popUp (url, name, opts) {
	si_popUpWin = si_popWin(url, name, opts, 'popup');
	return si_popUpWin;
}

function popUnder (si_popunderUrl, name, opts) { // Remove in 2003(?)
	si_popUnder (si_popunderUrl, name, opts);
}

function si_popUnder (si_popunderUrl, name, opts) {
	si_popUnderWin = si_popWin(si_popunderUrl, name, opts, 'opener');
	return si_popUnderWin;
}

function popPoll (si_pollUrl) { // Remove in 2003(?)
	si_popPoll (si_pollUrl);
}

function si_popPoll (si_pollUrl) {
	si_pollWin = si_popUp(si_pollUrl, 'pollresults', 'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=auto,resizable=no,width=510,height=430');
	return si_pollWin;
}

function popVideo (si_vidPath, si_fileslug) { // Remove in 2003(?)
	si_popVideo (si_vidPath, si_fileslug);
}

function si_popVideo (si_vidPath, si_fileslug) {
	options = 'width=410,height=575,menubar=no,resizable=yes';
	si_popVideo_o (si_vidPath, si_fileslug, options);
}

function si_popVideo_o (si_vidPath, si_fileslug, options) {
	si_fileslug = (si_fileslug == null) ? '' : si_fileslug;
	var si_video_inPopup = true;
	var isR1 = (ua.indexOf("R1") != -1) ? true : false; // is this browser actually the RealOne player

	si_vidFormat = '.js.html';
	if (GetCookie('sivideotype') != null && GetCookie('sivideotype').indexOf("Real") != -1) {
		si_vidFormat = '.np.ram';
		si_video_inPopup = false;
	}
	if (isR1) { // if you're in the RealOne player, you obviously want Real video, so override any other setting
		si_vidFormat = '.r1.smil';
		si_video_inPopup = false;
	}
	si_vidUrl = si_vidPath + '/' + si_fileslug + si_vidFormat;

	if (si_video_inPopup) {
		si_videoWin = si_popUp(si_vidUrl, 'videoplayer', options);
	} else {
		location.href = si_vidUrl;
		si_videoWin = this.window;
	}
/*
	if (GetCookie('VideoSplash') == null) {
		var expdate = new Date(new Date() + (86400 * 365)); // roughly one year from now
		SetCookie('VideoSplash', url, expdate, '/', 'cnn.com');
		splash = si_popUp('/URL-OF-SPLASH.page', 'VideoSplash', 'width=600,height=440');
		splash.focus();
	}
*/
	return si_videoWin;
}


function popScoreCast (sc_sport, sc_url) { // Remove in 2003(?)
	si_popScoreCast (sc_sport, sc_url);
}

function si_popScoreCast (sc_sport, sc_url) {
	si_scorePop = si_popUp(sc_url, sc_sport + 'scorecast', 'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=auto,resizable=no,width=510,height=430');
	return si_scorePop;
}



function detBrow() {
	var uAgent = navigator.userAgent.toLowerCase()
	this.major = parseInt( navigator.appVersion )
	this.ie = (uAgent.indexOf("msie") != -1)
	this.isMac = 0;

	if ((uAgent.indexOf("mac") != -1) && this.ie) {
		this.ie3 = (this.ie && (this.major == 3))
		this.isMac = 1;
	} else {
		this.ie3 = (this.ie && (this.major == 2))
	}
}

var sc_mlb = new Object;
sc_mlb.ad = '/live/baseball/scorecast-popup-ad.html';
sc_mlb.w = 618;
sc_mlb.h = 576;

var sc_ncaaf = new Object;
sc_ncaaf.ad = '/live/football/college/scorecast-popup-ad.html';
sc_ncaaf.w = 610;
sc_ncaaf.h = 552;

var sc_nfl = new Object;
sc_nfl.ad = '/live/football/pro/scorecast-popup-ad.html';
sc_nfl.w = 610;
sc_nfl.h = 552;

var sc_info = new detBrow();

function launchScoreCast( sc_page, sportConfig ) {
// use parameter's values if available, mlb values otherwise
	sc_adUrl = ( arguments.length == 2 ) ? sportConfig.ad : sc_mlb.ad;
	sc_width = ( arguments.length == 2 ) ? sportConfig.w : sc_mlb.w;
	sc_height = ( arguments.length == 2 ) ? sportConfig.h : sc_mlb.h;
	appletWindow = null;
	adWindow = null;
	extraOpts = null;
	if ( sc_info.ie3 ) {
		sc_width -= 12;
		sc_height -= 26;
	}
	if ( document.all ) {
		sc_height += 9;
	}
	if ( sc_info.isMac ) {
		sc_height += 13;
		resize = 'yes';
		extraOpts += 'scrollbars=yes';
	} else {
		resize = 'no';
	}
	appletWindow = si_popUp( sc_page, 'scorecastframeset', 'width=' + sc_width + ',height=' + sc_height + ',top=0,left=0,status=no,resizable=' + resize + extraOpts );
	adWindow = si_popUp( sc_adUrl, 'adwindow', 'width=275,height=275,resizable=yes,scrollbars=no' );
	if (appletWindow.opener == null) appletWindow.opener = self;
}

function WM_readCookie(name) {
        if(document.cookie == '') {
            return "";
        } else {
            //alert(document.cookie);
            var firstChar, lastChar;
                var theBigCookie = document.cookie;
                firstChar = theBigCookie.indexOf(name);
                var NN2Hack = firstChar + name.length;
                if((firstChar != -1) && (theBigCookie.charAt(NN2Hack) == '=')) {
                        firstChar += name.length + 1;
                        lastChar = theBigCookie.indexOf(';', firstChar);
                        if(lastChar == -1) lastChar = theBigCookie.length;
                        return unescape(theBigCookie.substring(firstChar, lastChar));
                } else {
                    //alert('no cookie found of that name');
                        return "";
                }
        }
} // WM_readCookie

function WM_browserAcceptsCookies() {
        var WM_acceptsCookies = false;
        if ( document.cookie == '' ) {
                document.cookie = 'WM_acceptsCookies=yes';
                if ( document.cookie.indexOf( 'WM_acceptsCookies=yes' ) != -1 ) {
                        WM_acceptsCookies = true;
                }
        } else {
                WM_acceptsCookies = true;
        }

        return ( WM_acceptsCookies );
}

function parseCookieData( cookieDataString ) {
        var cookieValues = new Object();
        var separatePairs = cookieDataString.split( '&' )
        for ( var i = 0; i < separatePairs.length; i++  ) {
                var separateValues = separatePairs[i].split( ':' );
                cookieValues[separateValues[0]] = separateValues[1];
        }
        return cookieValues;
}

function WM_killCookie(name, path, domain) {
        var theValue = WM_readCookie(name); // We need the value to kill the cookie
        if(theValue) {
                document.cookie = name + '=' + theValue + '; expires=Fri, 13-Apr-1970 00:00:00 GMT' + ((path)?';path=' + path:'') + ((domain)?';domain=' + domain:''); // set an already-expired cookie
        }
} // WM_killCookie

function WM_setCookie (name, value, hours, path, domain, secure) {
        if (WM_browserAcceptsCookies()) {
        	var not_NN2 = (navigator && navigator.appName
                                        && (navigator.appName == 'Netscape')
                                        && navigator.appVersion
                                        && (parseInt(navigator.appVersion) == 2))?false:true;

        	if(hours && not_NN2) {
        	        if ( (typeof(hours) == 'string') && Date.parse(hours) ) {
        	                var numHours = hours;
        	        } else if (typeof(hours) == 'number') {
        	                var numHours = (new Date((new Date()).getTime() + hours*3600000)).toGMTString();
        	        }
        	}
        	document.cookie = name + '=' + escape(value) + ((numHours)?(';expires=' + numHours):'') + ((path)?';path=' + path:'') + ((domain)?';domain=' + domain:'') + ((secure && (secure == true))?'; secure':''); // Set the cookie, adding any parameters that were specified.
        	//alert( "name = " + name + "\rvalue = " + value + "\rhours = " + numHours + "\rpath = " + path + "\rdomain = " + domain );
	}
}


/* for searchbar */
function validate( theFormValidate ) { return CNNSI_validateSearchForm( theFormValidate ); }
function CNNSI_validateSearchForm( theForm )
{
	var site = 'si';
	var queryString = '';

	if ( theForm.sites )
	{
		if ( theForm.sites.options ) {		//	"sites" should be a select
			site = theForm.sites.options[theForm.sites.selectedIndex].value;
		} else {
			if ( theForm.sites.length )
			{
				for ( i = 0; i < theForm.sites.length; i++ )
				{
					if ( theForm.sites[i].checked ) {
						site = theForm.sites[i].value;
					}
				}
			}
			else
			{
				site = theForm.sites.value;
			}
		}
	}

	if ( theForm.qt ) {
		queryString = theForm.qt.value;
	} else {
		if ( theForm.key ) {
			queryString = theForm.key.value;
		} else {
			if ( theForm.query ) {
				queryString = theForm.query.value;
			}
		}
	}

	if ( !queryString ) {
		return false;
	}

	switch ( site.toLowerCase() ) {
		case "google":
			theForm.action = "http://websearch.si.cnn.com/search/search";
			theForm.query.value = queryString;
			return true;
		case "si":
			theForm.action = "http://search.si.cnn.com/si/search";
			theForm.query.value = queryString;
			theForm.source.value = 'si';
			return true;
		default:
			return true;						//	unsupported site?
	}
}

function CNNSI_validateSearchForm_20( theForm )
{
	var site = 'si';
	var queryString = theForm.query.value;

	if ( theForm.sites )
	{
		if ( theForm.sites.options ) {		//	"sites" should be a select
			site = theForm.sites.options[theForm.sites.selectedIndex].value;
		} else {
			if ( theForm.sites.length )
			{
				for ( i = 0; i < theForm.sites.length; i++ )
				{
					if ( theForm.sites[i].checked ) {
						site = theForm.sites[i].value;
					}
				}
			}
			else
			{
				site = theForm.sites.value;
			}
		}
	}

	if ( !queryString ) {
		return false;
	}

	switch ( site.toLowerCase() ) {
		case "google":
			theForm.action = "http://websearch.si.cnn.com/search/search";
			theForm.query.value = queryString;
			return true;
		case "web":
			theForm.action = "http://websearch.si.cnn.com/search/search";
			theForm.query.value = queryString;
			return true;
		case "si":
			theForm.action = "http://search.sportsillustrated.cnn.com/pages/search/advanced.jsp";
			theForm.action = "http://search.sportsillustrated.cnn.com/pages/search/advanced.jsp";
			theForm.Coll.value = 'si_xml';
			theForm.QuerySubmit.value = 'true';
			theForm.Page.value = '1';
			theForm.QueryText.value = queryString;
			return true;
		default:
			return true;						//	unsupported site?
	}
}

function CNNSI_writeSearchFields() {
	document.write('<input type="hidden" name=Coll value="si_xml">');
	document.write('<input type="hidden" name="QuerySubmit"  value="true" />');
	document.write('<input type="hidden" name="Page"  value="1" />');
	document.write('<input type="hidden" name="QueryText" value="">');
}

