shopwell.modalReady = function(){
    $(window).scrollTop(0);
    
    // Handle the demographic profile selection.
    $(".demo_list li:not(.no_selection)").demographicSelection({
        demographicData: shopwell.demographicJSON
    });
    
    var isReloadPage = $(document).find(".sidebar_left .sidebar_profile").length > 0;
    if (!isReloadPage) {
        $("#profile_save").val("Save and Start Browsing").css("width", "220px");
    }
    
    // There's really only one preference suggestion that I know of right now.
    // Handle it simply here. Write a plugin later if there's more. -ps
    $("#GLUTEN_ALLERGY, #WHEAT_ALLERGY").click(function(event){
        var $allergy = $(this);
        var $wheat = $("#WHOLE_WHEAT");
        var $wheatContainer = $wheat.closest("dd");
        var titleText = $allergy.is("#GLUTEN_ALLERGY") ?
                            "Whole Wheat contains Gluten." :
                            "You have indicated that you shouldn't have Wheat.";
        var currentTitle = $wheatContainer.attr("title");
        
        if ($wheatContainer && $wheat.is(":checked") && $allergy && $allergy.is(":checked")) {
            $wheatContainer.addClass("alert_avoid");
            currentTitle += " " + titleText;
            $wheatContainer.attr("title", currentTitle);
        } else if ($wheatContainer && $allergy && !$allergy.is(":checked")) {
            if (!$("#GLUTEN_ALLERGY").is(":checked") && !$("#WHEAT_ALLERGY").is(":checked")) {
                $wheatContainer.removeClass("alert_avoid");
            }
            currentTitle = currentTitle.replace(titleText, "");
            $wheatContainer.attr("title", currentTitle);
        }
    });
    $("#WHOLE_WHEAT").click(function(event){
        var $glutenAllergy = $("#GLUTEN_ALLERGY");
        var $wheatAllergy = $("#WHEAT_ALLERGY");
        var $wheat = $(this);
        var $wheatContainer = $wheat.closest("dd");
        var titleText = "";
        
        if ($glutenAllergy.is(":checked")) { titleText += "Whole Wheat contains Gluten."; }
        if ($wheatAllergy.is(":checked")) { titleText += " You have indicated that you shouldn't have Wheat."; }
        
        if ($wheatContainer && $wheat.is(":checked") && 
            ($glutenAllergy.is(":checked") || $wheatAllergy.is(":checked"))) {
                $wheatContainer.addClass("alert_avoid").attr("title", titleText);
        } else {
            $wheatContainer.removeClass("alert_avoid").attr("title", "");
        }
    });
    
    // Wire up the save button.
    $("#profile_save").click(function(event){
        event.preventDefault();
        
        if ($(this).is(":enabled")) {
            $.post($("#profile_preferences_form").attr("action"), $("#profile_preferences_form").serialize(), function(data) {
                $("#modal").jqmHide();
                // Register the event with Google Analytics.
                try{
                    pageTracker._trackEvent('Profile', 'Save');
                } catch(err) {}
                if (isReloadPage) {
                    window.location.reload();
                } else {
                    window.location = "/browse";
                }
            });
        }
        
    });
};

(function($) {
    $.fn.demographicSelection = function(options) {
        var opts = $.extend({}, $.fn.demographicSelection.defaults, options);
        
        var $collection = this;
        var selectedIcon = "<img src='/css/images/profile/demo_icon_selected.png' class='check_selected' alt='selected' />"
        var editButton = "<button class='mini_button'>Edit</button>";
        var showDetailsLink = "<p id='show_demo_info_details'><a href='#show_details'>Show More Details</a></p>";
        
        // If there are any mini edit buttons, disable the click.
        $(opts.imageContainerSelector + " button.mini_button").live("click", function(event) {
            event.preventDefault();
        });
        
        return this.each(function() {
            var $this = $(this);
            
            // Support for the Metadata Plugin.
            var o = $.meta ? $.extend({}, opts, $this.data()) : opts;

            // Pull the metadata off of the element. Then, add it to the jquery data container
            // so we can modify it later when the user makes a selection.
            $this.data("displayData", $this.metadata());
            var displayData = $this.data("displayData");
            
            $this.click(function(event) {
                // This demographic is already selected. Create and show the popup.
                if ($this.is(".selected")) {
                    var $popup = $this.find(opts.popupSelector);
                    if ($popup && $popup.length > 0) {
                        if ($(event.target).closest(opts.popupSelector).length == 0) {
                            hidePopup($popup);
                        }
                    } else {
                        showPopup($this, displayData);
                    }
                } else {
                    $collection.removeClass("selected")
                                .find("img.check_selected").remove().end()
                                .find("button.mini_button").remove();
                    hidePopup($collection.find(opts.popupSelector));

                    $this.addClass("selected").append(selectedIcon);
                    $(opts.saveButtonSelector).removeClass("disabled").attr("disabled", false);
                    
                    $(opts.demoTypeFieldSelector).val($this.data("displayData").current_demo);
                    
                    updateDemographicSelection(displayData.ageGroup, displayData.current_demo);
                    
                    if (displayData.ageGroup != "FAMILY") {
                        $this.find(opts.imageContainerSelector).append(editButton);
                        showPopup($this, displayData);
                    }
                }
            });
        });
        
        function showPopup($container, displayData) {
            var $popup = createGenderPopup(displayData).appendTo($container);
            
            // Add a click listener to the radio buttons.
            $popup.find("input:radio").click(handleGenderRadioClick);
            
            // If this is the "ADULT" demographic, add click listener to the gender radio buttons.
            if (displayData.ageGroup == "ADULT") {
                $popup.find("input:radio[name=gender_ADULT]").click(handleOtherGenderClick);
            }
            
            // Add a click listener to the "Done" button.
            $popup.find("#gender_done").click(handleGenderDoneButton);
            
            $(window).click(function(event) {
                if ($popup && $popup.is(":visible")) {
                    if ($(event.target).closest(opts.popupSelector).length === 0) {
                        hidePopup($popup);
                    }
                }
            });
            
            window.setTimeout(function() {
                $popup.fadeIn("fast");
            }, 500);
        }
        
        function hidePopup($popup) {
            $popup.fadeOut("fast", function() { $popup.remove() });
        }

        function createGenderPopup(displayData) {
            var isFemale = displayData.current_demo.indexOf("FEMALE") >= 0;
            var maleDisplayType = displayData.ageGroup + "_MALE";
            var femaleDisplayType = displayData.ageGroup + "_FEMALE";

            var popup = "\
                <div class=\"" + opts.popupClass + "\">\
                    <div class=\"demo_gender_container\">\
                        <dl class=\"form_field_list clearfix\">\
                            <dt>Gender?</dt>\
                            <dd>\
                                <input type=\"radio\" name=\"gender_" +
                                displayData.ageGroup + "\" \
                                id=\"gender_" + maleDisplayType + "\" \
                                value=\"" + maleDisplayType + "\"";
            if (!isFemale) {
                popup += " checked=\"checked\"";
            }
            popup += "\
                                /><label for=\"gender_" + maleDisplayType + "\">M</label>";
            popup += "\
                                <input type=\"radio\" name=\"gender_" +
                                displayData.ageGroup + "\" \
                                id=\"gender_" + femaleDisplayType + "\" \
                                value=\"" + femaleDisplayType + "\"";
            if (isFemale) {
                popup += " checked=\"checked\"";
            }
            popup += "\
                                /><label for=\"gender_" + femaleDisplayType + "\">F</label>";
            popup += "\
                            </dd>\
                        </dl>";

            // Add the Other fields if this is an adult display demographic type.
            if (displayData.ageGroup == "ADULT") {
                popup += "\
                        <dl id=\"other_gender_section\" class=\"form_field_list clearfix";
                if (!isFemale) { popup += " disabled"; }
                popup += "\
                        \">\
                            <dt>Other</dt>\
                            <dd><ul>\
                                    <li><input type=\"radio\" name=\"other_ADULT_FEMALE\" \
                                        id=\"pregnant\" value=\"ADULT_FEMALE_PREGNANT\" ";
                if (!isFemale) { 
                    popup += "disabled=\"disabled\" ";
                } else if (displayData.current_demo == "ADULT_FEMALE_PREGNANT") { 
                    popup += "checked=\"checked\" ";
                }
                popup += "\
                                        />\
                                    <label for=\"pregnant\">Pregnant</label></li>\
                                    <li><input type=\"radio\" name=\"other_ADULT_FEMALE\" \
                                        id=\"nursing\" value=\"ADULT_FEMALE_NURSING\" ";
                if (!isFemale) { 
                    popup += "disabled=\"disabled\" "; 
                } else if (displayData.current_demo == "ADULT_FEMALE_NURSING") { 
                    popup += "checked=\"checked\" ";
                }
                popup += "\
                                        />\
                                    <label for=\"nursing\">Nursing</label></li>\
                                    <li><input type=\"radio\" name=\"other_ADULT_FEMALE\" \
                                        id=\"neither\" value=\"ADULT_FEMALE\" ";
                if (!isFemale) { 
                    popup += "disabled=\"disabled\" "; 
                } else if (displayData.current_demo == "ADULT_FEMALE") { 
                    popup += "checked=\"checked\" ";
                }
                popup += "\
                                         />\
                                    <label for=\"neither\">Neither</label></li>\
                            </ul></dd>\
                        </dl>";
            }
            popup += "\
                        <p class=\"button_container\">\
                            <button class=\"button\" id=\"gender_done\">Done</button>\
                        </p>\
                    </div>\
                    <div class=\"bubble_arrow top\"></div>\
            </div>";
            return $(popup);
        }

        function handleGenderRadioClick() {
            var $radio = $(this);
            var $container = $radio.closest(opts.containerSelector);

            var selectionId = $radio.val();
            $(opts.demoTypeFieldSelector).val(selectionId);
            
            updateDemographicSelection($container.attr("id"), selectionId);
        }

        function handleOtherGenderClick() {
            if ($(this).val() == "ADULT_MALE") {
                // Disable the other section.
                $("#other_gender_section").addClass("disabled").find("input:radio").attr("disabled", true);
                // Unselect all radio buttons in it.
                $("input:radio[name=other_ADULT_FEMALE]").attr("checked", false);
            } else if ($(this).val() == "ADULT_FEMALE") {
                // Enable the other section.
                $("#other_gender_section").removeClass("disabled").find("input:radio").attr("disabled", false);
                // Select "Neither" by default.
                $("input:radio[value=ADULT_FEMALE]").attr("checked", true);
            }
        }

        function handleGenderDoneButton(event) {
            event.preventDefault();

            var $button = $(this);
            var $popup = $button.closest(opts.popupSelector);
            var $container = $button.closest(opts.containerSelector);

            var genderSelection = $popup.find("input:radio[name*=gender]:checked").val();
            var otherSelection = $popup.find("input:radio[name=other_ADULT_FEMALE]:checked").val();

            var selectionId = otherSelection || genderSelection;
            $(opts.demoTypeFieldSelector).val(selectionId);
            hidePopup($popup);
            
            updateDemographicSelection($container.attr("id"), selectionId);
        }
        
        function updateDemographicSelection(selectionGroup, selectionId) {
            var $container = $("#" + selectionGroup);
            
            // Find the demographicData object associated with this selection.
            var selectedDemographicData = findDemographicData(selectionId);
            
            // Update the displayData on the container.
            $container.data("displayData").current_demo = selectionId;
            $container.find(".demo_image_container img")
                            .attr("src", "/images/profile/" + selectionId.toLowerCase() + ".png")
                            .attr("alt", selectedDemographicData.label);
            $container.find(".demo_label").text(selectedDemographicData.label);
            
            // Update the info area image.
            $(".profile_section .demo_selection_image img")
                    .attr("src", "/images/profile/" + selectionId.toLowerCase() + "_sm.png")
                    .attr("alt", selectedDemographicData.label);
            
            // Remove the details link if it exists.
            $("#show_demo_info_details").remove();
            
            // Truncate the description if necessary and add the Show More link.
            var $demoDescriptionContainer = $(".profile_section .demo_selection_info");
            var demoDescription = selectedDemographicData.description;
            if (demoDescription.length > 210) {
                demoDescription = demoDescription.substring(0, 210) + "...";
                
                $(showDetailsLink).appendTo($demoDescriptionContainer)
                                    .find("a").data("descriptionText", {
                                        truncated: demoDescription,
                                        full: selectedDemographicData.description
                                    });
            }
                                    
            $demoDescriptionContainer.removeClass("generic")
                    .find("p.demo_text").html(demoDescription);
            
            $("#show_demo_info_details a").click(function(event) {
                event.preventDefault();

                var $link = $(this);
                var $container = $link.closest(".profile_section .demo_selection_info");
                if ($link.text() == "Show More Details") {
                    $container.find("p.demo_text").html($link.data("descriptionText").full);
                    $link.text("Show Fewer Details");
                } else {
                    $container.find("p.demo_text").html($link.data("descriptionText").truncated);
                    $link.text("Show More Details");
                }
            });
        }
        
        function findDemographicData(id) {
            var retVal;
            $.each(opts.demographicData, function(i, obj) {
                if (obj.id === id) {
                    retVal = obj;
                    return false;
                }
            });
            return retVal;
        }
    };

    // default options
    $.fn.demographicSelection.defaults = {
        containerSelector: ".demo_list>li",
        popupClass: "content_bubble",
        popupSelector: ".content_bubble",
        imageContainerSelector: ".demo_image_container",
        demoTypeFieldSelector: "#demographic",
        demographicData: [],
        saveButtonSelector: "#profile_save"
    };

})(jQuery);