//<script>
if (typeof(Co) === "undefined")
	Co = {};

Co.LiveBroadcasts = {};
Co.LiveBroadcasts.States = {WILL_BEGIN: 0, BROADCASTING: 1, COMPLETE: 2};
Co.LiveBroadcast = function(articleId, mediaInfo)
{
	this.MediaInfo = mediaInfo;
	this.UpdateInterval = 600;
	this.ArticleId = articleId;
	this.ProximityCheck = false;
	if (typeof(Co.Tools) !== "undefined")
		this.UpdateManager = new Co.Tools.Timer();
	else	
		this.UpdateManager = new Co.Timer();
	
	this.UpdateManager.AddListener("interval", this.OnInterval, this);
	this.CountdownManager = null;
	
	this.St = null;
	
	//(^.*\/st\/)([0-9]{1,2}\/[0-9]{1,2}\/[0-9]{2,4}[^\/]*?|[^\/|$]*)(\/.*)?$
	var st = document.location.href.replace(/(^.*\/st\/)([^\/|$]*)(\/.*)?$/gi, "$2");
	if (st.indexOf("http") != -1)
		st = document.location.search.replace(/(^.*st\=)([^\&|$]*)(\&.*)?$/gi, "$2");
		
	if (st.indexOf("?") == -1)
	{
		st = new Date(decodeURIComponent(st))
	
		if (!isNaN(st) && st != "Invalid Date" && st > new Date("1/1/2000"))
			this.St = st;
	}

	this.CheckForUpdate();
	this.CachedState = this.State = -1;
	
	Co.LiveBroadcasts["item" + this.ArticleId] = this;
};
var proto = Co.LiveBroadcast.prototype;
proto.OnInterval = function(event)
{
	this.CheckForUpdate();
};
proto.CheckForUpdate = function()
{
	this.UpdateManager.Pause();
	var obj = document.createElement("SCRIPT");
	obj.src = this.MediaInfo.InstanceInfo.Domain + "/multimedia/mediaplayer/co_live_broadcast.js.asp?aid=" + this.ArticleId + (this.St != null ? "&st=" + this.St.toUTCString() : "") +"&co_rand_cache=" + (new Date).getTime() + "." + (Math.random() * 99999999);
	
	var head = document.getElementsByTagName("HEAD");
	if (head != null && head.length > 0)
		head = head[0];
	else
		head = document.body;
	
	head.appendChild(obj);
};

proto.UpdateCallback = function(eventInfo)
{
	this.EventInfo = eventInfo;
	
	if (eventInfo.Type.toLowerCase() == "archive")
	{
		this.State = Co.LiveBroadcasts.States.BROADCASTING;
	
		if (this.State != this.CachedState)
			this.BeginBroadcasting();
		
		this.CachedState = this.State;
		return;
	}
	
	this.EventInfo.CurrentTime = new Date(this.EventInfo.CurrentTime);
	
	if (typeof(this.OriginalTime) == "undefined")
		this.OriginalTime = this.EventInfo.CurrentTime
	
	var currentDate = this.EventInfo.CurrentTime;
	/*
		add override for "server-time";
		in progress
	*/
	
	if (this.St != null)
	{
		var diff = this.EventInfo.CurrentTime - this.OriginalTime;
		
		currentDate = this.St = new Date(parseInt(this.St.getTime()) + diff);
		
		this.EventInfo.CurrentTime = currentDate;
	}
	
	
	var startDate = new Date(eventInfo.StartDate);
	var endDate = new Date(eventInfo.EndDate);
	if (endDate < startDate)
		endDate.setDate(startDate.getDate()+1);
	
	this.EventInfo.CurrentDate = currentDate;
	this.EventInfo.StartDate = startDate;
	this.EventInfo.EndDate = endDate;
	
	if (this.EventInfo["Function"])
	{
		switch (this.EventInfo["Function"].Name.toLowerCase())
		{
			case "load_articleid" :
				this.Load_ArticleId([].concat(this.EventInfo["Function"].Arguments));
				break;
			case "reload_mediareference" :
				this.Reload_MediaReference([].concat(this.EventInfo["Function"].Arguments));
				break;
		}
	}
	
	this.UpdateState();

	if (this.State === Co.LiveBroadcasts.States.WILL_BEGIN)
	{
		this.UpdateManager.Milliseconds = (eventInfo.UpdateInterval * 1000);
	
		this.UpdateManager.Resume();
	}
	else if (this.State == Co.LiveBroadcasts.States.BROADCASTING)
	{
		//check for update every 3 minutes
		this.UpdateManager.Milliseconds = 180 * 1000;
		this.UpdateManager.Resume();
	}
	if (typeof(this.OnInitializeComplete) !== "undefined" && this.OnInitializeComplete != null)
	{
		this.OnInitializeComplete();
		this.OnInitializeComplete = null
	}
};
proto.UpdateState = function()
{
	this.CurrentSystemTime = new Date();
	var currentDate = this.EventInfo.CurrentDate;
	
	if (currentDate > this.EventInfo.EndDate && this.EventInfo.Type.toLowerCase() == "live")
		this.State = Co.LiveBroadcasts.States.COMPLETE;
	else if (currentDate > this.EventInfo.StartDate)
		this.State = Co.LiveBroadcasts.States.BROADCASTING;
	else
		this.State = Co.LiveBroadcasts.States.WILL_BEGIN;

	if (this.State != this.CachedState)
	{
		switch (this.State)
		{
			case Co.LiveBroadcasts.States.WILL_BEGIN :
				var timeDifference = this.GetTimeDifference(currentDate, this.EventInfo.StartDate)
				
				this.SetupCountdown();
				
				this.CountdownManager.Loops = parseInt(timeDifference / 1000, 10) + 1;
				
				this.OnCountdownInterval();
				
				this.CountdownManager.Reset();
				break;
			case Co.LiveBroadcasts.States.BROADCASTING:
				this.BeginBroadcasting();
				break;
			case Co.LiveBroadcasts.States.COMPLETE :
				this.EndBroadcast();
				break;
		}
	}
	
	this.CachedState = this.State;
	
	if (this.State == Co.LiveBroadcasts.States.WILL_BEGIN)
	{
		var timeDifference = this.GetTimeDifference(currentDate, this.EventInfo.StartDate)
		this.CountdownManager.Loops = parseInt(timeDifference / 1000, 10) + 1;
		this.CountdownManager.Reset();
	}
};
proto.SetupCountdown = function()
{
	if (this.CountdownManager !== null)
		return;
	
	if (typeof(Co.Tools) !== "undefined")
		this.CountdownManager = new Co.Tools.Timer();
	else	
		this.CountdownManager = new Co.Timer();
	
	this.CountdownManager.Milliseconds = 1000;
	this.CountdownManager.AddListener("interval", this.OnCountdownInterval, this);
	
	this.CreateCountdownContainer();
};
proto.CreateCountdownContainer = function()
{
	if (typeof(this.CountdownContainer) != "undefined")
		return;
	var instanceInfo = this.MediaInfo.InstanceInfo;
	
	var container = instanceInfo.Container;
	
	var countdownContainer = this.CountdownContainer = document.createElement("DIV");
	
	countdownContainer.className = "co_countdown_container";
	
	var table = countdownContainer.appendChild(document.createElement("TABLE"));
	
	var child = table.insertRow(-1);
	child = child.insertCell(-1);
	child.vAlign = "middle";
	
	this.CountdownTextContainer = child;
	
	var html = this.EventInfo.Message;
	if (typeof(html) === "undefined" || html == "")
		html = "The live broadcast of <b>" + this.EventInfo.Title + "</b> is scheduled to air:<br /><time /> your local time <countdown_message><countdown>until broadcast begins</countdown_message>";
		
	var eventInfo = this.EventInfo;
	html = html.replace(/<time(><\/time|\s?\/)>/gi, function(match)
	{
		var tzo = (new Date().getTimezoneOffset()/60)*(-1);
		
		var startDateString = eventInfo.StartDate.toLocaleString();
		/* for some reason, chrome does not format the date the way all other browsers do */
		if (navigator.userAgent.toLowerCase().indexOf(" chrome/") != -1 && typeof(new Date().toLocaleDateString) != "undefined")
		{
			startDateString = eventInfo.StartDate.toLocaleDateString() + " ";
			var tempDate = new Date(eventInfo.StartDate);
			var hour = tempDate.getHours();
			var ampm = "AM";
			if (hour >= 12)
			{
				tempDate.setHours(hour-12);
				ampm = "PM";
			}
			else if (hour == 0)
				tempDate.setHours(12);
			
			startDateString += tempDate.toLocaleTimeString() + " " + ampm;
		}
		
		startDateString = startDateString.replace(/(\s[0-9]{1,2}\:[0-9]{1,2})(?:\:[0-9]{1,2})?(\s[AP]M)?/gi, " at$1$2") + " (GMT " + tzo + ")";
		
		return "<span id=\"co_time_" + eventInfo.ArticleId + "\">" + startDateString + "</span>";
	});
	html = html.replace(/<countdown_message>(.*?)<\/countdown_message>/gi, function(match, group1)
	{
		return "<div class=\"countdown_message\">" + (group1.replace(/<countdown(><\/countdown|\s?\/)>/gi, function()
		{
			return "<div class=\"countdown\" id=\"co_countdown_" + eventInfo.ArticleId + "\"></div>";
		})) + "</div>";
	});
	node = child.appendChild(document.createElement("div"));
	node.innerHTML = html;
	this.MessageNode = node;
	
	container.appendChild(countdownContainer);
	
	this.CountdownObject = document.getElementById("co_countdown_" + eventInfo.ArticleId);
	this.CountdownTime = document.getElementById("co_time_" + eventInfo.ArticleId);
};
proto.OnCountdownInterval = function(ev)
{
	var currentDiff = this.GetTimeDifference(this.CurrentSystemTime, new Date());
	var diff = this.GetTimeDifference(this.EventInfo.CurrentDate, this.EventInfo.StartDate);
	
	diff = parseInt((diff - currentDiff) / 1000, 10) + 1;
	
	this.CountdownObject.innerHTML = this.GetCountdownTime(diff);
};
proto.BeginBroadcasting = function()
{
	if (this.CountdownManager != null)
		this.CountdownManager.Stop();
	if (typeof(this.CountdownContainer) !== "undefined")
		this.CountdownContainer.style.display = "none";
	
	var mediaPlayer = this.MediaPlayer = null;
	var instanceInfo = this.MediaInfo.InstanceInfo;
	/*
	if (typeof(Co_MediaPlayer) !== "undefined")
	{
		mediaPlayer = new Co_MediaPlayer(this.MediaInfo.InstanceInfo.Index, this.MediaInfo);
		mediaPlayer.AID = this.ArticleId;
	}
	else if (typeof(Co.MediaPlayer) !== "undefined")
	{
		mediaPlayer = new Co.MediaPlayer(this.MediaInfo.InstanceInfo.Index, this.MediaInfo);
		mediaPlayer.ArticleId = this.ArticleId;
	}
	*/
	var mediaPlayer = this.MediaPlayer = this.MediaInfo.MediaPlayer;
	mediaPlayer.BeginBroadcasting();
};
proto.EndBroadcast = function()
{
	this.CreateCountdownContainer();
	
	if (this.CountdownContainer.parentNode == null)
	{
		this.MediaInfo.InstanceInfo.Container.innerHTML = "";
		this.MediaInfo.InstanceInfo.Container.appendChild(this.CountdownContainer);
	}
	this.CountdownContainer.style.display = "block";
	this.MessageNode.innerHTML = this.EventInfo.FinishedMessage;
};
proto.Load_ArticleId = function(articleId)
{
	alert("not supported");
};
proto.Reload_MediaReference = function()
{
	alert("not supported");
};
proto.GetCountdownTime = function(difference)
{
	if (difference <= 0 || isNaN(difference))
	{
		if (typeof(this.StandbyInterval) == "undefined" || this.StandbyInterval == null)
		{
			if (typeof(Co.Tools) !== "undefined")
				this.StandbyInterval = new Co.Tools.Timer();
			else	
				this.StandbyInterval = new Co.Timer();
	
			this.StandbyInterval.AddListener("interval", function()
			{
				this.CheckForUpdate();
				this.StandbyInterval.Stop();
				this.StandbyInterval = null;
			}, this);
			this.StandbyInterval.Start(10 * 1000);
		}
		return "Please Stand by";
	}
	if (difference < 30 && !this.ProximityCheck)
	{
		this.ProximityCheck = true;
		this.CheckForUpdate();
	}
	else if (difference > 30)
		this.ProximityCheck = false;
		
	var seconds = this.PadLeft((difference % 60).toString(), "0", 2);
	difference = (difference - parseInt(seconds, 10)) / 60;
	var minutes = this.PadLeft((difference % 60).toString(), "0", 2);
	difference = (difference - parseInt(minutes, 10)) / 60;
	var hours = parseInt(difference % 24);
	var days = parseInt((difference - hours) / 24);
	
	return (days > 0 ? days + " day" + (days == 1 ? "" : "s") + " " : "") + (days > 0 || hours > 0 ? hours + " hour" + (hours == 1 ? "" : "s") + " : " : "") + (days > 0 || hours > 0 || minutes > 0 ? minutes + " minute" + (minutes == 1 ? "" : "s") + " : " : "") + seconds + " second" + (seconds == 1 ? "" : "s");
};
proto.GetTimeDifference = function(currentTime, startTime)
{
	return startTime - currentTime;
};
proto.PadLeft = function(strValue, padCharacter, length)
{
	if (typeof(strValue) == "undefined")
		strValue = "";
	while (strValue.length < length)
	{
		strValue = padCharacter + strValue;
	}
	return strValue;
};
//</script>
