(function ($) {

	var fruitmachine = $("#spinner-container"),
		reels = [],
		go = fruitmachine.find("#spinner-spin a"),
		motionBlur = new Image().src = '/wordpress/wp-content/themes/elephantcreative.co.uk/images/common/motion-blur.png', // preload
		activities = $.parseJSON(document.getElementById('x-current-activities').content),
		winLine = 0; // current line which the spinners are showing

	function Spinner (el) {
		this.el = el;
		this.$ = $(el);
		this.$item = this.$.find('.item');
		this.canSpin = true;
	}

	Spinner.prototype = {
		spriteHeight: 1000,
		spin: function () {
			if (!this.canSpin) return false;
			this.canSpin = false;
			var item = this.$item;
			item.css({overflow: 'hidden'}).animate ({
					lineHeight: '60px'
				}, 150, 'easeOutElastic').delay(50).animate ({
					lineHeight: '170px'
				}, 200, 'easeOutExpo');

			this.spinnimate ();
		},
		spinnimate: function () {
			var that = this,
				item = this.$item,
				speed = random (1100, 1400, true);

			item.addClass('spinning');
			item.css ({
				backgroundRepeat: 'no-repeat',
				backgroundPosition: '0px -1000px'
			});

			item.animate ({
					backgroundPosition: '0px 82px'
				}, speed, 'linear', function () {
					$(this).removeClass('spinning');
			});

			setTimeout (callback (Spinner.prototype.stop, that), speed-200); // stop in 1 second
		},
		stop: function () {
			var item = this.$item,
				that = this,
				noise = document.getElementById('sound-' + that.$.attr('id'));

			switch (that.$.attr('id')) {
				case 'spinner-activity':
					item.html (activities[winLine].activity);
					break;
				case 'spinner-item':
					item.html (activities[winLine].item);
					break;
				case 'spinner-client':
					item.html (activities[winLine].client);
					break;
			}

			item.css('line-height', 0);
			item.animate ({
				lineHeight: '82px'
			}, 300, 'easeOutElastic', function () {
					that.canSpin = true;
				});
			setTimeout (function () {
					if (noise && noise.canPlayType) {
						noise.pause();
						noise.currentTime = 0;
						noise.play();
					}
				}, 450);
		}
	}

	function init () {
		var spinners = fruitmachine.find(".spinner").get();
		for (var i = 0; i < spinners.length; i++) {
			reels.push (new Spinner (spinners[i]));
		}
		signupLightbox ();
		setupExpanders ();
		setupHeaderRotator ();
	}

	go.click (function (e) {
		// check through each spinner to see if it is spinnable. If one of them isn't, we shouldn't spin any of them
		var canSpin = true;
		$.each (reels, function (i) {
			if (!reels[i].canSpin) canSpin = false;
		});
		if (canSpin) {
			var newWinLine = 0,
				maxTries = 100;
			do {
				newWinLine = random (0, activities.length-1, true);
				if (!maxTries--) break;
			} while (newWinLine == winLine);
			winLine = newWinLine;
			spin (reels);
		}
		$(this).blur();
		e.preventDefault();
		return false;
	});


	function spin (reels) {
		noise = document.getElementById('sound-spin');
		if (noise && noise.canPlayType &&
				!((navigator.userAgent.match(/iPad/i)) || (navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i)))
			) {
			noise.pause();
			noise.currentTime = 0;
			noise.play();
		}


		for (var i = 0; i < reels.length; i++) {
			var spin = callback (Spinner.prototype.spin, reels[i]);
			setTimeout ( spin , 300*i);
		}

	}

	function callback (fn, obj) {
		return function () {
			fn.call(obj);
		}
	}

	function random (min, max, wholeNumber) {
		var rand = (Math.random() * (max - min + wholeNumber)) + min;
		return wholeNumber ? ~~rand : rand;
	}


	function setupExpanders () {
		$(".expander").each (function () {
			var $this = $(this);
			$this.find(".tweetmeme_button").next().siblings("p").slideUp(1);
			$this.find("ul,.hide").slideUp(1);
			$span = $('<span class="expand"><span></span> expand</span>').click (function () {
				$(this).fadeOut();
				$this.find("p, ul").slideDown();
				$this.find(".hide").css({"display": "inline"}).slideDown();
			});
			$this.append($span).append("<br style='clear: both' />");
		});
	}

	function setupHeaderRotator () {
		$("#the-website-of").css ({
			position: 'relative'
		});
		$("#the-website-of > li").each (function (index, elem) {
			$(elem).css ({
				position: 'absolute',
				left: index * 950 + 'px',
				width: '950px'
			});
		});
		setTimeout (rotateHeader, 5000);
	}

	function rotateHeader () {
		// has the first LI been removed and added to the end of the list?
		// needed because the animation callback will be called N times, and
		// the first element obviously only needs to be moved once!
		var movedFirstElement = false;
		$("#the-website-of li").animate ({
				left: '-=950px'
			}, 750, 'easeInOutExpo', function () {
				if (!movedFirstElement) {
					$("#the-website-of li:first-child").remove().appendTo ("#the-website-of").css ({
						left: ($("#the-website-of li").length - 1) * 950 + 'px'
					});
				}
				movedFirstElement = true;
		});
		setTimeout (rotateHeader, 5000);
	}


	function signupLightbox () {
		$("a[href$='/subscribe/']").live ("click", function (e) {
			e.preventDefault();
			e.stopPropagation ();
			openForm();
			return false;
		});
		$("#lightbox-mask").live ("click", function () {
			closeForm();
		});
	}
	function openForm () {
		if (document.getElementById('lightbox-mask')) return;
		$('<div id="lightbox-mask" />').css({opacity: 0, backgroundImage: 'url(/wordpress/wp-content/themes/elephantcreative.co.uk/images/common/ajax-loader.gif)'}).appendTo('body').animate ({
			opacity: 0.7
		}, 500, 'easeInOutExpo');


		$.get('/subscribe/', function (data) {
			$("#lightbox-mask").css({backgroundImage: 'none'});
			$form = $('<div id="formContainer" />').css({opacity: 0}).html(data);
			$form.appendTo('body').animate ({
				opacity: 1
			}, 500, 'easeInOutExpo');
			$("#formContainer form").submit (function (e) {
				if (!validForm()) {
					e.preventDefault ();
					return false;
				} else {
					sendForm();
					return true;
				}
			});
		});


	}

	function validForm () {
		return true;
	}

	function sendForm () {


		$("#formContainer").css({
			backgroundImage: 'url(/wordpress/wp-content/themes/elephantcreative.co.uk/images/common/ajax-loader.gif)',
			backgroundPosition: 'center center',
			backgroundRepeat: 'no-repeat'
		}).children().hide();


	}
	function closeForm () {
		$("#formContainer").fadeOut(100, function () {
			$(this).remove();
			$("#lightbox-mask").animate ({
				opacity: 0
			}, 300, 'easeInExpo', function () {
				$(this).remove();
			});
		});
		$("#enter-close-button").fadeOut (100, function () {
			$(this).remove();
		});
	}

	init();

})(jQuery);


