/**
 * Common functionality across the public website
 */

if (typeof($p) == 'undefined') $p = {};

$p.publicJS = function() {
	$p.megaMenus = [];
	
	//Breadcrumb links
	function setUpBreadCrumb(){
		// Grab the links
		$('#breadcrumb a.section').each(function(){
			var link = this;
			// Ping them
			var parent = $('li.' + $(link).attr('href').replace('#', ''))[0];
			$p.megaMenus.push(new $p.MegaMenu(link, parent, true));
			$(link).click(function(event){
				event.preventDefault();
				$('#subNav a.active').removeClass('active');
				$p.scrollingNav.scroll($('#headerContainer'));
			})
		});		
	}
	// Initiate everything in this file
	function init() {
		// Bread Crumbs
		if($('#breadcrumb a.section').length > 0){
			setUpBreadCrumb();	
		}
		
		// Mega Menus
		$('.megaMenu').each(function(){
			$p.megaMenus.push(new $p.MegaMenu(this));
		});	
		
		// Using your kit slider
		if(document.getElementById('usingYourKit')){
			$p.sliders = [];
			if(!$('#steps').hasClass('empty')){
				$('#steps li').each(function(){
					$p.sliders.push(new $p.Slider(this));
				})
			}
		}	
		
		// Genetic Counselor Contact
		if(document.getElementById('gcContactTog')){
			$p.gcContact();
		}
		
		// Scrolling 
		$p.scrollingNav.init();			
	}
	// Public
	return function(){
		init();
	};
}();


//Hook it up onload
$(document).ready(function(){
	$p.publicJS();
});


/**
 * @created March 2010
 * @usage looks for anchors with a class of 'megaMenu'. There href should 
 * correspond to an id on the page #element to open. - Rob
 * @param toggler
 * @return
 */

$p.MegaMenu = function(toggler, parent, wait){
	
	var self = this;
	var target = $($(toggler).attr('href'));
	// Breadcrumb links show wait for slider to finish
	var wait =arguments[2] || false
	var parent = arguments[1] || $(toggler).parents('li')[0];
	var close = $(target).find('.close');
	
	$(toggler).click(function(event){
		event.preventDefault();
		// Check if they're trying to close this one
		var alreadyOpen = $(parent).hasClass('open');
		// Close open ones
		if($('.openMenu').size() > 0){
			$('.openMenu').slideUp(
				'slow',
				function(){
					$(this).removeClass('openMenu');
					$('li.open').removeClass('open');
					if(!alreadyOpen){
						wait ? self.waitForSlide() : self.slideOpen();
					}
				}
			)
		} else {
			wait ? self.waitForSlide() : self.slideOpen();
		}
	})
	// Dont show the closing animation a link is clicked
	$(target).find('a').click(function(){
		$('#wrapper').unbind('click');
	});
	
	$(close).click(function(){
		self.close();
	})
	
	// open the desired menu
	this.slideOpen = function(){
		$(parent).addClass('open');
		$(target).addClass('openMenu');
		$(target).slideDown('slow', function(){
			// Clicking outside of the menu should close it
			$(target).mouseleave(function(){
				$('#wrapper').bind('click', function(){
					self.close()
				});
			})
			// But not inside it
			$(target).mouseenter(function(){
				$('#wrapper').unbind('click');
			});
		});
	}
	
	// CLose and unbind wrapper
	this.close = function(){
		$('.openMenu').slideUp(this.slideTime);
		$('li.open').removeClass('open');	
		$('#wrapper').unbind('click');
	}
	
	// Little nuance for the breadcrumbs
	this.waitForSlide = function(){
		setTimeout(
			function(){
				if($p.scrollingNav.autoScrolling){
					waiting = window.setInterval(self.checkScrolling, 10);
				} else {
					self.slideOpen();
				}
			},
			200
		);
	}
	this.checkScrolling = function(){
		if(!$p.scrollingNav.autoScrolling){
			window.clearInterval(waiting);
			self.slideOpen();
		}
	}
}

/* Sliders for the how it works section */
$p.Slider = function(toggler){
	var self = this;
	
	$(toggler).click(function(){
		var alreadyOpen = $(toggler).hasClass('open');
		if($('#steps li.open').length > 0){
			$('#steps li.open p').slideUp(function(){
				$('#steps li.open').removeClass('open');
				if(!alreadyOpen){
					self.show();
				}
			});
		} else {
			self.show();
		}
	});	
	
	this.show = function(){
		$(toggler).addClass('open');
		$(toggler).find('p').slideDown(
			function(){
				$(toggler).find('span.arrow').addClass('open');
				$('#wrapper').bind('click', function(){
					self.hide();
				})				
			});
	}
	
	this.hide = function(){
		$(toggler).find('p').slideUp(
			function(){
				$(toggler).find('span.arrow').removeClass('open');
				$(toggler).removeClass('open');	
				$('#wrapper').unbind('click');
			});		
	}
};

/**
 * @created March 2010
 * @usage Hook up the sub navigation to scrollTo and handle 'you are here' - Rob
 * @return
 */

$p.scrollingNav = function(){
	var sectionMap = [];		
	var offset = -145;
	var multiSection = $('#subNav a').length > 0;
	var autoScrolling = false;
	
	// ScrollTo for links in sub-navigation
	function scroll(target){
		$p.scrollingNav.autoScrolling = true;
		var location = $(target).is('a') ? $($(target).attr('href')) : target;
		$.scrollTo(location, 1000, {
				offset: {top:offset, left:0},
				onAfter:function(){
					$p.scrollingNav.autoScrolling = false;
					if(multiSection){
						updateLocation($(window).scrollTop());
					}
				}
			}
		);
	}
	// So we know where we are 
	function updateLocation(loc){
		var currentSection;
		for(var i = 0; i< sectionMap.length; i++){
			if(loc >= (sectionMap[i] + offset) && loc < sectionMap[i+1]){
				currentSection = $('#subNav a')[i];
				if(currentSection.className != 'active'){
					$('#subNav a.active').removeClass('active');
					currentSection.className = 'active';
				}
				break;
			}
		}
	}
	function setUpMulti(){
		// Lets get all the content sections and figure out where they are
		$('.contentSection').each(function(){
			var top = this.offsetTop;
			sectionMap.push(top);
		});
		
		// Hard set the first section to 0
		sectionMap[0] = 0;
		// In the footer so we can compare for the last section (saves making the logic more complex)
		sectionMap.push(document.getElementById('footer').offsetTop)

		// On scroll loop through and find where we are
		$(window).scroll(function(event){
			if(autoScrolling != true) {
				var location = $(window).scrollTop();
				updateLocation(location);
			}
		});			
	}
	// Start it up
	function init(){
		// find out where we are on load
		if(multiSection) {
			updateLocation($(window).scrollTop());
		}
		// For the dynamicly positioned header
		
		//check for a location in the cookie
		var initScrollLoc = $p.readCookie('pgScrollTo');

		if(initScrollLoc){
			// Give it just a breath before scrolling
			setTimeout(function(){
				scroll(initScrollLoc);
			}, 250);
			$p.clearCookie('pgScrollTo');
		}
		
		// Scroll to
		if(multiSection){
			$('#subNav a').click(function(event){
				event.preventDefault();
				if(!$(this).hasClass('active')){
					$('#subNav a.active').removeClass('active');
				}
				scroll(this);
			});
		}
		
		// For links in the page that scroll to other sections
		$('a.inPage').live('click', function(event){
			event.preventDefault();
			scroll(this);
		});
		
		// This stuff only happens for pages with multiple sections
		if(multiSection){		
			setUpMulti();
		}
	}
	// Public
	return {
		init:init,
		scroll:scroll
	};
}();

/**
 * @created April 2010
 * @usage Genetic Counseling contact form scripting - Rob
 * @return
 */

$p.gcContact = function(){
	// Set up the form after the ajax call
	function setUpForm(){
		Cufon.set('fontFamily', 'Futurabold').replace('#gcContact h2')('#gcContact span.button');
		// Cancel button
		$('#gcCancel').click(function(){
			$.fancybox.close();
		});
		$('#gcForm .req').blur(function(){
			this.value = $p.trim(this.value);
			validate(this);	
		});
		// Submit
		$('#gcSendBtn').click(function(){
			submit();
		});
		// Google Analytics
		if(typeof(pageTracker) !=  'undefined') {
			pageTracker._trackEvent('gc contact', 'open', 'counselor pop up');
		}
	}
	// Submit the form and make sure all is well
	function submit(){
		if($('#gcForm .valid').length == 3){
			$.post(
				document.gcForm.action,	
				$('#gcForm').serialize(),
				function(data){
					document.getElementById('gcContent').innerHTML = data;
					$.fancybox.resize();
					Cufon.set('fontFamily', 'Futurabold').replace('#gcContact h2')('#gcContact span.button');
					setTimeout(
						function(){
							$.fancybox.close();		
							$('#gcContact').remove();
						},
						2000
					);
				},
				'html'
			);
		} else {
			$('#gcForm .req').each(function(){
				if(!$(this).hasClass('valid')){
					validate(this);
				}
			});
		}
	}
	// TODO: extend Validate.js to handle this stuff
	function validate(field){
		var valid = true;
		if(field.name != 'gcEmail' && field.value != ''){
			$(field).removeClass('error');
			$(field).addClass('valid');
			$('#' + field.name + 'Error').removeClass('active');
		} else if (field.name == 'gcEmail'){
			var filter = /^([a-zA-Z0-9_.-])+@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/;
			if (field.value != '' && filter.test(field.value)){
				$(field).removeClass('error');
				$(field).addClass('valid');	
				$('#' + field.name + 'Error').removeClass('active');
			} else {
				valid = false;
			}
		} else {
			valid = false;
		}
		if(!valid){
			showError(field);
		} else {
			if($('#gcErrors li.active').length == 0){
				$('#gcErrors').removeClass('active');
			}
		}
		$.fancybox.resize();
	}
	// Show any errors
	function showError(field){
		$(field).removeClass('valid');
		$(field).addClass('error');
		if(!$('#gcErrors').hasClass('active')){
			!$('#gcErrors').addClass('active')
		}
		$('#' + field.name + 'Error').addClass('active');
	}
	// The load event
	function init(){
		// Set it up
		$('.gcContact').fancybox({
			margin : 0,
			padding: 0,
			overlayShow : true,
			centerOnScroll : true,
			scrolling : 'no',
			overlayOpacity : 0.6,
			overlayColor : '#333',
			titleShow : false,
			showNavArrows : false,
			onComplete : function(){setUpForm();}
		});		
	}
	// public
	return function(){
		init();
	};
}();