(function($) {
    var KPNA = window.KPNA = window.KPNA ? window.KPNA : {};
    var originalTop;
    var accountState = {};
    var closed = false;
    var myReturnUrl = "";
    var confirmationMessages= new Array();
    confirmationMessages["register"] = "<p>Thank you for registering. Your Kohler account has been created.</p>";
    confirmationMessages["forgot"] = "<p>Your password has been sent to the e-mail address provided.</p><p>Please check your e-mail and then return and log in to your account.</p>";

    $.fn.ajaxSubmit = function(e) { /* Change a form's submission type to ajax */
        this.submit(function() {
            var params = {};
            var foundIllegalChar = false;
            $(this).find("input[@checked], input[@type='text'], input[@type='hidden'], input[@type='password'], input[@type='submit'], option[@selected], textarea").filter(":enabled").each(function() {
                if (!(foundIllegalChar) && this.value.search("[<>{}\\[\\];\\&\\(\\)\"]") != -1) {
                    alert("The following characters are not permitted:\n< > { } [ ] ; & ( ) \"");
                    foundIllegalChar = true;
                } else {
                    params[ this.name || this.id || this.parentNode.name || this.parentNode.id ] = this.value;
                }
            });

            if (!(foundIllegalChar)) {
                $("body").addClass("curWait");

                //reset labels for any required fields marked as missing
                $(".content").find("h4.fieldNameError").attr("class", "fieldName");
                $(".content").find("div.pfTextFields").find("input,select").css("border", "1px solid #B4B2B2");
                $(".content").find("div.pfUpdateTextFields").find("input,select").css("border", "1px solid #B4B2B2");

                $.post(this.getAttribute("action"), params, function(json) {
                    $("body").removeClass("curWait");
                    var strError = "Unable to submit form. Please try again later.";
                    var action = json["action"];
					var strError = json["error"];
					var newScreenName = json["newScreenName"];
                    var missingFields = json["missingFields"];
					var errorFields = json["errorFields"];
                    var invalidCredentials = json["invalidCredentials"];
                    if (strError.length == 0) {
                        if (action == "login") {
                            if (myReturnUrl.length > 0) location.href = decodeURIComponent(myReturnUrl);
                            else {
                                if ($.browser.msie) document.location = document.location;
                                else document.location.reload();
                            }
                            closeLightbox();
                            if (newScreenName.length > 0) {
                                alert("Welcome back! We've set your screen name to " + newScreenName + ". If you'd like to change it, click the 'Update Account' link on the sidebar.");
                            }
                        } else if (action == "closefalse") {
                            $(".pfFooter").hide(); // turn off footer
                            $("#formErrors").html(""); // clear errors
                            $("#closeAccountContents").hide();
                            $("#closeAccountConfirmation").show();
                            $("#confirmLink").click(function() {
                                $("input#confirmed").val("true");
                                $("#closeAccountForm").submit();
                            });
                            $("#cancelLink").click(function() {
                                $(".pfFooter").show(); // turn on footer
                                $("#closeAccountContents").show();
                                $("#closeAccountConfirmation").hide();
                            });
                        } else if (action == "closetrue") {
                            $("#closeAccountConfirmation").html("<p class=\"pfTabContentsCopy\">Your Kohler account has been closed.</p>");
                            closed = true;
                            $(".pfTabLink").each(function() { $(this).css("cursor", "default"); });
                            $("#closeLightbox").click(function() {
                                if ($.browser.msie) document.location = document.location;
                                else document.location.reload();
                                closeLightbox();
                            });
                        } else if (action.indexOf("update") > -1) {
                            $(".pfFooter").css("display", "none"); // turn off footer
                            $("#formErrors").html(""); // clear errors
                            $("#" + action + "Contents").hide();
                            $("#" + action + "Confirmation").show();
                            $("#" + action + "Return").click(function() {
                                $("#" + action + "Contents").show();
                                $("#" + action + "Confirmation").hide();
                                $(".pfFooter").show(); // turn footer back on
                            });
                            if (action == "updateAccount") saveAccountState();
                            if (action == "updateEmail") {
                                $("#updateEmailForm").find("#oldEmailField").val($("#updateEmailForm").find("#newEmailField").val());
                                $("#updateEmailForm").find("#newEmailField,#newEmail2Field").val("");
                            } else if (action == "updateScreenName") {
                                $("#updateScreenNameForm").find("#oldScreenNameField").val($("#updateScreenNameForm").find("#newScreenNameField").val());
                                $("#updateScreenNameForm").find("#newScreenNameField,#newScreenName2Field").val("");
                                $("#closeLightbox").click(function() {
                                    if ($.browser.msie) document.location = document.location;
                                    else document.location.reload();
                                    closeLightbox();
                                });
                            } else if (action == "updatePassword") $("#updatePasswordForm").find("input[@type='password']").val("");
                        } else {
                            $("#formErrors").html(""); // clear errors
                            $(".content").find("#container").css("display", "none");
                            $(".pfHeaderCopy").html(confirmationMessages[action]);
                            $("#closeLightbox").click(function() {
                                if (action == "register" && myReturnUrl.length > 0) location.href = decodeURIComponent(myReturnUrl);
                                else {
                                    if ($.browser.msie) document.location = document.location;
                                    else document.location.reload();
                                }
                                closeLightbox();
                            });
                        }
                    } else {
                        window.scrollTo(0,0);
                        $("#formErrors").html("<h3>An error occurred while processing this form.<\/h3><ul>" + strError.replace(/(\t)(.+)/g, "<li>$2<\/li>") + "<\/ul>").filter(":hidden").fadeIn("normal");
                        if (missingFields.length > 0) {
                            for (var i = 0; i < missingFields.length; i = i + 1) {
                                $("h4#" + missingFields[i]).attr("class", "fieldNameError");
                                $("#" + missingFields[i] + "Field").css("border", "1px solid #900");
                            }
                        }
                        if (errorFields.length > 0) {
                            for (var i = 0; i < errorFields.length; i = i + 1) {
                                $("h4#" + errorFields[i]).attr("class", "fieldNameError");
                                $("#" + errorFields[i] + "Field").css("border", "1px solid #900");
                            }
                        }
                        if (invalidCredentials == "true") $("#emailField,#passwdField").val("");
                    }
                }, "json");
            }
            return false;
        });
        return this;
    }

    function callLightbox(obj) {
        $(obj).lightBox();
    }

    /**
     * Opens a layer with the parameter element in a modal box centered on the screen with a lightbox effect
     * @param element
     * @param callback
     */
    function openLightbox(element, action, callback) {
        closeLightbox();
        if ($.browser.msie) { // ie displays select elements over the lightbox, need to hide them
            $('iframe').each(function() {
                var iframeDocument = this.contentWindow.document;
                $(iframeDocument).find('select').each(function() {
                    $(this).hide();
                });
            });
            $('select').hide();
        }

        var lightbox = document.createElement("div");
        $(lightbox).attr('id', "lightbox");

        var lightboxBg = document.createElement("div");
        $(lightboxBg).addClass("lightboxBg");
        $(lightbox).append(lightboxBg);

        var contentOuter = document.createElement("div");
        $(contentOuter).addClass("contentOuter");
        $(lightbox).append(contentOuter);

        var content = document.createElement("div");
        $(content).addClass("content");
        $(contentOuter).append(content);

        $(content).append(element);
        $("body").append(lightbox);

        setLinks(action, content); // hook up functions to the links in the panel

        $(lightbox).css("display", "block");
        $(contentOuter).css("display", "block");
        positionLightbox();
        $(lightbox).css("display", "none");
        $(contentOuter).css("display", "none");

        $(window).resize(function() {
            positionLightbox();
        });

        originalTop = parseInt($(contentOuter).css("top"));
        $(window).scroll(function() {
            if ($.browser.msie) $("#lightbox").width($(window).width() + $(document).scrollLeft());
            $(contentOuter).css("top", (originalTop - $(document).scrollTop()));
        });

        $("#lightbox").css("top", ($(document).scrollTop()));

        $(lightbox).fadeIn("fast", function() {
            $(contentOuter).fadeIn("fast", function() {
                if ($.isFunction(callback)) {
                    callback();
                }
            });
        });

        if (action == "updateAccount") {
            saveAccountState();
        }
    }

    // save account info in an array in case we need to restore it
    function saveAccountState() {
        var fields = new Array("fname", "lname", "bname", "profile", "address", "address2", "city", "state", "zip", "country");
        for (var i = 0; i < fields.length; i++) {
            accountState[fields[i]] = $(".content").find("#" + fields[i] + "Field").val();
        }
    }

    function setLinks(action, content) {
        // if this is the update account layer, set up each submit button, hook up links on the tabs
        if (action == "updateAccount") {
            var updateFormNames = new Array("updateAccount", "updateEmail", "updateScreenName", "updatePassword", "closeAccount");
            for (var i = 0; i < updateFormNames.length; i = i + 1) {
                $(content).find("#" + updateFormNames[i] + "Form").ajaxSubmit();
            }

            // tabs
            var tabs = $(content).find(".pfTabLink");
            var tabContents = $(content).find(".pfTabContents");
            $(tabs).each(function() {
                $(this).click(function() {
                    if (!(closed)) switchTab(tabs, $(this).parent(), tabContents);
                });
            });
        } else {
            $(content).find("#" + action + "Form").ajaxSubmit();
        }

        // hook up inner links
        $(content).find("a#registerUser, a#registerUserFooter").click(function() {
            changeLightboxContents("register", content);
        })
        $(content).find("a#loginUser, a#loginUserFooter").click(function() {
            changeLightboxContents("login", content);
        })
        $(content).find("a#forgotPassword, a#forgotPasswordFooter").click(function() {
            changeLightboxContents("forgotPassword", content);
        })

        //attach close lightbox function to the close link
        $(content).find("#closeLightbox").click(function() {
            closeLightbox();
        })
    }

    function switchTab(allTabs, thisTab, allTabContents) {
        if (!(isActiveTab(thisTab))) {
            //clear error messages
            $("#formErrors").html("");
            
            //turn off all tabs
            $(allTabs).each(function() {
                if (isEndTab($(this).parent())) {
                    $(this).parent().attr("class", "pfEndTab pfInactiveEndTab");
                } else {
                    $(this).parent().attr("class", "pfTab pfInactiveTab");
                }
            });
			
			//turn off all tab contents
            $(allTabContents).each(function() { $(this).hide(); });
			
			//turn on the relevant tab
            if (isEndTab(thisTab)) {
                $(thisTab).attr("class", "pfEndTab pfActiveEndTab");
            } else {
                $(thisTab).attr("class", "pfTab pfActiveTab");
            }
			
			//turn on the relevant tab contents
            var tabName = $(thisTab).attr("id");
            var sectionName = tabName.substring(0, tabName.length - 3) + "Contents";
            $("div#" + sectionName).show();
            $("div#" + sectionName).find("h4.fieldNameError").each(function() { // restore original state to any erroneous fields
                var id = $(this).attr("id");
                $("div#" + sectionName).find("#" + id + "Field").val(accountState[id]);
                $("div#" + sectionName).find("#" + id + "Field").css("border", "1px solid #B4B2B2");
                $(this).attr("class", "fieldName");
            });

            // turn footer back on if it was hidden
            $(".pfFooter").show();
        }
    }

    function isActiveTab(tab) {
        return !($(tab).attr("class").match("InactiveTab") || $(tab).attr("class").match("InactiveEndTab"));
    }

    function isEndTab(tab) {
        return $(tab).attr("class").match("End");
    }

    /**
     * Calculates the position of the lightboxed element. Centers the element on screen.
     */
    function positionLightbox() {
        var contentOuter = $("#lightbox").find(".contentOuter");
        var element = $("#lightbox").find(".content").children().get(0);

        var x = ($(window).width() / 2 - $(element).width() / 2) + ($(document).scrollLeft() / 2) - 34;
        var elementHeight = $(element).height() + 68; // the 68 here is the padding

        if ($(window).height() > (elementHeight * 2) + 200)
            var y = 100;
        else {
            var y = $(window).height() / 2 - elementHeight / 2;
            if (y > 100) y = 100;
        }
        if (y < 10) y = 10; // keep the overlay from getting too close to the top, or extending past it in ie's case

        $(contentOuter).css({top:y + "px", left:x + "px"});
        if ($.browser.msie) { // ie hack
            $(contentOuter).width($(element).width());
        }

        if ($.browser.msie) {
            $("#lightbox").width($(window).width() + $(document).scrollLeft());
        } else {
            $("#lightbox").width($(document).width() + $(document).scrollLeft());
        }

        $("#lightbox").height($(document).height());
    }

    /**
     * Closes the currently open lightboxed modal
     */
    function closeLightbox() {
        $("#lightbox").find(".contentOuter").fadeOut("fast", function() {
            $("#lightbox").fadeOut("fast", function() {
                $("#lightbox").remove();
            })
        });

        if ($.browser.msie) { // bring back select elements if IE
            $('iframe').each(function() {
                var iframeDocument = this.contentWindow.document;
                $(iframeDocument).find('select').each(function() {
                    $(this).show();
                });
            });
            $('select').show();
        }
    }

    /**
     * Opens a user login/registration layer, depending on what string is passed in, and redirects to passed in url if needed
     */
    function userAction(action, returnUrl) {
        window.scrollTo(0,0);
        myReturnUrl = returnUrl;
        $.get("/project_folder/form_" + action + ".jsp", function(html) {
            openLightbox(html, action);
        });
    }

    /**
     * Used when we're going from one overlay to another, simply switches the contents of the content div rather than closing and reopening the lightbox.
     */
    function changeLightboxContents(action, contentDiv) {
        window.scrollTo(0,0);
        $.get("/project_folder/form_" + action + ".jsp", function(html) {
            $(contentDiv).html(html);
            setLinks(action, contentDiv);
            positionLightbox();
            originalTop = parseInt($(".contentOuter").css("top"));
        });
    }

    $.extend(KPNA, {
        callLightbox:callLightbox,
        openLightbox:openLightbox,
        closeLightbox:closeLightbox,
        userAction:userAction
    });
})(jQuery);

$(function() {
    $("a#registerUser").click(function() {
        KPNA.userAction("register", "");
    });
    $("a#loginUser").click(function() {
        KPNA.userAction("login", "");
    });
    $("a#updateUser").click(function() {
        KPNA.userAction("updateAccount", "");
    });
    $("a#logoutUser").click(function() {
        location.href = "/project_folder/logout.jsp?returnUrl=" + encodeURIComponent(document.location);
        return false;
    });
});