;(function($, undefined) {

    var pluginName = 'd_modal';

    function Modal(options) {
        this.options = $.extend({}, $.fn[pluginName].defaults, options);
        this.$modal = $(this.options.target).attr('class', 'modal fade').hide();
        var self = this;

        function init() {
            if (self.options.title === '') {
                self.options.title = ' ';
            }
        };

        init();
    }


    $.extend(Modal.prototype, {
        show: function() {
            var self = this
                ,$backdrop;
            if (!this.options.nobackdrop) {
                $backdrop = $('.modal-backdrop');
            }
//            if (!this.$modal.length) {
                var mdstr = '<div class="modal fade" id="' + this.options.target.substr(1) + '" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">';
                mdstr += 	'<div class="modal-dialog">';
                mdstr += 		'<div class="modal-content">';
                mdstr += 			'<div class="modal-header">';
                mdstr += 				'<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>';
                mdstr += 				'<h4 class="modal-title" id="myModalLabel"></h4>';
                mdstr +=             '</div>';
                mdstr += 			'<div class="modal-body">';
//                mdstr += 				'加载中。。。。';
                mdstr += 				'<div style="margin:40px auto;text-align:center;"><img src="'+ctxStatic+'/img/loading.gif"></img></div>';
                mdstr += 			'</div>';
                //mdstr += 			'<div class="modal-footer">';
                //mdstr += 				'<button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>';
                //mdstr += 			'</div>';
                mdstr += 		'</div>';
                mdstr += 	'</div>';
                mdstr += '</div>';
                //mdstr +=             '<div class="inner"/></div></div></div></div>';

                this.$modal = $(mdstr).appendTo(this.options.appendTo).hide();
                //this.$modal = $('<div class="modal fade" id="' + this.options.target.substr(1) + '"><div class="modal-header"><a class="close" href="#" data-dismiss="modal">×</a><h3> </h3></div><div class="inner"/></div>').appendTo(this.options.appendTo).hide();
//            }

            this.$modal.find('.modal-header h4').html(this.options.title);

            if (this.options.cssclass !== undefined) {
                this.$modal.attr('class', 'modal fade ' + this.options.cssclass);
            }

            if (this.options.width !== undefined) {
                this.$modal.width(this.options.width);
            }

            if (this.options.left !== undefined) {
                this.$modal.css({'left': this.options.left});
            }

            if (this.options.height !== undefined) {
                this.$modal.height(this.options.height);
            }

            if (this.options.top !== undefined) {
                this.$modal.css({'top': this.options.top});
            }

            if (this.options.keyboard) {
                this.escape();
            }

            if (!this.options.nobackdrop) {
                if (!$backdrop.length) {
                    $backdrop = $('<div class="modal-backdrop fade" />').appendTo(this.options.appendTo);
                }
                $backdrop[0].offsetWidth; // force reflow
                $backdrop.addClass('in');
            }

            this.$modal.off('close.' + pluginName).on('close.' + pluginName, function() {
                self.close.call(self);
            });
            if (this.options.remote !== undefined && this.options.remote != '' && this.options.remote !== '#') {
                this.$modal.find('.modal-body').load(this.options.remote);
//                this.$modal.find('.modal-body').html(this.options.content);
            } else {
//                this.$modal.find('.modal-body').html(this.options.content);
            	this.$modal.find('.modal-body').load(this.options.remote);
            }

            this.$modal.show().addClass('in');
            return this;
        }

        ,close: function() {
            this.$modal.hide().off('.' + pluginName).find('.inner').html('');
            if (this.options.cssclass !== undefined) {
                this.$modal.removeClass(this.options.cssclass);
            }
            $(document).off('keyup.' + pluginName);
            $('.modal-backdrop').remove();
            if (typeof this.options.onClose === 'function') {
                this.options.onClose.call(this, this.options);
            }
            return this;
        }

        ,destroy: function() {
            this.$modal.remove();
            $(document).off('keyup.' + pluginName);
            $('.modal-backdrop').remove();
            this.$modal = null;
            return this;
        }

        ,escape: function() {
            var self = this;
            $(document).on('keyup.' + pluginName, function(e) {
                if (e.which == 27) {
                    self.close();
                }
            });
        }
    });


    $.fn[pluginName] = function(options) {
        return this.each(function() {
            var obj;
            if (!(obj = $.data(this, pluginName))) {
                var  $this = $(this)
                    ,data = $this.data()
                    ,opts = $.extend({}, options, data)
                    ;
                if ( $this.attr('href') != undefined &&  $this.attr('href') != "undefined" && $this.attr('href') !== '' && $this.attr('href') != '#' && $this.attr('href').indexOf("javascript")==-1) {
                    opts.remote = $this.attr('href');
                }
                obj = new Modal(opts);
                $.data(this, pluginName, obj);
            }
            obj.show();
        });
    };


    $[pluginName] = function(options) {
        return new Modal(options);
    };


    $.fn[pluginName].defaults = {
        title: ' '		// modal title
        ,target: '#modal'	// the modal id. MUST be an id for now.
        ,content: ''		// the static modal content (in case it's not loaded via ajax)
        ,appendTo: 'body'	// where should the modal be appended to (default to document.body). Added for unit tests, not really needed in real life.
        ,cache: false		// should we cache the output of the ajax calls so that next time they're shown from cache?
        ,keyboard: false
        ,nobackdrop: false
    };


    $(document).on('click.' + pluginName, '[data-trigger="modal"]', function() {
        $(this)[pluginName]();
        if ($(this).is('a')) {
            return false;
        }
    }).on('click.' + pluginName, '[data-dismiss="modal"]', function(e) {
        e.preventDefault();
        $("body").removeClass("unoverflow");
        $(this).closest('.modal').trigger('close');
    });

})(jQuery);