self.zipper = {};
self.zipper.KEYSTROKE_ERROR = "Please enter numbers only";
self.zipper.FORM_ERROR = "Please enter a valid five-digit ZIP code";
self.zipper.VALIDITY_ERROR = "We could not recognize the ZIP code you entered.<br>Please enter a valid ZIP code and try again.";

(function($) {
    $.fn.ZipDialog = function(params) {
        var me = this;
        me.zipper = new $.zipper(this.get(0), params);
        self.zipper.dialog = {
            show: function() { me.zipper.show() },
            close: function() { me.zipper.close() },
            validate: function() {
                me.zipper.checkZip();
            }
        };
        return this;
    };
    
    $.zipper = function(container, params) {
        this.$container = $(container);
        this.$errorMsg = $("#"+params.errorMsg);
        this.$zipInput = this.$container.find("input[@type = 'text']");
        this.callback = params.callback;
        this.errback = params.errback;
        this.init();
    };
    
    $.zipper.prototype = {
        show: function() {
            this.$container.jqmShow();
            this.$zipInput.val('')[0].focus();
        },
        close: function() {
            this.$errorMsg.html('');
            this.$container.jqmHide();
        },
        checkZip: function() {
            var me = this;
            var myVal = this.$zipInput.val();
            if (/[0-9]{5}/.test(myVal)) {
                $.get("/go/includes/_zipValid.jsp", {'zc': myVal}, function(data) {
                    if (eval(data)) {  //Call returns a string, either "true" or "false"
                        me.$container.jqmHide();
                        if (typeof me.callback != "undefined") me.callback.call(window, myVal);
                        else me.doDefaultSuccess();
                    }
                    else {
                        me.$zipInput.val('');
                        me.$errorMsg.html(self.zipper.VALIDITY_ERROR);
                    }
                });
            }
            else {
                this.$errorMsg.text(self.zipper.FORM_ERROR);
            }
        },
        checkKey: function(event) {
            if (event.which == 13) {
                event.stopPropagation();
                this.checkZip();
            }
            else if (/\D/.test(this.$zipInput.val())) {
                this.$errorMsg.text(self.zipper.KEYSTROKE_ERROR);
            }
            else {
                this.$errorMsg.html('');
            }
        },
        doDefaultSuccess: function() {
            location.href = location.pathname + location.search.replace(/zc=([0-9]{5})?/g, "zc="+this.$zipInput.val());
        },
        init: function() {
            var me = this;
            this.$container.addClass("jqmWindow");
            this.$zipInput.keyup(function(event) { me.checkKey(event) });
            this.$container.jqm({modal:true, toTop: true});
        }
    };
})(jQuery);