/*
JS for tv.holysh1t.net
made by Lashknife <lashknife@gmail.com>
"Learn from this document, do not copy it!"
*/

// some JQuery requirements
$.ui.dialog.defaults.bgiframe = true;
$.fn.appendVal = function(txt) {
   return this.each(function(){
       this.value += txt;
   });
};

// some general declarations
var gametypeTitles = {
	'ctf' : 'Capture The Flag',
	'tdm' : 'Team Deathmatch',
	'ca' : 'Clan Arena',
	'ffa' : 'Free For All',
	'tourn' : 'Duel'
};

/* ** TV ** */

var strobj = new Object();
strobj.cSize = 600; // default view-width = 600px;
strobj.cSource = '--offline--'; // which is the active stream we're looking at, or is it standby or offline
strobj.availSources = new Object();
strobj.nothingonline = true;
/*
function initZoom() {
	$("#zoom-tv").click(
		function () {
			if (strobj.cSize == 400) {
				strobj.zoomiconsrc = 'images/icons/minus-icon.png';
				strobj.zoomicontitle = 'Reduce the streamsize';
				strobj.tvboxbg = 'none';
				strobj.w = 600;
				strobj.l = 3;
				switch (strobj.cSource) {
					case 'ustream' : strobj.h = 480; strobj.t = 3; break;
					default : strobj.h = 450; strobj.t = 18; break; // we assume justin is default!
				}
				strobj.cSize = 600;
			} else {
				strobj.zoomiconsrc = "images/icons/plus-icon.png";
				strobj.zoomicontitle = "Enlarge the streamsize";
				strobj.tvboxbg = 'url("images/tv-box-with-resize.jpg")';
				strobj.w = 400;
				strobj.l = 103;
				switch (strobj.cSource) {
					case 'ustream' : strobj.h = 320; strobj.t = 83; break;
					default : strobj.h = 300; strobj.t = 88; break; // we assume justin is default!
				}
				strobj.cSize = 400;
			}
			
			$("#tv-box").css({ 'background-image' : strobj.tvboxbg });
			if (strobj.cSource == 'ustream' && strobj.cSize == 600) {
				// large ustream box, lessen the radius of the rounded borders to fit corners
				$("#tv-box").addClass("ustream");
			} else {
				$("#tv-box").removeClass("ustream");
			}
			$("#zoom-tv").attr({ "src":strobj.zoomiconsrc, "title":strobj.zoomicontitle });
			$("#stream-obj").css({
				width: strobj.w + 'px',
				height: strobj.h + 'px',
				top: strobj.t + 'px',
				left: strobj.l + 'px'
			});
			$("#stream-embed").css({
				width: strobj.w + 'px',
				height: strobj.h + 'px',
				top: strobj.t + 'px',
				left: strobj.l + 'px'
			});
		}
	);
}
*/

function resetStream() {
	$.getJSON(
		'ajax.onair.php',
		'streams=live',
		function (data) {
			if (data.error != '') {
				if (data.error == 'no_streams') {
					if (strobj.cSource != '--offline--') { // already offline? no change required
						strobj.cSource = '--offline--';
						strobj.nothingonline = true;
						$('#tv-header').html('');
						loadStream();
					}
				} else {
					alert('error stream reset: please notify Lashknife!');
				}
			} else {
				/* MULTIPLE GAMES (which respective streamsources) -> LATER */
				/* FOR NOW: ONLY CM streams */
				// take in which streams are active, provide clickable options
				// not offline, so check who's up
				// set first all offline, then back online to see who stays online
				for (var source in strobj.availSources) {
					if (source == strobj.cSource) {
						// active wtaching stream is in use, so lets see if it must be removed from active view too
						if (data.streams[source]) {
							// if this passes, means the stream still exists
						} else {
							// stream is not in the active streams anymore, remove it from view, set back to choice!
							$("#tv-box").html('<div id="stream-obj" class="stream-is-offline">This streamsource is now offline!<br />Please choose another one!</div>');
						}
						
					}
					delete strobj.availSources[source];
				}
				// then set back online
				for (var source in data.streams) {
					strobj.availSources[source] = data.streams[source];
				}
				/*alert('next');
				for (var source in strobj.availSources) {
					alert(source + ' = ' + (strobj.availSources[source]?'online':'offline'));
				}
				alert('next2');*/
				// review standby options!
				
				// load tv-header
				tvhc = 0;
				tvh = '<em style="color:#ff6347">Available streams</em><ul>';
				for (var source in strobj.availSources) {
					tvhc++;
					tvh += '<li class="available-stream"><a href="#stream/' + source + '">' + source + '</a></li>';
				}
				tvh += '</ul>';
				if (tvhc > 0) {
					strobj.nothingonline = false;
				}
				$('#tv-header').html(tvh);
				$(".available-stream").css({ width: (600/tvhc)+"px" });
				
				if (tvhc > 0 && strobj.cSource == '--offline--') {
					// streams up but source still offline, so make offline msg the "choose" option
					loadStream();
				}
			}
		}
	);
}

function loadStream() {
//	$(".available-stream a").removeClass("active");
//	$(".available-stream stream-"+strobj.cSource).addClass("active");
	switch (strobj.cSource) {
		case 'ustream' :
			if (strobj.availSources['ustream']) {
				//$("#zoom-tv").css({ visibility: 'visible' });
				$("#tv-box").html('<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" width="' + (strobj.cSize==600?600:400) + '" height="' + (strobj.cSize==600?480:320) + '" id="stream-obj"><param name="flashvars" value="autoplay=true&amp;brand=embed&amp;cid=1119993"/><param name="allowfullscreen" value="true" /><param name="wmode" value="transparent" /><param name="allowscriptaccess" value="always"/><param name="movie" value="http://www.ustream.tv/flash/live/1/1119993"/><embed flashvars="autoplay=true" width="' + (strobj.cSize==600?600:400) + '" height="' + (strobj.cSize==600?480:320) + '" allowfullscreen="true" wmode="transparent" allowscriptaccess="always" id="stream-embed" src="http://www.ustream.tv/flash/live/1/1119993" type="application/x-shockwave-flash" /></object>');
				$("#stream-obj").css({ top:(strobj.cSize==600?0:80)+'px', left:(strobj.cSize==600?0:100)+'px' });
				//if (strobj.cSize == 600) { $("#tv-box").css({ background: 'none black' }); }
			}
			break;
		case 'justin' :
			if (strobj.availSources['justin']) {
				//$("#zoom-tv").css({ visibility: 'visible' });
				$("#tv-box").html('<object type="application/x-shockwave-flash" width="' + (strobj.cSize==600?600:400) + '" height="' + (strobj.cSize==600?450:300) + '" id="stream-obj" data="http://www.justin.tv/widgets/live_embed_player.swf?channel=holysh1ttv" bgcolor="#000000"><param name="allowFullScreen" value="true" /><param name="wmode" value="transparent" /><param name="allowScriptAccess" value="always" /><param name="allowNetworking" value="all" /><param name="movie" value="http://www.justin.tv/widgets/live_embed_player.swf" /><param name="flashvars" value="channel=holysh1ttv&auto_play=true&start_volume=25" /></object>');
				$("#stream-obj").css({ top:(strobj.cSize==600?15:90)+'px', left:(strobj.cSize==600?0:100)+'px' });
				//if (strobj.cSize == 600) { $("#tv-box").css({ background: 'none black' }); }
			}
			break;
		case 'livestream' :
			if (strobj.availSources['livestream']) {
				//$("#zoom-tv").css({ visibility: 'visible' });
				$("#tv-box").html('<object width="' + (strobj.cSize==600?600:400) + '" height="' + (strobj.cSize==600?480:320) + '" id="stream-obj" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"><param name="movie" value="http://static.livestream.com/grid/LSPlayer.swf" /><param name="flashVars" value="channel=holysh1ttv&autoPlay=true&mute=false" /><param name="allowScriptAccess" value="always" /><param name="allowFullScreen" value="true" /><param name="wmode" value="transparent" /><embed id="stream-embed" src="http://static.livestream.com/grid/LSPlayer.swf" flashVars="channel=holysh1ttv&autoPlay=true&mute=false" width="' + (strobj.cSize==600?600:400) + '" height="' + (strobj.cSize==600?480:320) + '" allowScriptAccess="always" allowFullScreen="true" type="application/x-shockwave-flash" wmode="transparent" /></object>');
				$("#stream-obj").css({ top:(strobj.cSize==600?0:80)+'px', left:(strobj.cSize==600?0:100)+'px' });
				//if (strobj.cSize == 600) { $("#tv-box").css({ background: 'none black' }); }
			}
			break;
		case 'watchquake' :
			if (strobj.availSources['watchquake']) {
				//$("#zoom-tv").css({ visibility: 'visible' });
				$("#tv-box").html('<object width="' + (strobj.cSize==600?600:400) + '" height="' + (strobj.cSize==600?480:320) + '" id="stream-obj" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"><param name="movie" value="http://static.livestream.com/grid/LSPlayer.swf" /><param name="flashVars" value="channel=watchquake&autoPlay=true&mute=false" /><param name="allowScriptAccess" value="always" /><param name="allowFullScreen" value="true" /><param name="wmode" value="transparent" /><embed id="stream-embed" src="http://static.livestream.com/grid/LSPlayer.swf" flashVars="channel=watchquake&autoPlay=true&mute=false" width="' + (strobj.cSize==600?600:400) + '" height="' + (strobj.cSize==600?480:320) + '" allowScriptAccess="always" allowFullScreen="true" type="application/x-shockwave-flash" wmode="transparent" /></object>');
				$("#stream-obj").css({ top:(strobj.cSize==600?0:80)+'px', left:(strobj.cSize==600?0:100)+'px' });
				//if (strobj.cSize == 600) { $("#tv-box").css({ background: 'none black' }); }
			}
			break;
		case 'livequakelive' :
			if (strobj.availSources['livequakelive']) {
				//$("#zoom-tv").css({ visibility: 'visible' });
				$("#tv-box").html('<object width="' + (strobj.cSize==600?600:400) + '" height="' + (strobj.cSize==600?480:320) + '" id="stream-obj" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"><param name="movie" value="http://static.livestream.com/grid/LSPlayer.swf" /><param name="flashVars" value="channel=livequakelive&autoPlay=true&mute=false" /><param name="allowScriptAccess" value="always" /><param name="allowFullScreen" value="true" /><param name="wmode" value="transparent" /><embed id="stream-embed" src="http://static.livestream.com/grid/LSPlayer.swf" flashVars="channel=livequakelive&autoPlay=true&mute=false" width="' + (strobj.cSize==600?600:400) + '" height="' + (strobj.cSize==600?480:320) + '" allowScriptAccess="always" allowFullScreen="true" type="application/x-shockwave-flash" wmode="transparent" /></object>');
				$("#stream-obj").css({ top:(strobj.cSize==600?0:80)+'px', left:(strobj.cSize==600?0:100)+'px' });
				//if (strobj.cSize == 600) { $("#tv-box").css({ background: 'none black' }); }
			}
			break;
		case 'own3d' :
			if (strobj.availSources['own3d']) {
				$("#tv-box").html('<object id="stream-obj" width="' + (strobj.cSize==600?600:400) + '" height="' + (strobj.cSize==600?480:320) + '"><param name="movie" value="http://www.own3d.tv/livestream/5" /><param name="allowfullscreen" value="true" /><param name="wmode" value="transparent" /><embed id="stream-embed" src="http://www.own3d.tv/livestream/5" type="application/x-shockwave-flash" allowfullscreen="true" width="' + (strobj.cSize==600?600:400) + '" height="' + (strobj.cSize==600?480:320) + '" wmode="transparent" /></object>');
				$("#stream-obj").css({ top:(strobj.cSize==600?0:80)+'px', left:(strobj.cSize==600?0:100)+'px' });
			
			}
			break;
		case 'esl' :
			if (strobj.availSources['esl']) {
				eslobjectcode = '<script type="text/javascript" src="http://tv.esl.eu/interface/esltv/player/live/js/octoshape.js"></script>';
				eslobjectcode += '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" id="stream-obj" width="' + (strobj.cSize==600?600:400) + '" height="' + (strobj.cSize==600?450:300) + '" codebase="http://fpdownload.macromedia.com/get/flashplayer/current/swflash.cab">';
				eslobjectcode += '<param name="movie" value="http://tv.esl.eu/interface/esltv/player/EslTvPlayer.swf" /><param name="quality" value="high" /><param name="allowScriptAccess" value="always" /><param name="allowFullScreen" value="true" /><param name="wmode" value="opaque" /><param name="FlashVars" value="channel=ESL.oph350&autostart=1" />';
				eslobjectcode += '<embed src="http://tv.esl.eu/interface/esltv/player/EslTvPlayer.swf" quality="high" width="' + (strobj.cSize==600?600:400) + '" height="' + (strobj.cSize==600?450:300) + '" name="octoshape_channels" align="middle" play="true" loop="false" quality="high" allowScriptAccess="always" allowFullScreen="true" type="application/x-shockwave-flash" wmode="transparent" FlashVars="channel=ESL.oph350&autostart=1" pluginspage="http://www.adobe.com/go/getflashplayer" />';
				eslobjectcode += '</object>';
				$("#tv-box").html(eslobjectcode);
				$("#stream-obj").css({ top:(strobj.cSize==600?15:90)+'px', left:(strobj.cSize==600?0:100)+'px' });
			}
			break;
		default :
			// default = offline, unless streams have come online
			if (strobj.nothingonline) {
				$("#tv-box").html('<div id="stream-obj" class="stream-is-offline">OFFLINE</div>');
			} else {
				$("#tv-box").html('<div id="stream-obj" class="stream-is-offline">Choose a stream!</div>');
			}
			//$("#zoom-tv").css({ visibility: 'hidden' });
			break;
	}
}

var casterReloadTimer = null;
var streamReloadTimer = null;

function initStream() {
	resetStream();
	loadStream();
	streamReloadTimer = window.setInterval("resetStream()",15000);
}

function initCasters() {
	loadCasters();
	casterReloadTimer = window.setInterval("loadCasters()",60000);
}

function loadCasters() {
	$.getJSON(
		'ajax.onair.php',
		'casters=live',
		function (data) {
			var casterhtml = '<span>CASTERS:</span>';
			if (data.error != '') {
				casterhtml += '<span class="no-casters">';
				if (data.error == 'no_casters') {
					casterhtml += 'No Holysh1t casters online at this time';
				} else {
					casterhtml += 'error: please notify Lashknife';
				}
				casterhtml += '</span>';
				$("#caster-list").html(casterhtml);
			} else {
				for (var i = 0; i < data.casters.length; i++) {
					casterhtml += '<span class="caster';
					if (i == 0) {
						casterhtml += ' first';
					}
					if ( i == data.casters.length - 1) {
						casterhtml += ' last';
					}
					casterhtml += '">' + data.casters[i] + '</span>';
				}
				$("#caster-list").html(casterhtml);
			}
		}
	);
}

/* ** SCHEDULE ** */
scheduleIsLoaded = false; // indicates if someone already viewed schedule dialog
function loadFullSchedule() {
	$.getJSON(
		'ajax.schedule.php',
		'full=1',
		function (data) {
			if (data.error != '') {
				$("#full-schedule").html('<p style="text-align:center"><em>' + data.error + '</em></p>');
			} else {
				var fullShtml = '';
				fullShtml += '<table id="full-schedule-table">';
				fullShtml += '<thead><tr>';
				fullShtml += '<td style="width:16px"><img src="images/icons/one_to_watch.png" alt="(*)" title="One to watch!" /></td><td>Who?</td><td class="txt-c" style="width:16px"><img src="images/icons/all_16.png" alt="gametype" title="Gametype" /></td><td>What?</td><td>When?</td>';
				fullShtml += '<td class="edit-schedule" style="width:16px"><img src="images/icons/edit_16.png" alt="E" title="Edit" /></td>';
				fullShtml += '<td class="remove-schedule" style="width:16px"><img src="images/icons/remove_16.png" alt="R" title="Remove" /></td>';
				fullShtml += '</tr></thead>';
				fullShtml += '<tbody>';
				fullShtml += '</tbody></table>';
				$("#full-schedule").html(fullShtml);
				var srow;
				for (var i = 0; i < data.schedules.length; i++) {
					srow = '<tr' + (i%2?' class="f-s-odd"':'') + ' id="schedule-item-' + data.schedules[i].sid + '">';
					srow += '<td>' + (data.schedules[i].onetowatch==true?'<img src="images/icons/one_to_watch.png" alt="(*)" title="One to watch!" />':'&nbsp;') + '</td>';
					srow += '<td><strong>' + data.schedules[i].teama + '</strong> vs <strong>' + data.schedules[i].teamb + '</strong></td>';
					srow += '<td class="txt-c"><img src="images/icons/' + data.schedules[i].gametype + '_16.png" alt="' + data.schedules[i].gametype + '" /></td>';
					srow += '<td>' + data.schedules[i].info + '</td>';
					srow += '<td>' + (data.schedules[i].tba=="true"?'<em>to be announced</em>':data.schedules[i].date) + '</td>';
					srow += '<td class="edit-schedule"><img src="images/icons/edit_16.png" alt="E" title="Edit" onclick="editSchedule(this,' + data.schedules[i].sid + ')" /></td>';
					srow += '<td class="remove-schedule"><img src="images/icons/remove_16.png" alt="R" title="Remove" onclick="removeSchedule(' + data.schedules[i].sid + ')" /></td>';
					srow += '</tr>';
					$("#full-schedule-table tbody").append(srow);
				}
			}
			scheduleIsLoaded = true;
			if(typeof window.showAdminEditFields == 'function') {
				showAdminEditFields();
			} else if (typeof window.hideAdminEditFields == 'function') {
				hideAdminEditFields();
			}
		}
	);
}

function initSchedule() {
	$.getJSON(
		'ajax.schedule.php',
		'latest=3',
		function (data) {
			var latestShtml = '';
			if (data.error != '') {
				latestShtml = '<p style="text-align:center"><em>' + data.error + '</em></p>';
			} else {
				latestShtml += '<ul>';
				for (var i = 0; i < data.schedules.length; i++) {
					latestShtml += '<li><img src="images/icons/' + data.schedules[i].gametype + '_16_w.png" alt="' + data.schedules[i].gametype + '" title="' + gametypeTitles[data.schedules[i].gametype] + '" style="margin-right:6px;"  /> ';
					latestShtml += '<strong>' + data.schedules[i].teama + '</strong> vs <strong>' + data.schedules[i].teamb + '</strong>';
					if (data.schedules[i].onetowatch == true) {
						latestShtml += '<img src="images/icons/one_to_watch.png" alt="(*)" title="One to watch!" style="margin-left:6px;"  />';
					} else {
						latestShtml += '<img src="images/icons/filler16.gif" alt="" style="margin-left:6px;" />';
					}
					latestShtml += '<br /><em>' + data.schedules[i].info + '</em>';
					latestShtml += '<br /><em>' + data.schedules[i].date + '</em><hr /></li>';
				}
				latestShtml += '</ul>';
			}
			$("#latest-schedule").html(latestShtml);
		}
	);
}

/* ** ANNOUNCEMENT ** */
announcementsIsLoaded = false; // indicates if someone already viewed announcements dialog
function loadFullAnnouncements() {
	$.getJSON(
		'ajax.announcements.php',
		'full=1',
		function (data) {
			if (data.error != '') {
				$("#full-announcements").html('<p style="text-align:center"><em>' + data.error + '</em></p>');
			} else {
				var fullAhtml = '';
				fullAhtml += '<table id="full-announcements-table">';
				fullAhtml += '<thead><tr>';
				fullAhtml += '<td style="width:16px"><img src="images/icons/special_announcement_16.png" alt="(!)" title="Special!" /></td>';
				fullAhtml += '<td>Announcement</td>';
				fullAhtml += '<td>Author</td>';
				fullAhtml += '<td style="width:135px">Date</td>';
				fullAhtml += '<td class="edit-announcements" style="width:16px"><img src="images/icons/edit_16.png" alt="E" title="Edit" /></td>';
				fullAhtml += '<td class="remove-announcements" style="width:16px"><img src="images/icons/remove_16.png" alt="R" title="Remove" /></td>';
				fullAhtml += '</tr></thead>';
				fullAhtml += '<tbody>';
				fullAhtml += '</tbody></table>';
				$("#full-announcements").html(fullAhtml);
				var arow;
	/*			'aid' => $row['aid'],
				'author' => $row['uname'],
				'message' => nl2br(stripslashes($row['amsg'])),
				'date' => $row['adatef'],
				'special' => $row['aspecial']
			*/
				for (var i = 0; i < data.announcements.length; i++) {
					arow = '<tr' + (i%2?' class="f-s-odd"':'') + ' id="announcements-item-' + data.announcements[i].aid + '">';
					arow += '<td>' + (data.announcements[i].special=="1"?'<img src="images/icons/special_announcement_16.png" alt="(!)" title="Special!" />':'&nbsp;') + '</td>';
					arow += '<td>' + data.announcements[i].message + '</td>';
					arow += '<td>' + data.announcements[i].author + '</td>';
					arow += '<td>' + data.announcements[i].date + '</td>';
					arow += '<td class="edit-announcements"><img src="images/icons/edit_16.png" alt="E" title="Edit" onclick="editAnnouncements(' + data.announcements[i].aid + ')" /></td>';
					arow += '<td class="remove-announcements"><img src="images/icons/remove_16.png" alt="R" title="Remove" onclick="removeAnnouncements(' + data.announcements[i].aid + ')" /></td>';
					arow += '</tr>';
					$("#full-announcements-table tbody").append(arow);
				}
			}
			announcementsIsLoaded = true;
			if(typeof window.showAdminEditFields == 'function') {
				showAdminEditFields();
			} else if (typeof window.hideAdminEditFields == 'function') {
				hideAdminEditFields();
			}
		}
	);
}
function initAnnouncements() {
	$.getJSON(
		'ajax.announcements.php',
		'latest=2',
		function (data) {
			var latestAhtml = '';
			if (data.error != '') {
				latestAhtml = '<p style="text-align:center"><em>' + data.error + '</em></p>';
			} else {
				for (var i = 0; i < data.announcements.length; i++) {
					latestAhtml += '<p>';
					if (data.announcements[i].special) {
						latestAhtml += '<img src="images/icons/special_announcement.png" alt="(!)" class="fl-l" style="position:relative;top:6px;left:4px;margin-right:10px;" />';
					}
					//if (data.announcements[i].message.length <= 300) {
						latestAhtml += data.announcements[i].message;
					/*} else {
						latestAhtml += data.announcements[i].message.substr(0,300) + ' <em><a href="#announcements">more...</a></em>';
					}*/
					latestAhtml += '</p>';
					//	<p>We did the layout again, to offer a bigger default view size, but for convenience, we put a resize button below the feed so you can watch it in default resolution as well.</p>
					//	<p>Still loads of things to complete and automate but the important thing is being able to have it online so we can broadcast.</p>
					//	<p>Hope you like it!</p>
					latestAhtml += '<p style="text-align:right">' + data.announcements[i].author + ' <em>(' + data.announcements[i].date + ')</em></p>';
					if (i < data.announcements.length-1) {
						latestAhtml += '<hr />';
					}
				}
			}
			$("#latest-announcement").html(latestAhtml);
		}
	);
}
function navAnnouncement(from_item,to_item) {
	$("#latest-announcement").html("<p>from " + from_item + " to " + to_item);
}

/* ** IRC ** */
var ircIsLoaded = false;
var ircWindowVisible = false;
function toggleIRC() {
	if (ircIsLoaded) {
		// visible so hide
		$("#irc-box").css({ height:"32px" });
		$("#irc-box-chat").html("");
		$("#irc-toggle-img").attr({
			'src' : 'images/icons/window_down.png',
			'title' : 'Show the chat window!'
		});
		ircIsLoaded = false;
	} else {
		// hidden so show
		$("#irc-box").css({ height:"432px" });
		$("#irc-box-chat").html('<embed height="390" width="548" style="margin: 0 10px" flashvars="channel=watchquake" wmode="transparent" allowscriptaccess="always" quality="high" bgcolor="#000000" name="livestreamChat" id="livestreamChat" src="http://cdn.livestream.com/chat/LivestreamChat.swf" type="application/x-shockwave-flash" />');
		$("#irc-toggle-img").attr({
			'src' : 'images/icons/window_up.png',
			'title' : 'Hide (and close) the chat window!'
		});
		ircIsLoaded = true;
	}
}
function showIRC() {
	$("#irc-box").css({ display:'block' });
	ircWindowVisible = true;
}
function hideIRC() {
	$("#irc-box").css({ display:'none' });
	ircWindowVisible = false;
}

/* ** NAVIGATION **/
function resetHash() {
	document.location.hash = "#home";
}

var currentAnchor = '#home';
//Function which chek if there are anchor changes, if there are, sends the ajax petition
function checkAnchor(){
	//Check if it has changes
	if(currentAnchor != document.location.hash){
		currentAnchor = document.location.hash;
		//if there is not anchor, the loads the default section
		if(!currentAnchor) {
			// load '#home' usually
		} else {
			//Creates the  string callback. This converts the url URL/#main&id=2 in URL/?section=main&id=2
			var splits = currentAnchor.substring(1).split('/');
			//Run through available options
			if (splits[0] == 'login') {
				loadDialog('login');
			} else if (splits[0] == 'logout') {
				processLogout();
			} else if (splits[0] == 'play') {
				// play (game-id,map-id)
				playwhichgame = splits[1]==undefined?1:splits[1];
				playwhichmap = splits[2]==undefined?1:splits[2];
				if (currentPage == 'library') {
					playLibGame(playwhichgame,playwhichmap);
				} else {
					if (confirm("Games are replayed on the library page!\nDo you want to navigate away from this page?")) {
						location.href = "index.php?page=library#play/" + playwhichgame + "/" + playwhichmap;
					} else {
						resetHash();
					}
				}
			} else if (splits[0] == 'watch') {
				// watch (hash)
				watchwhat = splits[1]==undefined?'latest':splits[1];
				if (currentPage == 'specials') {
					watchSpecial(watchwhat);
				} else {
					if (confirm("Specials are loaded on the specials page!\n Do you want to navigate away from this page?")) {
						location.href = "index.php?page=specials#watch/" + watchwhat;
					} else {
						resetHash();
					}
				}
			} else if (splits[0] == 'stream') {
				strobj.cSource = splits[1]==undefined?'default':splits[1];
				loadStream();
				resetHash();
			} else if (splits[0] == 'schedule') {
				loadDialog('schedule');
			} else if (splits[0] == 'announcements') {
				loadDialog('announcements');
			} else if (splits[0] == 'donate') {
				loadDialog('donations');
			} else if (splits[0] == 'links') {
				loadDialog('links');
			} else if (splits[0] == 'about') {
				loadDialog('about');
			} else if (splits[0] == 'request-coverage') {
				loadDialog('request-coverage');
			} else {
				// invalid so load '#home'
				resetHash();
			}
		}
	}
}

/* ** DIALOG ** */
function loadDialog(what) {
	if (what == 'login' && $("#dialog-login-click").css("display") == "none") {
		alert('Already logged on');
		resetHash();
	} else {
		$("#dialog-" + what).dialog('open');
	}
}
function processLogout() {
	if ($("#dialog-logout-click").css("display") == "none") {
		alert('Already logged out!');
	} else if (confirm("Are you sure you want to log out?")) {
		$.ajax({
			type: "GET",
			url: "backend.login.php",
			data: "logout=true",
			success: function(msg) {
				if (msg == 'logout_ok') {
					loadAdmin();
				}
			}
		});
	}
	resetHash();
}

function showBox(what) {
	$("#" + what + "-box").css({ display: 'block' });
}
function hideBox(what) {
	$("#" + what + "-box").css({ display: 'block' });
}

function hideFooter() {
	$("#footer").css({ display: 'none' });
}
function showFooter() {
	$("#footer").css({ display: 'true' });
}
/* ** ADMIN ** */
function loadAdmin() {
	$("#admin-box").load('ajax.admin.php');
}

/* ** INIT ** */
$(function () {
	$("#dialog-request-coverage").dialog({ autoOpen: false, modal: true, resizable: false, close: function(event, ui) { resetHash(); } });
	$("#dialog-about").dialog({ autoOpen: false, modal: true, resizable: false, close: function(event, ui) { resetHash(); } });
	$("#dialog-links").dialog({ autoOpen: false, modal: true, resizable: false, close: function(event, ui) { resetHash(); } });
	$("#dialog-login").dialog({ autoOpen: false, modal: true, resizable: false, close: function(event, ui) { resetHash(); } });
	$("#dialog-login").load("ajax.login.php");
	$("#dialog-schedule").dialog({ 
		autoOpen: false, 
		modal: true, 
		resizable: false,
		width: 800,
		open: function () {
			if (!scheduleIsLoaded) {
				loadFullSchedule();
			}
		},
		close: function(event, ui) { resetHash(); }
	});
	$("#dialog-announcements").dialog({
		autoOpen: false,
		modal: true,
		resizable: false,
		width: 800,
		open: function () {
			if (!announcementsIsLoaded) {
				loadFullAnnouncements();
			}
		},
		close: function(event, ui) { resetHash(); }
	});
	$("#dialog-donations").dialog({ autoOpen: false, modal: true, resizable: false, close: function(event, ui) { resetHash(); } });
	$("#library-nav-tab").hover(
		function () {
			$("#library-nav-warning").css({ display: 'block' });
		},
		function () {
			$("#library-nav-warning").css({ display: 'none' });
		}
	);
	// only start the following when on portal page
	if (currentPage == '') {
		initStream();
		initCasters();
		initSchedule();
		initAnnouncements();
		//initZoom();
	}
	loadAdmin();
	window.setInterval("checkAnchor()",300);
});