/*!
 * jQuery UI Dialog Enchance v0.9
 * http://blog.istvan-antal.ro/
 *
 * Copyright 2010, Antal István Miklós
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 *
 */

(function($) {
    /*
     *fixedcenter attribute for dialog
     */

    //variable that keeps fixedcenter elements
    var fcDialogs = [];

    //an event handler, that is called when we need to center the dialog
    var center = function() {
        for (var i=0;i<fcDialogs.length;i++) {
            $(fcDialogs[i]).dialog('option', 'position', ['center','center']);
        }
    }

    //attaching the event handler to the scroll and resize events
    $(window).scroll(center);
    $(window).resize(center);

    //the function that will make a dialog stay in the center
    var fixcenter = function(el) {
        fcDialogs.push(el);
    }

    //function that will remove a dialog element from the fixedcenter list
    var unfixcenter = function(el) {
        for (var i=0;i<fcDialogs.length;i++) {
            if (fcDialogs[i]==el) {
                fcDialogs.splice(i,1);
            }
        }
    }

    /*
     * Flash helpers
     */

    var enableFlash= function() {
        $('object').css('display','');
        //$('iframe').css('display','');
        $('embed').css('display','');
    }

    var disableFlash = function() {
        $('object').css('display','none');
        //$('iframe').css('display','none');
        $('embed').css('display','none');
    }

    //remember what were these functions before
    var osetData = $.ui.dialog.prototype._setData;
    var oinit = $.ui.dialog.prototype._init;

    //overwrite the ui.dialog methods with our own
    $.extend($.ui.dialog.prototype , {
        _init: function() {
            oinit.call(this);
            if (this.options.fixedCenter) {
                //enable fixedcenter
                fixcenter(this.element);
            }
            //fixflash
            if (this.options.fixFlash) {
                $(this.element).dialog('option','open',disableFlash);
                $(this.element).dialog('option','close',enableFlash);
            }

        },
        _setData:function(key,value){
            if (key=='fixedCenter') {
                if (value) {
                    //enable
                    fixcenter(this.element);
                } else {
                    //disable fixedcenter
                    unfixcenter(this.element)
                }
            } else {
                //call the original _setData
                osetData.call(this,key,value);
            }
        }
    });

})(jQuery);
