
//-- setup global vars:
var currentSection = "";
var currentSubSection = "";
var hasCalledOpenPage = true;

/**
 * Redirect to a hash location is hash exists
 */
$(window).load(function() {  
	var hashPath = window.location.hash;
	if (hashPath.length > 0) {
		hashPath = hashPath.substr(1,hashPath.length);
		window.location = BASE_URL + hashPath;
	}
});

/**
 * Document ready
 */
$(document).ready(function() {	
	//-- init variables:
	currentSection = findSectionName(window.location);
	currentSubSection =  findSubSectionName(window.location);
	
	//remove titles from the main menu:
	$('.mainMenu a').attr("title","");
	
	//-- because of IE, opacity on highlights in main menu need to be switched off manually:
	$('.mainMenu a .highlighted').css('opacity', 0);
	
	//-- turn on display of mainHeadingLoader by script because it has to be turned off by default:
	$('#mainHeadingLoader').css('display', 'block');
	
	
	//--- setup functions for navigation clicking:
	$('#nav li a').click(function(){
		openPage($(this).attr('href'));	
		return false;
	});	
	
	//------- setup link effects..
	setupMainMenuLinks();
	setupTagsLinks();
	setupMainContentLinks();
	setupMainBottomLinks();
	setupSubMenuLinks();
	setupSuggestedLinks();
	setupBlogContentLinks();
	setupBlogBottomLinks();
	
	//-- setup other page-specific stuff
	setupAfterPageLoaded();
	setupAfterBottomOfPageLoaded();
});

/**
 * Handling of back/forward browser buttons
 */
$.address.change(function(event) {
	//-- get page that is requested, without the "/" in its fron
	var pageToOpen = convertWindowHashedPathToNormal();
	
	//-- has this been called through the browser buttons rather than the openPage function?
	if (!hasCalledOpenPage) {
		openPage(pageToOpen);
	}	
	hasCalledOpenPage = false;
});

/**
 * Setup page-specific functions, after content is loaded and current section is known
 */
function setupAfterPageLoaded() {
	if (pageCanAddComments()) {
		setupAddCommentHtml();
		//-- turn off display of noscript objects:
		$('.noScript').css('display', 'none');
	}
	
	//--- nxcUserInteractionLibrary
	if (currentSubSection.indexOf("nxcUserInteractionLibrary") >= 0) {
		onNcxUserInteractionLibraryPageLoaded(currentSection + currentSubSection);
	}
}

function setupAfterBottomOfPageLoaded() {
	if (pageCanAddComments()) {
		setupShowAddCommentButton();
		setupShareButtons();
	}
}


/**
 * Opens a new page using JQuery effects
 * params: pageUrl: full URL of page (e.g. openPage("<?php echo base_url();  ?>work");  )
 */
function openPage(pageURL_, reloadOtherPanels) {
	var pageURL = pageURL_ + "";
	hasCalledOpenPage = true;
	
	if(reloadOtherPanels == null) reloadOtherPanels = true; //default behaviour of left and right panels
	
	//-- remove 'index.php' from the path
	pageURL.replace("/index.php","");
	//-- find out whether it is an internal link, if external change location
	if (pageURL.indexOf(BASE_URL) < 0) {
		window.open(pageURL,'_blank');
		return true;
	}
	
	//-- find the current and new section name:
	var newSection = findSectionName(pageURL);
	var newSubSection = findSubSectionName(pageURL);
	
	//-- set browser hash to reflect path:
	window.location.hash = newSection + newSubSection;
	
	//-- animate away from rollover state
	$(this).find('.highlighted').animate({
		'opacity': 0
	},500);
	
	//-- get paths to what to load:		
	var newTagsContent = pageURL +' #tagsContent';
	
	var newScriptContent = pageURL + '#scripts';
	var newMenuContent = pageURL+' #menuContent';
	var newSuggestedContent = pageURL +' #suggestedContent';
				 
	var newMainHeading = pageURL +' #mainHeading'; 
	var newMainContent = pageURL +' #mainContent';
	var newMainBottom = pageURL +' #mainBottom';
	
	var newTitle = pageURL + ' title';

	//-- timing settings:
	var DELAY_CONTENT_AFTER_MENU = 200;
	var DELAY_TAGS_AFTER_MAIN_CONTENT = 200;
	var DELAY_BOTTOM_AFTER_MAIN_CONTENT = 400;
	
	//-- show preloaders & load new content:
	
	//- is new page? when new subsection name or when subsections match but new section
	var isNewPage = false;
	if (newSubSection != currentSubSection) {
		isNewPage = true;
	} else {
		if (newSection != currentSection) {
			isNewPage = true;
		}
	}
	
	var isNewSection = false;
	if (newSection != currentSection) {
		isNewSection = true;
	}
	
	//--- remember the current section:
	currentSection = newSection;
	currentSubSection = newSubSection;
	
	
	//-- never reload tags
	/*if (isNewPage) {
		loadNewContentWithFadeIn($('#tagsContent'), newTagsContent, DELAY_CONTENT_AFTER_MENU, DELAY_TAGS_AFTER_MAIN_CONTENT, setupTagsLinks);
	}*/
	
	//-- reload page title
	loadNewContent($('title'), newTitle, 0, 0);
	
	//-- display prelaoder & load page heading
	$("#mainHeadingLoader").css("opacity", 1);
	if (reloadOtherPanels) {
		loadNewContentWithFadeIn($('#mainHeading'), newMainHeading, DELAY_CONTENT_AFTER_MENU,0,function() {
			//-- call reinitialize on typeface js so that the new heading is rendered
			window._typeface_js.reinitialize();
		});
	}
	
	//-- always load content
	loadNewContentWithFlicker($('#mainContent'), newMainContent, DELAY_CONTENT_AFTER_MENU, 0, function() { 	
		setupMainContentLinks();
		$("#mainHeadingLoader").css("opacity", 0);
		setupAfterPageLoaded();
		
	});
	loadNewContentWithFadeIn($('#mainBottom'), newMainBottom, DELAY_CONTENT_AFTER_MENU, DELAY_BOTTOM_AFTER_MAIN_CONTENT, function() {
		setupMainBottomLinks();
		setupAfterBottomOfPageLoaded();
	});
	
	//-- only change submenu if new section:
	if (reloadOtherPanels) {
		if (isNewSection) {
			loadNewContentWithSlideIn($('#menuContent'), newMenuContent, 0, 0, setupSubMenuLinks);
			//--- set the section menu heading:
			displayNewContentWithFadeIn($("#sectionHeading"),"[" + newSection+"]" );
		} else {
			redisplaySubMenus();
		}
		
		//-- only load suggested if new page:
		if (isNewPage) {
			loadNewContentWithSlideIn($('#suggestedContent'), newSuggestedContent, 0, 0, setupSuggestedLinks);
		}
	}	
}





/** ================================================== LINK EFFECTS =============================== **/
/**
 * Make all links in main menu fade into highlighed on hover
 */
function setupMainMenuLinks() {
	setUpLinkEffects($(".mainMenu a"),function() { //mouseover for main meny links
		$(this).find('.highlighted').animate({
			'opacity': 1
		},MAIN_MENU_SPEED_IN);
	},function() { //mouseout
		$(this).find('.highlighted').animate({
			'opacity': 0
		},MAIN_MENU_SPEED_OUT);
	}); 
}


/**
 * Make all links Tags enlarge on hover
 */
function setupTagsLinks() {
	
	setUpLinkEffects($("#tagsContent a"),function() {
		this.originalSize = $(this).css('font-size');
		var col = 'rgb(255,255,0)';
		var targetSize = parseInt(this.originalSize) + 2;
		$(this).animate({
			'color': col,
			'font-size' : targetSize + 'px'
		},SUB_MENU_SPEED_IN);
	},function() { //mouseout
		var col = 'rgb(255,255,255)';
		$(this).animate({
			'color': col,
			'font-size' : this.originalSize
		},SUB_MENU_SPEED_OUT);
	}); 
}


/**
 * Make all links in main content turn blue on hover & openPage on click if of 'internal' class
 */
function setupMainContentLinks() {
	//--- setup click effects:
	$('#mainContent a:not(.button)').click(function() {
		//-- if there is class noReloadOtherPanels, don't reload other pages
		if ($(this).hasClass('noReloadOtherPanels')) {
			openPage($(this).attr('href'), false);
		} else {
			openPage($(this).attr('href'));
		}
		return false;
	});
	//-- setup effects on ordinary text links:
	var original = $('#mainContent a:not(.largeButton)').css('color');
	setUpLinkEffects($('#mainContent a:not(.largeButton)'), function() { 
		var col = 'rgb(17,51,68)';
		$(this).animate({
			'color': col
		},LINK_SPEED_IN);
	},function() { //mouseout
		$(this).animate({
			'color': original
		},LINK_SPEED_OUT);
	});
	
	//-- setup effects on large buttons
	var original2 = $('#mainContent').find(".largeButton").css('background-color');
	setUpLinkEffects($('#mainContent').find(".largeButton"), function() { 
		//var col2 = 'rgb(153,153,153)';
		var col2 = 'rgb(150,150,0)';
		$(this).animate({
			
			'background-color': col2
		},LINK_SPEED_IN);
	},function() { //mouseout
		$(this).animate({
			'background-color': original2
		},LINK_SPEED_OUT);
	});
}

/**
 * Make all links in bottom, main section call openPage on click if of 'internal' class
 * Make all links in bottom, main section animate to the top and change color
 */
function setupMainBottomLinks() {
	//--- setup click effects:
	$('#mainBottom a:not(.button)').click(function() {
		//-- if there is class noReloadOtherPanels, don't reload other pages
		if ($(this).hasClass('noReloadOtherPanels')) {
			openPage($(this).attr('href'), false);
		} else {
			openPage($(this).attr('href'));
		}
		return false;
	});
	//-- setup effects:
	var originalSize = $('#mainBottom a').css('font-size');
	var original = $('#mainBottom a').css('color');
	setUpLinkEffects('#mainBottom a', function() { //mouseover for yellow links, to white
		var col = 'rgb(255,255,255)';
		var targetSize = parseInt(originalSize) + 1;
		$(this).animate({
			'color': col,
			
			'padding-top' : '1px',
			//'font-size' : targetSize + 'px',
		},LINK_SPEED_IN);
	},function() { //mouseout
		$(this).animate({
			'color': original,
			
			//'font-size' : originalSize,
			'padding-top' : '4px',
		},LINK_SPEED_OUT);
	});
}



/**
 * Make all links in submenu call openPage on click
 * Make all links in submenu animate to the left and glow on hover
 */
function setupSubMenuLinks() {
	//-- hide all submenus and dispplay proper one:
	redisplaySubMenus();
	//--- setup click effects:
	$('#menuContent li a:not(.button)').click(function(){
		if ($(this).hasClass('noReloadOtherPanels')) {
			openPage($(this).attr('href'), false);
		} else {
			openPage($(this).attr('href'));
		}		
		return false;
	});
	//--- setup effects:
	setUpLinkEffects($('#menuContent a'), function() { 
		var col = 'rgb(255,255,0)';
		$(this).animate({
			'color': col,
			'padding-left' : '2px'
		},SUB_MENU_SPEED_IN);
	},function() { //mouseout
		var col = 'rgb(255,255,255)';
		$(this).animate({
			'color': col,
			'padding-left' : '0px'
		},SUB_MENU_SPEED_OUT);
	});
}

/**
 * Make all links in Suggested call openPage on click
 * Make all links in Suggested animate to the left and glow on hover
 */
function setupSuggestedLinks() {
	//--- setup click effects:
	$('#suggestedContent li a').click(function(){
		if ($(this).hasClass('noReloadOtherPanels')) {
			openPage($(this).attr('href'), false);
		} else {
			openPage($(this).attr('href'));
		}
		return false;
	});
	//--- setup effects:
	setUpLinkEffects($('#suggestedContent a'), function() { 
		var col = 'rgb(255,255,0)';
		$(this).animate({
			'color': col,
			'padding-left' : '2px'
		},SUB_MENU_SPEED_IN);
	},function() { //mouseout
		var col = 'rgb(255,255,255)';
		$(this).animate({
			'color': col,
			'padding-left' : '0px'
		},SUB_MENU_SPEED_OUT);
	});
}


/**
 * Make all links in blog content turn blue on hover & openPage on click if of 'internal' class
 */
function setupBlogContentLinks() {
	//--- setup click effects:
	$('#blogContent a:not(.button)').click(function(){
		if ($(this).hasClass('noReloadOtherPanels')) {
			openPage($(this).attr('href'), false);
		} else {
			openPage($(this).attr('href'));
		}
		return false;
	});
	//-- setup effects:
	var original = $('#blogContent a:not(.inverted)').css('color');
	setUpLinkEffects($('#blogContent a:not(.inverted)'), function() { 
		var col = 'rgb(17,51,68)';
		$(this).animate({
			'color': col
		},LINK_SPEED_IN);
	},function() { //mouseout
		$(this).animate({
			'color': original
		},LINK_SPEED_OUT);
	});
}


/**
 * Make all links in bottom, blog section call openPage on click if of 'internal' class
 * Make all links in bottom, blog section animate to the top and change color
 */
function setupBlogBottomLinks() {
	//--- setup click effects:
	$('#blogBottom a:not(.button)').click(function(){
		if ($(this).hasClass('noReloadOtherPanels')) {
			openPage($(this).attr('href'), false);
		} else {
			openPage($(this).attr('href'));
		}
		return false;
	});
	//-- setup effects:
	var originalSize = $('#blogBottom a').css('font-size');
	var original = $('#blogBottom a').css('color');
	setUpLinkEffects('#blogBottom a', function() { //mouseover for yellow links, to white
		var col = 'rgb(255,255,255)';
		var targetSize = parseInt(originalSize) + 1;
		$(this).animate({
			'color': col,
			'padding-top' : '1px',
		},LINK_SPEED_IN);
	},function() { //mouseout
		$(this).animate({
			'color': original,
			
			//'font-size' : originalSize,
			'padding-top' : '4px',
		},LINK_SPEED_OUT);
	});
}



//========================================== DISPLAYING SUBMENUS

var lastSubSectionMainName = "";

/**
 * Hide all submenus and display current
 */
function redisplaySubMenus() {
	//-- only do something if new subsection
	var currentSubSectionMainName = findSubSectionMainName(currentSubSection);	
	if (lastSubSectionMainName != currentSubSectionMainName) {
		$('#menuContent li ul').css("display","none");
		//-- find current subsection menu & display it
		$('#menuContent li #'+currentSubSectionMainName).slideToggle(MAIN_MENU_SPEED_IN);
		lastSubSectionMainName = currentSubSectionMainName;
	}
}


//========================================== DISPLAYING NEW CONTENT
/**
 * Display new content using fade out / fade in animation
 */
function displayNewContentWithFadeIn(contentDiv, newContent, delayBeforeAnimation, delayBetweenOldAndNew) {
	if(delayBeforeAnimation == null) delayBeforeAnimation = 0; //default delay before fading out
	if(delayBetweenOldAndNew == null) delayBetweenOldAndNew = 0; //default delay between hiding and showing content
	$(contentDiv).animate( {'opacity':1}, delayBeforeAnimation, function() { //this executes the delay, animates into visible when still visible
		$(contentDiv).animate( {'opacity':0}, FAST_SPEED, function() {
			$(contentDiv).animate( {'opacity':0}, delayBetweenOldAndNew, function() { //this executes the delay, animates into invisible when already invisible
				$(contentDiv).html(newContent);
				$(contentDiv).animate( {'opacity':NORMAL_SPEED});
			})
		})
	});
}

/**
 * Display new content using fade out / fade in animation
 */
function displayNewContentWithSlideIn(contentDiv, newContent, delayBeforeAnimation, delayBetweenOldAndNew) {
	if(delayBeforeAnimation == null) delayBeforeAnimation = 0; //default delay before fading out
	if(delayBetweenOldAndNew == null) delayBetweenOldAndNew = 0; //default delay between hiding and showing content
	$(contentDiv).animate( {'opacity':1}, delayBeforeAnimation, function() { //this executes the delay, animates into visible when still visible
		$(contentDiv).animate( {'opacity':0}, FAST_SPEED, function() {
			$(contentDiv).animate( {'opacity':0}, delayBetweenOldAndNew, function() { //this executes the delay, animates into invisible when already invisible
				$(contentDiv).html(newContent);
				$(contentDiv).slideToggle(NORMAL_SPEED);
			})
		})
	});
}


//=========================================== LOADING NEW CONTENT


/**
 * Load and display new content using flickering animation
 */
function loadNewContentWithFlicker(contentDiv, newContentPath, delayBeforeAnimation, delayBetweenOldAndNew, onCommpletedFunction) {
	if(delayBeforeAnimation == null) delayBeforeAnimation = 0; //default delay before flickering
	$(contentDiv).animate( {'opacity':1}, delayBeforeAnimation, function() { //this executes the delay, animates into visible when still visible
		//-- initial flickering animation with old content:
		$(contentDiv).animate( {'opacity':0}, 50, function() {
			$(contentDiv).animate( {'opacity':1}, 100, function() {
				_typeface_js.initialize(); //re-call the typeface rendering so that it shows properly on windows
				$(contentDiv).animate( {'opacity':0},50, function() {
					$(contentDiv).animate( {'opacity':1}, 50, function() {
						$(contentDiv).slideToggle(FAST_SPEED, function() {
							//--- animation finished, load content:
							$(contentDiv).load(newContentPath,'', function() {
								//-- content loaded, flicker one more time and display :
								$(contentDiv).attr('opacity',1);
								$(contentDiv).slideToggle(NORMAL_SPEED);
								onCommpletedFunction();
							})
						})
				
					});
				});
			});
		});
	});
}

/**
 * Load and display new content using sliding in animation
 */
function loadNewContentWithSlideIn(contentDiv, newContentPath, delayBeforeAnimation, delayBetweenOldAndNew, onCommpletedFunction) {
	$(contentDiv).slideToggle(NORMAL_SPEED, function() {
		$(contentDiv).load(newContentPath,'', function() {
			//-- content loaded, display by sliding in:
			$(contentDiv).slideToggle(NORMAL_SPEED);
			onCommpletedFunction();
		})
	});
}

/**
 * Load and display new content using fade out / fade in animation
 */
function loadNewContentWithFadeIn(contentDiv, newContentPath, delayBeforeAnimation, delayBetweenOldAndNew, onCommpletedFunction) {
	if(delayBeforeAnimation == null) delayBeforeAnimation = 0; //default delay before fading out
	if(delayBetweenOldAndNew == null) delayBetweenOldAndNew = 0; //default delay between hiding and showing content
	$(contentDiv).animate( {'opacity':1}, delayBeforeAnimation, function() { //this executes the delay, animates into visible when still visible
		$(contentDiv).animate( {'opacity':0}, NORMAL_SPEED, function() {
			$(contentDiv).animate( {'opacity':0}, delayBetweenOldAndNew, function() { //this executes the delay, animates into invisible when already invisible
				$(contentDiv).load(newContentPath,'', function() {
					//-- content loaded, display by sliding in:
					$(contentDiv).animate( {'opacity':1});
					if (onCommpletedFunction != null) {
						onCommpletedFunction();
					}
				})
			})
		})
	});
}

/**
 * Just load content with no effects
 */
function loadNewContent(contentDiv, newContentPath, delayBeforeAnimation, delayBetweenOldAndNew, onCommpletedFunction) {
	$(contentDiv).load(newContentPath,'', function() {
		$(contentDiv).replaceWith($(contentDiv).html());
		//alert($(contentDiv)..
		//$(contentDiv).remo
		//-- content loaded, call function
		if (onCommpletedFunction != null) {
			onCommpletedFunction();
		}
	})
}







