/**
 * Global Metalier Setup
 * 
 * Creates all basic functionality for the entire Metalier website.
 * Built in a [Metalier] object so as not to clutter up the global
 * variable space.
 * 
 * @author Seven.co.nz
 *
 */


var Metalier = {};


// Variables ________________________________________________________________
Metalier.countryCodeURL = '';		// Country code in the URL
Metalier.countryCodeGeo = '';		// Country code defined by Google



// Methods __________________________________________________________________

/* [init]
 * Runs all the setup methods
 */
Metalier.init = function() {
	/* Every page
	*/
	// Retrieve country codes
	if (typeof(google) == 'undefined') {
		google = {};
	} 
	if (google.loader.ClientLocation == null) {
		google.loader.ClientLocation = WIPlocation;
	}
	Metalier.countryCodeURL = $('meta[name=region]').attr('content');
	Metalier.countryCodeGeo = google.loader.ClientLocation.address.country_code.toLowerCase();
	
	// Build events
	Metalier.setupCommonEvents();
	
	// Signup form
	$('#newsletterMenu fieldset').each(function() {
		$('#signUpSubmit', this).click(function() {
			Metalier.newsletterSignup($('#newsletterSignUp').val());
			return false;
		});
	});
	
	
	/* Specific pages
	*/
	// Home
	$('#featureCarousel').each(function() {
		$(this).carousel();
	});
	
	// Metal Coatings: Tabs
	$('#coatingTabs').each(function() {
		// Set the open/close topics
		$('h5 a', this).click(function() {
			Metalier.toggleTopic($(this).parent().parent());
			return false;
		});
		
		// Set the first topic open by default
		$('.topicPanel:not(:first)', this).removeClass('open');
	});
	
	// Finish/Inspiration categories
	$('#previewTypesList .previewCategory').each(function() {
		// Events
		$(this).mouseenter(function() {
			$(this).addClass('mouseOver');
			$('.previewCategory').stop(true, true);
			$('.previewCategory:not(.mouseOver)').css({
				opacity: 0.4
			});
			$('.prev, .next', this).css({ opacity: 0.2 }).animate({ opacity: 1 }, 300, 'easeOutQuad');
		});
		$(this).mouseleave(function() {
			$('.previewCategory:not(.mouseOver)').fadeTo('easeOutQuad', 1);
			$(this).removeClass('mouseOver');
		});
		
		// Image carousel
		$('.thumbs', this).jCarouselLite({
			btnPrev:	$('.prev', this),
			btnNext:	$('.next', this),
			easing:		'easeOutCubic',
			speed:		300,
			visible:	1,
			afterEnd:	function(selected) {
				// Update set link to selected image
				var link = $('a', selected).attr('href');
				var set = $(this).parent().parent().prev();
				set.attr('href', link);
			}
		});
		
		// Pop-up gallery frame
		$("a.frame", this).fancybox({
			margin:			0,
			padding: 		0,
			overlayOpacity:	0.7,
			overlayColor:	'#000000',
			width:			820,
			height:			550,
			type:			'ajax',
			onComplete:		function() {
				Metalier.setupGallery();
			}
		});
	});
	
	// Gallery
	$('#galleryPage').each(function() {
		Metalier.setupGallery();
	});
	
	// Application
	$('#layoutApplication').each(function() {
		// Open the section most relevant to the visitor
		var visitorRegion = $('#region_' + Metalier.countryCodeGeo);
		if (visitorRegion.length == 0) {
			visitorRegion = $('#region_row');
		}
		if (visitorRegion.hasClass('open') == false) {
			$('.topicPanel.open').removeClass('open');
			visitorRegion.addClass('open');
		}
		
		// Topic section events
		$('.topicPanel h5 a', this).click(function() {
			var topic = $(this).parent().parent();
			if (topic.hasClass('open')) {
				// Close
				$('.topicContent', topic).slideUp({ duration: 600, easing: 'easeOutQuint' });
				topic.removeClass('open');
			} else {
				// Open
				$('.topicContent', topic).slideDown({ duration: 400, easing: 'easeOutExpo' });
				topic.addClass('open');
			}
			return false;
		});
		
		// Apply sidebar events
		$('#advantagesToggle', this).click(function() {
			var section = $(this).parent();
			if (section.hasClass('open')) {
				// Close
				$('span', this).text('Read more');
				$('.advantages', section).slideUp({ duration: 900, easing: 'easeOutQuint' });
				section.removeClass('open');
			} else {
				// Open
				$('span', this).text('Close');
				$('.advantages', section).slideDown({ duration: 600, easing: 'easeOutExpo' });
				section.addClass('open');
			}
			return false;
		});
	});
	
	// Contact
	$('#layoutContact').each(function() {
		// Topic section events
		$('.topicPanel h5 a', this).click(function() {
			var topic = $(this).parent().parent();
			if (topic.hasClass('open')) {
				// Close
				$('.topicContent', topic).slideUp({ duration: 600, easing: 'easeOutQuint' });
				topic.removeClass('open');
			} else {
				// Open
				$('.topicContent', topic).slideDown({ duration: 400, easing: 'easeOutExpo' });
				topic.addClass('open');
			}
			return false;
		});
	});
}

/* [preloadImages]
 * Preloads layout-dependent images
 */
Metalier.preloadImages = function(imageList) {
	preloadedImage = new Image();
	var i = imageList.length; while(i--) {
		preloadedImage.src = imageList[i];
	}
}

/* [setupCommonEvents]
 * Creates common events for things such as press and focus states
 */
Metalier.setupCommonEvents = function() {
	// Button events
	$('input').focus(function() { 
		$(this).addClass('focus'); 
	});
	$('input').blur(function() { 
		$(this).removeClass('focus'); 
	});
}

/* [toggleTopic]
 * Opens/Closes a topic area within a tab section
 * @param {HTMLElement} topic - 	Topic section div
 */
Metalier.toggleTopic = function(topic) {
	if (topic.hasClass('open')) {
		// Close
		$('.topicContent', topic).slideUp({ duration: 600, easing: 'easeOutQuint' });
		topic.removeClass('open');
	} else {
		// Open
		$('.topicContent', topic).slideDown({ duration: 400, easing: 'easeOutExpo' });
		topic.addClass('open');
	}
}

/* [setupGallery]
 * Builds the gallery
 */
Metalier.setupGallery = function() {
	// Image gallery
	var index = $('li', '.thumbnails').index($('.thumbnails .selected'));
	$('.thumbnails').gallery({ imageIndex: index });
}

/* [newsletterSignup]
 * Event when a visitor signs up to the newsletter
 * @param {String} emailAddress - Signup address
 */
Metalier.newsletterSignup = function(emailAddress) {
	// Validation
	var filter = /^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i;
	if (filter.test(emailAddress) === false) {
		$('#newsletterMenu label')
			.addClass('error')
			.html('Please enter a valid address...')
			.hide()
			.fadeIn({ duration: 800, easing: 'easeOutExpo' });
		return;
	}
	
	// Send address
	//$.post("http://www.alphamail.co.nz/api/Metalier.Add.Subscriber", { address: 'jason@notarealdomain.com', region: "nz" } );
	
	// Display thanks message
	//$('#newsletterSignUp').remove();
	//$('#signUpSubmit').remove();
	//$('#newsletterMenu fieldset').append('<p>Thanks</p>');
	
	// Submit form
	$('#newsletterSignUpForm').submit();
}


// Begin ____________________________________________________________________
$(document).ready(function() {
	Metalier.init();
});