/******************************
 ** CONSTANTS *****************
 ******************************/
window.LAST_PAGE_COOKIE_NAME = "lastWorldsPageViewed";

/******************************
 ** OBJECTS *******************
 ******************************/

/**
 * PageState
 * The page state object
 */
PageState = function( pagePath, bookmarkValue ) {
	this.pagePath = pagePath;
	this.changeUrl = bookmarkValue || false;
	this.displayPage();
}

dojo.extend(
	PageState,
	{
		back: function() {
			this.showBackForwardMessage("BACK for State Data: " + this.pagePath);
			this.displayPage();
		},
		forward: function() {
			this.showBackForwardMessage("FORWARD for State Data: " + this.pagePath);
			this.displayPage();
		},
		displayPage: function() {
			showPage( this.pagePath );
		},
		showBackForwardMessage: function( message ) {
			if ( console && console.debug ) {
				console.debug( message );
			}
		}
	}
);

/**
 * DialogState
 * The dialog state object
 */
DialogState = function( dialogId, bookmarkValue ) {
	this.dialogId = dialogId;
	this.changeUrl = bookmarkValue || false;
}

dojo.extend(
	DialogState,
	{
		back: function() {
			this.showBackForwardMessage( "BACK for State Data: " + this.dialogId );
			this.closeDialog();
		},
		forward: function() {
			this.showBackForwardMessage( "FORWARD for State Data: " + this.dialogId );
			// Do nothing
		},
		closeDialog: function() {
			dijit.byId( this.dialogId ).hide();
		},
		showBackForwardMessage: function( message ) {
			console.debug( message );
		}
	}
);

/**
 * Hashtable for special functions to run for specific pages
 */
var pageLoadHash = new dojox.collections.Dictionary();
// Teaser Home
//pageLoadHash.add( "teaser/index", function() {
//
//	var container = dojo.byId( "specialHolder" );
//
//	dojo.addClass( "contentHolder", "hide" );
//	dojo.addClass( container, "display" );
//	
//	if ( container.hasChildNodes() ) {
//		// TODO remove child nodes if need to implement more of these special function handlers
//	}
//	else {
//		var flashDiv = document.createElement( "div" );
//		flashDiv.id = "homePageFlash";
//		container.appendChild( flashDiv );
//
//		swfobject.embedSWF(
//			"common/swf/home.swf", 
//			"homePageFlash", 
//			"1024", 
//			"565", 
//			"9.0.0", 
//			"", 
//			{}, 
//			{
//				align: "t",
//				salign: "t",
//				scale: "noscale",
//				bgcolor: "#F4F1E4",
//				wmode: "opaque",
//				base: "common/swf",
//				menu: "false"
//			}
//		);
//	}
//	
//	updateTitle( window.defaultTitle );
//
//	pageTracker._trackPageview( "/worlds/2008/" + window.defaultHomePage + ".html" );
//
//	dojo.cookie( LAST_PAGE_COOKIE_NAME, window.defaultHomePage );
//
//
//	if ( dojo.exists( "setOnState", dojo.byId( "headerFlash" ) ) ) {
//		dojo.byId( "headerFlash" ).setOnState( "teaser/index" );
//	}
//} );

/**
 * Hashtable for special functions to run after a specific page has been loaded
 */
var postLoadHash = new dojox.collections.Dictionary();
postLoadHash.add( "content/home", function() {

	dojo.attr( "newsNoJavaScriptMessage", "style", "display: none;" );
	dojo.removeAttr( "newsLoadingMessage", "style" );

	loadNewsTabs( getHostPath() );

	// flash movie
	swfobject.embedSWF(
		"common/swf/WC08_movie_main.swf", 
		"animationFlash", 
		"500", 
		"415", 
		"9.0.0", 
		"", 
		{}, 
		{
			align: "t",
			salign: "t",
			bgcolor: "#F4F1E4",
			wmode: "transparent",
			base: "common/swf",
			play: "true",
			loop: "false",
			menu: "false"
		}
	);

	// flash counter
//	swfobject.embedSWF(
//		"common/swf/countdownFlip_txt.swf", 
//		"countdownFlash", 
//		"475", 
//		"100", 
//		"9.0.0", 
//		"", 
//		{}, 
//		{
//			align: "t",
//			salign: "t",
//			bgcolor: "#F4F1E4",
//			wmode: "transparent",
//			base: "common/swf",
//			play: "true",
//			loop: "false",
//			menu: "false"
//		}
//	);
});

postLoadHash.add( "content/whatis/index", function() {
	// flash movie
	swfobject.embedSWF(
		"common/swf/WC08_movie.swf", 
		"animationFlash", 
		"700", 
		"582", 
		"9.0.0", 
		"", 
		{}, 
		{
			align: "t",
			salign: "t",
			bgcolor: "#F4F1E4",
			wmode: "transparent",
			base: "common/swf",
			play: "true",
			loop: "false",
			menu: "false"
		}
	);
});
/******************************
 ** FUNCTIONS *****************
 ******************************/

/**
 * setPageTitle
 * Sets the text in the title bar using a hiddle div in the page
 */
function setPageTitle() {
	var tDiv = dojo.byId( "pageTitle" );
	if ( tDiv == null ) {
		return;
	}

	updateTitle( tDiv.innerHTML );
	
	this.focus();
	window.focus();
	setTimeout( "window.focus()", 500 );
}

/**
 * updateTitle
 * Sets the text in the title bar
 */
function updateTitle( newTitle ) {

	var title = $$( "html title" );
	if ( title.length > 0 ) {
		try {
			title[ 0 ].text = newTitle;
		}
		catch ( e ) {
			// Do nothing
		}
	}
}

/**
 * useSIFR
 * Use sIFR to replace some html text with flash text that has an explicit font
 */
function useSIFR( selector, bgColor, flashFile, padding, flashVars ) {
	sIFR.replaceElement(named({
		sSelector: selector, 
		sFlashSrc: "common/swf/" + flashFile, 
		sColor:"#000000", 
		sLinkColor:"#000000", 
		sWmode:"transparent",
		sBgColor: bgColor, 
		sHoverColor:"#000000", 
		nPaddingTop: padding, 
		nPaddingBottom: padding, 
		sFlashVars: flashVars
	}));
}

/**
 * doLink
 * Execute a link
 */
function doLink( path ) {
	dojo.back.addToHistory( new PageState( path ) );
}

/**
 * showPage
 * Get and show the actual page
 */
function showPage( path, doSpecielLookup ) {

	if ( path == null || path == "" ) {
		return;
	}

	if ( doSpecielLookup == undefined ) {
		doSpecielLookup = true;
	}

	if ( doSpecielLookup ) {
		var specialFunc = pageLoadHash.item( path );
		if ( specialFunc != null ) {
			specialFunc();
			return;
		}
	}

	var hostPath = getHostPath();

	if ( path.indexOf( "||" ) >= 0 ) {
		window.currentBookmark = path.substring( path.indexOf( "||" ) + 2 );
		path = path.substring( 0, path.indexOf( "||" ) );
	}

	// Get and display the page
	dojo.xhrGet( {
		url: hostPath + path + ".html",
		handleAs: "text",
		handle: function( responseText) {
			if ( responseText == undefined ) {
				this.error( null );
				return;
			}
	
			loadPage( responseText, path );
		},
		error: function( response ) {
			dojo.xhrGet( {
				url: hostPath + "pagenotfound.html",
				handleAs: "text",
				handle: function( responseText) {
					loadPage( responseText, "pagenotfound" );
				}
			} );
		}
	} );
}

/**
 * setHeaderOnState
 * Set the on state of the header
 */
function setHeaderOnState( pagePath ) {
	if ( dojo.exists( "setOnState", dojo.byId( "headerFlash" ) ) ) {
		dojo.byId( "headerFlash" ).setOnState( pagePath );
	}
}

/**
 * loadPage
 * Loads a pages content and anything else that needs to be done
 */
function loadPage( pageText, pagePath, customPageFrame ) {

	var frame;
	if ( customPageFrame != undefined ) {
		frame = customPageFrame;
	}
	else {
		frame = window.pageFrame;
	}

	setTimeout( setHeaderOnState, 0, pagePath );

	frame.innerHTML = pageText;

	dojo.removeClass( "specialHolder", "display" );
	dojo.removeClass( "contentHolder", "hide" );

	useSIFR( "body #page #content h1.withoutSidebar", "#5E5D5D", "headerfont.swf", 10, "textalign=center&offsetTop=0" );
	useSIFR( "body #page #content h1.withSidebar", "#5E5D5D", "headerfont.swf", 10, "textalign=left&offsetTop=0" );
	useSIFR( "body #page #content h2", "#5E5D5D", "headerfont.swf", 10, "textalign=left&offsetTop=0" );

	var specialFunc = postLoadHash.item( pagePath );
	if ( specialFunc != null ) {
		specialFunc();
	}

	if ( dojo.exists( "correctPNG" ) ) {
		correctPNG();
	}

	setPageTitle();

	pageTracker._trackPageview( "/worlds/2008/" + pagePath + ".html" );

	if ( pagePath != "pagenotfound" ) {
		dojo.cookie( LAST_PAGE_COOKIE_NAME, pagePath );
	}

	if ( window.currentBookmark == "" || window.currentBookmark == "#" ) {
		window.scroll( 0, 0 );
	}
	else {
		scrollToElement( window.currentBookmark );
		window.currentBookmark = "";
	}
	
	var id_prefix = "sidebar_";
	var sidebar_item_id = id_prefix + pagePath.substring( pagePath.indexOf( "/" ) + 1 );
	while ( sidebar_item_id.indexOf( "/" ) >= 0 ) {
		sidebar_item_id = sidebar_item_id.replace( "/", "-" );
	}
	var sidebar_item = document.getElementById(sidebar_item_id);
	if ( sidebar_item != undefined ) {
		dojo.addClass(sidebar_item, "highlighted");
	}

	ua=navigator.userAgent.toLowerCase();
	
	if (ua.indexOf("mac") != -1)
	{
		dojo.addClass(document.getElementsByTagName("html")[0], "mac");
	}

}

/**
 * 	displayPhotoGallery
 * Displays a photo gallery
 */
function displayPhotoGallery( ref ) {

	if ( ref == null || ref == "" ) {
		return;
	}

	// Make back button close dialog
	dojo.back.addToHistory( new DialogState( "photoDialog" ) );

	var urlString = ref + ".json";
	var store = new dojo.data.ItemFileReadStore( {url: urlString } );
		
	var gal = dijit.byId( "photoGallery" );
	gal.reset();
	try {
		gal.setDataStore(
			store, 
			{query: {}, count: 5}, 
			{imageThumbAttr: "thumb", imageLargeAttr: "large"}
		);
	}
	catch ( e ) {
		// Do nothing
	}

	dojo.xhrGet( {
		url: urlString,
		handleAs: "json",
		handle: function( responseJson ) {
			var d = dijit.byId( "photoDialog" );
			d.titleNode.innerHTML = responseJson.title;
			d.show();

			pageTracker._trackPageview( "/worlds/2008/photos/" + ref + ".html" );
		}
	} );
}


/**
 * displayVideo
 * Displays a flash video
 */
function displayVideo( ref ) {

	if ( ref == null || ref == "" ) {
		return;
	}

	// Make back button close dialog
	dojo.back.addToHistory( new DialogState( "videoDialog" ) );

	var urlString = ref + ".json";
	dojo.xhrGet( {
		url: urlString,
		handleAs: "json",
		handle: function( responseJson ) {

			swfobject.embedSWF(
				"common/swf/videoplayer.swf", 
				"videoplayer", 
				"490", 
				"425", 
				"8", 
				"", 
				{
					title: responseJson.title,
					videoPath: "" + responseJson.videoPath
				}, 
				{
					align: "t",
					salign: "t",
					wmode: "transparent",
					scale: "noscale",
					base: "common/swf"
				}
			);

			var downloadFile = responseJson.downloadFile.substring( responseJson.downloadFile.indexOf( "/worlds/2008/" ) );

			// Update the download href
			dojo.attr( 
				"videodownload", 
				"href",
				downloadFile 
			);

			dojo.attr( 
				"videodownload", 
				"onclick",
				downloadFile
			);

			var d = dijit.byId( "videoDialog" );
			d.titleNode.innerHTML = responseJson.title;
			
			d.show();

			pageTracker._trackPageview( "/worlds/2008/videos/" + ref + ".html" );
		}
	} );
}

/**
 * trackPage
 * Track a clicked link passing in the anchor object
 */
function trackPage( link ) {
	pageTracker._trackPageview( link.pathname );
}


/******************************
 ** UTILITIES *****************
 ******************************/

/**
 * scrollToElement
 * Scroll to an element (only works by id attribute)
 */
function scrollToElement(elementID)
{
	var theElement = dojo.byId( elementID );
	if(theElement != null) {
		var selectedPosX = 0;
		var selectedPosY = 0;
 
			while( theElement != null ){
			selectedPosX += theElement.offsetLeft;
			selectedPosY += theElement.offsetTop;
			theElement = theElement.offsetParent;
		}
 
		window.scrollTo( selectedPosX, selectedPosY );
	}
 
}

/**
 * getHostPath
 * Get the host path (minus the ending file)
 */
function getHostPath() {
	var path = new String( window.location );
	if ( path .lastIndexOf( "?" ) > 0 ) {
		path = path .substring( 0, path .lastIndexOf( "?" ) );
	}
	else if ( path .lastIndexOf( "#" ) > 0 ) {
		path = path .substring( 0, path .lastIndexOf( "#" ) );
	}
	else {
		path = path .substring( 0, path .lastIndexOf( "/" ) + 1 );
	}

	return path;
}


/**
 * openWindow
 * Opens a New (non-scrolling) Window with the specified URL
 */
function openWindow(url, target, width, height, centerWindow) {
	var left, top;
	if (centerWindow) {
		left = (screen.width - width) / 2;
		top = (screen.height - height) / 2;
	} else {
		left = 0;
		top = 0;
	}
	var win = window.open(url, target, "toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=no, width=" + width + ", height=" + height + ", top=" + top + ", left=" + left);
	if (win === null || typeof (win) == "undefined") {
		alert("It appears that you have pop up blocking for this website turned on.  To view the form, please turn off pop up blocking for this website.");
	}

	win.focus();
	
	return win;
}

/**
 * openExternalLink
 * Checks to see if the pop up needs to be displayed before going to the link
 */
function openExternalLink( linkObject ) {
	if ( !linkObject ) {
		return;
	}

	var link = linkObject.href;
	popup = openWindow("/common/popup.html?url=" + link, "_blank", 450, 200, true);

	return false;
}

/**
 * clearVideo
 * Destroys the video player so the sound doesn't keep playing
 */
function clearVideo() {
	var oldVP = dojo.byId( "videoplayer" );
	var parent = oldVP.parentNode;
		
	var newVP = document.createElement( "div" );

	parent.replaceChild( newVP, oldVP );

	dojo.attr( newVP, "id", "videoplayer" );

	return true;
}

/**
 * addEvent
 * Non-destructively attach a function to any event.
 * @example addEvent(window, 'load', functionName);
 */
if (typeof addEvent == 'undefined') {
	function addEvent(obj, evType, fn) {
		if (obj.addEventListener) {
			obj.addEventListener(evType, fn, true);
			return true;
		} else if (obj.attachEvent){
			var r = obj.attachEvent("on"+evType, fn);
			return r;
		} else {
			return false;
		}
	}
}

/******************************
 ** ON PAGE LOAD **************
 ******************************/

dojo.addOnLoad( function() {

	// Save original title
	window.defaultTitle = document.title;

	// Initialize the page frame variable
	window.pageFrame = dojo.byId( "contentBottom" );

	// Should we display the default page, or is one defined in the query string?
	var appState;
	var cookieValue = dojo.cookie( window.LAST_PAGE_COOKIE_NAME );
	var query = window.location.hash;
	if ( query != null && query != "" && query != "#" ) {
		if ( query.indexOf( "||" ) > 0 ) {
			window.currentBookmark = query.substring( query.indexOf( "||" ) + 2 );
			query = query.substring( 0, query.indexOf( "||" ) );
		}
		appState = new PageState( query.substring( 1 ) );
		window.location.hash = "#";
	}
	else if ( cookieValue != null && cookieValue != "" && cookieValue.indexOf( window.defaultHomePage.substring( 0, window.defaultHomePage.indexOf( "/" ) ) ) == 0 ) {
		appState = new PageState( cookieValue );
	}
	else {
		appState = new PageState( window.defaultHomePage );
	}
	dojo.back.setInitialState( appState );

	// Remove the video player swf because the sound will continue to play
	dojo.connect( 
		dijit.byId( "videoDialog" ), 
		"onCancel",
		null,
		"clearVideo"
	);
} );
