var scrolledSections = [];
var isScrollingFromClick = false;

$(function(){
	// Register each section as a waypoint.
	$('.mainsection').waypoint(function(event) {
		if (!isScrollingFromClick) {
			var dataId = $(this).data('analyticsid');
			if ($.inArray(dataId, scrolledSections) === -1) {
				scrolledSections.push(dataId);
				log('_trackEvent Navigation scroll ' + dataId);
				_gaq.push(['_trackEvent', 'Navigation', 'scroll', dataId]);
			}
		}
		event.stopPropagation();
	}, {
		// offset: '50%'
	});

	// The same for all waypoints
	$('.mainsection').bind('waypoint.reached', function(event, direction) {
		var $active = $(this);

		if (direction === "up") {
			$active = $active.prev();
		}
		if (!$active.length) $active.end();

		$('.selected').removeClass('selected');
		$('a[href=#'+$active.attr('id')+']').addClass('selected');
	});

	// Negates the flash of non-active nav.
	$('header a').click(function() {
		$(this).addClass('selected');
		log('_trackEvent Navigation click ' + $(this).attr('href').substr(1));
		_gaq.push(['_trackEvent', 'Navigation', 'click', $(this).attr('href').substr(1)]);
	}).eq(0).addClass('selected');

	// Wicked credit to
	// http://www.zachstronaut.com/posts/2009/01/18/jquery-smooth-scroll-bugs.html
	var scrollElement = 'html, body';
	$('html, body').each(function () {
		var initScrollTop = $(this).attr('scrollTop');
		$(this).attr('scrollTop', initScrollTop + 1);
		if ($(this).attr('scrollTop') == initScrollTop + 1) {
			scrollElement = this.nodeName.toLowerCase();
			$(this).attr('scrollTop', initScrollTop);
			return false;
		}
	});

	// Smooth scrolling for internal links
	$("a[href^='#']:not(.top)").click(function(event) {
		event.preventDefault();

		isScrollingFromClick = true;

		var $this = $(this),
		target = this.hash,
		$target = $(target);

		$(scrollElement).stop().animate({
			'scrollTop': $target.offset().top
		}, 500, 'swing', function() {
			window.location.hash = target;
			isScrollingFromClick = false;
		});
	});

	// Hide top link until top is not visible
	$('.top').addClass('invisible');
	$.waypoints.settings.scrollThrottle = 30;
	$('body').waypoint(function(event, direction) {
		$('.top').toggleClass('invisible', direction === "up");
	}, {
		offset: '-100%'
	}).find('header').waypoint(function(event, direction) {
		$(this).parent().toggleClass('sticky', direction === "down");
		event.stopPropagation();
	});






	// HOME
	$.fn.cycle.transitions.scrollVertUp = function($cont, $slides, opts) {
		$cont.css('overflow','hidden');
		opts.before.push(function(curr, next, opts, fwd) {
			$.fn.cycle.commonReset(curr,next,opts);
			opts.cssBefore.top = fwd ? (next.cycleH-1) : (1-next.cycleH-1);
			opts.animOut.top = fwd ? -curr.cycleH : curr.cycleH;
		});
		opts.cssFirst = { top: 0 };
		opts.cssBefore= { left: 0 };
		opts.animIn   = { top: 0 };
		opts.animOut  = { left: 0 };
	};

	$('#stage').cycle({
		fx: 'scrollVertUp',
		speed: 1000,
		pause: 1,
		timeout: 7000,
		delay: 500,
		prev: '#slider-down',
		next: '#slider-up'
	});





	// GALLERY
	/* PORTFOLIO GALLERIES - GLOBAL */
	// We only want these styles applied when javascript is enabled
	$('div.navigation').css({'width' : '300px', 'float' : 'left'});
	$('div.content').css('display', 'block');

	/* PORTFOLIO GALLERIES - INDIVIDUAL */
	var gallery = $('#thumbs-0').galleriffic({
		delay:                     2500,
		preloadAhead:              10,
		enableTopPager:            true,
		enableBottomPager:         true,
		maxPagesToShow:            7,
		imageContainerSel:         '#preview-0',
		controlsContainerSel:      '#controls-0',
		captionContainerSel:       '#caption-0',
		loadingContainerSel:       '#loading-0',
		renderSSControls:          true,
		renderNavControls:         true,
		nextLinkText:              'Next Slide',
		enableHistory:             false,
		autoStart:                 false,
		syncTransitions:           true,
		defaultTransitionDuration: 400
	});

	if (num_portfolio_items > 1) {
	var gallery = $('#thumbs-1').galleriffic({
		delay:                     2500,
		preloadAhead:              10,
		enableTopPager:            true,
		enableBottomPager:         true,
		maxPagesToShow:            7,
		imageContainerSel:         '#preview-1',
		controlsContainerSel:      '#controls-1',
		captionContainerSel:       '#caption-1',
		loadingContainerSel:       '#loading-1',
		renderSSControls:          true,
		renderNavControls:         true,
		nextLinkText:              'Next Slide',
		enableHistory:             false,
		autoStart:                 false,
		syncTransitions:           true,
		defaultTransitionDuration: 400
	});
	}

	if (num_portfolio_items > 2) {
	var gallery = $('#thumbs-2').galleriffic({
		delay:                     2500,
		preloadAhead:              10,
		enableTopPager:            true,
		enableBottomPager:         true,
		maxPagesToShow:            7,
		imageContainerSel:         '#preview-2',
		controlsContainerSel:      '#controls-2',
		captionContainerSel:       '#caption-2',
		loadingContainerSel:       '#loading-2',
		renderSSControls:          true,
		renderNavControls:         true,
		nextLinkText:              'Next Slide',
		enableHistory:             false,
		autoStart:                 false,
		syncTransitions:           true,
		defaultTransitionDuration: 400
	});
	}

	if (num_portfolio_items > 3) {
	var gallery = $('#thumbs-3').galleriffic({
		delay:                     2500,
		preloadAhead:              10,
		enableTopPager:            true,
		enableBottomPager:         true,
		maxPagesToShow:            7,
		imageContainerSel:         '#preview-3',
		controlsContainerSel:      '#controls-3',
		captionContainerSel:       '#caption-3',
		loadingContainerSel:       '#loading-3',
		renderSSControls:          true,
		renderNavControls:         true,
		nextLinkText:              'Next Slide',
		enableHistory:             false,
		autoStart:                 false,
		syncTransitions:           true,
		defaultTransitionDuration: 400
	});
	}

	if (num_portfolio_items > 4) {
	var gallery = $('#thumbs-4').galleriffic({
		delay:                     2500,
		preloadAhead:              10,
		enableTopPager:            true,
		enableBottomPager:         true,
		maxPagesToShow:            7,
		imageContainerSel:         '#preview-4',
		controlsContainerSel:      '#controls-4',
		captionContainerSel:       '#caption-4',
		loadingContainerSel:       '#loading-4',
		renderSSControls:          true,
		renderNavControls:         true,
		nextLinkText:              'Next Slide',
		enableHistory:             false,
		autoStart:                 false,
		syncTransitions:           true,
		defaultTransitionDuration: 400
	});
	}






	// CONTACT
	$('input[placeholder], textarea[placeholder]').placeholder();

	$.validator.addMethod("phone", function(ph, element) {
		if (ph == null) {
			return false;
		}
		var stripped = ph.replace(/[\s()+-]|ext\.?/gi, "");
		// 10 is the minimum number of numbers required
		return ((/\d{10,}/i).test(stripped));
	}, "Please enter a valid phone number");

	var contactForm = $('#contact-form');
	contactForm.validate();
	contactForm.submit(function() {
		$.ajax({
			type: 'POST',
			url: '/contact/',
			data: contactForm.serializeArray(),
			success: function(response) {
				if (response.success) {
					contactForm.fadeOut('slow', function() {
						contactForm.html('<p class="success">' + response.message + '</p>').fadeIn('slow');
					});
				}
			}
		});

		_gaq.push(['_trackEvent', 'Form', 'submit', 'contact']);

		return false;
	});
});

