// Gossamar website designed and built by Ned Schwartz, The Interned Web Design and Development Studio.
// http://www.theinterned.net
// 

(function($){
//----------------------------------
// clear and reset the search field
//----------------------------------
	var searchValue = "search";
	$('#s')
		.focus(function(){
			var $search = $(this);
			if( $search.val() === searchValue )		
				$search.val('');
		})
		.blur(function(){
			var $search = $(this);
			if ($search.val() === '')
				$search.val(searchValue);
		});

//----------------------------------
// Login overlay
//----------------------------------
//$('#client_login').click(function(){
//	$("#login_panel").slideDown();
//	return false;
//});
$('#login_panel p.button.close, #login_panel a.close').click(function(){
	$("#login_panel").slideUp();
});

//----------------------------------
// Homepage presentation
//----------------------------------
// does the work of showing and hiding the overlay pop-ups when hovering the hotspots on the graphic.
	document.frameIndex = -1;
	// showTime is the delay from nothing to black text in the popup being visible
  var showTime = 500;
  // hideTime is the time the black text is hidden from the popup. This and preceeding one are for adjusting fade parms
	var hideTime = 250;
  var hideDelay = 300;
	var showTimeout = null;
	// Was set at 3500, but changed to 10,000 to pause display animations long enough to read whole panel.
	var homeFrameRate = 12000;
	var homeroot = $('body.home');
	var popups = $('.overlay', homeroot);
	var tabs = $('.tab', homeroot);
	var navs = $('#main_nav .page_item');
	var tabNames = ["more_leads", "higher_quality", "lower_cost", "get_started"];
	
	// this is the main event that handles the tab switching
	tabs.hoverIntent({
		over : showHomeTab,
		out : function(){},// hideHomeTab
		interval : 100
	});
	// hack cause IE is a moron about z-index: this passes mousehovers that get intercepted by the funnel 
	// graphic to it's underlying tab
	$('.ftab').hoverIntent({
		over : function(event){
			var realTab = $("#"+this.id.split("_").slice(0,2).join("_"));
			showHomeTab.call(realTab[0], event);			
		},
		out : function (){},
		interval : 100
	});	
	// main nav tabs select the correspoinding tab in the graphic and stops the animation as well
	$('#main_nav .page_item:not(.page-item-3)').hoverIntent({
		over	: function(e){
			freezeHomePage(e);
			var identity = '.tab.'+findRelatedNav($(this), 'page_item');
			identity = $(identity);
			showHomeTab.call(identity[0], e);
		},
		out		: function(){}
	});
	// start and stop the animation
	$('#content', homeroot).hoverIntent({
		over 	: freezeHomePage,
		out 	: animateHomePage
	});
	// the home tab has no corresponding tab in the graphic, 
	// so we need to start the animation when the mouse is on the home tab
	$("#main_nav .page-item-3").hoverIntent({
		over 	: animateHomePage,
		out 	: function(){}
	});
	// extra security
	$("#main_nav").hoverIntent({
		over 	: function(){},
		out 	: animateHomePage
	});

	function showHomeTab(event) {		
		var $this = $(this);		
		var popup = $("#"+this.id+"_overlay");		
		// this check is just becasue IE is such a stupid head
		if ( !$this.hasClass("highlighted") ) {
			// hide all tabs
			popups.fadeOut(hideTime);
			// unhighlight all tabs
			tabs.removeClass('highlighted');
			// unhighlight nav btns
			navs.removeClass('highlighted');
			// highlight this tab
			// highlight this tab's nav btn
			setHighlighted($this);
			// move the pointer
			moveOverlayPointer(this);	
			// wait for all tabs to hide		
			showTimeout = setTimeout(function(){				
					popups.hide();
					// show this tab					
					popup.fadeIn(showTime);
				}, hideDelay
			);
			// update the document.frameIndex
			document.frameIndex = tabs.index( this );
		}
	};
	function hideHomeTab(event) {};
	
	function setHighlighted(el){
		$el = $(el);
		var identity = findRelatedNav($el[0], '.tab');
		$('#main_nav .'+identity).addClass('highlighted');
		$el.addClass('highlighted');
	};
	function removeHighlighted(el){
		$el = $(el);
		var identity = findRelatedNav($el[0], '.tab');
		$('#main_nav .'+identity).removeClass('highlighted');
		$el.removeClass('highlighted');
	};
	function findRelatedNav(el, className) {		
		var tab = ( $(el).hasClass(className) ) ? $(el) : $(el).parent(className);
		var identArray = tab.attr('class').split(' ');		
		var identity = $.grep(identArray, function(n){
	    return (n.indexOf("page-item-") != -1);
		});
		return identity[0];
	};
	function moveOverlayPointer(el){
		$.each(tabNames, function(){ $("#overlay_container").removeClass(this); });
		$("#overlay_container").addClass(el.id);
	};

	// The big animation for the graphic at rest
	
	homePageAnimationInterval = null;
	function doHomePageAnimation() {
		document.animatingHomePage = true;
		document.frameIndex = (
			document.frameIndex+1 < tabs.length && 
			document.frameIndex >= 0 ) ?  
				document.frameIndex+1 : 0;		
		var currentTab = tabs[document.frameIndex];
		$(currentTab).each(function(){ showHomeTab.apply(this, arguments); });						
	};
	function animateHomePage(){	
		clearInterval(homePageAnimationInterval);		
		homePageAnimationInterval = setInterval( doHomePageAnimation, homeFrameRate);
	};	
	function freezeHomePage(){					
		clearInterval(homePageAnimationInterval);
		document.animatingHomePage = false;
	};

	// start the animation
	$('body.home #more_leads').each(function(){ 
		// show the overlay
		$('#overlay_container')
		.slideDown(300)
		.fadeIn(400);
		// start the home page cycling.
		doHomePageAnimation();
		animateHomePage();
	});
	
//----------------------------------
// the glossary panels
//----------------------------------
/*
	var $glossaryRoot = $('#content.glossary');
	var $definitions =  $('.post.definition', $glossaryRoot);
	var $terms = $('#section_nav li', $glossaryRoot);
	var glossaryShowTime = 500;
	// move all teh glossary named anchors to the top of the document to prevent jumping around
	$('a.anchor', $glossaryRoot).remove().prependTo('body');	
	// set up the click events
	$terms.each(function(){
		$('a', $(this) ).click(function(){
			$terms.removeClass('current_page_item');
			$(this).parent('li').addClass('current_page_item');
			var $def = $('#post-'+ this.id.split('_')[1] );
			$($definitions.selector+":visible").hide();
			$.scrollTo(0, 200);					
			$def.fadeIn(glossaryShowTime, function(){} );
		});
	});
	
	$glossaryRoot.each(function(){
		var myAnchor = document.location.hash;
		if (myAnchor.match('#')) { // the URL contains an anchor
		  // click the navigation item corresponding to the anchor
		  $('#section_nav a[href="' + myAnchor + '"]').trigger('click');
		} else {
		  // click the first navigation item
		  $('#section_nav li:first a').trigger('click');
		}
	});
*/
	
//----------------------------------
// the glossary tooltip
//----------------------------------
// wonderful plugin by Jeff Robbins
// http://plugins.jquery.com/project/bt	
	$('a.glossary').each(function(){
			$(this).bt({
			trigger: 			  			['mouseover', 'none'],
			clickAnywhereToClose: true,              // clicking anywhere outside of the tip will close it 
	    closeWhenOthersOpen:  true,              // tip will be closed before another opens - stop >= 2 tips being on
		  ajaxPath: 			  		["$(this).attr('href').replace('#','')", 'div.entry'],
			ajaxData: 			   		{tooltip : true},
			ajaxCache: 		   			true,					// cache ajax results and do not send request to same url multiple times
			ajaxLoading: 		   		'<p><blink>Loading...</blink></p>',  // yes folks, it's the blink tag!
	    ajaxError:       	   	'<p><em>%error</em></p>',
			cssClass: 			  		'glossaryPopup',
			padding: 			  			'0px 21px',
		  width: 				  			250,
		  spikeLength: 		  		20,
		  spikeGirth: 		  		30,
		  cornerRadius: 		  	6,
		  fill: 				  			'#0a3142',
		  strokeWidth: 		  		1,
		  strokeStyle: 		  		'#000',
			positions: 			  		['bottom', 'top', 'right', 'left'],
			shadow: 			  			true,
			shadowOffsetX:        0,
	    shadowOffsetY:        2,
	    shadowBlur:           10,
			noShadowOpts: 		  	{strokeStyle: '#000'},
			positions: 			  		["most"]
		});		
	});
	$('.glossaryPopup .close a').live("click",function(){
		// $(this).attr("href", "");
		$('a.bt-active').btOff();
		// console.log(this);
		return false;		
	});
		
	// Code to hide the popups after 2 seconds
	// We start a timer when the mouse leaves either the link or
	// the popup and cancel it if it re-enters either one of them
	
	// NOTE: the timeout is firing immediatley without waiting for 
	// the 2000 milliseconds. Not sure why...
		
	var glossaryTimeout;	
	function hideGlossary(){
		$('a.bt-active').btOff();
	};	
	$('a.glossary, .bt-content').live('mouseover', function(){		
		clearTimeout(glossaryTimeout);
	});
	$('a.glossary, .bt-content').live('mouseout', function(){
		glossaryTimeout = setTimeout(function(){hideGlossary();}, 1000);		
	});
	
})(jQuery);
