// *****************************************************************************
// 1.0 UTILITY FUNCTIONS
// /.element/ssi/js/3.0/globallib.js
// *****************************************************************************

	// GLOBAL settings
	var IE = (document.all) ? 1 : 0;
	var DOM = (document.getElementById) ? 1 : 0;
	var NS4 = (document.layers) ? 1 : 0;
	var MAC = ((navigator.appVersion.indexOf("PPC") >0) || (navigator.appVersion.indexOf("Mac") >0)) ? 1 : 0;
	var ua = '$User_Agent';
	var OPERA = (ua.indexOf("Opera") > 0) ? 1 : 0;
	var global = new Object();
	global.IE = document.all?true:false; // is IE?
	global.cookies = new Array(); // All page cookies
	var tmpArray = document.cookie.replace(/;\s+/g,';').split(';');
	for (var i = 0; i < tmpArray.length; i++) {
		var a = unescape(tmpArray[i]);
		var x = a.indexOf('=');
		if ( x != -1) global.cookies[a.substring(0, x)] = a.substring(x+1, a.length);
	}
	global.env = 'prod';
	if (location.hostname.match(/dev[0-9]\.turner/)) global.env = 'dev';
	if (location.hostname.match(/ref[0-9]\.turner/)) global.env = 'ref';
	if (location.hostname.match(/prod[0-9]\.turner/)) global.env = 'prev';
	if (location.hostname.match(/preview\.turner/)) global.env = 'prev';
	global.host = location.hostname;
	global.full_host = location.hostname;
	if (location.port) global.full_host += ':'+location.port;
	
	// get element by id and class
	function e(e, f) { 
		if (f==null) return document.getElementById(e); 
		else return getElementByClass(f,'*',document.getElementById(e)); 
	}
	function show(e) { if (e.style) e.style.display = "block"; }
	function hide(e) { if (e.style) e.style.display = "none"; }
	function rand(lo,hi) { return Math.floor(Math.random()*(hi-lo+1))+lo; }
	function find(srch,str) { if (str.indexOf(srch)>=0) return true; else return false; }

	function includeJS(file){
		document.write('<scr'+'ipt src='+'"'+file+'" type="text/javascript"'+'></sc'+'ript>'+"\n");
	}
	
	// set_cookie
	function set_cookie ( name, value, hours, path, domain, secure ) {
		if ( hours ) 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':'');
	}

	// read_cookie
	function readCookie ( name ) { return cookie[name]; }

	// kill cookie
	function kill_cookie ( name, path, domain ) {
		if ( cookie[name] ) document.cookie = name+'='+theValue+'; expires=Fri, 13-Apr-1970 00:00:00 GMT'
			+((path)?';path='+path:'')+((domain)?';domain='+domain:'');
	}

	// dynamically add actions to onload
	function addLoadEvent(func) {
		var oldonload = window.onload;
		if (typeof window.onload != 'function') window.onload = func;
		else {
			window.onload = function() {
				if (oldonload) { oldonload(); }
				func();
			}
		}
	}
	
	// getElementsByClass - little different than prototype's
	function getElementsByClass(searchClass,tag,node) {
		var classElements = new Array();
		if ( node == null ) node = document;
		if ( tag == null ) tag = '*';
		if (!node.getElementsByTagName) return false;
		var els = node.getElementsByTagName(tag);
		var elsLen = els.length;
		var pattern = new RegExp('(^|\\s)'+searchClass+'(\\s|$)');
		for (i = 0, j = 0; i < elsLen; i++) {
			if ( pattern.test(els[i].className) ) { classElements[j] = els[i]; j++; }
		}
		return classElements;
	}

	// getElementByClass
	function getElementByClass(searchClass,tag,node) {
		var x = getElementsByClass(searchClass,tag,node);
		if (x) {
			if (x.length > 0) { return x[0]; }
		}
		return false;
	}

	// get Param: returns URL query parameter of 'name'
	function getParam( name ) {
		var regex = new RegExp( "[\\?&]"+name+"=*([^&#]*)" );
		var results = regex.exec( window.location.href );
		if( results == null ) { return false; } else { return results[1]; }
	}


// *****************************************************************************
// X.0 ANIMATION FUNCTIONS
// *****************************************************************************

//tourFadeOut: allows elements to fade out; 
function tourFadeOut(id, millisec) {
	//speed for each frame
	var speed = Math.round(millisec / 100);
	var timer = 0;
	var opacityStart = 100
	var opacityEnd	 = 0;

	for(i = opacityStart; i >= opacityEnd; i--) {
		setTimeout("tourChangeOpacity(" + i + ",'" + id + "')",(timer * speed));
		timer++;
	}
}

//tourFadeOut: allows elements to fade in; 
function tourFadeIn(id, millisec) {
	//speed for each frame
	var speed = Math.round(millisec / 100);
	var timer = 0;
	var opacityStart = 0
	var opacityEnd	 = 100;

	for(i = opacityStart; i <= opacityEnd; i++)
	{
		setTimeout("tourChangeOpacity(" + i + ",'" + id + "')",(timer * speed));
		timer++;
	}

}

//tourChangeOpacity: changes the opacity for different browsers
function tourChangeOpacity(opacity, id) {
	var object = $(id).style; 
	object.opacity = (opacity / 100);
	object.MozOpacity = (opacity / 100);
	object.KhtmlOpacity = (opacity / 100);
	object.filter = "alpha(opacity=" + opacity + ")";
}

// *****************************************************************************
// X.0 PAGE ACTION FUNCTIONS
// *****************************************************************************

function tourTab ( tabID, contentID, activeClassName ) 
{
	var tabArray = tabID.split('_');
	var tabNum = tabArray[1];
	var section = tabArray[2];
	var tabSiblings = $(tabID).siblings(); 
	var contentSiblings = $(contentID).siblings(); 
	
	if(activeClassName == null) activeClassName = 'active';

	tourTabToggle(tabID, activeClassName);
	tourTabToggle(contentID, activeClassName);
}

function tourTabToggle(layerID, className) {
	var tabSiblings = $(layerID).siblings();
	for(i=0; i<tabSiblings.length; i++){ 
		tabSiblings[i].removeClassName( className );
	}
	$(layerID).addClassName( className );
}

// tourOpenTab
function tourAjaxOpenTab ( tabID, contentID, activeClassName ) {
	var tabArray = tabID.split('_');
	var tabNum = tabArray[1];
	var section = tabArray[2];
	var tabSiblings = $(tabID).siblings(); 

	if(activeClassName == null) activeClassName = 'active';
	
	//deactivates all other tabs
	for(i=0; i<tabSiblings.length; i++){ 
		tabSiblings[i].removeClassName( activeClassName );
	}

	//activates currentTab
	$(tabID).addClassName( activeClassName );

	//var temp_url = '/.devel/mhynson/t1/includes/'+tabNum+'.html';
	//Homepage T1 URL: 
	var url = '/.element/ssi/auto/3.0/cms/sect/r/hp_t1_'+tabNum+'.html'
//	var url = <!#--include virtual="/.element/ssi/sect/3.0/s/t1.txt"-->
	//loads content div
	tourLoadContent( contentID, url );

}

function tourLoadContent(contentId, url) {
	tourPreloader(contentId);
	tourAjaxContentLoader(contentId, url);
}
	
function tourPreloader(id) {
	var PreLoadContent = '';
	PreLoadContent += '<div style="color:#fff; margin:20px; font-size:12px;"><img src="https://s.cnn.net/pgatour/.element/img/3.0/global/loading_blue.gif" width="16" height="16" alt="Loading..." align="top"/>';
	PreLoadContent += '<img src="https://s.cnn.net/pgatour/.element/img/1.0/main/1.gif" width="5" height="1" />Loading Content...</div>';
	$(id).innerHTML = PreLoadContent;
}

function tourAjaxContentLoader(contentId, url, afterFunction) {
	if ($(contentId)) {
		new Ajax.Request(url,
		{
			method:'get',
			onSuccess: function(transport){
				$(contentId).innerHTML = transport.responseText;
				if (afterFunction != null) {
					if (typeof afterFunction == 'function') {
						afterFunction();
					}
				}
			},
			onFailure: function(){ 
				$(contentId).innerHTML = '<!- missing "'+url+'" -->';
			 }
		});
	}
}

//CNN_openPopup
function CNN_openPopup( url, name, widgets, openerUrl )

{
	var host = location.hostname;
	try {
		window.top.name = "opener";
	} catch (e) {}
	var popupWin = window.open( url, name, widgets );
	if(popupWin) {cnnHasOpenPopup = 1;}
	if ( popupWin && popupWin.opener ) {
		if ( openerUrl )
		{
			popupWin.opener.location = openerUrl;
		}
	}
	if ( popupWin) {
		popupWin.focus();
	}
}

//cnnVideo, a supplement for the old js calls to video
function cnnVideo(action, url){
	action = ''; //discard the param
	cnnOpen( url );
}

function cnnOpen(url) {
	if (typeof url != 'undefined') {
		lowerUrl = url.toLowerCase().replace(' ', '');
		if (lowerUrl.indexOf('/video/video') > -1 || lowerUrl.indexOf('/video/audio') > -1 ||	((lowerUrl.indexOf('/video/') > -1 ) && (lowerUrl.indexOf('/video/liveat/') < 0))) { window.location = '/video/?'+url; }
		else if (lowerUrl.indexOf('/photos/20') > -1) { window.location = '/photos/?'+url; }
		else if (lowerUrl.indexOf('/video/liveat/?') == 0) { openLiveAt(url.replace('/video/liveat/?', '')); }
		else if (lowerUrl.indexOf('/swingplex') > -1) {
			CNN_openPopup(url,'780x445','toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no,width=780,height=445');}
		else if(lowerUrl.indexOf('/liveat/') != -1) { tourOpenLiveat(url); }
		else { window.location = url; }
	}
}
function tourOpen(url) { cnnOpen(url); }
function tourOpenLiveat(url) {
	var year = url.substr(url.indexOf('/liveat/') + 8, 4);
	var tour_id = url.substr(url.indexOf('/liveat/') + 13, 4);
	var popup_url_launch = '/liveat/' + year + '/' + tour_id + '/launch.html';
	var popup_url_redir = '/liveat/' + year + '/' + tour_id + '/';
	var features = 'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no,width=900,height=700';
	var newWin = window.open(popup_url_launch, 'liveat', features);
	if (!newWin) {
		location.href = popup_url_redir;
	}
}
function openLiveAt(url_) { // LIVE@ Window Launcher
    CNN_openPopup(url_,'900x683','toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no,width=900,height=683');
}

function openLiveAtPlayer(playerURL)	{ // LIVE@ Window Launcher - 2.0
		CNN_openPopup(playerURL,'1000x640','status=no,toolbar=no,resizable=no,scrollbars=no,menubar=no,location=no,width=1000,height=640');
}

// FORM functions
function selectOption(select, value){
	for(var i=0; i<select.length; i++){
		if (select[i].value == value) {
			select[i].selected = true; break;
		}
	}
}
function removeOption(select, value){
	for(var i=0; i<select.length; i++){
		if (select[i].value == value) {
			select.remove(i); break;
		}
	}
}

function addOption(select, value, text){
	var tmp = new Option(text,value);
	if (select) select.options[ select.options.length ] = tmp;
}

// INPAGE Play Video
function playlistVideo(video) {
	alert( 'got play '+video); 
	alert(window.HPvideo);
	if (window.video_player.Player) {
		alert( 'Full '+video); 
		window.video_player.Player.loadMedia(video);
	} else if (window.HPvideo.Player) {
		alert( 'HP '+video); 
		window.HPvideo.Player.loadMedia(video);
	}
}

function play (video) { play_video(video); }

// *****************************************************************************
// Cookies - this is a extension for prototype.js
// *****************************************************************************
var Cookie = {
  set: function(name, value, daysToExpire) {
    var expire = '';
    if (daysToExpire != undefined) {
      var d = new Date();
      d.setTime(d.getTime() + (86400000 * parseFloat(daysToExpire)));
      expire = '; expires=' + d.toGMTString();
    }
    return (document.cookie = escape(name) + '=' + escape(value || '') + expire);
  },
  get: function(name) {
    var cookie = document.cookie.match(new RegExp('(^|;)\\s*' + escape(name) + '=([^;\\s]*)'));
    return (cookie ? unescape(cookie[2]) : null);
  },
  erase: function(name) {
    var cookie = Cookie.get(name) || true;
    Cookie.set(name, '', -1);
    return cookie;
  },
  accept: function() {
    if (typeof navigator.cookieEnabled == 'boolean') {
      return navigator.cookieEnabled;
    }
    Cookie.set('_test', '1');
    return (Cookie.erase('_test') === '1');
  }
};


// *****************************************************************************
// 2010 HP Redesign Functions
// *****************************************************************************
    // Set up today's date in YYYYMMDD format.
	var taD = new Date();
	var fixedMonth = taD.getMonth()+1;
	if (fixedMonth<10){ fixedMonth = '0'+fixedMonth+''; }
	var fixedDate = taD.getDate();
	if (fixedDate<10){ fixedDate = '0'+fixedDate+''; }

	// This is the global variable we will use.
	todaysCode = taD.getFullYear()+''+fixedMonth+''+fixedDate;

var sectRegex = new RegExp('^/[rsh]/');
var sectTestPath = window.location.pathname.match(sectRegex);
var theTest = (sectTestPath)?sectTestPath[0]:'';

switch (theTest) {
	case '/s/':
		theCurrentTour = 's';
		break;
	case '/h/':
		theCurrentTour = 'h';
		break;
	case '/r/': // Fall through
	default:
		theCurrentTour = 'r';
		break;
}

function cleanUpTimeObj(timeObj) {
	if (timeObj.tour){
		// if timeObj.tour.length is undefined, than we are oly dealing with 1 tournament
		// To unify the way in which we work with the object, we have to resort to some --hackery-- "object shuffling.
		if (undefined == timeObj.tour.length){
			timeObj.temp = [];
			timeObj.temp[0] = CleanTimeTourObj(timeObj.tour);
			timeObj.tour = timeObj.temp;
			timeObj.temp = null;
			timeObj.tour.length=1;
		} else { // Otherwise we are dealing with multiple tournaments
			for (var i=0, pLen=timeObj.tour.length; i<pLen; i++) {
				timeObj.tour[i] = CleanTimeTourObj(timeObj.tour[i]);
			}
		}
	}
	return timeObj;
}

function CleanTimeTourObj(timeObj) {

	if (timeObj.tvtime){
		timeObj.times = timeObj.tvtime.times;
		timeObj.tvtime = null;
		// Create easy access to the tournament id.
		timeObj.tID = timeObj.code +''+ timeObj.id;
		timeObj.nextTV = false;
		timeObj.tv_times = [];
		timeObj.xm_times = [];

		// Loop through the times to clean them up.
		for (var i=0, tLen=timeObj.times.length; i<tLen; i++) {

			var tvDay = timeObj.times[i].date.split('\/');
			if (tvDay[0]<10){ tvDay[0]= '0'+tvDay[0]; }
			if (tvDay[1]<10){ tvDay[1]= '0'+tvDay[1]; }
			var sTime = timeObj.times[i].stime.split(':');
			if (sTime[0]>12){
				sTime[0] -= 12;
				timeObj.times[i].standardSTime = sTime[0]+':'+sTime[1];
				timeObj.times[i].standardSTimeAPM = 'p'
			} else {
				if (sTime[0] == '00' || sTime[0] == '0'){sTime[0] = 12;}
				timeObj.times[i].standardSTime = sTime[0]+':'+sTime[1];
				timeObj.times[i].standardSTimeAPM = 'a'
			}
			var eTime = timeObj.times[i].etime.split(':');
			if (eTime[0]>12){
				eTime[0] -= 12;
				timeObj.times[i].standardETime = eTime[0]+':'+eTime[1];
				timeObj.times[i].standardETimeAPM = 'p'
			} else {
				if (eTime[0] == '00' || eTime[0] == '0'){eTime[0] = 12;}
				timeObj.times[i].standardETime = eTime[0]+':'+eTime[1];
				timeObj.times[i].standardETimeAPM = 'a'
			}
			timeObj.times[i].month = tvDay[0];
			timeObj.times[i].month_day = tvDay[1];

			// YYYYMMDD

			var tvDateCode = '2010'+tvDay[0]+''+tvDay[1];

			if ( (todaysCode<=tvDateCode && timeObj.nextTV == false) ) {
				timeObj.nextTV = tvDateCode;
				timeObj.month = tvDay[0];
				timeObj.month_day = tvDay[1];
				timeObj.day = timeObj.times[i].day;
			}

			if (!timeObj.tv_times[tvDateCode]){ timeObj.tv_times[tvDateCode] = []; }
			switch (timeObj.times[i].network.toLowerCase()) {
				case 'sirius-xm': useObj = 'xm'; break;
				default: useObj = 'tv'; break;
			}
			if (!timeObj.tv_times[tvDateCode][useObj]){ timeObj.tv_times[tvDateCode][useObj] = []; }
			timeObj.tv_times[tvDateCode][useObj].push(timeObj.times[i]);

			// if it is an XM Time, Push it to the XM Variable
			if (useObj == 'xm'){ timeObj.xm_times.push(timeObj.times[i]) };
		}
	}

	return timeObj;
}