"use strict";

/*globals $, jQuery, window, document */

(function () {
	var wrapper, imgs, current = 0, morePosts, newerPosts;

	function getNextIndex() {
		return (current + 1) >= imgs.length ? 0 : current + 1;
	}

	function getNext() {
		current = getNextIndex();
		rotateImages();
	}

	function rotateImages() {
		window.setTimeout(function () {
			imgs.eq(getNextIndex()).css('z-index', 3).show();
			imgs.eq(current).fadeOut(300, function () {			
				$(this).removeAttr('style');
				imgs.eq(getNextIndex()).css('z-index', 4);
				getNext();
			});		
		}, 3000);	
	}

	function togglePosts() {
		morePosts.click(function () {
			$(this).hide();
			newerPosts.fadeIn();
		
			return false;
		});	
	}		
	
	function checkField(form, field, value) {
		return form.find('input[name="' + field + '"]').val() !== value;
	}
	
	function toggleField() {
		var elem = $(this), label;		
	
		label = elem.attr('value');
	
		elem
			.focus(function () {
				if (elem.val() === label) {
					elem.val('');
				}
			})
			.blur(function () {
				if (elem.val() === '') {
					elem.val(label);
				}
			})	
	}
	
	function submitFanForm() {
	
		$('#fanForm')
			.find('input[type="text"]')
				.each(toggleField)
			.end()
			.submit(function () {
				var wrap = $(this).closest('.wide_content'), f = $(this);
				
				if (checkField(f, 'first', 'First Name') && 
					checkField(f, 'last', 'Last Name') && 
					checkField(f, 'email', 'Email Address') ) {
		
					$.ajax({
						url : 'send_fan.php',
						data: f.serialize(),
						type: 'post',
						success: function (data) {
							if (parseInt(data, 10) === 1) {
								wrap
									.find('.not_submitted')
										.hide()
									.end()	
									.find('.submitted')
										.show()
									.end();								
							} else {
								wrap
								.find('.error')
									.text('There was an error submitting the form :(')
									.show();
							}
						}
					});
							
				} else {
					wrap.find('.error').show();
				}
				
				return false;
			});
	}

	$(document).ready(function () {
		wrapper = $('#image_layer');
		imgs = wrapper.find('img');
		morePosts = $('a.older_posts');
		newerPosts = $('.more_posts');
		
		if (morePosts) {
			togglePosts();
		}
		
		imgs.eq(0).show().css('z-index', 4);
		
		rotateImages();
		submitFanForm();
	});
}());
