// JavaScript Document

var player = null;
var playerControl = new Object();




// outside of jq becasue the document might not be ready yet
playerControl.onInit = function() {
	
	jQuery( function($) {	// wait for the DOM to be ready
		// player is loaded and ready to go
		player = $("#playerFlash").get(0);
		playerSetVolume();
		$("#volumeSlider").slider(
			"value", PLAYER_VOLUME
		);
		PLAYER_INITIALISED = true;
	});
}


// =============================================================================
// Player config options
// =============================================================================

var MAX_TRACK_RESTART_TIME = 2000;		// the delay required before you are allowed to click on the current track
										// name again to restart it. (preventing accidental double clicks) 
									
var PLAYER_VOLUME_DISPLAY_DELAY = 800	// the length of time (ms) to show the volume slider after you're not using it anymore




// =============================================================================
// Player global vars initialisation - do not change for normal operation
// =============================================================================
	
var PLAYER_TRACK_INDEX = null;
var PLAYER_TRACK_COUNT = 0;
var PLAYER_PAUSED = false;
var PLAYER_PLAYING = false;
var PLAYER_VOLUME = 50;
var TRACK_LIST_INIT = false;
var RECENT_CLICK = false;
var PLAYER_INITIALISED = false;


var AJAX_LINKS = false;

	
jQuery( function($) {
				 
	initCuber(window.location.href);			 
				 
	
	playerControl.onUpdate = function() {
		
		/*
		$i =$("#info_volume");
		
		$i.empty();
		
		$i.append("Pos: " + this.position + " / " + this.duration + "<br>");
		$i.append("Playing: " + PLAYER_PLAYING + "<br>");
		$i.append("isPlaying: " + this.isPlaying + "<br>");
		$i.append("Paused: " + PLAYER_PAUSED + "<br>");
		
		$i.append("Now: " + Date.now() + "<br>");
		*/
		
		//window.console.log("PLAYER_PLAYING:" + PLAYER_PLAYING + "     this.isPlaying:" + this.isPlaying + "     PLAYER_JUST_STARTED_PLAYING:" + PLAYER_JUST_STARTED_PLAYING);
		if (PLAYER_PLAYING && (this.isPlaying == "false")) {
			//window.console.log("auto - moving to next track");
			if (!playerNext()) {
				playerStop();
				changeTrack(0);
			}
		}

		PLAYER_POSITION = this.position;

	}
		
				 
				 
	var PLAYER_TRACK_COUNT = $("#playerContainer .playlist a").length;

	//$("#dragHandle").css("opacity", 0.5),
	$("#playerControler").draggable(
									{
										opacity:		0.7,
										handle:			'#dragHandle',
										containment:	'body' 
									}
								);


	// ===========================
	// Drop down menues
	// ===========================
	
	$(".menu .hasMenu").each(	// top level menu items that have a drop down
		function(i, mainNav) {
			$mainNav = $(mainNav);
			var $menu = $($mainNav.attr("rel"));	// rel of the top level button is a selector for the submenu
			
			// position the sub menu in the right place
			$menu.css("left", ($mainNav.position().left));
			$menu.css("top", ($mainNav.position().top + $mainNav.outerHeight()));
			$menu.data('parent', $mainNav);
			
			// disable the click on the top level menu item
		//	$mainNav.click(function(){return false});
			
			// create the hover events
			$menu.mouseover(function() {showMenu($menu)});
			$menu.mouseout(hideMenus);
			$mainNav.mouseover(function() {showMenu($menu)});
			$mainNav.mouseout(hideMenus);
		}				 
	);
	
	
	var MENU_TIMER = null;
	var MENU_DELAY = 700;
	

	function cancelHideMenu () {
		 window.clearTimeout(MENU_TIMER);
	}

	function showMenu ($menu) {
		cancelHideMenu();
		hideMenusNow();
		$menu.show();
		
		$menu.data('parent').addClass('menu_btn_hover');
	}
	
	function hideMenus() {
		 MENU_TIMER = window.setTimeout(hideMenusNow, MENU_DELAY);
	}
	
	
	function hideMenusNow () {
		$(".menu .popupMenu").hide();
		$(".menu .hasMenu").removeClass('menu_btn_hover');	
	}
	


	// ===========================
	// Dynamic roll over menu
	// ===========================

/*	Commented

	var $melodiesNav = $("#melodies_menu");
	var $melodiesMenu = $("#melodiesMenu");
	var MENU_TIMER = null;
	var MENU_DELAY = 700;
	

	$melodiesNav.click(function(){return false});
	$melodiesNav.mouseover(showMenu);
	$melodiesNav.mouseout(hideMenu);
	$melodiesMenu.mouseover(showMenu);
	$melodiesMenu.mouseout(hideMenu);

	function cancelHideMenu () {
		 window.clearTimeout(MENU_TIMER);
	}

	function showMenu () {
		cancelHideMenu();
		$melodiesMenu.show();

		$melodiesNav.css({'background-position' : "0 0px", 'color':'#fff'});
	}
	
	function hideMenu() {
		 MENU_TIMER = window.setTimeout(hideMenuNow, MENU_DELAY);
	}
	
	function hideMenuNow () {
		$melodiesMenu.hide();
		$melodiesNav.css({'background-position' : "0 -41px", 'color':'#fff'});
	}

*/


	// ========================
	// Open headphones and start playing
	// ========================
	
	
	function openPlayerIfClosed() {
		//	window.console.log("hello");
			if($("#headphones:visible").length > 0) {
					$("#headphones").trigger("click");
				
			}
		}			
	;
													 



	// ===========================
	// Head phone click to show player
	// ===========================
	$("#headphones").click(function () {
									$("#headphones").hide();
									$("#playerContainer #playerControler").show();
									if (!TRACK_LIST_INIT) {
										// if we haven't shown the player yet - create the scroll pane first
										$("#playerContainer .playlist").jScrollPane({
											scrollbarWidth: 5,
											animateTo: true										
										});
										
										// select the first track ready for the play button
										changeTrack(0);
	
									}
									TRACK_LIST_INIT = true;
									AJAX_LINKS = true;
									return false;
								}
							);
	
	$("#playerControler > #close").click(function () {
									$("#headphones").show();
									$("#playerContainer #playerControler").hide();
									AJAX_LINKS = false;
									//PLAYER_INITIALISED = false;
									playerStop();
								}
							);


	// magic ajax a elements
/*
	var $mainContent = $("#mainContent");

	$("a").click(function () {
						   
	

		// if you clicked on a link in a player don't try to do an ajax page load
		if (
			
				($(this).attr("id") == "headphones")
			||
				($(this).parents("#playerContainer").length > 0)
			||
				($(this).hasClass("notALink"))
			||	
				($(this).parents("#fancybox-wrap").length > 0) // if this is a link inside a fancy box then don't do a magic page change
			||	
				($(this).parents("#lightbox").length > 0) // if this is a link inside a lightbox then don't do a magic page change
			)
			{
					
		} else {
		
			var url = $(this).attr("href");
			
			changePage(url);
			
			return false;
		}
	})
	
*/



	
	
	// ===========================
	// Player controls
	// ===========================




	
	function getCurrentTrackUrl() {
		var url = $("#playerContainer .playlist a").eq(PLAYER_TRACK_INDEX).attr("href");
//		window.console.log(url);
		return url;
	}
	
	
	function changeTrack(newIndex) {
		//console.log("requested index: " + newIndex);
		if ((newIndex >=0) && (newIndex < PLAYER_TRACK_COUNT)) {
			//console.log("changing track to: " + newIndex);
			PLAYER_TRACK_INDEX = newIndex;
			$("#playerContainer .playlist a").removeClass('currentTrack');
			$("#playerContainer .playlist a").eq(PLAYER_TRACK_INDEX).addClass('currentTrack');
			
			
			
			$("#playerContainer .playlist")[0].scrollTo("a:eq(" + PLAYER_TRACK_INDEX + ")");

			return true;
		} else {
			return false;	
		}
	}
	


	playerPlay = function () {
		//window.console.log("PLAYER TRACK INDEX =" + PLAYER_TRACK_INDEX + "player playing = " + PLAYER_PLAYING);
		if (PLAYER_TRACK_INDEX == null) {
			changeTrack(PLAYER_TRACK_INDEX);
		}
		
		if (!PLAYER_PLAYING) {
			//window.console.log("changing track url to: " + getCurrentTrackUrl());
			player.SetVariable("method:setUrl", getCurrentTrackUrl());
		}
		
		player.SetVariable("method:play", "");		
		player.SetVariable("enabled", "true");
		PLAYER_PAUSED = false;
		PLAYER_PLAYING = true;
	
	}
	
	playerStop = function () {
		player.SetVariable("method:stop", "");
		player.SetVariable("enabled", "false");
		PLAYER_PLAYING = false;
		PLAYER_PAUSED = false;
		// force a 'play' button
		var options = {
			label: 'pause',
			icons: {
				primary: 'ui-icon-play'
			}
		};
		$('#playerControls > #toolbar > #playControl').button('option', options);
			
	}
	
	playerPause = function () {
		player.SetVariable("method:pause", "true");
		player.SetVariable("enabled", "false");
		PLAYER_PAUSED = true;
	}
	

	playerNext = function () {
		if (changeTrack(PLAYER_TRACK_INDEX+1)) {
			player.SetVariable("method:setUrl", getCurrentTrackUrl());
			if (PLAYER_PLAYING && !PLAYER_PAUSED) {
				player.SetVariable("method:play", "");
			}
			return true;
		} else {
			return false;	
		}
	}
	
	playerPrevious = function () {
		if (changeTrack(PLAYER_TRACK_INDEX-1)) {
			player.SetVariable("method:setUrl", getCurrentTrackUrl());
			if (PLAYER_PLAYING && !PLAYER_PAUSED) {
				player.SetVariable("method:play", "");
			}
		}
	}
	
	playerSetVolume = function () {
		player.SetVariable("method:setVolume", PLAYER_VOLUME);
	}

	
	// ===========================
	// Events for player controls
	// ===========================

	//console.log($('#playerControls > #toolbar > #playControl'));
	$('#playerControls > #toolbar > #playControl').button({
			text: false,
			icons: {
				primary: 'ui-icon-play'
			}
		})
		.click(function() {
		
			var options;
			if (PLAYER_PAUSED || !PLAYER_PLAYING) {
				playerPlay();
				playerStartAnimation();
				options = {
					label: 'pause',
					icons: {
						primary: 'ui-icon-pause'
					}
				};
			
			} else {
				playerPause();
				playerStopAnimation();
				options = {
					label: 'Play',
					icons: {
						primary: 'ui-icon-play'
					}
				};
				this.blur();
			}
			$(this).button('option', options);
	});
	
	
	$('#playerControls > #toolbar > #previousControl').button({
		text: false,
		icons: {
			primary: 'ui-icon-seek-prev'
		}
	})
	.click(
		function() {
			playerPrevious();
			this.blur();
		}
	);
	
	
	$('#playerControls > #toolbar > #nextControl').button({
		text: false,
		icons: {
			primary: 'ui-icon-seek-next'
		}
	})
	.click(
		function() {
			playerNext();
			this.blur();
		}
	);
	
	$('#playerControls > #toolbar > #volumeControl').button({
		text: false,
		icons: {
			primary: 'ui-icon-volume-on'
		}
	})
	.click(
		function() {
			showVolume();
			this.blur();
		}
	);	

	$('#playerControler > #close').button({
		text: false,
		icons: {
			primary: 'ui-icon-circle-close'
		}
	});	



	// ===========================
	// Volume control
	// ===========================
	var VOLUME_TIMER = null;
		
	$("#volumeSlider").slider({
							  	slide:	function(event, ui) {
								  			PLAYER_VOLUME =  ui.value;
											
											playerSetVolume();
							  			},
								value:	100
							  });
	
	$("#volumeContainer")
	.mouseover(
		stopVolumeTimer
	)
	.mouseout(
		startVolumeTimer
	);


	function startVolumeTimer() {
		VOLUME_TIMER = window.setTimeout(hideVolume, PLAYER_VOLUME_DISPLAY_DELAY);
	}
	
	function stopVolumeTimer() {
		window.clearInterval(VOLUME_TIMER);
	}


	function showVolume() {
		$("#volumeContainer").show();	
		startVolumeTimer();
	}
	
	
	
	function hideVolume() {
		$("#volumeContainer").hide();
	}
	

	

	$(".playlist a").live("click",
		function(event) {
			event.preventDefault();
			
			//window.console.log("a click" + PLAYER_INITIALISED + PLAYER_PLAYING);
			openPlayerIfClosed();

			if(!PLAYER_INITIALISED) {
				$this = $(this);
				window.setTimeout(function() {$this.trigger("click")}, 200);
				return false;	
			}
			
			var url = $(this).attr('href');
			var linkWeWant = $("#playerContainer .playlist a[href=" + $(this).attr('href') + "]"); 
//			window.console.log(linkWeWant)
			var index = $("#playerContainer .playlist a").index(linkWeWant);
//			window.console.log(index);
			if (RECENT_CLICK && (index == PLAYER_TRACK_INDEX)) {
				// make sure you can't start playing the same track twice very quickly 
				return false;	
			}
			
			RECENT_CLICK = true;
			
			
			changeTrack(index);
			playerStop();	// stop ...
			playerPlay();	// ... so that playing again resets the url.
			playerStartAnimation();
			
			
			window.setTimeout("RECENT_CLICK=false", MAX_TRACK_RESTART_TIME)
			
			// force a 'pause' button
			var options = {
				label: 'pause',
				icons: {
					primary: 'ui-icon-pause'
				}
			};
			$('#playerControls > #toolbar > #playControl').button('option', options);
			
			
			//return false;	
		}
		
	);

	
	var PLAYER_ANIMATION_TIMER = null;
	var PLAYER_ANIMATION_INDEX = 0;
	var $PLAYER_CONTAINER = $("#playerContainer");
	var PLAYER_ANIMATION_CSS = [
		{"background-position" : "0px 0px"},
		{"background-position" : "0px -273px"},
		{"background-position" : "0px -546px"},
		{"background-position" : "0px -273px"}
	];
	
	function playerStartAnimation() {
		PLAYER_ANIMATION_TIMER = window.setTimeout(playerAnimate, 120);	
	}
	function playerStopAnimation() {
		window.clearTimeout(PLAYER_ANIMATION_TIMER);
		PLAYER_ANIMATION_INDEX = 0;
		$PLAYER_CONTAINER.css(PLAYER_ANIMATION_CSS[PLAYER_ANIMATION_INDEX]);
		
	}
	function playerAnimate() {
	
		$PLAYER_CONTAINER.css(PLAYER_ANIMATION_CSS[PLAYER_ANIMATION_INDEX]);

		PLAYER_ANIMATION_INDEX++;
		PLAYER_ANIMATION_INDEX = (PLAYER_ANIMATION_INDEX % 4);
		
	
		if (PLAYER_PLAYING) {
			playerStartAnimation();
		}
	}
	
	
	


});

	
function changePage(url) {
	// this is a separate function so we can also call it from the cu3er thingy...
	if (AJAX_LINKS) {
//		console.log(url);
		$("#mainContent").load(url + " #mainContent > *",function(){
			initCuber(url);
		}); 
	} else {
		window.location = url;	
	}
}

function changePageFlash(url) {
	if (AJAX_LINKS) {
		window.setTimeout("changePage('" + url +"')", 500);
	} else {
		changePage(url);	
	}
	
}

function initCuber(url) {
// horrid hack to make the cuber thingy work on the home page for ajax loaded pages
	if ( ($("#cu3er").length > 0) && (url != "") ){

// add your FlashVars
		var page = url.match(/\/([^\/]+).html$/);
		page = page ? page[1] : "index";
//			console.log(page[1]);


var vars = { xml_location : '/cu3er_config/' + page + '.xml' };
// add Flash embedding parameters, etc. wmode, bgcolor...
var params = { bgcolor : '#000000' };
// Flash object attributes id and name
var attributes = { id:'cu3er', name:'cu3er' };
// dynamic embed of Flash, set the location of expressInstall if needed
swfobject.embedSWF('/flash/cu3er.swf', "cu3er", 735, 200, "9.0.45", "/js/expressinstall.swf", vars, params, attributes );
// initialize CU3ER class containing Javascript controls and events for CU3ER
//  var CU3ER = new CU3ER("CU3ER");

//			var flashvars = {};
//			console.log(url);
//			var page = url.match(/\/([^\/]+).html$/);
//			page = page ? page[1] : "index";
//			console.log(page[1]);
//			flashvars.xml = "/cu3er_config/" + page + ".xml";
//					flashvars.font = "/font.swf";
//			var attributes = {};
//			attributes.wmode = "transparent";
//			attributes.id = "slider";
//			swfobject.embedSWF("/flash/cu3er.swf", "cu3er-container", "735", "200", "9", "/expressInstall.swf", flashvars, attributes);
	}
	
	// also init light boxes that we might need here
	$('a:has(img)[rel=gallery]').lightbox();
	$('a:has(img)[rel=gallery-lighting]').lightbox();
	$('a:has(img)[rel=gallery-bronze]').lightbox();
	$('a:has(img)[rel=gallery-silver]').lightbox();
	$('a:has(img)[rel=gallery-gold]').lightbox();
	$('a[rel=gallery]').lightbox();
	
	
	// and fancy boxes...
	
/*	$("a.fancyBox").fancybox({
		'titleShow'		: false,
		'type': 'iframe',
		'width': 700,
		'height': 520
		
	});
*/
	$("a.fancyBox").fancybox({
		'titleShow'		: false,
		type: 'swf'
		
	});


	// wait till the page has loaded before displaying the nivo slider
	$(window).load(function() {
		$('#slider').css('display','block');
	});


}


