if (!Function.prototype.bind) {
    Function.prototype.bind = function(object) {
        var __method = this;
        return function() {
            return __method.apply(object, arguments);
        };
    };
}

var PageHandler = function() {};
$.extend(PageHandler.prototype, {
	init : function() {
	    var msg = "";
	    switch ($.query.get("confirm")) {
	        case "1":
	            msg = "<p>You have just been sent an email to confirm your email address.  Please click on the link in this email to confirm your subscription.</p>";
	            break;
	        case "2":
	            msg = "<p>You have been successfully added to our email list.  Thanks for joining!</p>";
	            break;
	    }
		if (msg) {
			$("#email-list-success").html(msg).show();
		}
		$("#email-list-join-btn").click(this.join_email_list_clicked.bind(this));
	},
	
	errors : [],
	
	join_email_list_clicked : function() {
		return this.validate();
	},
	
	validate : function() {
		this.errors = [];
		
		this._validate_required("full-name-field", "Full name");
		this._validate_required("email-address-field", "Email address");
		this._validate_required("confirm-email-field", "Confirm email");
		this._validate_fields_match("email-address-field", "confirm-email-field", "The email address you entered does not match the confirm email address field.");
		
		if (this.errors.length != 0) {
			this._display_form_errors();
			return false;
		}
		
		return true;
	},
	
	_display_form_errors : function() {
		html = "<ul>";
		for (var i in this.errors) {
			html += "<li>"+this.errors[i]+"</li>";
		}
		html += "</ul>";
		$("#email-list-errors").html(html).show();
	},
	
	_validate_fields_match : function(id1, id2, message) {
		if ($("#"+id1).val() != $("#"+id2).val()) {
			this.errors[this.errors.length] = message;
			return false;
		}
		return true;
	},
	
	_validate_required : function(id, friendlyName) {
		if (!$("#"+id).val()) {
			this.errors[this.errors.length] = "The '"+ friendlyName + "' field is required.";
			return false
		}
		return true;
	},
	
	submit : function() {
		callback = function(resp) {
			console.log(resp);
		};
		this.api.subscriber.add_and_resubscribe($("#full-name-field").val(), $("#email-address-field").val(), callback);
	}
});

page = new PageHandler();
$(document).ready(function() { page.init(); })