﻿(function($) {
    var r, o = null;
    $.fn.replaceSelect = function(options) {
        r = this;
        o = options;
        if (!o) o = {};
        if (r.attr("tagName") != "SELECT") return;
        init();
    }
    function init() {
        r.hide();
        var s = o.labelContainer || $("<span/>");
        var ul = $("<ul/>").css({ position: "absolute" });

        if (o.labelClass) s.addClass(o.labelClass);
        if (o.labelId) s.attr("id", o.labelId);
        if (o.boxClass) ul.addClass(o.boxClass);
        if (o.boxId) ul.attr("id", o.boxId);

        slideSpeed = o.slideSpeed || 200;

        r.find("option").each(function() {
            var op = $(this);
            ul.append(
				$("<li/>")
				.text(op.text())
				.click(function() {
				    op.attr("selected", "selected");
				    s.text(op.text());
				    ul.slideUp(slideSpeed);
				    r.change();
				})
			)
			.hide();
            if (op.attr("selected")) s.text(op.text());
        });
        s.click(function() {
            //calculate where to position the ul
            var st = s.attr("offsetHeight") + s.attr("offsetTop");
            var sl = s.attr("offsetLeft");

            ul.css({ top: st, left: sl });
            ul.slideToggle(slideSpeed);
        });

        s.insertAfter(r);
        ul.insertAfter(s);
    }
})(jQuery);

$(document).ready(function() {
    $("#section").replaceSelect({ labelId: "sectionLabel", boxId: "sectionBox" });
    $("#keywords").blur(function() {
        if (this.value == '') this.value = 'type search criteria';
    })
    .focus(function() {
        if (this.value == 'type search criteria') this.value = '';
    }).keypress(function(event) {
        if ((event.which && event.which == 13) || (event.keyCode && event.keyCode == 13)) {
            doSearch();
            return false;
        }
    });

    $("#searchBtn").click(function() {
        doSearch();
        return false;
    });

    function doSearch() {
        window.location = "/" + $("#section").val() + "/SearchResults/" + escape($("#keywords").val()).replace(/[\/]/g, "");
    }
});
