/**
 * jQuery Modal Plugin for UCMVC.
 *
 * @author Kyle B. Thomas <k.thomas@unmarkedconsulting.com>
 * @copyright Copyright (c) 2008-2009, Kyle B. Thomas. All rights reserved.
 * @category UCMain
 * @package UCMain_JS
 */
;(function($) {
    /**
     * Opened status for the modal.
     * 
     * @var boolean
     * @access private
     */
    var opened = false;

    /**
     * Opened modal options.
     *
     * Should be set to null if there is no opened modal.
     * @var array
     * @access private
     */
    var openedOpts = null;

    /**
     * jQuery function sets the onclick event for each item to open a modal.
     *
     * @param array options
     * @access public
     * @return jQuery
     */
    $.fn.cwmodal = function(options) {
        $(this).click(function(event) {
            event.preventDefault();
            openModal(options);
        });
        return this;
    };
    
    /**
     * Global function creates a modal with the given options.
     *
     * @param array options
     * @access public
     * @return jQuery
     */
    $.cwmodal = function(options) {
        openModal(options);
    };
    
    /**
     * Global function returns the current modal opened status.
     *
     * @access public
     * @return boolean
     */
    $.cwmodal.isOpened = function() {
        return opened;
    }
         
    /**
     * Modal default options.
     *
     * @var array
     * @access public
     */
    $.cwmodal.defaults = {
        type: 'ajax',
        source: null,
        css: {
            position: 'fixed',
            padding: 0,
            margin: 0,
            textAlign: 'center',
            color: '#333333',
            border: '3px solid #333333',
            background: '#fff url("/media/images/bg-body.jpg") top left repeat-x',
            color: '#333333',
            zIndex: 1002
        },
        loadingCss: {
            position: 'fixed',
            background: '#fff url("/media/images/ajax-loader.gif") no-repeat fixed center center',
            padding: 0,
            margin: 0,
            width: '300px',
            height: '150px',
            textAlign: 'center',
            color: '#000',
            border: '3px solid #333333',
            zIndex: 1001
        },
        overlayCss: {
            position: 'fixed',
            padding: 0,
            margin: 0,
            height: '100%',
            width: '100%',
            left: 0,
            top: 0,
            backgroundColor: '#000',
            opacity: '0.6',
            cursor: 'default',
            zIndex: 1000
        },
        logoCss: {
            position: 'absolute',
            padding: 0,
            margin: 0,
            zIndex: 1001
        },
        closeButtonCss: {
            position: 'absolute',
            padding: 0,
            margin: 0,
            top: '10px',
            right: '15px',
            height: '16px',
            width: '16px',
            cursor: 'pointer',
            zIndex: 1003
        },
        logoImage: '/media/images/small-logo.jpg',
        closeButtonImage: '/media/images/ico-close.png',
        constrainTabKey: true,
        focusInput: true,
        onOpen: null,
        onLoaded: null,
        onClose: null
    };
    
    /**
     * Local/private function creates, loads, and displays a modal.
     *
     * @param array options
     * @access private
     * @return void
     */
    function openModal(options) {
        // Extend our default options with those provided.
        var opts = $.extend({}, $.cwmodal.defaults, options);
        
        // Setup each layer of the modal
        var overlay = $('<div>').attr('id', 'cwmodalOverlay').css(opts.overlayCss).hide().appendTo('body');
        var loadingModal = $('<div>').attr('id', 'cwmodalLoading').css(opts.loadingCss).hide().appendTo('body');
        var modal = $('<div>').attr('id', 'cwmodal').css(opts.css).hide().appendTo('body');
        var logo = $('<img>').attr({src: opts.logoImage}).css(opts.logoCss).hide().prependTo(modal);
        var closeButton = $('<img>').attr({id: 'cwmodalCloseButton', src: opts.closeButtonImage}).css(opts.closeButtonCss).hide().prependTo(modal);

        // Show the overlay
        overlay.show();
        // Calculate the height, width, and margins of the loading modal
        var loadingW = loadingModal.width();
        var loadingH = loadingModal.height();
        var loadingMt = -(loadingH / 2);
        var loadingMl = -(loadingW / 2);

        // Set the loading modal's initial CSS so that it starts at the top of the page
        loadingModal.css({top: 0, left: '50%', marginTop: loadingMt+'px', marginLeft: loadingMl+'px'});
        // Unhide the loading modal
        loadingModal.show();
        // Animate the loading modal down to the middle of the page
        loadingModal.animate({top: '50%'}, 500, function() {
            if (opts.type == 'ajax' && opts.source !== null) {
                $.ajax({
                    type: 'GET',
                    url: opts.source,
                    dataType: 'html',
                    success: function(data) {
                        modal.append(data);
                        
                        // Get the height of the window (leave some space) and the modal
                        var windowHeight = $(window).height() - 30;
                        var modalHeight = modal.height();
                        
                        // Get the modal width
                        var w = modal.width();
                        
                        // Make sure that the modal's height fits inside the window
                        var h = (modalHeight <= windowHeight) ? modalHeight : windowHeight;
                        
                        // Set the modal height incase it was changed to fit the window
                        modal.height(h);
                        
                        // Calculate the left and top margins
                        var ml = -(w/2);
                        var mt = -(h/2);
                        
                        // Animate the loading modal to fit the content modal's dimensions
                        loadingModal.animate({width: w+'px', height: h+'px', marginLeft: ml+'px', marginTop: mt+'px'}, 500, function() {
                            // Set the position of the modal
                            modal.css({left: '50%', top: '50%', marginLeft: ml+'px', marginTop: mt+'px'});
                            // Hide the loading modal and show the content modal, logo, and its close button
                            loadingModal.hide();
                            modal.show();
                            logo.show();
                            closeButton.show();
                            $('#modal-content input:first').focus();
                        });
                    }
                });
            }
        });
        
        // Set the onclick event for the close button
        closeButton.click(closeModal);

        // Set the modal status to opened and save the options for later use
        opened = true;
        openedOpts = opts;
    }
    
    /**
     * Local/private function closes the modal.
     *
     * @access private
     * @return void
     */
    function closeModal() {
        // Make sure there is actually an open modal
        if (opened === false) {
            return;
        }
        
        $('#cwmodal, #cwmodalLoading, #cwmodalOverlay, #cwmodalCloseButton').remove();
        
        // Set the modal status to closed and clear the old options
        opened = false;
        openedOpts = null;
    }

})(jQuery);
