﻿/// <reference path="lib/jquery-1.3.2-vsdoc.js" />

(function($) {

    var window = this,
        _app = window.app;

    window.app = window.app || {};

    var Popup = window.app.Popup = function(triggerName, pathToFile, options) {
        var _trigger = $(triggerName),
            _box = "popup-box",
            _opts = options || { width: '400px' };

        function box() {
            return $("#" + _box);
        }

        function appendBoxMarkup() {
            $('body').append('<div id="' + _box + '">Loading ...</div>');
        }

        function setBoxWidth() {
            box().css("width", _opts.width);
        }

        function handleClick(event) {
            event.preventDefault();

            $(document).bind('keypress', hEscapeKey);

            // the order of these methods are important
            drawCurtain();
            appendBoxMarkup();
            setBoxWidth();

            box().load(pathToFile, function(html) {
                box().empty().append(html);
                addCloseBehavior();
                center();
                box().fadeIn('slow');
            });
        }

        function center() {
            function top() {
                return ($(window).height() - box().outerHeight()) / 2;
            }

            function left() {
                return ($(document).width() - box().outerWidth()) / 2;
            }

            box()
            .css('top', top())
            .css('left', left());
        }

        function drawCurtain() {
            var css = {
                position: 'fixed',
                'background-color': '#000',
                border: 'solid 1px #000',
                top: '0',
                left: '0',
                width: '100%',
                height: '100%',
                filter: 'alpha(opacity=50)',
                '-moz-opacity': '0.50',
                opacity: '0.50',
                'z-index': '100'
            };

            $('body').append('<div id="curtain"></div>');
            $('#curtain').css(css);
        }

        function addCloseBehavior() {
            $("#popup-close a").click(function(event) {
                close();
                event.preventDefault();
            });
        }

        function hEscapeKey(event) {
            if (event.keyCode == 27) {
                event.preventDefault();
                close();
            }
        }

        function close() {
            box().fadeOut('slow', function() {
                $('#curtain').remove();
                box().remove();
            });

            $(document).unbind('keypress', hEscapeKey);
        }


        // hook into the trigger element's click event

        _trigger
        .bind('click', handleClick)
        .mouseover(function(e) { $(this).css('cursor', 'pointer'); });

        return this;
    };

})(jQuery);