Application.FrontPage = new Class({

	Extends : Application.Page,
	/**
	 * Constructor
	 */
	initialize : function() {
		this.initializeTicker();
		this.setupQuickList();
		this.parent();
		this.formatTimers();
	},

	setupQuickList : function() {
		$('#quick-list .item').each(function() {
			var $this = $(this);
			$this.find('.sale-info').hoverSlide($this.find('img'));

			$this.click(function() {
				var href = $this.find('.name a').attr('href');
				window.location = href;
			});

		}).mouseover(function() {
			$('.activity-message').hide();
		});
	}

});

Application.FrontPage1 = new Class({

	/**
	 * Base class
	 */
	Extends : Application.Page,

	Implements: [Options],
	
	options : {
		stepsSelector : '.steps'
	},
	
	/**
	 * Constructor
	 */
	initialize : function(options) {
		
		if (options == null) { options = {}; } 
		this.setOptions(options);
		this.lazyloadImages();
		$('.ajax-loading-screen').remove();
		this.tickerMaxItems = 200;

		this.ticker = new Application.Modules.OmniTicker(this);
		this.$featureBar = $('.feature-bar');
		
		this.initializeSlidingForm();
		this.parent();
		this.initializeForms();
		this.initializeWindowListeners();
		this.initializeJQueryPlugins();
		setTimeout( this.resizeBackground.bind(this), 50 );
	},
	
	
	initializeSlidingForm : function() {
		this.$steps = $( this.options.stepsSelector );
		this.$steps.show();
		this.slidingForm = new Application.Tools.SlidingForm(
				this.$steps, this.getSlidingFormOptions());
		this.slidingForm.addEvent('moved', function(){
//			console.log('hiding');
			this.ticker.disableAuto();
			this.ticker.tickerTooltip.hideTickOverlay();
		}.bind(this));
	},
	
	getSlidingFormOptions : function() {
		return {
			initialStep : '.location'
		};
	},
	
	initializeForms : function() {
		this.loginForm = new Application.Modules.LoginForm();
		this.reminderForm = new Application.Modules.ReminderForm();
		this.registrationForm = new Application.Modules.RegisterForm();
	},
	
	
	initializeWindowListeners : function() {
		$(window).resize(this.resizeBackground.bind(this));
		this.resizeBackground();
	},
	
	initializeJQueryPlugins : function(){
		$('select[name=location]').selectmenu({
			style: 'popup'
		});
	},

	resizeBackground : function() {

		var $window = $(window);
		var $bg = $('.register-form-bg');
		if ($bg.data('aspectratio') == null) {
			$bg.data('aspectratio', 1920/1080);
		}
		
		console.log($window.width()/$window.height(), $bg.data('aspectratio'), $window.width()/$window.height() < $bg.data('aspectratio'));
		
		if ($window.width()/$window.height() < $bg.data('aspectratio')) {
			$bg.addClass('valign').removeClass('halign');
		} else {
			$bg.addClass('halign').removeClass('valign');
		}
		
		
		// move the logo, in order to center the menus
		$('.register-form-logo').css({
		    marginTop: this.getNewLogoPlacement()
		});
		
		clearTimeout(this.togglerTimeout);
		// hide feature-bar when it intersects with the sign-in boxes
		this.togglerTimeout = setTimeout( this.toggleFeatureBar.bind(this), 100 );

	},
	
	togglerTimeout : null,
	
	
	toggleFeatureBar : function() {
		
		var $fbpane = $('.facebook-pane');
		var $bar = this.$featureBar;
		
		var startedVisible = $bar.is(':visible');
		var endVisible;
		$bar.show();
		
		if ($fbpane.offset().top + $fbpane.outerHeight(true) + 25 > $bar.offset().top) {
			endVisible = false;
		} else {
			endVisible = true;
		}
		
		if (startedVisible) {
			if (endVisible === false) { $bar.fadeOut(); }
		} else {
			$bar.hide();
			if (endVisible === true) { $bar.fadeIn();}
		}
		
	},
	
	
	getNewLogoPlacement : function() {
		
		var height = $(window).height();
		var minOffset =-400, maxOffset=50, heightFloor=100, heightCeil= height < 766 ? 766 :  $(window).width() < 978 ? 766 : 1000;
		var offsetD = maxOffset-minOffset;
		var heightD = heightCeil-heightFloor;
		
		
	    if (height < heightFloor) { return minOffset; }
	    else if (height > heightCeil) { return maxOffset; }
	    else {
	        var value = ((height-heightFloor) * (offsetD/heightD))+minOffset;
	        if (value > maxOffset) { value = maxOffset;}
//	        console.log(height, value);
	        return value;
	    }
	}

});

Application.Modules.LoginForm = new Class({

	/**
	 * Parent class
	 */
	Extends : Application.Tools.AjaxTrigger,

	/**
	 * Methods bound to this class
	 */
	Binds : [ 'loginFailed' ],

	/**
	 * Constructor
	 */
	initialize : function(options) {

		if (options == null) {
			options = {};
		}

		this.$form = $('form#login-form');
		this.parent(this.$form, {
			success : this.loginFailed
		});

		this.$form.validate({
			rules : {
				Email_Address : {
					required : true,
					email : true
				},
				Password : {
					required : true
				}
			},
			messages : {
				Email_Address : {
					required : "What's your email address?",
					email : "This email address doesn't look right."
				},
				Password : "You gotta type in your password."
			},
			showErrors : function( errorList, errorObjs ) {
				this.defaultShowErrors();
				
				var $container = $('form#login-form h5');
				var original = $container.data('originalMessage');
				if (original == null) { 
					original = $container.html();
					$container.data('originalMessage', original);
				}
				
				if (errorObjs.length > 0) {
					(function(item){
						var $target = $(item.element);
						$container.html(item.message);
					})(errorObjs[0]);
				} else if ($('form#login-form input.error').length <= 0){
					$container.html(original);
				}
				
			},
			
			errorPlacement : function(){}
		});

	},

	/**
	 * Submit handler for bad-login
	 */
	loginFailed : function(json) {

		this.$form.find('.error.message').html(json.error).show();
		this.$form.closest('.step').effect('shake', {
			times : 4
		}, 50);
		this.$form.find('#password').val('');

	}

});

Application.Modules.ReminderForm = new Class({

	/**
	 * Parent class
	 */
	Extends : Application.Tools.AjaxTrigger,

	/**
	 * Methods bound to this class
	 */
	Binds : [ 'handleResults' ],

	initialize : function() {

		this.$form = $('form#reminder-form');
		this.parent(this.$form, {
			type : 'post',
			success : this.handleResults
		});
		
		this.$form.validate({
			rules : {
				Email_Address: {
					required: true,
					email: true
				}
			},
			messages: {
				Email_Address: {
					required: 'What\'s your email address?',
					email: 'That doesn\'t look like an email address'
				}
			},
			showErrors : function( errorList, errorObjs ) {
				this.defaultShowErrors();
				
				var $container = $('#reminder-form h5');
				var original = $container.data('originalMessage');
				if (original == null) { 
					original = $container.html();
					$container.data('originalMessage', original);
				}
				
				if (errorObjs.length > 0) {
					(function(item){
						var $target = $(item.element);
						$container.html(item.message);
					})(errorObjs[0]);
				} else if ($('#reminder-form input.error').length <= 0){
					$container.html(original);
				}
				
			},
			
			errorPlacement : function(){}
		});

	},

	handleResults : function(json) {

		if (json.success) {
			this.$form.find('h5').removeClass('error')
					.addClass('success').html("Zoooom! You should be receive a password reminder ").show();
		} else {
			this.$form.find('h5').addClass('error')
					.removeClass('success').html(json.error).show();
			this.$form.closest('.step').effect('shake', {
				times : 4
			}, 50);
		}

	}

});


Application.Modules.RegisterForm = new Class({
	
	Extends : Application.Tools.AjaxTrigger,
	
	initialize : function() {
		this.$form = $('form#register-form');
		this.parent(this.$form, {});
		this.$form.validate( this.rules() );
		this.addEvent("success", this.failHandler);
		
	},
	
	
	failHandler : function(json){
		this.$form.find('h5').html(json.error);
	},
	
	rules : function() {
		return { 
			rules : {
				Email_Address : {
					required : true,
					email : true,
					remote : '?action=register.EmailCheck'
				},
				First_Name : 'required',
				Last_Name : 'required',
				Password : {
					required : true,
					minlength : 6
				},
				Confirm_Password : {
					required : true,
					equalTo : '#register-form #password'
				}
			},
			messages : {
				Email_Address : {
					required : "Your email will be your login username.",
					email : "This is not a valid email address"
				},
				First_Name : {
					required : "What's your first name?"
				},
				Last_Name : {
					required : "What's your last name?"
				},
				Password : {
					required : "You need a password",
					minlength : "Make this at least 6-characters"
				},
				Confirm_Password : {
					required : "Please confirm your password",
					equalTo : "This doesn't match your password."
				}
			},
			showErrors : function( errorList, errorObjs ) {
				this.defaultShowErrors();
				
				var $container = $('#register-form h5');
				var original = $container.data('originalMessage');
				if (original == null) { 
					original = $container.html();
					$container.data('originalMessage', original);
				}
				
				if (errorObjs.length > 0) {
					(function(item){
						var $target = $(item.element);
						$container.html(item.message);
					})(errorObjs[0]);
				} else if ($('#register-form input.error').length <= 0){
					$container.html(original);
				}
				
			},
			
			errorPlacement : function(){}
		};
	}
	
});

Application.FrontPage2 = new Class({
	
	Extends: Application.FrontPage1,
	
	glowTimeout : null,
	
	initialize: function(options) {
		this.parent();
		this.centerFacebookPane(true);
		$(window).resize(this.centerFacebookPane.bind(this));
		this.featureBar = new Application.Modules.SuperRedistributedScroller();
		this.featureBar.addEvent('itemClicked', function($item){
			this.slidingForm.seekTo('.register');
			$('.step.register').addClass('glow');
			clearTimeout(this.glowTimeout); 
			this.glowTimeout = setTimeout(function() {				
				$('.step.register').removeClass('glow');
			}, 2000)
		}.bind(this));
	},
	
	centerFacebookPane : function(noAnimate) {
		var transform = {
			top: $('.register-form-logo').position().top + $('.register-form-logo').outerHeight(true),
			left: $(window).width()/2
		};
		if (noAnimate === true) {
			$('.facebook-pane.step').css(transform).show();
		} else {
			$('.facebook-pane.step').show().stop(true, false).css('top', transform.top).animate(transform);
		}
	},
	
	getSlidingFormOptions : function() {
		var opts = this.parent();
		opts.initialStep = '.first-step';
		opts.direction = 'vertical';
		return opts;
	}
	
});



Application.Modules.SuperRedistributedScroller = new Class({
	
	Implements : [ Events, Options ],
	options : {
		mainSelector : '.feature-bar',
		listSelector : '.feature-list',
		messageSelector: '.feature-bar-message',
		minMargin : 10,
		easing : 'easeInOutBack',
		animationTime : 1500,
		maxItemsPerPage : 4
	},
	
	$bar : null,
	$list : null,
	$items : null,
	leftMostItem : 0,
	
	initialize: function() {
		this.$bar = $(this.options.mainSelector);
		this.$list = this.$bar.find(this.options.listSelector);
		this.$list.css({
			position: 'relative',
			left: 0
		});
		this.$message = $(this.options.messageSelector);
		this.$items = this.$list.children();
		this.$bar.show();
		this.resize(true);
		$(window).resize(this.resize.bind(this));
		this.initializeItemBehavior();
		
	},
	
	
	initializeItemBehavior : function() {
		this.$items.click(function(event){
			this.fireEvent('itemClicked', [ $(event.currentTarget) ] );
		}.bind(this));
		
		this.addEvent('itemClicked', this.showMessage);
		
	},
	
	
	showMessage : function($clicked){
		
		if (this.$message.is(':visible')) {
			this.$message.stop(true, false).animate({
				left: $clicked.offset().left
			});			
		} else {
			this.$message.stop(true, false).show().animate({
				left: $clicked.offset().left
			});
		}
		
		clearTimeout(this.hideMessageTimeout);
		this.hideMessageTimeout = setTimeout(function(){
			this.$message.fadeOut();
		}.bind(this), 2000);
		
	},
	
	hideMessageTimeout : null,
	
	
	resizeTimeout : null,
	
	/**
	 * Resize event listener
	 * @param noWait, bypass the waiting mechanism
	 */
	resize: function(noWait) {
		
		
		var thankyoucomeagain = function(){
			this.resize(true);
		}.bind(this);
		
		// window resize get triggered twice per resize
		// the next block is to force it to only execute once
		if (noWait !== true) {
			window.clearTimeout(this.resizeTimeout);
			this.resizeTimeout = window.setTimeout(thankyoucomeagain, 100);
			return;
		}
		
		// for whatever reason there's a scheduled event in resizeTimeout, get rid of it
		window.clearTimeout(this.resizeTimeout);
		
		if (this.$bar.is(':hidden')) { return; }
		
		// calculate how much space we have to work with
		var availableSpace = this.$list.parent().outerWidth(true);
		
		// now, calculate the width of the items ( this assumes they all have the same widths)
		var itemWidth = this.$items.outerWidth(true);

		
		// another point of failure is when the width of the item is 0
		// this makes bunnies cry
		if (itemWidth <= this.options.minMargin*2) {
			window.clearTimeout(this.resizeTimeout);
			this.resizeTimeout = window.setTimeout(thankyoucomeagain, 50);
			return;
		}
		
		// figure out how many items will fit on the space
		this.itemsPerPage = Math.min(Math.floor(availableSpace/itemWidth), this.options.maxItemsPerPage);
		
		if (this.itemsPerPage <= 2) { this.$bar.hide(); }
		
		this.$list.parent().css( 'width', this.itemsPerPage * this.$items.outerWidth(true));
		this.recenterPage();
		
	},
	
	
	nextPage : function() {
		
		var curPage = this.currentPage();
		var nextLeftmost = (curPage + 1) * this.itemsPerPage;
		
		// over shoot
		if (nextLeftmost > this.$items.length) {
			nextLeftmost = Math.floor( this.$items.length / this.itemsPerPage ) * this.itemsPerPage;
		}
	
		this.seekTo(nextLeftmost);
		
	},
	
	prevPage : function() {
		
		var curPage = this.currentPage();
		var nextLeftmost = (curPage - 1) * this.itemsPerPage;

		
		if (nextLeftmost <= 0 ) { nextLeftmost = 0; }
		else if (nextLeftmost > this.$items.length) {
			nextLeftmost = Math.floor( this.$items.length / this.itemsPerPage ) * this.itemsPerPage;
		}
		
		this.seekTo(nextLeftmost);
	},

	
	recenterPage : function() {
		
		var curPage = this.currentPage();
		var nextLeftmost = (curPage) * this.itemsPerPage;

		if (nextLeftmost <= 0 ) { nextLeftmost = 0; }
		
		this.seekTo(nextLeftmost);
	},
	
	currentPage : function() {
		var leftMostItem =  Math.floor( Math.abs(this.$list.position().left) / this.$items.outerWidth(true) ) ;
		console.log('current', Math.ceil( leftMostItem / this.itemsPerPage ), 'leftmost', leftMostItem);
		return  Math.ceil( leftMostItem / this.itemsPerPage );
	},
	
	
	seekTo : function(itemNo) {
		
		console.log('going to ', itemNo);
		
		var $target = this.getItem(itemNo);
		if ($target == null || $target.length <= 0) { return; }

		console.log($target);
		
		this.$list.animate({
			left: -$target.position().left
		}, this.options.animationTime, this.options.easing);
		
	},
	
	
	getItem : function(selector) {
		
		var $target;
		if (typeof selector == 'number') {
			$target = $(this.$items[selector]);
		} else {
			$target = $(this.$items.find(selector));			
		}
		
		return $target;
		
	}
	
});


switch ($_YOTTA_.ab) {
case 1:
	Application.Start(Application.FrontPage1); break;
case 2:
	Application.Modules.LoginForm = new Class({
		Extends: Application.Modules.LoginForm,
		loginFailed : function(json) {
			this.$form.find('h5').html(json.error);
		}
	});
	Application.Tools.SlidingForm = new Class({
		Extends : Application.Tools.SlidingForm,
		getCenterHPosition : function() {
			return this.$container.width() / 2 - this.$current().outerWidth(true);
		}
	});
	Application.Start(Application.FrontPage2); break;
default:
	Application.Start(Application.FrontPage);

};

