// For the HTML templates. The Django pages use ~ on the base template.
if (typeof ROOT_URL == 'undefined'){ ROOT_URL = '../';}

// Init various items
jQuery(function($) { 
	// A hook for CSS if JS is enabled
	$('body').addClass('jsEnabled');
	
	$("#searchForm label").overlabel();
	
	var media = $('.intro .media');
	var lis = $('.intro .text li:first');
	if (media.length && lis.length){
		var pad = $('.intro .media').outerWidth(true);
		if (lis.position().top < media.outerHeight(true) + media.position().top){
				lis.parents('ul').css('margin-left', pad);
		}
	}
	
	$('#selectForm input').click(function(){
		$("#sidebar .innerBox:visible").slideUp('fast');
		$("#" + $("#selectForm select").val()).slideDown('fast');			
		return false;
	});
	
	if ($('.home #flash').length){
		flashembed("flash", {src: ROOT_URL+'swf/home.swf?r20', wmode:"transparent"} );
	}
	
	$("form.quiz, .icon_quiz form, form.answers").jqTransform();

	var loc = window.location.href;
	var pos = loc.indexOf('?');
	if (pos != -1){
		loc = loc.substr(pos+1);
		$('#'+loc).prev('a').click();
	}		
	
	$(".quizlet .jqTransformRadio").click(function(){
		var show = $("#" + $(this).next('input').val());
		$(".quizlet .answers").fadeOut("slow", function(){
			show.fadeIn("fast");
		});
	});
	
});

// POPUPS
// target="_blank" in xhtml documents
jQuery(function($) { 
	$("a[rel~='external'], a.New_Window, a[href$=pdf]").click(function(){
		window.open($(this).attr("href"));
		return false;
	});
});	




// Quiz
jQuery(function($){ 
	$("form.quiz .submit").click(function(){
		if ($('.quiz input:checked').length < $('.quiz input').length / 2){
			$("#box_quiz_validate").slideDown("fast");

		} else {
			$("#quiz_questions").slideUp("fast", function(){
				$(this).parent().attr('class','inner_bot_answer');
				var yes = $('.quiz input:checked[value=1]');
				if (yes.length){
					yes.each(function(){
						$("#" + $(this).attr('id') + "_answer").show();
					});
					$("#quiz_yes").slideDown("fast");
				} else {
					$("#quiz_no").slideDown("fast");
				}
			});
		}
		return false;
	});
});


// Distribute spacing across menu items
jQuery(function($){ 
	var lis = $('#header .menu>ul>li>a');

	lis.css({'padding-left': '0','padding-right': '0'});

	var spaceLeft = ($('#header .menu').width() - $('#header .menu>ul').width());
	var padRound = Math.floor(spaceLeft / (lis.length * 2))
	
	lis.css({'padding-left': padRound,'padding-right': padRound});


});


// PRINT button and print preview
jQuery(function($) {
	// For the site's print button 
	$('#print').click(do_print);
	// IE supports attaching this behavor to the File > Print menu item 
	if ($.browser.msie){
		window.onbeforeprint = function(event){
			// preventDefault here doesn't prevent IE's launching of the print dialog. 
			// Instead, it prevents a bug where the print dialog doesn't appear until the uses clicks anywhere.
			if (!event) {event = document.parentWindow.event} 
			if (!event.preventDefault){ event.preventDefault = function(){ this.returnValue = false;} }
			event.preventDefault();
	    	do_print(false);
	    };	
	    var delay = 1500;
	} else {
	    var delay = 300;		
	}
	
	function do_print(fireprint){
		if (typeof fireprint == 'undefined'){ var fireprint = true; }
		$('link[media=screen]').attr('media','none');
		$('link[media=print]').attr('media','all');
		
		window.scrollTo(0,0);
		
		if (fireprint){
			setTimeout(function(){
				window.print();
			},100);
		}
		setTimeout(function(){
			$('link[media=none]').attr('media','screen');
		},delay);
		setTimeout(function(){
			$('link[media=all]').attr('media','print');
		},delay+1);
		return false;
	};
});



/*
 * SimpleModal Confirm Modal Dialog
 * http://www.ericmmartin.com/projects/simplemodal/
 * http://code.google.com/p/simplemodal/
 *
 * Copyright (c) 2010 Eric Martin - http://ericmmartin.com
 *
 * Licensed under the MIT license:
 *   http://www.opensource.org/licenses/mit-license.php
 *
 * Revision: $Id: confirm.js 238 2010-03-11 05:56:57Z emartin24 $
 *
 */
 
/* 
The following code started well but is currently a mess.  
My apologies to anyone involved.
FIXME unify these 3 functions! Cleanup mess of IDs and classes in the CSS!
*/

jQuery(function ($) {
	var external_whitelist = ['novartis','meningitis.com','menveo.com','menveo.abstractedge.com','meningitis.abstractedge.com','youtube','addthis.com'];
	$('a[href^=http]').click(function (e) {
		var href = $(this).attr('href');

		for (var i=0, t=external_whitelist.length; i<t;  i++){
			if (href.indexOf(external_whitelist[i]) != -1){
				return true;	
			}
		}

		e.preventDefault();

		confirm(function () {
			window.location.href = href;
		});
	});
});

function confirm( callback) {
	$('#simplemodal')
	.attr('class','confirm')
	.modal({	
		closeHTML: null,
		position: ["20%",],
		overlayClose: true,
		opacity: 20,
		appendTo: '#container',
		onShow: function (dialog) {
			$('.yes', dialog.data[0]).click(function () {
				if ($.isFunction(callback)) {
					callback.apply();
				}
			});
		},
		onOpen: function (dialog) {
			$('.inner', dialog.data[0]).append($('#confirm'));
			$('body').remove('body > #confirm'); 
			dialog.overlay.fadeIn(200, function () {
				dialog.container.fadeIn(200, function () {
					dialog.data.fadeIn(200, function () {
					});												   
				});
			});
		},
		onClose: function (dialog){
			$('body').append($('#confirm'));		
			$.modal.close();
		}
	});
}



// Search
jQuery(function($) { 
	$('#searchSubmit').click(function(){
		$('#searchForm').submit();
		return false;
	});
	$('#searchForm').submit(function(e){
		var val = $('#search').val();
		if (val == ''){ return false; }

		// Setup the template to receive the search
		$('#flash, #tagline, #extraText, #content, #sidebar, #iconMenu').remove()
		$('#bottomNav').html('&nbsp;');
		$('#wrapper').html('<div id="content"><div id="contentInner"><h1>Search results for <strong>' + val + '</strong></h1><div id="results"></div></div></div><div id="sidebar">&nbsp;</div><div style="clear: both;"></div>').css({'margin-top':42});
		$('.home #content').css({width:695}).show();

		// Instantiate the search
		var control = new GSearchControl();
		
		// Display as much results as possible.
		control.setResultSetSize(GSearch.LARGE_RESULTSET);
		// Open links in the same window.
		control.setLinkTarget(GSearch.LINK_TARGET_SELF);
		
		// Create the web search object and set restrictions.
		searcher = new GwebSearch();
		var options = new GsearcherOptions();
		options.setExpandMode(GSearchControl.EXPAND_MODE_OPEN);
		options.setNoResultsString("No results found.")

		searcher.setSiteRestriction("www.menveo.com");
		control.addSearcher(searcher, options);
		
		/*	Set draw mode to tabbed. We'll hide the tabs later with CSS, but this is the one
			that most closely matches our design. */
		var drawOptions = new GdrawOptions();
		drawOptions.setDrawMode(GSearchControl.DRAW_MODE_TABBED);
		control.draw(document.getElementById("results"), drawOptions);
			
		// Do the search
		control.execute(val);
		
		// Cancel the form submission
		return false;
	});	
});	



// TRACKING
// Tracking has to be the last click event bind to A elements
jQuery(function($) { 
	
	var get_label = function(a){
		a = $(a)
		var label;
		var href = a.attr('href');
		if (!href){ return ""; }
		var hreflo = href.toLowerCase();
		// If the link points to a PDF or to another website, the URL is displayed.
		if (hreflo.indexOf('.pdf') != -1 || (hreflo.indexOf('http') != -1 && hreflo.indexOf(document.domain) == -1)){
			href = href.replace('http://', '');
			href = href.replace('www.', '');
			label = href;			
		// If it's a link in our site, we display the link text, or the alt attribute if it's an image link (such as the logo).
		} else {
			if (a.text() != '' && a.text() != ' ' && a.text() != ' '&& a.text() != '&nbsp;') {
				label = a.text();			 
			} else if (a.find('img').length) {
				label = a.find('img').attr('alt');
			} else {
				label = href; // We fallback to the href if no other option.
			}
		}
		return smartTrim(label, 30)
	}
	
	var track = function(selector, category, label){
		$(selector).click(function(e){
			var label = label || get_label(this);
			var data = ['_trackEvent', category, 'click', label];
			if (_gaq){ _gaq.push(data); }
			// If the link has other events that prevent it's redirect, let them happen. 
			// Otherwise, redirect using a timeout so we have time to hit the tracking server.
			// This is the Google-sanctioned technice as per
			// http://www.google.com/support/googleanalytics/bin/answer.py?hl=en&answer=55527
			if (!e.isDefaultPrevented() && label.indexOf('addthis.com') == -1) {
				setTimeout('document.location = "'+ $(this).attr('href') +'"', 200);
				return false;
			}
		});		
	}

	var smartTrim = function(string, maxLength) {
	    if (!string) return string;
	    if (maxLength < 1) return string;
	    if (string.length <= maxLength) return string;
	    if (maxLength == 1) return string.substring(0,1) + '...';
	
	    var midpoint = Math.ceil(string.length / 2);
	    var toremove = string.length - maxLength;
	    var lstrip = Math.ceil(toremove/2);
	    var rstrip = toremove - lstrip;
	    return string.substring(0, midpoint-lstrip) + '...' + string.substring(midpoint+rstrip);
	}	
	
	track("#header .menu a", "Top nav");
	track("#header .logo a, #searchForm a, #toolsMenu a", "Header");
	track("#footer a", "Footer");
	track(".sidebarTout a", "Sidebar tout");
	track("#extraText a", "Footnotes");
	track(".summary a, .intro a, .contentText a, #callout a", "Content");	
	track("#selectForm input", "State Reqs GO");
	track(".home #wrapper a", "Homepage");
	track("form.quiz a", "Main Quiz");		
	
});	

// For Flash
function shareNow(){
	if (_gaq){ _gaq.push(['_trackEvent', 'Homepage', 'click', 'Share now']); }	
	$('.addthis_button').click();
}

function reduce(){
	if (_gaq){ _gaq.push(['_trackEvent', 'Homepage', 'click', 'Reduce the risk']); }
	// FIXME this is hardcoded, if we ever do another language of this site, we'll need to make it dynamic
	var href = '/about-meningitis/vaccination/';
	setTimeout('document.location = "'+ href +'"', 300);
}



// OVERLABEL
// http://scott.sauyet.com/thoughts/archives/2007/03/31/overlabel-with-jquery/#comment-24381
( function( $ ) {
 
    // plugin definition
    $.fn.overlabel = function( options ) {
 
        // build main options before element iteration
        var opts = $.extend( {}, $.fn.overlabel.defaults, options );
 
        var selection = this.filter( 'label[for]' ).map( function() {
 
            var label = $( this );
            var id = label.attr( 'for' );
            var field = document.getElementById( id );
 
            if ( !field ) return;
 
            // build element specific options
            var o = $.meta ? $.extend( {}, opts, label.data() ) : opts;
 
            label.addClass( o.label_class );
 
            var hide_label = function() { label.css( o.hide_css ) };
            var show_label = function() { this.value || label.css( o.show_css ) };
 
            $( field )
                 .parent().addClass( o.wrapper_class ).end()
                 .focus( hide_label ).blur( show_label ).each( hide_label ).each( show_label );
 
            return this;
 
        } );
 
        return opts.filter ? selection : selection.end();
    };
 
    // publicly accessible defaults
    $.fn.overlabel.defaults = {
 
        label_class:   'overlabel-apply',
        wrapper_class: 'overlabel-wrapper',
        hide_css:      { 'text-indent': '-10000px' },
        show_css:      { 'text-indent': '0px', 'cursor': 'text' },
        filter:        false
 
    };
 
} )( jQuery );






