/**
 * Better Brief JS
 *
 * The custom JavaScript used for the added functionality.
 *
 * @author Will Morgan <will.morgan@betterbrief.co.uk>
 * @author Dave Hill <dave.hill@betterbrief.co.uk>
 * @author Doug Proctor <doug.proctor@betterbrief.co.uk>
 * @version 0.9
 * @copyright 2011 Better Brief LLP
 *
 */

"use strict";

//Load jQuery
google.load("jquery", "1.7");

// effectively 'on document ready'
google.setOnLoadCallback(function() {

	var J = jQuery.noConflict();
	J(function($) {

		// Navigation tracer.
		(function() {
			var $nav = $('#Navigation'),
				$cur = $nav.find('a.current');
			var $tracer = $('<span />', {
				id: 'Tracer',
				css: {
					top: $nav.offset().top + $nav.outerHeight() - 8
				}
			});
			function moveTracerTo($element, duration) {
				duration = duration || 500;
				$tracer.stop().animate(generateCSS($element), duration);
			}
			function generateCSS($element) {
				return {
					width: $element.outerWidth() - 1,
					left: $element.offset().left - $nav.offset().left
				};
			}
			/***about page slider***/
			$.fn.replaceClass = function(classes) {
				return this.each(function() {
					var i, oldClass, $this = $(this);
					for(i in classes) {
						if($this.hasClass(classes[i])) {
							oldClass = classes.splice(i, 1)[0];
							return $this.removeClass(oldClass).addClass(classes.join(''));
						}
					}
					return $this;
				});
			}
			switch (document.body.id){
				case 'AboutPage':
				var $accordionHolder = $('#Team'), $ul = $('ul', $accordionHolder);
				if ($accordionHolder.length) {
					$ul.hide().filter('.people').find('a').each(function() {
						var $this = $(this), text = $this.text();
					});
					$('h3 a, h4 a', $accordionHolder).click(function() {
						var $this = $(this);
						$this.replaceClass(['open', 'closed']).closest('li').children('ul').slideToggle('fast');
						return false;
					});
				}
			break;
			}
			/******/
			$tracer.insertAfter($nav);
			if($cur.length) {
				$tracer.css(generateCSS($cur));
			}
			$('a', $nav).hoverIntent({
				over: function() {
					moveTracerTo($(this));
				},
				out: function() {
					if($cur.length) {
						moveTracerTo($cur, 1000);
					}
				},
				timeout: 50,
				interval: 50
			});
		})();


		// Slideshow
		var Slideshow = {
			activeIndex: 0,
			timer: null,
			elements: {
				container: null,
				slides: null,
				controls: null,
				activeSlide: null,
				activeControl: null
			},
			init: function() {
				// Set some elements up.
				this.elements.container	= $('#Slideshow');
				this.elements.slides	= this.elements.container.find('ol.Slides > li');
				this.elements.controls	= this.elements.container.find('ol.Controls > li > a');

				// Set the first slide up.
				this.elements.slides.filter(':first').css('bottom', 0);
				this.setActive(this.activeIndex, this.slideIn);

				// Clicking controls will activate the corresponding slide.
				this.elements.controls.bind('click', function(ev) {
					Slideshow.switchTo($(this).parent().index());
					ev.preventDefault();
				});

				// Stop/start the timer on mousein/mouseout.
				this.elements.container.hover(Slideshow.stopTimer, Slideshow.startTimer);

				// Start the timer if we have more than one slide.
				if(this.elements.slides.length > 1) {
					this.startTimer();
				}
			},
			hasActive: function() {
				return !!(this.elements.activeSlide && this.elements.activeControl);
			},
			setActive: function(index, callback) {
				this.activeIndex			= index;
				this.elements.activeSlide	= this.elements.slides.eq(index);
				this.elements.activeControl = this.elements.controls.eq(index);
				(callback && callback.call(this));
			},
			slideOut: function(callback) {
				var preparedCallback = function() {
					Slideshow.elements.activeSlide.css({ bottom: -310 });
					return callback.call(Slideshow);
				}
				this.elements.activeControl.removeClass('active');
				this.elements.activeSlide.stop(true, true).animate({ bottom: 310 }, 750, preparedCallback);
			},
			slideIn: function() {
				this.elements.activeSlide.css({ bottom: -310 }).stop(true, true).animate({ bottom: 0 }, 750);
				this.elements.activeControl.addClass('active');
			},
			switchTo: function(index) {
				if(this.activeIndex === index) {
					return;
				}

				// HELLO!! hHOW ARE YOU!
				// this bit does: sliding out! it slides out to the top! no grey underneath!
				this.elements.activeControl.removeClass('active');
				this.elements.activeSlide.animate({ bottom: 310 }, 750);
				// Slides in new slide from underneath
				this.setActive(index, function() {this.slideIn();});
			},
			incrementIndex: function() {
				var newIndex = this.activeIndex + 1;
				if(newIndex > this.elements.slides.length - 1) {
					newIndex = 0;
				}
				return newIndex;
			},
			getTimerFunction: function() {
				return function() {
					this.switchTo(this.incrementIndex());
				}.call(Slideshow);
			},
			startTimer: function() {
				Slideshow.timer = window.setInterval(Slideshow.getTimerFunction, 5000);
			},
			stopTimer: function() {
				window.clearInterval(Slideshow.timer);
			}
		};
		Slideshow.init();

		// Newsletter form.
		var $NewsletterSubmitButton = $('#NewsletterSubmitButton');
		$NewsletterSubmitButton.click(function() {
			var $FieldSet = $NewsletterSubmitButton.closest('fieldset');
			var $Form = $FieldSet.parent();
			//var formMethod = $Form.attr('method');
			var formAction = $Form.attr('action');
			var data = '';
			var success = true;
			$FieldSet.children('input:not([type=submit])').each(function() {
				var $this = $(this);
				var label = $FieldSet.children('label[for=' + $this.attr('id') +']').html();
				var labelclean = label.replace(':','');
				if ($this.val() && $this.val() != label) {
					if (label == 'Email'){
						if (echeck($this.val()) == false) {
							$this.css({'background-color':'#FED0D0','color':'#DC1313'});
							success = false;
							if (!$('#EmailError').length) {
								$FieldSet.append('<div id="EmailError"><p>Please enter a valid e-mail address</p></div>');
							}
						}
						else {
							$('#EmailError').remove();
							$this.css({'background-color':'','color':''});
						}
					}
					if (success) {
						$('#' + labelclean + 'Error').remove();
					}
				}
				else {
					success = false;
					if (!$('#' + labelclean + 'Error').length) {
						$FieldSet.append('<div id="' + labelclean + 'Error"><p>Please enter a valid ' + labelclean + '</p></div>');
					}
				}
			});
			data = $Form.serialize();
console.log(data);
			if (success){
			   $.post(
				  'NewsletterWidget_Controller/doAjaxSignup',
				  data
			   );
				$FieldSet.fadeOut('slow',function() {
					$(this).parent().append('<div id="NewsletterThanks" style="display:none"><p>Thanks</p></div>').children('#NewsletterThanks').fadeIn('slow');
				});
			}
			return false;
		});
	});

	// Latest News carousel

	var newsContainer = J('.slider ol'),
		nextButton = J('a.next'),
		prevButton = J('a.prev');

	prevButton.show();
	nextButton.show();

	prevButton.css('opacity', '0.3');

	var position = 0;

	prevButton.click(function() {
		if (position > 0) {

			nextButton.css('opacity', '1.0');

			newsContainer.animate({
			  left: '+=312'
			}, 300, function() {
			  // Animation complete.
			});

			position--;

			if (position == 0) {
				prevButton.css('opacity', '0.3');
			}
		}
		return false;
	});

	nextButton.click(function() {
		if (position < 4) {

			prevButton.css('opacity', '1.0');

			newsContainer.animate({
			  left: '-=312'
			}, 300, function() {
			  // Animation complete.
			});

			position++;

			if (position == 4) {
				nextButton.css('opacity', '0.3');
			}
		}
		return false;
	});

	// Portfolio Overlay

	var $ = J,
		ie7 = $.browser.msie && $.browser.version == 7,
		thumbnails = J('.showcase li.sub'); // was set to other-projects

	if (!ie7) {

		thumbnails.click(function() {

			var overlay = J(this).next('.overlay');

			var verticalOffset = J(document).scrollTop() + 50;

			//alert(verticalOffset);

			//console.log(J('.overlay-container').css('margin-top'));

			//J('.overlay-container').css('margin-top', verticalOffset);

			overlay.show();

			//console.log(J('.overlay-container').css('margin-top'));

			J('.close').click(function() {
				overlay.hide();
				return false;
			});

			J('.overlay').click(function(e) {
				overlay.hide();
				e.stopPropagation();
			});

			return false;
		})

	} else {
		thumbnails.click(function() {
			//return false;
		})
	}

	//Contact page smooth scrolling
	$('a.scroll').click(function(event) {
		event.preventDefault();
		var parts = $(this).attr('href').split('#'),
			target_offset = $('#' + parts[1]).offset().top,
			page = $('html, body');

		//Stop it nicely at the bottom
		if((page.height() - target_offset) < $(window).height()) {
			target_offset = page.height() - $(window).height();
		}

		page.animate({ scrollTop: target_offset }, 2000);
	});

});

//Google analytics tracking
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-5532417-8']);
_gaq.push(['_trackPageview']);

(function() {
  var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
  ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
  (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(ga);
})();

