/*
@description Add tab JS for multiple pages tabs, using Ajax for loading each tab
@author VictoriaChan
@created 2009-02
Notes: Uses jQuery v. 1.1.4 + page_setup.js
*/

jQuery(function() {
	//width-based changes for mobile devices
	if (document.documentElement.clientWidth > 600) {
		var tab_links = jQuery('#tabbed-header ul.tabs li:not(.noajax)');

		if(tab_links.length){
			//init tab hover effect (function in page_setup.js)
			initSimpleRollovers(tab_links, 'active');
					
			//actions for tabs
			tab_links.click(function(eventObj){
				var this_anchor = jQuery(this).find('a');
				ajaxTabbedContentClicked(jQuery(this_anchor).attr('href'), this, tab_links, true);
				document.location.hash = jQuery(this_anchor).attr('class');
				
				eventObj.preventDefault();
			});
			
			//actions for inner section nav
			jQuery('#inner-section-nav a').click(ajaxTabbedInnerNavClicked);
			
			//which one to show first?
			var hash = document.location.hash;
			if(hash.length > 0){
				jQuery('#tabbed-header .tabs li a').each(function(){
					if('#' +jQuery(this).attr('class') == hash){
						jQuery(this).click();
					};
				});
			};
			
		}	
	}
});

function ajaxTabbedInnerNavClicked(eventObj){
	var selected = jQuery(this).attr('href');
	jQuery('#inner-section-nav li a.selected').removeClass('selected');
	jQuery(this).addClass('selected');
	ajaxTabbedContentClicked(selected, jQuery('#tabbed-header ul.tabs li.currently-active'), jQuery('#tabbed-header ul.tabs li'), false);
	eventObj.preventDefault();
}
function ajaxTabbedContentClicked(selected, tab, tab_links, reload_nav){
	
	//load tab
	jQuery("#ajax-content-wrapper").fadeOut('fast', function(){
		jQuery("#ajax-content-wrapper").html('<p class="loading-notice">&nbsp;</p>');
		jQuery("#ajax-content-wrapper").fadeIn('slow', function(){
			//add to Google Analytics
			try{ _gaq.push(['_trackPageview',selected]); } 
				catch(err) { /*do nothing obvious if GA not set up*/ 
						jQuery('body').addClass('GA_Ajax_Problem'); }
			
			//fetch tab content
			if(jQuery(tab).hasClass('application')){
				jQuery("#ajax-content-wrapper").load(selected + "&isajax=1 #ajax_results", ajaxContentRefresh);
			}else{
				jQuery("#ajax-content-wrapper").load(selected + " #tab-content", ajaxContentRefresh);
			};
		});
	});
	
	//load inner-section-nav inner-section-nav-wrapper
	if(reload_nav == true){
		jQuery("#inner-section-nav-wrapper").slideUp('fast', function(){
			jQuery("#inner-section-nav-wrapper").html('');
			jQuery("#inner-section-nav-wrapper").load(selected + " #inner-section-nav", function(){
				if(jQuery("#inner-section-nav").length){
					jQuery("#inner-section-nav-wrapper").slideDown('slow');
					
					jQuery('#inner-section-nav .inner-section-nav a').click(ajaxTabbedInnerNavClicked);
				};
			});
		});
	}

	
	//highlight tab
	tab_links.removeClass('currently-active');
	jQuery(tab).addClass('currently-active');
	
	//Update also in this project links
	updateAlsoInThisProjectLinks();
	
}

function knowledgeDatabaseAjaxTweaks(){
	/* KNOWLEDGE BASE SUBJECTS */
	$('#ajax-content-wrapper .knowledge_database_results .listing .subjects ul').hide();
	$('#ajax-content-wrapper .knowledge_database_results .listing .subjects > a').toggle(
		function(){
			$(this).parent().find('ul').show();
	},function(){
			$(this).parent().find('ul').hide();
	});
}

function ajaxContentRefresh(){	
	//reload swfobject and other onload functions
	knowledgeDatabaseAjaxTweaks();
	loadSWFMovInTab();
	loadSWFAudioInTab();
	initStandardTeasersRollover('#tab-content .hover-wrapper', 'hover-wrapper-hovered');
	loadSlideShowInTab();
}
function loadSlideShowInTab(){
	if (jQuery('#tab-content .slideshow-wrapper').length){
		jQuery.getScript( "/javascript/jquery/jquery.scrollTo-1.4.0-min.js",  function(){	
			jQuery.getScript( "/javascript/jquery/jquery.serialScroll-1.2.1-min.js",  function(){
				jQuery.getScript( "/javascript/jquery/jquery.ifixpng.js",  function(){
					jQuery.getScript( "/javascript/slideshow.js");
				});
			});		
		});
	};
}

function correctTitle(containerId){
	var oldTitle = document.title // get the title before being bug
	try{
		// clean the title if needed
		if(oldTitle.indexOf('#')!=-1) oldTitle=oldTitle.substring(0,oldTitle.indexOf('#'));
		var iv = setInterval(function () {
			// Whenever its loaded just push in the old title again
			if ($('#'+containerId).readyState == 4) {
				clearInterval(iv)
				document.title = oldTitle;
			}
		}, 100)
	}
	catch(e){}	
}

function loadSWFMovInTab(){
	jQuery("#tab-content .swfobject-flvplayer").each(function(){
		var this_filename = jQuery(this).find("input[name='filename']").val();
		var this_duration = jQuery(this).find("input[name='duration']").val();
		var this_width = jQuery(this).find("input[name='width']").val();
		var this_height = jQuery(this).find("input[name='height']").val();
		var this_image = jQuery(this).find("input[name='image']").val();
		var this_container_id = jQuery(this).attr('id');
		
		correctTitle(this_container_id);
		
		var flashvars = {
			file: this_filename,
			skin: "/swf/jwplayer/skins/kf.swf",
			controlbar: "over",
			lightcolor: "AEBA33",
			backcolor:"333333",
			image: this_image,
			duration: this_duration
		};
		var params = {
			menu: "false",
			allowfullscreen: "true",
			allowscriptaccess: "always"
		};
		swfobject.embedSWF("/swf/jwplayer/player.swf", 
		this_container_id, this_width, this_height, "9.0.0", false, flashvars, params, false);
	});
}
function loadSWFAudioInTab(){	
	jQuery("#tab-content .swfobject-audioplayer").each(function(){
		var this_filename = jQuery(this).find("input[name='filename']").val();
		var this_duration = jQuery(this).find("input[name='duration']").val();
		var this_container_id = jQuery(this).attr('id');
		
		correctTitle(this_container_id);
		
		var flashvars = {
			file: this_filename,
			skin: "/swf/jwplayer/skins/kf_audio.swf",
			lightcolor: "AEBA33",
			backcolor:"333333",
			duration: this_duration
		};
		var params = {
			menu: "false",
			allowscriptaccess: "always"
		};
		swfobject.embedSWF("/swf/jwplayer/player.swf", 
		this_container_id, "250", "27", "9.0.0", false, flashvars, params, false);
	});
}

function updateAlsoInThisProjectLinks(){
	//add link currently non-linked li - first get the class
	
	var oldclass="nonexistent";
	
	//get the class of the previously active link
	//seems the only way to do this reliably is to loop over the lis and find the one that isn't an a
	jQuery('.page-seealso ul li').each(function(){
		if( jQuery(this).children(':first').is('a') ){
			
		}else{
			var oldclass = jQuery(this).attr('class');
		};
	});
	//get the url of the equivalent tab so we can add the link back
	var urltoadd = jQuery('ul.tabs li a.' + oldclass).attr('href');
	//add the link back - have to loop again to find the one that isn't an a
	jQuery('.page-seealso ul li').each(function(){
		if( jQuery(this).children(':first').is('a') ){

		}else{
			jQuery(this).wrapInner('<a href="' + urltoadd + '" />');
		};
	});
	//add the '&nbsp;&raquo;' back
	var oldlinktext = jQuery('.page-seealso ul li.' + oldclass + ' a').text();
	oldlinktext = oldlinktext + String.fromCharCode(160);
	oldlinktext = oldlinktext + String.fromCharCode(187);
	jQuery('.page-seealso ul li.' + oldclass + ' a').text(oldlinktext);
	
	//get url of currently active tab
	var currentlyactiveurl = jQuery('ul.tabs li.currently-active a').attr('href');
	//get the class of the currently active tab
	var currentlyactiveclass = jQuery('ul.tabs li.currently-active a').attr('class');

	//remove a tag from current page text
	var linktext = jQuery('.page-seealso ul li.' + currentlyactiveclass + ' a').text();
	//alert(linktext);
	jQuery('.page-seealso ul li.' + currentlyactiveclass + ' a').replaceWith(linktext);
	
	//remove '&nbsp;&raquo;' from current page text
	var newtext = replaceRAQ(linktext);
	newtext = replaceNbsps(newtext);
	jQuery('.page-seealso ul li.' + currentlyactiveclass).text(newtext);
	
	
}

//function to strip out nonbreaking space
function replaceNbsps(str) {
  var re = new RegExp(String.fromCharCode(160), "g");
  return str.replace(re, " ");
}

//function to strip out &raquo;
function replaceRAQ(str) {
  var re = new RegExp(String.fromCharCode(187), "g");
  return str.replace(re, " ");
}

