/**
* ZD.Signup
* 
*/
ZD.Signup = (function() {
	
	var subscriptions = ["paygo", "monthly", "yearly"];
	var $this,
		user,
		form,
		validator;
	
	/**
	* click-handler for all signup buttons, eg: [Get Started Today], [Signup now], etc
	*/
	var onClickSignup = function() {
		var sub = this.id.split('-').pop();
		var url;
		
		if (user && user.subscription.type === sub) {
			$.gritter.add({
				title: 'Notice',
				text: 'You are already subscribed for the ' + sub + ' plan',
				sticky: false
			});
			return false;
		}
		
		if (jQuery.inArray(sub, subscriptions) >= 0) {
			url = "/signup/" + sub;
		} else {
			url = "/pricing";
		}
		document.location = url;
	};
	/**
	* click-handler for cancel signup links
	*/
	var onClickCancel = function() {
		var user = ZD.getUser();
		
		$.gritter.add({
			title: 'Cancel Signup',
			text: '-- NOT IMPLEMENTED --',
			sticky: false
		});
	}
	return {
		buttonSelector: 'div.btn-signup',
		subscription: null,
		formSelector: '#signup-form',
		
		init: function(config) {
			user = ZD.getUser();
			$this = ZD.Signup;
			$.extend($this, config);
			
			// Attach signup button click-handler			
			jQuery($this.buttonSelector).click(onClickSignup);
			jQuery('.signup-cancel').click(onClickCancel);
			
			form = $this.getForm();
			if (form) {
				$this.execute();
			}
			
			// If we're on the /pricing page and we have a logged-in user, highlight their selected subscription
			var products = $('ul.pricing');
			if (user && products) {
				var selected = products.find('li.' + user.subscription.type);
				selected.addClass('selected');				
			}
			
		},
		onSuccess: function(handler, scope) {
			ZD.Signup.getForm().bind('success', function(ev, res) {
				handler.call(scope||ZD.Signup, res);
			});
		},
		getForm: function() {
			if (form) {
				return form;
			}
			var rs = jQuery(ZD.Signup.formSelector);
			return rs.length ? rs : null;
		},
		execute: function() {
			validator = form.validate({});	
			form.bind('submit', $this.onSubmit);
		},
		onSubmit: function(e) {
			e.preventDefault();
			if (!validator.valid()) {
				return false;
			}
			
			$(this).ajaxSubmit({
				success: function(json, response) {
					var res = jQuery.parseJSON(json);
					if (res.tid && res.user) {
						user = res.user;
						ZD.setUser(user);
						form.trigger('success', res);
						
						if (!ZD.Checkout) {
							document.location = '/app';
						}
					} else {
						var errors = res.errors;
						jQuery.each(errors.fields, function(index, field) {
							var error = {};
							error['user[' + field.name + ']'] = field.message.join('.');
							validator.showErrors(error);
						});
					}
				}
			});
		}
	};
})();

