/* http://www.jslint.com/ */

/*global
	window: true,
	fp: true,
	jQuery: true,
	console: true,
	streamdata: true */



/* ==================================================================================================================================
	DOM READY
================================================================================================================================== */

	jQuery(function($){

		/* Log LightCast data and time info for reference
		console.log(streamdata);
		console.log(fp.icampus.getTimeInfo()); */

		/* Override console data on load */
			fp.icampus.overrideConsoleData();

		/* Add link to ASL */
			$('#asl-toggle').click(fp.icampus.toggleASL);

		/* Toggle chat */
			$('#chat-toggle').click(function(){
				var	$chat = $('#chat');
				if (parseInt($chat.css('left')) < 530) {
					fp.icampus.showChat();
				} else {
					fp.icampus.hideChat();
				}
			});


		/* Turn down lights */
			$('#lights-toggle').toggle(fp.icampus.lightsDown, fp.icampus.lightsUp);


		/* No cookie for chat nickname */
			if (fp.icampus.hasChatName() === false) {
				fp.icampus.chatLeave();
			}

		/* Turn off autocomplete */
			$('#chat-input').attr('autocomplete','off');

		/* Submit chat */
			$('#chat-form').submit(fp.icampus.postChat);

		/* Tabs */
			$('#connect-tabs a').click(fp.icampus.onTabClick);

		/* Map
			google.load('maps', '2', {'callback' : fp.icampus.onMapsApiLoaded}); */
		fp.icampus.onMapsApiLoaded();

		/* Update chat */
			fp.icampus.getChat(true);

		/* Clicking user names */
			$('ul#chat-entries li span, ul#chat-entries li strong').live('click', fp.icampus.onNameClick);

		/* Init contact form */
			fp.icampus.initContactForm();
			$('#contact-form').submit(fp.icampus.cardSubmitHandler);

	});


/* ==================================================================================================================================
	COOKIE UTILITY
		write a cookie:	$.cookie('cookieName', 'cookieValue');
		read a cookie:		$.cookie('cookieName');
		delete a cookie:	$.cookie('cookieName', null);
================================================================================================================================== */

	jQuery.cookie = function(name, value, days) {

		var date, expires, nameEQ, cookieAry, i, c;

		/* Read cookie */
		if (typeof value === 'undefined') {
			nameEQ = (name + "=");
			cookieAry = document.cookie.split(';');
			for (i = 0; i < cookieAry.length; i++) {
				c = cookieAry[i];
				while (c.charAt(0) === ' ') {
					c = c.substring(1, c.length);
					if (c.indexOf(nameEQ) === 0) { return c.substring(nameEQ.length, c.length); }
				}
			}
			return null;

		/* Write or delete cookie */
		} else {
			days = (value === null) ? -1 : days;
			if (days) {
				date = new Date(); date.setTime(date.getTime()+(days*24*60*60*1000));
				expires = '; expires=' + date.toGMTString();
			} else { expires = ''; }
			document.cookie = name + '=' + value + expires + '; path=/';
		}

	};


/* ==================================================================================================================================
	LOGGING
		Avoid errors when console is not available.
================================================================================================================================== */

	if (typeof console === 'undefined') {
		console = { log:function(msg){} };
	}


/* ==================================================================================================================================
	JQUERY SELECTOR CACHING
		Used to cache frequently selected objects
================================================================================================================================== */

	jQuery.gE_cache = jQuery.gE_cache ? jQuery.gE_cache : {};
	jQuery.gE = function(selector, cache) {
		cache = cache || true;
		if (!cache || typeof jQuery.gE_cache[selector] === 'undefined') {
			jQuery.gE_cache[selector] = jQuery(selector);
		}
		return jQuery.gE_cache[selector];
	};


/* ==================================================================================================================================
	ICAMPUS

		Function reference:
			@getTimeInfo
			@overrideConsoleData
			@onServiceEnd				Executed when the video ends
			@isASL					Returns true if the current video is ASL
			@toggleASL				Switches video to or from ASL
			@onTabClick				Handles what happens when a tab is clicked
			@cardSubmitHandler			Handles what happens when the communication card is submitted

			@hideConnect
			@showConnect
			@hideDescription
			@showDescription
			@hideChat
			@showChat
			@lightsDown
			@lightsUp
			
================================================================================================================================== */

	jQuery.extend(fp.icampus, (function($){

		var	map,
			locationMarkers = {};


		/* @onMapsApiLoaded
		======================================================= */

			function onMapsApiLoaded(){

				var	ui;

				map = new google.maps.Map2($('div#map').get(0));
				map.setCenter(getPoint('38.27268853598097,-7.03125'), 2);
				map.setMapType(G_HYBRID_MAP);

				ui = map.getDefaultUI();
				ui.zoom.scrollwheel = false;
				ui.controls.maptypecontrol = false;
				ui.controls.menumaptypecontrol = true;
				map.setUI(ui);

			}


		/* @getMap
		================================================================= */

			function getMap(lat, lng){
				return map;
			}


		/* @getPoint
		================================================================= */

			function getPoint(lat, lng){
				if (lat instanceof google.maps.LatLng) { return lat; }
				lat = lat.toString();
				lng = lng ? lng.toString() : '';
				if (lng.length === 0) {
					lng = lat.split(',')[1];
					lat = lat.split(',')[0];
				}
				return new google.maps.LatLng(lat, lng);
			}


		/* @isASL
		======================================================= */

			function isASL(){
				return (streamdata.console_id * 1) === (fp.icampus.SERVICECONSOLEIDDEAF * 1);
			}


		/* @toggleASL
		======================================================= */

			function toggleASL(){
				streamdata.console_id = isASL() ? fp.icampus.SERVICECONSOLEID : fp.icampus.SERVICECONSOLEIDDEAF;
				/*	We only need to reinit the console if the video has started.
					There's no need to reinit the console while the countdown is going.
					Doing so will cause the countdown function to be called multiple times.
					There's currently no way to cancel the countdown timeout because it is not assigned to a variable. */
				fp.icampus.reinit_console_flag = getTimeInfo().secsUntilStart <= 0;
				window.lcm_reloaddata();
			}


		/* @getTimeInfo
		======================================================= */

			function getTimeInfo() {
				var	duration = streamdata.duration ? streamdata.duration : (isASL() ? fp.icampus.SERVICEDURATIONDEAF : fp.icampus.SERVICEDURATION),
					localTime = Math.round(new Date().getTime()/1000),
					localStart = (streamdata.simlive_start + window.lcm_timeoffset),
					localEnd = localStart + (streamdata.duration * 1),
					secsUntilStart = (streamdata.simlive_start + window.lcm_timeoffset) - localTime,
					secsLapsed = (localTime - (streamdata.simlive_start + window.lcm_timeoffset)),
					secsRemaining = streamdata.duration - secsLapsed;
				return {
					duration : duration,			/* Video duration in seconds */
					localTime : localTime,			/* Current local time in seconds */
					localStart : localStart,			/* Local start time in seconds */
					localEnd : localEnd,			/* Local end time in seconds */
					secsUntilStart : secsUntilStart,	/* Seconds until video starts */
					secsLapsed : secsLapsed,			/* Seconds into video (if already started) */
					secsRemaining : secsRemaining		/* Seconds remaining in video */
				};
			}


		/* @overrideConsoleData
			Because we only use one console for each service time,
			we may not have updated the console start time yet.
			Which means we need to override the start time with
			the start time from our database.
		======================================================= */

			function overrideConsoleData() {
				var timeInfo = fp.icampus.getTimeInfo();

				if (isNaN(timeInfo.secsRemaining) || timeInfo.secsRemaining <= 10) {
					console.log('Video has ended.  Overriding console time and duration.');
					streamdata.simlive_start = fp.icampus.SERVICESTARTTIMESTAMP;
					streamdata.duration = (isASL() ? fp.icampus.SERVICEDURATIONDEAF : fp.icampus.SERVICEDURATION);
				}
			}


		/* @onServiceEnd
		======================================================= */

			function onServiceEnd(){
				var	asl = isASL(),
					thumbSize = fp.iphone ? '278x185' : '480x320';

				console.log('Video has ended.');

				/* Remove "live" class.  This class allows us to style the icampus differently when the video is playing. */
				$('body').removeClass('live');

				/* Destroy video */
				$.gE('#lcm_video').html('');
				console.log('Removed embeded video.');

				/* Get new icampus data */
				$.getJSON('/ajax/icampus-next', function(data, textStatus){

					/* Update icampus data */
					$.extend(fp.icampus, data);

					/* Reset image and title */
					$.gE('#video_image').css('backgroundImage', 'url(' + fp.icampus.SERVICEIMAGEURL + '?size=' + thumbSize + ')');
					$.gE('#video_title h2').html(fp.icampus.SERVICETITLE);
					$.gE('#video_description').html(fp.icampus.SERVICEDESCRIPTION);
					console.log('Reset image, title, and description.');

					/* Reload script. */
					streamdata.console_id = asl ? fp.icampus.SERVICECONSOLEIDDEAF : fp.icampus.SERVICECONSOLEID;
					fp.icampus.reinit_console_flag = true;
					window.lcm_reloaddata();
				});
			}


		/* @onTabClick
		======================================================= */

			function onTabClick(){
				var	$this = $(this),
					id = $this.attr('href').split('#')[1],
					$section = $('#' + id);
				$('ul#connect-tabs li').removeClass('on');
				$this.parent().addClass('on');
				$.gE('div#connect-content > div').hide();
				$section.show();
				return false;
			}


		/* @cardSubmitHandler
		======================================================= */

			function cardSubmitHandler(){
				var	$form = $(this),
					haveLastName = ($.trim($('#MessageName').val()).split(' ').length > 1),
					isEmail = /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i.test($('#MessageEmail').val()),
					errorMsg = '',
					data,
					temp,
					pairs;

				/* Check first and last name */
				if (!haveLastName) {
					errorMsg += 'Please provide your first and last name\n';
				}

				/* Check email */
				if (!isEmail) {
					errorMsg += 'Please provide a valid email address.\n';
				}

				/* If we have errors, alert */
				if (errorMsg.length) {
					alert(errorMsg);
				/* If no errors, submit form via ajax */
				} else {
					data = {ajax:1};
					temp = [];
					pairs = $($form.serialize().split('&')).each(function(){
						temp = this.split('=');
						data[temp[0]] = temp[1];
					});
					$.post('/icampus/communication-card', data, function(){
						$form.hide();
						$('#contact-success').show();
						$('#contact-success img').unbind('click').click(function(){
							$('#contact-success').hide();
							$('#contact-form').show();
						});
					});
				}
				return false;
			}


		/* @hideConnect
		================================================================= */

			function hideConnect(callback) {
				$('#connect').animate({top:'1000px'}, 'slow', callback);
			}


		/* @showConnect
		================================================================= */

			function showConnect(callback) {
				$('#connect').animate({top:'410px'}, callback);
			}


		/* @hideDescription
		================================================================= */

			function hideDescription() {
				$('#description').animate({left:'165px'});
			}


		/* @showDescription
		================================================================= */

			function showDescription() {
				$('#description').animate({left:'580px'});
			}


		/* @hideChat
		================================================================= */

			function hideChat() {
				$('#chat').animate({left:'165px'});
				if (fp.icampus.chatTimeout) {
					clearTimeout(fp.icampus.chatTimeout);
				}
			}


		/* @showChat
		================================================================= */

			function showChat() {
				$('#chat').animate({left:'531px'});
				if (fp.icampus.chatTimeout) {
					clearTimeout(fp.icampus.chatTimeout);
				}
				getChat();
			}


		/* @isChatVisible
		================================================================= */

			function isChatVisible() {
				return (parseInt($('#chat').css('left')) > 165);
			}


		/* @lightsDown
		================================================================= */

			function lightsDown() {
				var	$headerElems = $('#logo'),
					$lights = $('#lights');
				$headerElems.animate({opacity : '0.43'});
				$lights.fadeOut('slow', function(){
					hideDescription();
					$('#chat').animate({left:'140px'});
					$('#stage-content').animate({left:'205px'});
					hideConnect();
					$('#lights-toggle span').html('Turn Up the Lights');
				});
			}


		/* @lightsUp
		================================================================= */

			function lightsUp() {
				var	$headerElems = $('#logo'),
					$lights = $('#lights');
				$headerElems.animate({opacity : '1'});
				$lights.fadeIn('slow');
				$('#stage-content').animate({left:'0px'});
				showChat();
				showDescription();
				showConnect();
				$('#lights-toggle span').html('Turn Down the Lights');
			}


		/* @isChatStarted
		================================================================= */

			function isChatStarted() {
				return typeof fp.icampus.CHATSTARTED !== 'undefined' && fp.icampus.CHATSTARTED === 1;
			}


		/* @hasChatName
		================================================================= */

			function hasChatName() {
				return typeof fp.icampus.chatName === 'string' && fp.icampus.chatName.length > 0;
			}


		/* @addMessages
		================================================================= */

			function addMessages(html) {
				var	$wrapper = $('#chat-entries-wrapper'),
					$entries = $('#chat-entries'),
					h = ($entries.height()-$wrapper.height()),
					st = $wrapper.scrollTop();
				$entries.append(html);
				if (h-st < 10) {
					$wrapper.stop();
					$wrapper.animate({ scrollTop: $wrapper.attr('scrollHeight') }, 3000);
				}
			}


		/* @createMessage
		================================================================= */

			function createMessage(msg) {
				var	i,
					user;
				return '<li><span class="id_' + fp.icampus.chatID + '">' + fp.icampus.chatName + '</span>' + msg.replace(/<[^>]*>/g, '').replace(/@([a-zA-Z0-9_-]+)/gi, '<strong>$1</strong>') + '</li>';
			}


		/* @getChatInterval
		================================================================= */

			function getChatInterval() {
				/* If chat is closed */
					if (!isChatVisible()) {
						return 20000;
				/* If participating */
					} else if (hasChatName()) {
						return 3000;
				/* If not participating */
					} else {
						return 10000;
					}
			}


		/* @getChat
		================================================================= */

			function getChat(refresh) {

				/* Set in progress flag */
					if (fp.icampus.fetchInProgress) { return; }
					fp.icampus.fetchInProgress = true;

				$.ajax({
					type : 'post',
					url : '/icampus/chat-get',
					timeout : 60000,
					dataType : 'json',
					data : {
						refresh : (refresh === true ? 1 : 0),
						longpoll : (hasChatName() && isChatVisible() ? 1 : 0)
					},
					success : function(data, textStatus){

						/* If refreshing (or initial page load), remove existing entries */
							if (data.REFRESH === 1) { $('#chat-entries').empty(); }

						/* Add chat messages */
							if (data.MSG.length) { addMessages(data.MSG); }

						/* If chat started */
							if (!isChatStarted() && data.STARTED === 1) {
								startChat();
						/* Or if chat stopped */
							} else if (isChatStarted() && data.STARTED === 0) {
								stopChat();
							}

						/* If there are updates */
						if (data.UPDATES) { applyUpdates(data.UPDATES); }

					},
					error : function(){
						/* TO DO */
					},
					complete : function(){
						/* if (isChatVisible()) { */
							/* Set timeout to get new chat messages */
								fp.icampus.chatTimeout = setTimeout('fp.icampus.getChat()', getChatInterval());
						/* } */
						/* Reset inprogress flag */
							fp.icampus.fetchInProgress = false;

						/* Set timestamp for last get */
							fp.icampus.lastGet = new Date();
					}
				});
			}


		/* @postChat
		================================================================= */

			function postChat() {
				var	$input = $('#chat-input'),
					$send = $('#chat-submit'),
					msg = $.trim($input.val()),
					isCommand = /^#(help|stats|login|logout|leave|nick|start|stop|users|userlist|ban|unban)/i.test(msg);

				if (msg.length === 0) { return; }

				/* Unrecognized command */
					if (/^#/.test(msg) && !isCommand) {
						if (chatLang('unrecognizedCommand').length) { alert(chatLang('unrecognizedCommand')); }
						return false;

				/* If user is already a chat member, output their message to the screen */
					} else if (hasChatName() && isChatStarted() && !isCommand) {
						addMessages(createMessage(msg));

					} else if (hasChatName() && !isChatStarted() && !isCommand) {
						alert(chatLang('cantWait'));
						return false;

				/* Otherwise, prepare to send their chat nickname */
					} else {
						$send.attr('disabled','disabled');
					}

				/* Send message */
					$.ajax({
						type : 'POST',
						url : '/icampus/chat-post',
						data : {msg:msg},
						dataType:'json',
						success : function(data, textStatus){

							/* Display error if any */
							if (data.ERROR.length) {
								alert(data.ERROR);
							}

							/* Accept chat name */
							if (data.CHATNAME) {
								chatJoin(data.CHATNAME);
							}

							/* Start/stop chat */
							if (!isChatStarted() && data.STARTED === 1) {
								startChat();
							} else if (isChatStarted() && data.STARTED === 0) {
								stopChat();
							}

							/* Logout */
							if (data.LOGOUT || data.LEAVE) {
								chatLeave();
							}

							/* Append chat */
							if (typeof data.MSG !== 'undefined' && data.MSG.length > 0) {
								addMessages(data.MSG);
							}

						},
						error : function(){
							alert(chatLang('sendError'));
						},
						complete : function() {
							$send.removeAttr('disabled');
						}
					});


				/* Clear input */
					$input.val('');
				
				return false;
			}


		/* @applyUpdates
		================================================================= */

			function applyUpdates(updates) {
				var	i;
				try {
					if (updates.length === 0) { console.log('no updates'); return; }
					for (i = 0; i < updates.length; i++) {
						switch (updates[i].TYPE.toLowerCase()) {
							case 'addlocationmarker' :
								addLocationMarker(updates[i].DATA); break;
							case 'removelocationmarker' :
								removeLocationMarker(updates[i].DATA); break;
							default :
								console.log('Unknown update type: ' + updates[i].TYPE);
						}
					}
				} catch(err) { /* IE has thrown errors applying updates.  Catching them until we figure it out. */ }
			}


		/* @addLocationMarker
		================================================================= */

			function addLocationMarker(data) {
				if (!locationMarkers[data.ID]) {
					locationMarkers[data.ID] = new google.maps.Marker(getPoint(data.LAT, data.LNG));
					map.addOverlay(locationMarkers[data.ID]);
				}
			}


		/* @removeLocationMarker
		================================================================= */

			function removeLocationMarker(data) {
				if (locationMarkers[data.ID]) {
					map.removeOverlay(locationMarkers[data.ID]);
					locationMarkers[data.ID] = null;
				}
			}


		/* @onNameClick
		================================================================= */

			function onNameClick() {
				var	$this = $(this);
					$input = $('#chat-input'),
					text = $.trim($input.val()),
					id = parseInt(this.className.split('_')[1]),
					name = $this.html(),
					mention = '@' + name,
					re = new RegExp(mention + '$');

				/* If user clicked on their own name */
					if (name === fp.icampus.chatName || id === fp.icampus.chatID) {
						return;
					}
				/* If user not participating, prompt them to join */
					if (!hasChatName()) {
						return alert('Before replying to ' + name + ', please join the chat by entering your name or nickname.');
					}
				/* If they're not adding the same name twice in a row */
					if (!re.test(text)) {
						$input.val($.trim(text + ' ' + mention) + ' ');
					}
				$input.focus();
			}


		/* @chatJoin
		================================================================= */

			function chatJoin(name) {
				fp.icampus.chatName = name;
				$('body').addClass('chat-participant');
				$('#chat-input').unbind('.chatLoggedOut');
			}


		/* @chatLeave
		================================================================= */

			function chatLeave() {
				fp.icampus.chatName = null;
				$('body').removeClass('chat-participant');
				$('#chat-input')
					.bind('focus.chatLoggedOut', function(){
						$this = $(this);
						if ($this.val().toLowerCase() === chatLang('defaultInputText').toLowerCase()) {
							$(this).val('');
						}
					})
					.bind('blur.chatLoggedOut', function(){
						$this = $(this);
						if ($this.val().length === 0) {
							$(this).val(chatLang('defaultInputText'));
						}
					})
					.blur();
			}


		/* @startChat
		================================================================= */

			function startChat() {
				fp.icampus.CHATSTARTED = 1;
				$('body').addClass('chat-active');
				$('#chat-entries li.system').slideUp('slow');
			}


		/* @stopChat
		================================================================= */

			function stopChat() {
				fp.icampus.CHATSTARTED = 0;
				$('body').removeClass('chat-active');
			}


		/* @chatLang
		================================================================= */

			function chatLang(key) {
				return fp.icampus.chatLang[key.toUpperCase()].replace('[name]', fp.icampus.chatName);
			}


			function initContactForm() {
				$('input, textarea', '#contact-form')
					.focus(function(){
						var	$this = $(this),
							label = $this.prev().text();
						if ($this.val().toLowerCase() === label.toLowerCase()) {
							$this.val('');
						}
					})
					.blur(function(){
						var $this = $(this);
						if ($this.val().length === 0) {
							$this.val($this.prev().text());
						}
					}).blur();
			}


		/* @Expose public functions
		======================================================= */

			return {
				getTimeInfo : getTimeInfo,
				overrideConsoleData : overrideConsoleData,
				onServiceEnd : onServiceEnd,
				isASL : isASL,
				toggleASL : toggleASL,
				onTabClick : onTabClick,
				initContactForm : initContactForm,
				cardSubmitHandler : cardSubmitHandler,
				hideChat : hideChat,
				showChat : showChat,
				lightsDown : lightsDown,
				lightsUp : lightsUp,

				getChat : getChat,
				postChat : postChat,
				hasChatName : hasChatName,
				onNameClick : onNameClick,
				chatLeave : chatLeave,

				getMap : getMap,
				onMapsApiLoaded : onMapsApiLoaded
			};

	})(jQuery));


(function($){


/* ==================================================================================================================================
	CUSTOM LIGHTCAST FUNCTIONS

		@lcm_started				This event is triggered when the video is started or restarted.  Called by lcm_console_init

		@lcm_loaded				This event is triggered after the data is reloaded with lcm_reloaddata.

		@lcm_reloaddata			This event is triggered every 30 seconds by the LightCast countdown function.
								We are overwriting it here because the original does not take into account width and height.

		@lcm_finished				Just here for future reference.  We do not use it because it is only fired if the video is
								finished onload, so it's only good for those hitting the iCampus after the service has ended.
								This doesn't do us any good, because we already know that the video has ended and we're showing
								the countdown to the next video.
================================================================================================================================== */


	/* @lcm_started
	======================================================= */

	window.lcm_started = function() {

		var	timeInfo = fp.icampus.getTimeInfo();

		console.log('Starting video');

		/* Add "live" class to body tag.  This class allows us to style the icampus differently when the video is playing. */
		$('body').addClass('live');

		/* Set a timeout to trigger onServiceEnd. */
		if(fp.icampus.videoEndTimeout) { clearTimeout(fp.icampus.videoEndTimeout); }
		fp.icampus.videoEndTimeout = setTimeout(fp.icampus.onServiceEnd, (timeInfo.secsRemaining*1000));
		console.log('Video will end in ' + timeInfo.secsRemaining + ' seconds.');

		/* Open chat if lights are up */
			if ($('#lights').is(':visible')) {
				fp.icampus.showChat();
			}

	};


	/* @lcm_reloaddata
		We're overriding this function because the original
		does not pass the width and height params in the url
	======================================================= */

	window.lcm_reloaddata = function() {
		var url = 'http://' + streamdata.iserver + streamdata.ipath + '?dataformat=js&u='+streamdata.client_id+'&c='+streamdata.console_id+'&ip='+streamdata.ip+'&width='+streamdata.width+'&height='+streamdata.height;
		var script = document.createElement('script');
		script.src = url;
		console.log('Reloading data.  Script URL = ' + url);
		document.body.appendChild(script);
	};


	/* @lcm_finished
	======================================================= */

	window.lcm_finished = function() { /* We have no use for this function.  See notes above. */ };


	/* @lcm_loaded
	======================================================= */

	window.lcm_loaded = function() {

		var	asl = fp.icampus.isASL(),
			iPhoneAlt = 'Turn ' + (asl ? 'off' : 'on') + ' sign language';

		console.log('Console data was reloaded.');

		fp.icampus.overrideConsoleData();

		/* Add or remove the "asl" class. This class allows us to style the icampus differently for ASL. */
		/* no need to do this anymore */ /* $('body')[asl ? 'addClass' : 'removeClass']('asl'); */
		$('#asl-toggle span').html('Turn Sign Language ' + (asl ? 'Off' : 'On'));
		$.cookie('ASL', asl ? 1 : 0);
		console.log('ASL is ' + (asl ? 'on' : 'off'));

		/* iPhone */
		if (fp.iphone) {
			$('#asl').attr('alt', iPhoneAlt).attr('title', iPhoneAlt);
			$('#join_link').attr('href', '/icampus/iphone-video/?asl=' + (asl ? 1 : 0));
		}

		/* (re) initialize the console */
		if (fp.icampus.reinit_console_flag === true) {
			console.log('Calling lcm_console_init');
			window.lcm_console_init();
			fp.icampus.reinit_console_flag = false;
		}
	};


	/* @lcm_console_init
		- If iPhone, override lcm_console_init.
		We don't want the visitor automatically redirected
		to the video.  We want to give them the opportunity
		to choose ASL, then click "Join Now".
	======================================================= */

	if (fp.iphone) {

		console.log('Overriding lcm_console_init for iPhone.');

		window.removeEventListener('load', lcm_console_init, false);

		window.lcm_console_init = function() {
			var	curtime = new Date(),
				secs = (streamdata.simlive_start + lcm_timeoffset) - Math.round(curtime.getTime()/1000);

			if(streamdata.rtmppath) { streamdata.url += '&rtmppath=' + escape(streamdata.rtmppath) + '&rtmpfile=' + escape(streamdata.rtmpfile); }
			if(streamdata.smilpath) { streamdata.url += '&smilpath=' + escape(streamdata.smilpath); }

			if(streamdata.ctype && (streamdata.ctype == 'L' || streamdata.ctype == 'F')) {
				if(secs < 1 && streamdata.duration && streamdata.duration > 0 && Math.abs(secs) > (streamdata.duration - 30)) {
					if(window.lcm_finished) {
						lcm_finished();
					} else {
						lcm_setinner('lcm_simlive_countdown', 'This event has finished');
					}
					return false;
				} else if(secs > 1) {
					return lcm_countdown();
				} else {
					if(streamdata.ctype != 'F') {
						if(streamdata.rtmppath || streamdata.smilpath) { streamdata.url += '&sec='+Math.abs(secs); }
					} else {
						streamdata.url += '%26sec%3D' + Math.abs(secs);
					}
				}
			}
			if(window.lcm_started) { lcm_started(); }
		};

		if(typeof window.addEventListener != 'undefined') { window.addEventListener('load', lcm_console_init, false); } //.. gecko, safari, konqueror and standard

	} /* END IF fp.iphone */

})(jQuery);