jQuery(document).ready(function($) {
	
	/*
	 * Initialize
	 * ----------------------------------------
	 */
	var routes = new Routes();
	var vertical = new Vertical();
	var services_horizontal = new Horizontal($('#services-sections'));
	var company_horizontal = new Horizontal($('#company-sections'));
	var sections = new Sections();
	var layering = new Layering();
	var transitions = new Transitions();
	var inquiry_box = new Inquiry();
	var istickybar = new iStickyBar($('#home'), $('#home > .bottom'));
	var cycle = new Cycle($('#home .case-study'), {duration: 20000, speed: 500});
	
	var colorbox_is_open, active_section, services_sub_id, company_sub_id;
	
	//This will allow us to track if the colorbox is open or not.
	var colorbox_is_open = false;
	
	//Set the active nav item to home. 
	setActiveNavItem('home');
	
	//Reposition all layers.
	layering.reposition();
	
	//Transition the horizontal sections.
	transitionSection($('#services'));
	transitionSection($('#company'));
	
	//Add a class of "click" to the press section.
	$('#press .container li').addClass('click');
	$('#work li').addClass('click');
	
	//Vertically center the contents of each horizontal sections.
	$.each($('.section-group'), function(index, el) {
		$.each($('section', el), function(index, section) {
			var section_wrapper = $('> .section-wrapper', section);
			section_wrapper.css('margin-top', Math.ceil(( Math.abs( $(section).height() - $(section_wrapper).outerHeight() )) / 2 ) + 'px');
		});
	});
	
	/*
	 * Form submission
	 *-----------------------------------------
	 */
	$('#subForm a.slant').bind('click', function(){
		$('#subForm').submit();
		return false;
	});
	
	/*
	 * Form placeholder fix
	 *-----------------------------------------
	 */
	$('[placeholder]').focus(function() {
		var input = $(this);
		if (input.val() == input.attr('placeholder')) {
			input.val('');
			input.removeClass('placeholder');
		}
	}).blur(function() {
		var input = $(this);
		if (input.val() == '' || input.val() == input.attr('placeholder')) {
			input.addClass('placeholder');
			input.val(input.attr('placeholder'));
		}
	}).blur();
	
	$('[placeholder]').parents('form').submit(function() {
		$(this).find('[placeholder]').each(function() {
			var input = $(this);
			if (input.val() == input.attr('placeholder')) {
				input.val('');
			}
		})
	});
	
	/*
	 * Functions
	 * ----------------------------------------
	 */
	function transitionSection(el) {
		var config =el.attr('data-transition-properties');
	    if (config !== undefined)
	    	config = $.parseJSON(config);
	    else
	    	return;
		
		var group = el.parentsUntil('.section-group').parent();
	    transitions.transition_to_background_color(group, config.background);
	    transitions.transition_to_opacity($('.static .texture', group), config.texture);
	    transitions.transition_to_opacity($('.static .gradient', group), config.gradient);
	}
	
	function setActiveNavItem(id) {
		$('nav#primary a').removeClass('active');
		$('a[data-relates-to-section-id="' + id + '"]', 'nav#primary').addClass('active');
	}
	
	function setActiveSubNavItem(parent, id) {
		$('a[data-relates-to-section-id="'+ parent +'"] + ul a').removeClass('active');
		$('a[data-relates-to-section-id="'+ id +'"]').addClass('active');
	}
	
	/*
	 * Define Routes
	 * ----------------------------------------
	 * Notes:
	 *   1. setActiveNavItem should only be called in horizontal sub sections. Primary sections are set in the sections.onenter event handler.
	 */
	routes.addPath('#!/home', function() {
	    vertical.move($('html, body'), document.getElementById('home'), 800, 'easeOutQuart');
	    $.colorbox.close();
	    
	    active_section = 'home';
	    
	    _gaq.push(['_trackEvent', 'Section', 'Home']);
	}).setRoot();
	
	routes.addPath('#!/services', function() {
	    vertical.move($('html, body'), document.getElementById('services-sections'), 800, 'easeOutQuart');
	    services_horizontal.move($('#services'), 800, 'easeOutQuart');
	    $.colorbox.close();
	    transitionSection($('#services'));
	    
	    if (active_section == 'services-sections' || active_section == 'strategy' || active_section == 'engagement' || active_section == 'analytics' || active_section == 'creative')
	   		setActiveSubNavItem('services-sections', 'services-sections');
	   		
	   	active_section = services_sub_id = 'services-sections';
	   	
	   	_gaq.push(['_trackEvent', 'Section', 'Services']);
	});
	
	routes.addPath('#!/services/strategy', function() {
	    vertical.move($('html, body'), document.getElementById('services-sections'), 800, 'easeOutQuart');
	    services_horizontal.move($('#strategy'), 800, 'easeOutQuart');
	    $.colorbox.close();
	    transitionSection($('#strategy'));
	    
	    active_section = services_sub_id = 'strategy';
		setActiveSubNavItem('services-sections', 'strategy');
		
		_gaq.push(['_trackEvent', 'Section', 'Services', 'Strategy']);
	});
	
	routes.addPath('#!/services/engagement', function() {
	    vertical.move($('html, body'), document.getElementById('services-sections'), 800, 'easeOutQuart');
	    services_horizontal.move($('#engagement'), 800, 'easeOutQuart');
	    $.colorbox.close();
	    transitionSection($('#engagement'));
	    
	    active_section = services_sub_id = 'engagement';
	    setActiveSubNavItem('services-sections', 'engagement');
	    
	    _gaq.push(['_trackEvent', 'Section', 'Services', 'Engagement']);
	});
	
	routes.addPath('#!/services/analytics', function() {
	    vertical.move($('html, body'), document.getElementById('services-sections'), 800, 'easeOutQuart');
	    services_horizontal.move($('#analytics'), 800, 'easeOutQuart');
	    $.colorbox.close();
	    transitionSection($('#analytics'));
	    
	    active_section = services_sub_id = 'analytics';
	    setActiveSubNavItem('services-sections', 'analytics');
	    
	    _gaq.push(['_trackEvent', 'Section', 'Services', 'Analytics']);
	});
	
	routes.addPath('#!/services/social-interactive', function() {
	    vertical.move($('html, body'), document.getElementById('services-sections'), 800, 'easeOutQuart');
	    services_horizontal.move($('#creative'), 800, 'easeOutQuart');
	    $.colorbox.close();
	    transitionSection($('#creative'));
	    
	    active_section = services_sub_id = 'creative';
	    setActiveSubNavItem('services-sections', 'creative');
	    
	    _gaq.push(['_trackEvent', 'Section', 'Services', 'Creative']);
	});
	
	routes.addPath('#!/work', function() {
	    vertical.move($('html, body'), document.getElementById('work'), 800, 'easeOutQuart');
	    $.colorbox.close();
	    
	    active_section = 'work';
	    _gaq.push(['_trackEvent', 'Section', 'Services', 'Analytics']);
	});
	
	routes.addPath('#!/company', function() {
	    vertical.move($('html, body'), document.getElementById('company-sections'), 800, 'easeOutQuart');
	    company_horizontal.move($('#company'), 800, 'easeOutQuart');
	    $.colorbox.close();
	    transitionSection($('#company'));
	    
	    if (active_section == 'company-sections' || active_section == 'clients' || active_section == 'jobs' || active_section == 'press' || active_section == 'team')
	    	setActiveSubNavItem('company-sections', 'company-sections');
	    	
	    active_section = company_sub_id = 'company-sections';
	    
	    _gaq.push(['_trackEvent', 'Section', 'Company']);
	});
	
	routes.addPath('#!/company/clients', function() {
	    vertical.move($('html, body'), document.getElementById('company-sections'), 800, 'easeOutQuart');
	    company_horizontal.move($('#clients'), 800, 'easeOutQuart');
	    $.colorbox.close();
	    transitionSection($('#clients'));
	    
	    active_section = company_sub_id = 'clients';
	    setActiveSubNavItem('company-sections', 'clients');
	    
	    _gaq.push(['_trackEvent', 'Section', 'Company', 'Clients']);
	});
	
	routes.addPath('#!/company/jobs', function() {
	    vertical.move($('html, body'), document.getElementById('company-sections'), 800, 'easeOutQuart');
	    company_horizontal.move($('#jobs'), 800, 'easeOutQuart');
	    $.colorbox.close();
	    transitionSection($('#jobs'));
	    
	    active_section = company_sub_id = 'jobs';
	    setActiveSubNavItem('company-sections', 'jobs');
	    
	    _gaq.push(['_trackEvent', 'Section', 'Company', 'Jobs']);
	});
	
	routes.addPath('#!/company/press', function() {
	    vertical.move($('html, body'), document.getElementById('company-sections'), 800, 'easeOutQuart');
	    company_horizontal.move($('#press'), 800, 'easeOutQuart');
	    $.colorbox.close();
	    transitionSection($('#press'));
	    
	    active_section = company_sub_id = 'press';
	    setActiveSubNavItem('company-sections', 'press');
	    
	    _gaq.push(['_trackEvent', 'Section', 'Company', 'Press']);
	});
	
	routes.addPath('#!/company/team', function() {
	    vertical.move($('html, body'), document.getElementById('company-sections'), 800, 'easeOutQuart');
	    company_horizontal.move($('#team'), 800, 'easeOutQuart');
	    $.colorbox.close();
	    transitionSection($('#team'));
	    
	    active_section = company_sub_id = 'team';
	    setActiveSubNavItem('company-sections', 'team');
	    
	    _gaq.push(['_trackEvent', 'Section', 'Company', 'Team']);
	});
	
	routes.addPath('#!/contact', function() {
	    vertical.move($('html, body'), document.getElementById('contact'), 800, 'easeOutQuart');
	    $.colorbox.close();
	    active_section = 'contact';
	    
	    _gaq.push(['_trackEvent', 'Section', 'Company', 'Contact']);
	});
	
	setTimeout(function() {
		routes.listen();
	}, 500);
	
	
	/*
	 * Event Listners
	 * ----------------------------------------
	 */
	sections.onenter = function() {
		var ctx = this;
		active_section = this.name;
		
		var nav_anchor = $.find('a[data-relates-to-section-id="' + active_section + '"]');
		setActiveNavItem(active_section);
		
		switch(active_section) {
			case 'services-sections':
				setActiveSubNavItem(active_section, services_sub_id);
				break;
			case 'company-sections':
				setActiveSubNavItem(active_section, company_sub_id);
				break;
		}
		
		setTimeout(function() {
			if (sections.active === ctx)
				$("+ *", nav_anchor).slideDown();
		}, 500);
	}
	
	sections.onleave = function() {
		var nav_anchor= $.find('a[data-relates-to-section-id="' + this.name + '"]');
		$("+ *", nav_anchor).slideUp();
	}
	
	if (window.onresize === null || window.onresize === undefined) {
		window.onresize = function(event) {
			services_horizontal.reposition();
			company_horizontal.reposition();
			layering.reposition();
			inquiry_box.reposition();
			istickybar.reposition();
			
			/* There is a rare bug when a lightbox is open
			 * and you resize the browser, it scrolls back to the beginning
			 * of the horizontal section, but it doesn't update the color. This
			 * is a fix to update the color. */
			if (colorbox_is_open) {
				transitionSection($('#services'));
				transitionSection($('#company'));
			}
		}
	}
	
	if (window.onscroll === null || window.onscroll === undefined) {
		window.onscroll = function() {
			sections.reposition();
			layering.reposition();
			istickybar.reposition();
		}
	}
	
	$('.click').bind('click', function(e) {
		var a = $('a:first', this);
		var href = a.attr('href');
		var target = a.attr('target');
		
		if (typeof href !== 'undefined') {
			if (typeof target == 'undefined')
				routes.setLocation(href);
			else
				window.open(href);
		}
	});
	
	$('a').bind('click', function(e) {
		if ($(this).attr('href') === location.hash) {
	    	routes.dispatch($(this).attr('href'));
	    }
	});
	
	$('header#site-header a').bind('click', function(e) {
	    $.colorbox.close();
	});
	
	/*
	 * Home Page Cycle
	 * ----------------------------------------
	 */
	cycle.animation = function(element, nextElement, direction, callback) {
	    $(element).fadeOut(cycle.speed, function() {
	    	$(this).css('display', 'block');
	    	$(this).css('left', '-9999em');
	    	
	    	$(nextElement).css('left', '0px');
	    	$(nextElement).hide();
	    	$(nextElement).fadeIn(cycle.speed, function() {
	    		callback.call();
	    	});
	    	
	    	$('#home').attr('class', nextElement[0].id);
	    	var activeSelector = $('#home .bottom .selector a[rel='+ element[0].id +']').removeClass('active');
	    	var nextSelector = $('#home .bottom .selector a[rel='+ nextElement[0].id +']');
	    	nextSelector.after(nextSelector.clone().addClass('active').hide().fadeIn(cycle.speed, function() {
	    		nextSelector.addClass('active');
	    		$(this).remove();
	    	}));
	    	
	    });
	};
	
	$('#home .bottom .selector a').bind('click', function() {
	    cycle.goto($(this).attr('rel'));
	    return false;
	});
	
	$($('#home')[0]).attr('class', $('#home .case-study')[0].id);
	$($('#home .case-study')[0]).css('display', 'block');
	$($('#home .case-study')[0]).css('left', '0px');
	
	
	/*
	 * Dynamically register paths.
	 * ----------------------------------------
	 */
	jQuery.each($('*[data-register-path]'), function(key, el) {
		
		var hash = el.getAttribute('data-register-path');
	    
	    routes.addPath(hash, function(el) {
	        
	        var overlay = el.getAttribute('data-wants-overlay');
	        
	        if (overlay !== null) {
				config = $.parseJSON(overlay);
	        	var offset = 0;
	        	$.colorbox( {
		    		transition: "fade",
		    		opacity: 1,
		    		href: config.data_source,
		    		scrolling: false,
		    		initialWidth: "1240px",
		    		width: "1240px",
		    		top: "0px",
	        		onOpen: function() {
	        			colorbox_is_open = true;
	        			offset = $(document).scrollTop();
	        			$('.wrapper.primary #sections').css('display', 'none');
	        			$('body').css('overflow-y', 'scroll');
	        		},
	        		onLoad: function() {
	        			$('#cboxClose').hide();
	        		},
	        		onComplete: function() {
	        			$('body').css('overflow-y', 'auto');
	        			$('#cboxClose').show();
	        		},
	        		onCleanup: function() {
	        			colorbox_is_open = false;      			
	        			$('.wrapper.primary #sections').css('display', 'block');
	        			$(document).scrollTop(offset);
	        		}
	        	});
	        }
	    }, el);
	});
	
});
