//
// Put this library in the nlm.autocomplete scope
//
var nlm = nlm || {};
(function($, context) {

  var prefix = location.protocol + "//www.nlm.nih.gov";

	$.ajax({
		type: "GET",
		url: prefix + "/sitenavext.json",
		dataType: "jsonp",
		cache: false,
		jsonp: false,
		jsonpCallback: "buildSiteNav",
		scriptCharset: "utf-8",
		success: function(menu) {
			$(document).ready(function() {
				//console.info("Building menu");
				//console.info(menu);
				$("ul.topnav li:first").remove();
				for (var menulen = menu.length, i = 0; i < menulen; i++) {
					var topnav = menu[i].topnav;
					var subnav = menu[i].subnav;
					//console.info(topnav);
					var content = '<a href="#">' + topnav + '</a><ul class="subnav">';
					for (var subnavlen = subnav.length, j = 0; j < subnavlen; j++) {
						var subtitle = subnav[j].subtitle;
						var location = subnav[j].location;
						//console.info(subtitle + " => " + location);
						content += '<li><a href="' + location + '">' + subtitle + '</a></li>';

						
					}
					content += '</ul>';
					$('<li></li>').html(content).appendTo('.topnav');

					
				}
				addMenuBehaviors();
				$("ul.topnav").show();
				if ("PIE" in window) {
					$('ul.topnav').each(function() {
						PIE.attach(this);
						
					});
					
				}

				
			});

			
		}

		
	});

	$(document).ready(function() {

		$("#nojs").hide();

		/* Temporary hacks */
		/* Correct linked image in #footer-usa to usa.gov*/
		$("#footer-usa a").attr("href", "http://www.usa.gov/");
		/* Correct the search input box */
		$("#search").attr("name", "query");

		//$(document).ajaxError(function(e, xhr, settings, exception) {
		//	console.info('Failed');
		//	console.info(exception);
		//	});
		// Clear Search on focus - add text on blur
		$('input.search-input').each(function() {
			$(this)
			.data('default', $(this).val())
			.addClass('inactive')
			.focus(function() {
				$(this).removeClass('inactive');
				if ($(this).val() == $(this).data('default') || '') {
					$(this).val('');
					
				}
				
			})
			.blur(function() {
				var default_val = $(this).data('default');
				if ($(this).val() == '') {
					$(this).addClass('inactive');
					$(this).val($(this).data('default'));
					
				}
				
			});

			
		});

		
	});

	if ("PIE" in window) {
		$(function() {
		    
			$('#main-body, .search-input, #barbranding, #footer, #footer-sub, #portal').each(function() {
				PIE.attach(this);
			});
			
		});

		
	}



	function addMenuBehaviors()
	 {
		// Dropdown Menu
		$("ul.topnav li a").hover(function()
		 {
			//When trigger is clicked...
			//Following events are applied to the subnav itself (moving subnav up and down)
			$(this).parent().find("ul.subnav").stop(true, true).delay(200).slideDown(200);
			//Drop down the subnav on click *** Changed to Hover
			$(this).parent().hover(function() {
				},
			function()
			 {

				$(this).parent().find("ul.subnav").stop(true, true).slideUp('fast');
				//When the mouse hovers out of the subnav, move it back up
				
			});

			//Following events are applied to the trigger (Hover events for the trigger)
			
		}).hover(function()
		 {
			$(this).addClass("subhover");
			//On hover over, add class "subhover"
			
		},
		function()
		 {
			//On Hover Out
			$(this).removeClass("subhover");
			//On hover out, remove class "subhover"
			
		});

		$("ul.topnav li a").focus(function() {
			//When trigger is clicked...
			//Following events are applied to the subnav itself (moving subnav up and down)
			$(this).parent().find("ul.subnav").slideDown('fast').show();
			//Drop down the subnav on click *** Changed to Hover
			$(this).parent().focus(function() {
				},
			function()
			 {
				$(this).parent().find("ul.subnav").slideUp('fast').hide();
				//When the mouse hovers out of the subnav, move it back up
				
			});


			
		});

		
	}


  context.openPopup = function (POPUP) {
    var popup =  window.open(POPUP,'popup','resizable=yes,scrollbars=yes,width=400,height=600');
    popup.focus();
  };

	//
	// JavaScript loader
	// based on http://friendlybit.com/js/lazy-loading-asyncronous-javascript/
	// and http://www.nczonline.net/blog/2009/07/28/the-best-way-to-load-external-javascript/
	//
	function loadScript(url, callback) {

		var script = document.createElement("script");
		script.type = "text/javascript";
		script.async = true;

		if (script.readyState) {
			//IE
			script.onreadystatechange = function() {
				if (script.readyState == "loaded" || 
				script.readyState == "complete") {
					script.onreadystatechange = null;
					callback();
					
				}
				
			};
			
		} else {
			//Others
			script.onload = function() {
				callback();
				
			};
			
		}

		script.src = url;
		var x = document.getElementsByTagName("script")[0];
		x.parentNode.insertBefore(script, x);

		return script;

		
	}	// loadScript
	
function loadStyle(url, media)
	 {
		var css = document.createElement("link");
		css.rel = "stylesheet";
		css.href = url;
		css.type = "text/css";
		if (media) {
			css.media = media;
			
		}
		document.getElementsByTagName("head")[0].appendChild(css);

		return css;

		
	}	// loadStyle

	//
	// Load search autocomplete
	//
	loadStyle(prefix + "/core/jquery-ui/1.8/jquery-ui.css");
	loadStyle(prefix + "/core/nlm-autocomplete/1.0/nlm-autocomplete.css");
	loadScript(prefix + "/core/jquery-ui/1.8/jquery-ui.min.js", 
	function() {
		loadScript(prefix + "/core/nlm-autocomplete/1.0/nlm-autocomplete.js", 
		function() {
			$(document).ready(function() {
				nlm.autocomplete.add({
					element: "#search",
					dictionary: "nlm-ac-dictionary",
					width: 0
				});
				
			});
			
		});
		
	});


	//
	// Load AddThis
	//
	$(window).load(function() {
		loadScript(location.protocol + "//s7.addthis.com/js/250/addthis_widget.js#username=nationallibraryofmedicine", 
		function() {
			// call AddThis API here rather than rely on class based configuration?
			});
		
	});


}) (jQuery, nlm) // masterfull.js scope

//
// Legacy. We should remove $nlm and let apps deal deal with jQuery as they wish
//
var $nlm = jQuery.noConflict();

//
// Legacy. We should move this into nlm scope
//
function openPopup(POPUP) {
  nlm.openPopup(POPUP);
}

