var shopwell = {}; // shopwell namespace

$(function() {
    var $search = $("#search");
    $search.example("Enter your search term here... (e.g. cereal)", { className: "prompt" });
    $search.focus(function(event){ $(this).addClass("focus")})
            .blur(function(event){ $(this).removeClass("focus")});
    $("#search_form").submit(function(event) {
        if ($search.val() == "") {
            event.preventDefault();
            window.location = "/browse";
        }
    });

    $("#modal").jqm({ 
        trigger: false,
        modal: true,
        onShow: shopwell.showModalHandler
    });
    $("a[rel$='modal']").live("click", function(event) {
        event.preventDefault();
        $("#modal").jqmShow($(this));
    });
    $("a.jqmClose").live("click", function(event) {
        event.preventDefault();
        $("#modal").jqmHide();
    });
    $("a[rel$='external']").live("mouseover",
        function(){ this.target = "_blank";
    });
    
    if ($("#message_main") || $("#error_main")) {
        window.setTimeout(function(){
            $("#message_main, #error_main").fadeTo("slow", 0.01, function(){
                $("#message_main, #error_main").slideUp();
            });
        }, 5000);
    }
});

shopwell.showModalHandler = function(hash) {
    var $modal = hash.w;
    var $trigger = $(hash.t);
    var $overlay = $(hash.o);
    
    $(document).keyup(function (event) {
        if (event.keyCode == 27) {
            $modal.jqmHide();
        }
    });
    
    $.ajax({ 
        url: $trigger.attr("href"),
        cache: false,
        type: "GET",
        success: function(data) {
            $modal.html(data).show();
            
            // Must wire up this event here to prevent FF link double-click bug.
            $overlay.click(function(event) {
                $("#modal").jqmHide();
            });
            
            var data = $trigger.metadata();
            var readyCallback = eval(data && data.modalReady ? data.modalReady : "shopwell.modalReady");
            
            if (readyCallback) {
                readyCallback.call();
            }
        }
    });
};