
// Declarations for global scope
var menu, player, counter, chat, watching, refreshTimeout, debugTimer;

/* Override is set on template.php if "debug" parameter is passed to homepage 
 * It must be passed on every ajax request to make sure that time overrides are
 * taken into consideration in ajax processing 
 */
if(typeof(override) == 'undefined') 
	var override = 0; // 0 because false for javascript is detected by php as string 'false'
else {
	// For debugging, time should increase every second, but starting with overridden value
	window.debugTimer = setInterval('override += 1;', 1000);
}

$(document).ready(function(){
	$("a.chat").mouseover(function(){
		window.status = 'chat';
	});
	/*
	 * Object controlling all aspects of the player, it's init method
	 * will show player controls and load the embeded flash player
	 */
	player = {
		rightControls: $("#rightControls"), // Capture control's jQuery object
		leftControls: $("#leftControls"),
		pollTimer: null,
		active: false,
		playerType: 'video', // If player is audio or video
		dimming: false,
		toggleDim: function(callback){ // Dims/undims window
			this.dimming = true;
			if($("#overlay").css('display') == 'none'){
				menu.hide();
				this.rightControls.find("a.dim").html('BRIGHTEN');
				$("#overlay").fadeIn(1000);
				$("#overlay").queue(function(){
					queue = this;
					$("#playerGlow").fadeIn(1500, function(){
						player.dimming = false;
						$(queue).dequeue();
					});
				});
			} else {
				this.rightControls.find("a.dim").html('DIM');
				if(typeof(callback) == 'function') callback();
				$("#overlay").queue(function(){
					queue = this;
					$("#playerGlow").fadeOut(500, function(){
						$(queue).dequeue();
					});
				});
				$("#overlay").fadeOut(400);
			}
		},
		showPromotionalImage: function(){
			/* Replace video area with promotional image */
			var promImage = $("#playerWindow").find('img');
			if(promImage.attr('src')){ // Image is already there, it was hidden when player appeared
				promImage.fadeIn(300);
			} else {
				$.ajax({
					url: '/ajax/ajax.homepage.php',
					dataType: 'html',
					data: {playerImage: true},
					type: 'get',
					success: function(response){
						$("#playerWindow").append(response);
						$("#playerWindow").find("img").load(function(){
							$(this).fadeIn(300);
						});
						$("#playerWindow").find("div.loading").remove();
					}
				});
			}
		},
		hidePromotionalImage: function(){
			var promImage = $("#playerWindow").find('img');
			promImage.fadeOut(300);
		},
		hide: function(){
			this.active = false;
			// Called when stream ends
			clearInterval(this.pollTimer);
			// Undim
			if($("#overlay").css('display') != 'none') this.toggleDim();
			
			$("#playerContainer").hide();
			$("#playerContainer").remove();
			player.showPromotionalImage();
			
			watching.hide();
			this.rightControls.fadeOut(300);
			// Only display counter once menu has moved down
			menu.pullMenuDown(function(){
				counter.init(); // Restart counter
			});
			if(serviceType == 'live') // Change to next service's type
				serviceType = 'sim';
			else
				serviceType = 'live';
		},
		hideDisplay: function(){
			$("#playerContainer").css('visibility','hidden');
			this.rightControls.hide();
		},
		showDisplay: function(){
			if(this.active){
				$("#playerContainer").css('visibility','visible');
				this.rightControls.show();
			}
		},
		pollForServiceRunning: function() {
			// Called every minute to find out if service is still running
			$.ajax({
				url: '/ajax/ajax.serviceRunning.php',
				type: 'get',
				dataType: 'html',
				// Passed to override time (might be false)
				// noCache is to avoid IE response caching
				data: {override: override, noCache: new Date().getTime()}, 
				success: function(response){
					if(!response) {
						// Service has ended
						player.hide();
					}
				}
				
			});
		},
		activateQuality: function(quality){
			$("#playerContainer").remove();
			var sToken;
			// For different quality streams & services
			if(serviceType == 'live'){ // Live service
				switch(quality){
					case 'low': 
						sToken = 'gv651rbp'; // Set to low quality stream token
						break;
					case 'med':
						sToken = 'ib0j2u71'; // Set to med quality stream token
						break;
					case 'high':
						sToken = 'sqlhj8a7'; // Set to high quality stream token
						break;
					case 'auto':
						sToken = 'xzq9sob7'; // Auto quality
						break;
					case 'audio':
						sToken = 'k2ji2ab6'; // Set to audio feed
						break;
				}
			} else {
				switch(quality){ // Sim Live service
					case 'low': 
						sToken = 'a5b8v750'; // Set to low quality stream token
						break;
					case 'med':
						sToken = 'm6t5c19r'; // Set to med quality stream token
						break;
					case 'high':
						sToken = 'un4h5w4x'; // Set to high quality stream token
						break;
					case 'auto':
						sToken = 'n49uo1p6'; // Auto quality
						break;
					case 'audio':
						sToken = 'ca336vn2'; // Set to audio feed
						break;
					}
			}
			if(quality == 'audio') this.activateAudio(sToken,serviceType); else this.activatePlayer(sToken);
		},
		activatePlayer: function(serviceToken){
			this.playerType = 'video';
			// Load player into window
			$("#playerWindow").append('<div id="playerContainer"><div id="live_player"></div></div>');
			
			// Set the button's label to audio only
			this.rightControls.find('a.audio').html('AUDIO ONLY');
			
			// Show quality controls in case they were hidden 
			this.rightControls.find('.quality').show();
			
			// Start audio player
			var so = new SWFObject("http://vidego.multicastmedia.com/templates/livefull2.swf", "live_player", "768", "462", "9", "#000000");
			so.addVariable("sToken", serviceToken);
			so.addVariable("serviceURL", "http://vidego.multicastmedia.com/services/index.php");
			so.addVariable("doResize", "false");
			so.addParam("allowFullScreen", "true");
			so.addParam("allowScriptAccess", "always");
			so.addVariable("typePlayer","live");
			so.write("playerContainer");
		},
		activateAudio: function(serviceToken,serviceType){
			this.playerType = 'audio';
			// Load player into window
			$("#playerWindow").append('<div id="playerContainer"><div id="live_player"></div></div>');
			
			// Set the button's label to video
			this.rightControls.find('a.audio').html('VIDEO');
			
			// Hide quality controls
			this.rightControls.find('.quality').hide();
			
			var so;
			if (serviceType == 'sim')
				so = new SWFObject("http://vidego.multicastmedia.com/templates/livefull2.swf", "live_player", "240", "206", "9", "#000000");
			else
				so = new SWFObject("http://vidego.multicastmedia.com/templates/live_radio_player.swf", "live_player", "240", "206", "9", "");
			so.addVariable("sToken", serviceToken);
			so.addVariable("serviceURL", "http://vidego.multicastmedia.com/services/index.php");
			so.addVariable("doResize", "false");
			so.addParam("allowFullScreen", "true");
			so.addParam("allowScriptAccess", "always");
			so.addVariable("typePlayer","live");
			so.write("playerContainer");
			// Center player
			$("#live_player").css({top: '50%', left: '50%', position: 'absolute', 'margin-left': '-120px', 'margin-top': '-103px'});
			
		},
		checkFlash: function(){
			if(typeof(showNoFlash) != 'undefined') return false;
			var requiredMajorVersion = 9;
			var requiredMinorVersion = 0;
			var requiredRevision = 0;
			return DetectFlashVer(requiredMajorVersion, requiredMinorVersion, requiredRevision);
		},
		init: function(){
			if(this.checkFlash()){
				this.active = true;
				this.rightControls.show();
				// Initialize dim lock & Bind Dim toggle action tu button
				window.dimming = false;
				$("#playerControls a.dim").click(function(){ player.toggleDim();});
				// Initialize quality switchs
				$("#playerControls a#high").click(function(){player.activateQuality('high');});
				$("#playerControls a#med").click(function(){player.activateQuality('med');});
				$("#playerControls a#low").click(function(){player.activateQuality('low');});
				$("#playerControls a.audio").click(function(){
					if(player.playerType == 'audio') 
						player.activateQuality('auto');
					else
						player.activateQuality('audio');
				});
				// Start viewers count (this will also display it on player frame - comment out to disable visitor watcher
				//watching.init();
				
				// Remove loading icon
				$("#playerWindow").find(".loading").remove();
				
				// Hide image
				this.hidePromotionalImage();
				
				/* Load player! */
				this.activateQuality('auto'); // CHANGE TO DEFAULT STREAM
				this.pollTimer = setInterval('player.pollForServiceRunning()', 60000);
			} else {
				// Remove loading icon
				$("#playerWindow").find(".loading").remove();
				$("#playerWindow").append('<div id="flashNotice">To view the Live Service you must have Adobe Flash Player installed.<br /><br />To install it please follow <a href="http://www.adobe.com/go/getflash">this link</a></div>');
			}
		}
	};
	
	watching = {
		viewers: null,
		countries: null,
		visitorsTimeout: null,
		toggleWatchingDropdown: function(){
			menu.toggle('watching', null);
			this.loadWatching(function(){	
				if(watching.viewers == 1) 
					msg = 'There is one person watching from one country';
				else if (watching.countries > 1){
					msg = 'There are '+watching.viewers+' people watching from '+watching.countries+' countries.';
				} else {
					msg = 'There are '+watching.viewers+' people watching from one country.';
				}
				$("#content").html(msg);
			});
		},
		loadWatching: function(callback){  
			
			// This method will update the viewers count and also act as 
			// a keep alive.
			// -------------
			// If this method isn't called for 3 minutes, user will be 
			// removed from viewers count.
			
			$.ajax({
				url: '/ajax/ajax.doGetVisitors.php',
				type: 'get',
				dataType: 'json',
				success: function(response){
                                        var wContent = '';
					// Set globally on the object so that data is available on callback
					watching.viewers = response.people;
					watching.countries = response.country;

					if(watching.viewers>1)
						wContent = watching.viewers + ' people watching';
					else
						wContent = watching.viewers + ' person watching';
					$(".watching").html(wContent);
					// Trigger callback
					if(typeof(callback) == 'function') callback();
				}
			});
		},
		hide: function(){
			$("a.watching").css({opacity: 0}).css('display','block').animate({opacity: 1});
			clearInterval(watching.visitorsTimeout);
		},
		init: function(){
			// Counter to update visitors every 60 seconds
			this.visitorsTimeout = setInterval("window.watching.loadWatching()",60000);
			this.loadWatching(); // 1st call
			
			// Initialize viewer number dropdown
			$("a.watching").fadeIn(300);
			$("a.watching").click(function(){
				watching.toggleWatchingDropdown();
			});
		}
	};
	
	/*
	 * Object controlling the menu
	 * It's init action will start all menu actions
	 */
	menu = {
		displayed: false, // True when submenu is visible
		mainMenu: $("#menu"), // Capture main menu's jQuery object
		dropdown: $("#dropdown"), // Capture dropdown's jQuery object
		selectedMenu: null,
		selectedSubmenu: null,
		init: function(){
			/* Menu hovers
			 * Adds hover class to li when hovering a
			 */                 
			$("#menu ul li a").mouseenter(function(){
				$(this).parent().addClass('hover');
			});
			$("#menu ul li a").mouseleave(function(){
				$(this).parent().removeClass('hover');
			});
			this.mainMenu.find("ul li a").each(function(i){
				// Add click triggers on each main menu item
				$(this).click(function(){
					menu.toggle($(this).attr('title'), null);
					$(this).parent().addClass('selected');
				});
			});
			
			// Close button
			this.dropdown.find("#close").click(function(){
				menu.hide();
			});
		},
		toggle: function(item, subitem){ // An item is clicked
			replaceSubmenu = true;
			// Only do something if you are not clicking the selected item
			if((this.selectedMenu != item)||((this.selectedMenu == item) && (this.selectedSubmenu != null) && (this.selectedSubmenu != subitem))){
				if(!this.displayed){
					// Undim player if dimmed
					if($("#overlay").css('display') != 'none') 
						player.toggleDim(function(){
							menu.show(); // Dropdown animation
						});
					else
						menu.show(); // Dropdown animation
				}
				// Selected a diferent main menu.
				if(this.selectedMenu != item){
					this.mainMenu.find("ul li").each(function(i){
						if($(this).hasClass(menu.selectedMenu)) $(this).removeClass('selected');
					});
				} else { // Selected a different subitem on the same menu
					replaceSubmenu = false;
					this.dropdown.find("#submenu ul li a").each(function(){
						// Switch selected item
						if($(this).attr('title') != subitem) {
							$(this).parent().removeClass('selected');
						} else {
							$(this).parent().addClass('selected');
						}
					});
				}
				this.selectedMenu = item;
				this.selectedSubmenu = subitem;
				// Workaround for IE7 (pre serialize data)
				data = {menu: item, submenu: subitem}; 
				dataSerialized = $.param(data);
				if(replaceSubmenu) menu.dropdown.find("#submenu").html('').hide();
				// Fetching the menu!
				this.dropdown.find("#content").hide();
				$.ajax({
					url: '/ajax/ajax.homepage.php',
					data: dataSerialized,
					dataType: 'json',
					type: 'get',
					success: function(response){
						menu.dropdown.find("#content").fadeIn(200);
						if(replaceSubmenu) {
							menu.dropdown.find("#submenu").html(response.submenu).fadeIn(200);;
						}
						menu.initSubmenu();
						menu.dropdown.find("#content").html(response.content);
						/* 
						 * Find which submenu option is selected if toggle is called 
						 * with null subitem then the only way to know which is the
						 * one selected by default is scaning each item
						 */
						menu.dropdown.find("#submenu ul li").each(function(item){
							if($(this).hasClass("selected")) {
								menu.selectedSubmenu = $(this).attr('title');
							}
						});
					}
				});
			}
		},
		toggleLoading: function(){
			loading = this.dropdown.find(".loading");
			if(loading.css('display') == 'none'){
				loading.fadeIn(100);
			} else {
				loading.fadeOut(100);
			}
		},
		show: function(){
			counter.hide();
			this.dropdown.animate({top: '0'}, 1000);
			this.displayed = true;
			if(!counter.activeCountdown) this.pullMenuDown();
		},
		hide: function(){
			this.dropdown.animate({top: '-130px'}, 1000);
			this.selectedMenu = null;
			this.selectedSubmenu = null;
			this.displayed = false;
			this.mainMenu.find("ul li").each(function(i){
				$(this).removeClass('selected');
			});
			if(counter.activeCountdown)
				counter.show();
			else
				this.pullMenuUp();
		},
		initSubmenu: function(){
			// Called when submenu is replaced, it will activate hovers
			this.dropdown.find("#submenu a").mouseenter(function(){
				$(this).parent().addClass('hover');
			});
			this.dropdown.find("#submenu a").mouseleave(function(){
				$(this).parent().removeClass('hover');
			});
			this.dropdown.find("#submenu a").each(function(i){
				$(this).click(function(){
					menu.toggle(menu.selectedMenu, $(this).attr('title'));
				});
			});
		},
        pullMenuUp: function(){
            this.mainMenu.animate({top:'590px'},1000);
        },
        pullMenuDown: function(callback){
            this.mainMenu.animate({top:'720px'},1000, function(){
            	if(typeof(callback) == 'function') callback();
            });
        },
        position: function(){
            if(counter.activeCountdown)
                this.pullMenuDown();
            else
                this.pullMenuUp();
        }

	};
	
	/*
	 * Object controlling countdown
	 * It's init method will make an ajax call to fill the counter's container
	 * This call will also trigger the start method which will trigger counters
	 */
	counter = {
		mainContainer: $("#countdown"),
		countdownContainer: $("#countdownContainer #countdown"),
		loading: $("#countdownContainer .loading"),
		startTime: null, // Time to set as progress bar start
		endTime: null, // Time to set as progress bar end
		actualTime: null, // Store actual time. Approximate record used to calculate progress bar percentage
		cycleCounter: 0, // To update progressbar only every 30 seconds (not 1)
		/*if it is true, if menu is displayed and counter is hidden
		  counter will be shown again when menu dissappears */
		activeCountdown: false,
		progressBarCycle: function(){
			if(counter.cycleCounter == 30){
				counter.actualTime += 30; // Add 30 seconds to progress bar's start time
				counter.updateProgressBar();
				counter.cycleCounter = 0;
			} else {
				counter.cycleCounter++;
			}
		},
		updateProgressBar: function(){
			var percentage = Math.round(((counter.actualTime - counter.startTime) / (counter.endTime - counter.startTime))*1000)/10;
			counter.countdownContainer.find("#progressBarLine").css('width', percentage+'%');
			counter.countdownContainer.find("#progressBarGlow").css('left', percentage+'%');
		},
		triggerPlayer: function(){
			player.init();
			chat.init();
			counter.activeCountdown = false; // Don't restore if menu is closed
			counter.hide(function(){
				if(!menu.displayed) menu.pullMenuUp();
			});
		},
		start: function(_startTime, _endTime, now){
			/* 
			 * Start counting & set up progress bar
			 * _startTime will be the last service's date
			 */
			this.startTime = _startTime; this.endTime = _endTime; this.actualTime = now;
			// This counter will start the player 10 minutes before the real service time
			$("#hiddenCountdown").countdown({until:(counter.endTime - counter.actualTime - 600), onExpiry: counter.triggerPlayer});
			// Real time
			$("#textCountdown").countdown({until: (counter.endTime - counter.actualTime), layout: '{dn} days&nbsp;&nbsp;{hn} hrs&nbsp;&nbsp;{mn} min&nbsp;&nbsp;{sn} sec', onTick: counter.progressBarCycle});
			this.updateProgressBar();
		},
		hide: function(callback){
			this.mainContainer.fadeOut(800, function(){
				if(typeof(callback) == 'function') callback();
			});
		},
		show: function(){
			setTimeout('counter.mainContainer.fadeIn(400)',1000);
		},
		init: function(){
			/* 
			 * Load the counter. 
			 * Won't start counting until start method is called (it is called from ajax response)
			 */
			// If menu is displayed, and countdown is activated, it won't show up
			// until menu is closed (but it will start anyway)
			if(menu.displayed) this.mainContainer.hide();
			
			this.loading.show();
			this.activeCountdown = true; // If menu hides countdown, it will be restored when menu is closed
			this.countdownContainer.load('/ajax/ajax.countdown.php',{override: override}, function(){ // Override is passed for debug
				counter.loading.hide();
				if(!menu.displayed)	counter.countdownContainer.show();
			});		
		}
	};
	
	/* 
	 * Object controlling chat area
	 * Duration is determined by PHP variable set on template
	 * It's start time is calculated from 
	 */	
	chat = {
		pollTimer: null,
		keepButton: false,
		toggleChat: function() {
			var chatBox = $("#playerWindow").find("iframe");
			if(chatBox.attr("src")){
				if(chatBox.css('visibility') == 'hidden'){
					// Set visibility to hidden so it chat flash isn't over player flash.
					// Player will keep working
					player.hideDisplay();
					chatBox.css('visibility','visible');
					$("#leftControls .chat").html('END CHAT');
				} else { 
					chatBox.css('visibility','hidden'); // Hide chat
					player.showDisplay(); // Restore player
					if(this.keepButton){ // In case chat time ends, but they are still chatting
						this.keepButton = false;
						this.hideButton();
					}
					$("#leftControls .chat").html('CHAT');
				}
			} else {
				player.hideDisplay();
				$("#playerWindow").append('<iframe width="770px" scrolling="no" height="475px" frameborder="0" src="/chat.php" id="chat" />');
				$("#playerWindow").find('iframe').show();
				$("#leftControls .chat").html('END CHAT');
			}
		},
		displayButton: function(){
			$("#leftControls .chat").css('opacity','0').css('display','block').animate({opacity: 1}, 300);
			// Start 4hs refresh timer. This is a measure in case
			// user leaves browser open after 1st service, it will 
			// force a page refresh to make sure the application's state
			// is reset to default status. This is a very rare case,
			// but it must be adressed
			refreshTimeout = setTimeout('window.location.reload(true)', 14400000); // 4hs
		},
		hideButton: function(){
			var chatBox = $("#playerWindow").find("iframe");
			if(chatBox.attr('src') && (chatBox.css('visibility') != 'hidden')){
				this.keepButton = true;
			} else {
				$("#leftControls .chat").fadeOut(300);
			}
		},
		init: function(start){
			$("#leftControls .chat").click(function(){
				chat.toggleChat();
			});
			if(start){
				this.displayButton();
				this.pollTimer = setInterval("chat.pollForChat('end')", 60000);
			} else {
				this.pollTimer = setInterval('chat.pollForChat()', 60000);
			}
		},
		pollForChat: function(event) {
			// Called every minute to find out if chat button should be displayed
			$.ajax({
				url: '/ajax/ajax.chatRunning.php',
				type: 'get',
				dataType: 'html',
				// noCache is to avoid IE response caching
				data: {override: override, noCache: new Date().getTime()},
				success: function(response){
					if(response) {
						if(event != 'end'){
							chat.displayButton();
							// Reset interval to start waiting for the end
							clearInterval(chat.pollTimer);
							chat.pollTimer = setInterval("chat.pollForChat('end')", 60000);
						}
					} else {
						if(event == 'end'){
							chat.hideButton();
							clearInterval(chat.pollTimer);
						}
					}
				}
				
			});
		}
	};
	
	/* Initialize main menu's actions */
	menu.init();
	
	/* Start the player if it's showtime!, if not wait until counter tells us */
	if(typeof(showLivePlayer) != 'undefined') {
		player.init();
		menu.position();
		if(typeof(showChat) != 'undefined') chat.init(true); else chat.init();
	} else {
		// If service player isn't displayed, but chat should be (it's after service, but it's still chat time)
		if(typeof(showChat) != 'undefined') chat.init(true);
		// Start countdown
		counter.init();
		player.showPromotionalImage();
	}
});