/*
------- Process Type Foundry
------- jQuery impelemenations  
*/

$(document).ready(function(){


	var outTimerOne;
	var outTimerTwo;
	var scrollyNavOver = false;
	$(".scrollable .items, .scrollable_font .items").mouseenter(function()
	{
		scrollyNavOver = true;	
		$('a.scrollyNav').css('visibility','visible');
		
	}).mouseleave(function()
	{
		scrollyNavOver = false;	
		outTimerOne = setTimeout( checkOutOne, 125 );
	});
	
	$(".scrollable a.scrollyNav, .scrollable_font a.scrollyNav").mouseenter(function()
	{
		scrollyNavOver = true;
		
	}).mouseleave(function()
	{
		scrollyNavOver = false;
		outTimerTwo = setTimeout( checkOutTwo, 125 );
	});
	
	function checkOutOne(){
		clearTimeout( outTimerOne );
		checkScrollyOver();
	}
	
	function checkOutTwo(){
		clearTimeout( outTimerTwo );
		checkScrollyOver();
	}	
	
	function checkScrollyOver()
	{
		if ( scrollyNavOver == false ) $('a.scrollyNav').css('visibility','hidden');
	}
	
	
	$('.four-feature').hover(
	function(){
		$(this).children().filter('.four-feature-reveal')
			.css('display','block')
			.height( $(this).height() - 36 + 4 );
	},
	function(){
		$(this).children().filter('.four-feature-reveal').css('display','none');
	});
	
	// -- -- -- -- -- -- -- -- --
	// MAIN MENU / FONT SUBMENU
	// -- -- -- -- -- -- -- -- --
	
	var fontSub = $('#fontSubmenu');
	var rememberLastActive = null;
	var outFont = false;
	var fontOutTimerId;
	var ieOpacity = ( ! jQuery.support.opacity ) && ( jQuery.browser.version.substr(0,3) >= 7 );
	
	$('#fontsMenuItem').mouseenter(function(){
		outFont = false;
		stopOutTimer();
		if( ieOpacity ) fontSub.addClass('iefix');
		fontSub.fadeIn( 200, function(){ if( ieOpacity ) fontSub.removeClass('iefix'); });
		if ( fontSub.parent().hasClass('active') == false )
		{
			rememberLastActive = fontSub.parent().parent().children().filter('.active');
			fontSub.parent().addClass('sortaActive');
			rememberLastActive.removeClass('active');
		}
	});
	
	$('#fontsMenuItem').mouseleave(function(){
		outFont = true;	
		startOutTimer();	
	});
	
	function startOutTimer() {
		fontOutTimerId = setTimeout( evaluateOutness, 110 );
	}

	function stopOutTimer() {
		clearTimeout( fontOutTimerId );
	}
	
	function evaluateOutness() {
		stopOutTimer();
		if ( outFont )
		{
			if( ieOpacity ) fontSub.addClass('iefix');
			fontSub.fadeOut( 200, function(){ if( ieOpacity ) fontSub.removeClass('iefix'); });
			if ( rememberLastActive != null ) { 
				tempClassSwitch = null;
				fontSub.parent().removeClass('sortaActive');
				rememberLastActive.addClass('active');
			}			
		}
	}
	
	// -- -- -- -- -- -- -- -- --
	// HEADER / LOGIN FLYOUT
	// -- -- -- -- -- -- -- -- --
	
	// ie6 users don't get the cool login flyout
	if ( ! ( jQuery.browser.msie && jQuery.browser.version.substr(0,3) <= 6 ) )
	{
		var loginPrepared = false;
		var form = $('#loginBox form');
		var loginBox = 	$('#loginBox');
			loginBox.empty();
			loginBox.append( form );
		var loginOutTimerId;
		var loginOut = false;
			
		$('.container .login')
		.click(function(e){
			e.preventDefault();
			//$(loginBox).toggleClass("make_hidden");
		})
		.mouseenter(function(e){
			if ( !loginPrepared ) prepareLogin(); 
			$(loginBox).removeClass("make_hidden");	//	Show the loginBox
			loginOut = false;			
		})
		.mouseleave(function(e){
			startLoginOutTimer();
			loginOut = true;
		});
		
		$(loginBox).mouseenter(function(e){
			loginOut = false;
		})
		.mouseleave(function(e){
			startLoginOutTimer();
			loginOut = true;		
		});
	}
	
	function prepareLogin()
	{
		loginPrepared = true;
		if ( loginBox.lenth != 0 ) //	If loginBox exsists (shouldn't be in the html if user is already logged in)
		{
			//	Grab elements we need
			var email 		= $(form).children("[name='email_address']").attr("id","loginEmail");		
			var pass 		= $(form).children("[name='password']").attr("id",'loginPassword');
			var security	= $(form).children("[name='securityToken']");
							// add an id attribtue so we can style, and change the text to something we like
			var forget 		= $(form).children("a").eq(0).attr("id",'loginForget').text('Forgot your password?');
			
			//	Reconstruct the markup our way
			loginBox.prepend( "<div id='loginClose'><span>close <b>x</b></span></div>" );
			$(loginBox).children("#loginClose").click(function(e){
				$(loginBox).addClass("make_hidden");
			});
			
			form.empty().append( email, pass, "<button type='submit' id='loginGo'>GO</button><br/>", forget, security );				
			
			//	If autofill hasn't filled in, then insert the word email
			if ( email.val() == '' ) email.val('email');
			
			//	If autofill hasn't filled in then create a dummy input
			//	to display the words 'password'
			if ( pass.val() == ''  )
			{ 
				pass.after( "<input type='text' id='loginTempPass' value='password' >" );
				pass.addClass( "make_hidden" );
				
				// ADD EVENT LISTENERS
				
				$(email).focus(function(e){
					$(this).val('');	//	First click removes the word 'email'
					$(email).unbind();	//	Unbind so subsequent clicks don't remove what the user entered
				});
				
				$('#loginTempPass').focus(function(e){
					//	Swap the 'fake' password field for the real one
					$(this).addClass( "make_hidden" );
					pass.removeClass( "make_hidden" );
					pass.focus(); // put the cursor in the real password field
				});
			}
		}		
	}
	
	function startLoginOutTimer() {
		loginOutTimerId = setTimeout( evaluateLoginOutness, 2*1000 ); // 1,000 milliseconds = 1 second
	}

	function stopLoginOutTimer() {
		clearTimeout( loginOutTimerId );
	}
	
	function evaluateLoginOutness() {
		stopLoginOutTimer();
		if ( loginOut ) $(loginBox).addClass("make_hidden");
	}	
	
	// -- -- -- -- -- -- -- --
	// CONTACT FORM
	// -- -- -- -- -- -- -- --
	
	$("form#contact").submit(function(){
		var allGood = true;
		textInputs.each(
			function() { 
				if( $(this).val() == '' ) allGood = false;
			}
		);
		if ( allGood ) return true;
		else return false;
	});

	var textInputs = $("form#contact input[type='text']").add("form#contact textarea");
	var firstFocus = [];
	
	textInputs.focus(function(e){
		if ( ! firstFocus[$(this).attr('name')] )  {
			firstFocus[$(this).attr('name')] = true;
			$(this).val('');
		}
		$(this).addClass('textInputFocus');
	});
	
	textInputs.blur(function(e){
		$(this).removeClass('textInputFocus');
		if ( $(this).val() == ''  )
		{
			var attrName =  $(this).attr('name');
			$(this).after( "<span class='requiredField required-" + attrName + "'>" + attrName + " required</span>" );
			$(this).bind( "keydown", {}, keyDownHandler );
		}
	});
	
	function keyDownHandler(e){
		$( '.required-' + $(this).attr('name') ).remove();
	}
	
	// -- -- -- -- -- -- -- --
	// PURCHASE OPTIONS - Get Price
	// -- -- -- -- -- -- -- --
	
	$('.productId, .quantity').change(function()
	{
		var pageId		= $(this).attr('id').substr(1);
		var quantity	= $( '#q' + pageId ).val();
		var productId	= $( '#p' + pageId ).val();
		if ( quantity == undefined ) quantity = 1;
		newPriceGetter( pageId, productId, quantity );
	});

	function newPriceGetter( pageId, productId, quantity ){
		$.post(
		
			"/shop/ajax/newPriceGetter.php",
			
			{ productId: productId, quantity: quantity },
			
			function(data)
			{
				$('#displayPrice'+pageId).html( data );
			}, 
			
			"html"
		);		
	}
	
	
	
	function updatePrice( pageId, productId, qty ){
		$.post(
		
			"/shop/ajax/priceGetter.php",
			
			{ productId: productId, quantity: qty },
			
			function(data)
			{
				$('#displayPrice'+pageId).text(data.price);
				if( data.price != data.undiscountedPrice )
				{
					$('#oldPrice'+pageId).text(data.undiscountedPrice);
				}
			}, 
			
			"json"
		);
	}

	// -- -- -- -- -- -- -- --
	// PURCHASE OPTIONS - SHOW PACKAGE SLIDING DOOR
	// -- -- -- -- -- -- -- --
	
	var closeHeight = "0";
	var openState = [];
	var openCloseContainers = [];
	var newId = 0;
	
	// itterate over all of the "Show Package" links
	//	- add a custom attribute with a unique value
	//  - add click handlers
	//  - find relevant relatives based on markup relationship
	//  - add the same attribute and click handlers to those relatives
	
	$('.font .description .styles a').each(function(i){
	
		this.openCloseId = newId;
		
		var target = $(this).parent().parent().parent().children().filter('.package');
		openCloseContainers[ newId ] = target;
		openState[ newId ] = false;
		
		target.each(function(i){
			this.openCloseId = newId;
		}).click(function(){
			openCloseController( this.openCloseId );
		});
		
		newId++;
		
	}).click(function(){
	
		openCloseController( this.openCloseId );
		
	});
	
	// Handles state logic and animation for the "show package" functionality
	function openCloseController( id )
	{
		var newHeight;
		
		if ( openState[ id ] == false )
		{ 
			openState[ id ] = true;		
			openCloseContainers[ id ].css('height','100%');
			if ( jQuery.browser.msie && jQuery.browser.version.substr(0,3) < 7 ) openCloseContainers[ id ].css('height','auto');
			newHeight = openCloseContainers[ id ].height();
			openCloseContainers[ id ].css('height','0');
		} 
		else if ( openState[ id ] == true )
		{	
			openState[ id ] = false;		
			newHeight = closeHeight;
		}
		
		openCloseContainers[ id ].animate({
			height: newHeight
		});		
	}
	
	// -- -- -- -- -- -- -- --
	// TOOLTIPS
	// -- -- -- -- -- -- -- --
	// we have to move the tooltips in the DOM for MSIE because 
	// it was applying styles in the cascade that screwed up the calculation
	// of the tooltips final x/y coords
	
	if (jQuery.browser.msie) $('#tooltips').insertAfter(".header");	
	
// -- -- -- -- -- -- -- --
	// FAQ Plugin + Scrolling
	// -- -- -- -- -- -- -- --

	var hash = jQuery.url.attr("anchor");
	var reg = /^(\w+)(\d+)$/; // a 'word' followed by a 'number'
	
	if ( hash != null && hash.match( reg ) )
	{
		// to preopen and scoll to a certian item 
		// give the <dt> a unique id, like 'purchasingFonts'
		// then pass a url like this '/help/#purchasingFonts0'
		// which will open the zereoth, i.e. the first, item
		var listSel = "";
		listSel		= RegExp.$1;
		var item	= RegExp.$2;
		
		// initializes the lists for proper calculations;
		// skips the list that will be initalized below with an item index to pre-open
		$('.faq').each(function(){
			if( $(this).attr('id') != listSel ) $(this).faq();
		});
		
		if ( $("#"+listSel).length > 0 )
		{
			// open the item by integer index; i.e. '0' is the first item, '1' is the second
			var index = parseFloat(item);
			$("#"+listSel).faq(index);
			
			// scroll to the item
			var selector = "#"+listSel+" dt";
			var distance = $(selector).eq(index).offset().top - 30;
			var time = distance; // 1000 pixels per second
			$('html, body').animate(
				{ scrollTop: distance }, 
				time
			);	
		}
	}
	else
	{
		$('.faq').faq();	
	}
});
