/*
@description Add general site-wide js funtionality to the page (e.g. print page button)
@author VC
@created 2009-02
Notes: Uses jQuery v. 1.1.4
*/
var currentTeaserScrollerIndex = 0;

/* puts placeholder text in input boxes */
function fieldHint(element){
	$(element).focus(function(){
		if($(this).val() == $(this).attr("title")){
			$(this).val("");
			$(this).addClass("active");
		}else{
			$(this).addClass("active");
		}
	});
	$(element).blur(function(){
		if($(this).val() == $(this).attr("title") || !$(this).val().length){
			$(this).removeClass("active");
			$(this).val($(this).attr("title"));
		}
	});
	$(element).blur();	
}

/* Primary column teasers rollover effect */
function initStandardTeasersRollover(selector, hoverclass){ 
	jQuery(selector).hover(
		function () {
			jQuery(this).addClass(hoverclass);
			
			//add hover sifr
			if(jQuery(this).find('h2 a').length){
				var sifrh2selector = "."+ hoverclass + " h2 a";
				sIFR.rollback(sifrh2selector);
				jQuery(sifrh2selector).addClass('sifr-hovered');
			};
			
		},function () {
			//replace pre-hover sifr
			if(jQuery(this).find('h2 a.sifr-hovered').length){
				sIFR.rollback("h2 a.sifr-hovered");
				var themeColour = getBodyThemeInfo().theme.color; /* defined in sifr/sifr-config.js */
			}
			jQuery(this).removeClass(hoverclass); 
		}
	);
	jQuery(selector).click(function(){
		var link = jQuery(this).find('a');
		if(link.length){
			document.location = jQuery(link[0]).attr('href');
		}
	});
}

function initTwitter(selector){
	$(selector).getTwitter({
		userName: "thekingsfund",
		numTweets: 3,
		loaderText: "Loading tweets...",
		slideIn: false,
		showHeading: false,
		showProfileLink: true
	});
	$('.widget_panel_twitter .profileLink').click(function(){
		eventTrack('Twitter profile link', 'click');
	});
}

/* tab etc rollovers class for IE6 */
function initSimpleRollovers(jqueryelement, hoverclass){
	jqueryelement.hover(
		function () {
			jQuery(this).addClass(hoverclass); 
		},function () {
			jQuery(this).removeClass(hoverclass); 
		}
	);
}

//IE6 hack for hover effect on nav links
function initNavLinkHover(jqueryelement, hoverclass){
	initSimpleRollovers(jQuery('ul#header-links li.toplevel'), 'over');
	initSimpleRollovers(jQuery('ul#header-links li ul li'), 'over');
	//initSimpleRollovers(jQuery('ul#header-links li ul li'), 'over');
}

function initMobile(){
	
	$('#secondary-nav-toggle').remove();
	if ((!$.browser.msie || ($.browser.msie && $.browser.version > 8)) && document.documentElement.clientWidth <= 600) {
		$('<div id="secondary-nav-toggle"><span>Show menu</span></div>').toggle(
			function(){
				$('#secondary-nav').show();
				$('#secondary-nav-toggle span').html("Hide menu").addClass("selected");
				return false;
			},
			function(){
				$('#secondary-nav').hide();
				$('#secondary-nav-toggle span').html("Show menu").removeClass("selected");
				return false;
			}
		).appendTo('#header-wrapper');
		$('#secondary-nav').hide();
		
		//add special menu items
		if(!$('#secondary-nav .navitem-findus').length){
			//hide original about us item and clone it higher in menu
			$('#secondary-nav .navitem-about_us').hide();
			$('#secondary-nav .navitem-home').after($('#secondary-nav .navitem-about_us').clone().show().addClass("mobile"));
			$('#secondary-nav .navitem-home').after($('#header-links .press').clone().addClass("mobile level-0"));
			$('#secondary-nav .navitem-home').after($('#header-links .who').clone().addClass("mobile level-0"));
			$('#secondary-nav .navitem-home').after('<li class="level-0 navitem-findus mobile"><a href="/about_us/how_to_find_us.html">How to find us</a></li>');
		}
		
		//move email updates
		$('#primary-content').append($('#quick_signup_teaser').clone().addClass("mobile"));
		$('#quick_signup_teaser').hide();
	}else{
		$('#secondary-nav').show();
		$('#secondary-nav-toggle').remove();
		$('#secondary-nav .mobile, #primary-content .mobile').remove();
		$('#secondary-nav .navitem-about_us').show();
		$('#quick_signup_teaser').show();
	}
}


$(function() {
	$('body').addClass('hasjs');
	initStandardTeasersRollover("#primary-content .hover-wrapper:not('.no-hover')", 'hover-wrapper-hovered');
	initStandardTeasersRollover("#secondary-content .hover-wrapper:not('.no-hover')", 'hover-wrapper-hovered');
	initNavLinkHover();
	
	fieldHint($('#quick_signup_teaser input[type=text]'));
	fieldHint($('#header-search-box'));
	
	$('.footer-sitemap').hide();
	
	//expanding sitemap in header
	$('.footer-sitemap-wrapper h1 a').toggle(
		function(){
			$('.footer-sitemap').slideDown().parent().addClass('expanded');
			$('.footer-sitemap-wrapper .close a').show();
			eventTrack('Sitemap' ,'open');
		},
		function(){
			$('.footer-sitemap').slideUp().parent().removeClass('expanded');
			$('.footer-sitemap-wrapper .close a').hide();
			eventTrack('Sitemap' ,'close');
		}
	);
	$('.footer-sitemap-wrapper .close a').click(function(){
		$('.footer-sitemap').slideUp().parent().removeClass('expanded');
		$('.footer-sitemap-wrapper .close a').hide();
		eventTrack('Sitemap' ,'close');
		
		return false;
	});
	
	$('#footer-sitemap a').click(function(){
		try{_gaq.push(['_trackEvent', 'Sitemap', 'click', 'from: ' + document.location.href + ' to: '+ $(this).attr("href")]);}catch(e){}
		return true;
  	});
	
	/* expanding login box in header */
	$('#my_content_sidebar').hide();
	$('#header-links .signin .trigger').toggle(
		function(){
			$('#my_content_sidebar').show();
			return false;
		},
		function(){
			$('#my_content_sidebar').hide();
			return false;
		}
	);
	
	
	//Header tagline show and hide
	$('#header-tagline .left-area').hover(function() {
		$('span',this).show();
			}, function() {
			$('span',this).hide();
	});

	$('#header-tagline .left-area').click(function() {
		$('#header-tagline .right-area').show();
	});
	
	$('#header-tagline .right-area').click(function() {
		$(this).hide();
	});

	// Check nav secondary list last item and add a class
	$('#secondary-nav ul li:last').addClass('last-li');
	
	// My content profile link hover style
	$('ul.saved_items .remove-button').hover(function() {
		$(this).siblings('div').addClass('hover-wrapper-hovered');
		}, function() {
			$(this).siblings('div').removeClass('hover-wrapper-hovered');
	});

	$('ul.saved_items .hover-wrapper').hover(function() {
		$(this).siblings('.remove-button').addClass('hovered-remove-button');
		}, function() {
			$(this).siblings('.remove-button').removeClass('hovered-remove-button');
	});

	$('ul.saved_items .remove-button').hover(function() {
		$(this).addClass('hovered-remove-button');
		}, function() {
			$(this).removeClass('hovered-remove-button');
	});
	
	$('ul#project-publications-links li').hover(function() {
		$(this).addClass('over');
		}, function() {
			$(this).removeClass('over');
	});
	
	// Tracking of various sitewide events
	$('#homepage_features_tabs a strong span').click(function(){
		eventTrack('Homepage feature tab: ' + $(this).html(), 'click');
	});
	$('#header-links a').click(function(){
		eventTrack('Header: ' + $(this).html(), 'click');
	});
	$('#footer .bottom-links a, #view-map').click(function(){
		eventTrack('Footer: ' + $(this).html(), 'click');
	});
	$('#keeping_in_touch a').click(function(){
		eventTrack('Keep in touch: ' + $(this).html(), 'click');
	});
	$('#secondary-nav .level-0 > a').click(function(){
		eventTrack('Primary nav: ' + $(this).html(), 'click');
	});
	
	
	// track all outbound/document links
	RegExp.escapeDomains = function(text) {
		return (text) ? text.replace(/[-[\]{}()*+?.,\\^$#\s]/g, "\\$&") : '';
	}

	// Attach onclick event to document only and catch clicks on all elements.
	$(document.body).click(function(event) {
		// Catch the closest surrounding link of a clicked element.
		$(event.target).closest("a").each(function() {
			// Expression to check for absolute internal links.
			var isInternal = new RegExp("^(https?):\/\/" + window.location.host, "i");
			// Expression to check for download links.
			var isDownload = new RegExp("\\.(doc|xls|ppt|pdf|zip|pot|dot|mp3|mp4|wav)$", "i");

			// Is the clicked URL internal?
			if (isInternal.test(this.href)) {
				// Is download tracking activated and the file extension configured for download tracking?
				if (isDownload.test(this.href)) {
					// Download link clicked.
					var extension = isDownload.exec(this.href);
					_gaq.push(["_trackEvent", "Document download", extension[1].toUpperCase(), this.href.replace(isInternal, '')]);
				}
			}else {
				if ($(this).is("a[href^=mailto:]")) {
					// Mailto link clicked.
					_gaq.push(["_trackEvent", "Mailto link", "click", this.href.substring(7)]);
				}else if (this.href) {
					// External link clicked.
					_gaq.push(["_trackEvent", "Outbound link", "click", this.href]);
				}
			}
		});
	});
	
	//width-based changes for mobile devices
	$(window).resize(function() {
		initMobile();
	});

	initMobile();
	
});

//used for some video/audio
function trackPlay(actionType, mediaId){
	if (mediaId && !isNaN(parseInt(mediaId)) ) {
		$.get('/applications/my_content/log_action.rm', {'action_type': actionType, 'media_id': mediaId})
	} else {
		$.get('/applications/my_content/log_action.rm', {'action_type': actionType})
	}
}

function eventTrack(source, action){
	try{_gaq.push(['_trackEvent', source, action, document.location.href + ' - ' + $('title').html().replace(/\'/g,"")]);}catch(e){}
}
