﻿//Select Behavior

var visiblePopup = null;

jQuery.fn.extend({
    attachSelectBehavior: function(properties) {
        var $select = $(this);
        var $popup = $("div.popup", $select);

        var escapeId = function(id) {
            return '#' + id.replace(/(:|\.)/g, '\\$1');
        }
        var popup_blur = function(event) {
            if (!$(event.target).parents().filter("#" + escapeId(properties.id)).length) hidePopup();
        }
        var showPopup = function() {
            hideSelects();
            $popup.show();
            visiblePopup = $popup;
            $(document.body).bind('click', popup_blur);
        }
        var hidePopup = function() {
            if ($popup == visiblePopup) showSelects();
            $popup.hide();
            if ($popup == visiblePopup) visiblePopup = null;
            $(document.body).unbind('click', popup_blur);
        }
        var togglePopup = function() {
            if ($popup.is(":visible"))
                hidePopup();
            else
                showPopup();
        }

        return this.each(function() {
            $("span.select", $select).click(function() {
                var selectWidth = $(this).outerWidth();
                var popupWidth = $popup.outerWidth();
                $popup.css("left", (window.screen.width - popupWidth) / 2);
                togglePopup($popup);
            });
            $("div.CloseButton img", $select).click(function() { hidePopup($popup); });
            $("div.content span.option", $popup).click(function() {
                var $option = $(this);
                hidePopup($popup);
                $("span.select span", $select).text($option.text());
            });
            $select.data("FieldName", properties.fieldName);
            $select.data("AutoPostBack", properties.autoPostBack);
        });
    }
});

function select_chooseOption(sender, value) {
    var $select = $(sender).closest("div.select");
    var $form = $select.closest("form");
    if ($form.length === 0) return;
    var form = $form[0];
    var hiddenField = form[$select.data("FieldName")];
    if (!hiddenField) return;
    hiddenField.value = value;
    if ($select.data("AutoPostBack"))
        form.submit();
};