﻿$(function ()
{
    $(".popup").css ("top", "50%") ;
    $(window).resize (function ()
    {
        var panel = $(".popup .panel:visible") ;
        if (panel.length == 0)
            return ;
        if (panel.height () > 200)
        {
            var top = panel.height () ;
            if ($(window).height () < panel.height ())
                top = $(window).height ();
            panel.css ("top", - top / 2) ;
        }
    }) ;
}) ;

function PopupForm (settings, callback)
{
    this.Id = settings.Id ;
    this.CallbackFunc = callback ;
    this.Events = settings.Events ;
    this.Settings = settings ;
    this.Form = $("#" + this.Id + "_form > div") ;
    var obj = this ;
    this.KeyPressFunc = function (e) { obj.KeyPressHandler (e) ; }
    this.OverlayClickFunc = function (e) { obj.OverlayClickHandler (e) ; }
    this.Form.find (".close-button div").click (function () { obj.Hide () ; }) ;
}

PopupForm.prototype.Show = function ()
{
    this.RaiseOnShow ({}) ;

    $("#Overlay").fadeTo (0, 0).show ().fadeTo ('fast', 0.5);
    var obj = this ;
    $(window).bind ("keypress", this.KeyPressFunc) ;
    $("#Overlay").click (this.OverlayClickFunc) ;
    this.Form.show () ;
    obj.Form.css ("top", - obj.Form.height () / 2) ;
    this.Form.find ("fieldset input,fieldset textarea,fieldset select").filter (":enabled").first ().focus () ;
}

PopupForm.prototype.KeyPressHandler = function (e)
{
    if (e.keyCode == 27)
        this.Hide () ;
}

PopupForm.prototype.OverlayClickHandler = function (e)
{
    this.Hide () ;
}

PopupForm.prototype.Hide = function ()
{
    var args = { Cancel : false } ;
    this.RaiseOnHide (args) ;
    if (args.Cancel)
        return ;
    $("#Overlay").unbind ("click", this.OverlayClickFunc) ;
    $(window).unbind ("keypress", this.KeyPressFunc) ;
    this.Form.hide () ;
    $("#Overlay").fadeTo ('fast', 0, function () { $("#Overlay").hide () ;}) ;
}

PopupForm.prototype.Callback = function (data, context)
{
    this.CallbackFunc (JSON.stringify (data), context) ;
}

PopupForm.prototype.OnCallbackResult = function (result, context)
{
    var obj = eval("(" + result + ")") ;
    this.RaiseOnCallbackComplete ({ Result : obj, Context : context }) ;
}

PopupForm.prototype.RaiseOnCallbackComplete = function (args)
{
    if (this.Events.OnCallbackComplete)
        this.Events.OnCallbackComplete (this, args) ;
}

PopupForm.prototype.RaiseOnShow = function (args)
{
    if (this.Events.OnShow)
        this.Events.OnShow (this, args) ;
}

PopupForm.prototype.RaiseOnHide = function (args)
{
    if (this.Events.OnHide)
        this.Events.OnHide (this, args) ;
}

