﻿GoodNitesUserControls.Confirmation = function(serverVars) {
    this.ServerVars = serverVars;
    this.Initialize();
};

GoodNitesUserControls.Confirmation.prototype = {
    Initialize: function() {
        var triggerSelector = this.ServerVars.triggerSelector;
        var confirmContainerSelector = '#' + this.ServerVars.confirmContainer;

        // we use a selector here to attach a click event handler to anything
        // that matches the trigger selector that is passed in.
        $(triggerSelector).click(function(e) {
            // prevent default prevents buttons from actually performing their click operation
            // effectively allowing you to intercept the click.
            e.preventDefault();
            var control = this;

            // the confirm method handles the modal dialog.  its completion will signal the 
            // control that was clicked to be "clicked" via javascript, allowing the event to pass through.
            confirm(confirmContainerSelector, function() {
                $(control).click();
            });
        });
    }
};

function confirm(selector, callback) {
    $(selector).modal({
        close: false,
        overlayId: 'confirmModalOverlay',
        containerId: 'confirmModalContainer',
        onShow: function(dialog) {
            // if the user clicks "yes"
            dialog.data.find('.yes').click(function() {
                // call the callback
                if ($.isFunction(callback)) {
                    callback();
                }
                // close the dialog
                $.modal.close();
            });

            // if the user clicks "no"
            dialog.data.find('.no').click(function() {
                // close the dialog
                $.modal.close();
            });

            // bind the keypress event for the escape key.  if a user hits escape they will close the dialog without voting
            $('form:first').bind('keypress', function(e) {
                if (e.keyCode == 27) {// this is the escape key
                    // close the dialog
                    $.modal.close();
                }
            });
        }
    });
}

GoodNites.Extend(GoodNitesUserControls.Confirmation, GoodNites.Core);