/*
* SimpleModal 1.2.3 - jQuery Plugin
* http://www.ericmmartin.com/projects/simplemodal/
* Copyright (c) 2009 Eric Martin
* Dual licensed under the MIT and GPL licenses
* Revision: $Id: jquery.simplemodal.js 185 2009-02-09 21:51:12Z emartin24 $
*/
(function($) {
    var ie6 = $.browser.msie && parseInt($.browser.version) == 6 && typeof window['XMLHttpRequest'] != "object",
    ieQuirks = null,
    w = [];
    $.modal = function(data, options) {
        return $.modal.impl.init(data, options);
    };
    $.modal.close = function(method) {
        $.modal.impl.close(method);
    };
    $.fn.modal = function(options) {
        return $.modal.impl.init(this, options);
    };
    $.modal.defaults = {
        opacity: 60,
        overlayId: 'modalOverlay',
        overlayCss: {},
        title: 'apis networks',
        containerId: 'modalContainer',
        dataCss: {},
        zIndex: 100,
        containerCss: {},
        close: true,
        position: ['15%', null],
        closeTitle: 'X',
        closeHTML: '<a href="#" id="modalClose" class="modalClose">X</a>',
        closeClass: 'modalClose',
        persist: false,
        onOpen: null,
		full: false,
		underlayBorder: '10px',
        onShow: function() {
            $(document).keydown(function(e) {
                if (e.which == 27) {
					
                    // ESC
                    $.modal.close();
                }
            });
        },
		width: null,
        onClose: null
    };
    $.modal.impl = {
        opts: null,
        dialog: {},
        init: function(data, options) {
            if (this.dialog.data) {
                return false;
            }
            ieQuirks = $.browser.msie && !$.boxModel;
            this.opts = $.extend({},
            $.modal.defaults, options);
            this.zIndex = this.opts.zIndex;
            this.occb = false;
            if (typeof data == 'object') {
                data = data instanceof jQuery ? data: $(data);
                if (data.parent().parent().size() > 0) {
                    this.dialog.parentNode = data.parent();
                    if (!this.opts.persist) {
                        this.dialog.orig = data.clone(true);
                    }
                }
            }
            else if (typeof data == 'string' || typeof data == 'number') {
                data = $('<div/>').html(data);
            }
            else {
                alert('SimpleModal Error: Unsupported data type: ' + typeof data);
                return false;
            }
            this.dialog.data = data.addClass('simplemodal-data').css(this.opts.dataCss);
            data = null;
            this.create();
            this.open();
			
			// Center it 
			var offset = $('#modalMsg').position();
			var h = $('#modalContainer').height()-offset.top;
			var y = (h - $('#modalMsg').height())/2;
			//$('div#modalMsg').css('top',Math.floor(y) + 'px');
            if ($.isFunction(this.opts.onShow)) {
                this.opts.onShow.apply(this, [this.dialog]);
            }
			if (jQuery.ui != undefined && jQuery.ui.draggable != undefined)
			 this.dialog.container.draggable({handle: 'h1'}).addClass('modal-resizable');
            return this;
        },
        create: function() {
            w = this.getDimensions();
			this.dialog.msg = $('<div id="modalMsg" />');
			var $modalFix;
            if (ie6) {
                this.dialog.iframe = $('<iframe src="javascript:false;"/>').css($.extend(this.opts.iframeCss, {
                    display: 'none',
                    opacity: 0,
                    position: 'fixed',
                    height: w[0],
                    width: w[1],
                    zIndex: this.opts.zIndex,
                    top: 0,
                    left: 0
                })).appendTo('body');
            }

            this.dialog.container = $('<div id="modalPosFix">').css({
				display: 'none',
				position: 'fixed',
				zIndex: this.opts.zIndex + 2
			});
			
			if (this.opts.width) this.dialog.container.css('width',this.opts.width);

            this.dialog.overlay = $('<div/>').attr('id', this.opts.overlayId).addClass('simplemodal-overlay').
				css($.extend(this.opts.overlayCss, {
					opacity: this.opts.opacity/100, 
					zIndex: this.opts.zIndex +1, 
					display:'none'
				}));
			var $modalFix = $('<div id="modalFrame" />');
			var $container = $('<div />').attr('id', this.opts.containerId).
				addClass('simplemodal-container').
				css(this.opts.containerCss).css('zIndex', this.opts.zIndex+3).
				append(this.opts.title ? $('<h1>' + this.opts.title + '</h1>') : '').
				append(this.opts.close ? $(this.opts.closeHTML).addClass(this.opts.closeClass) : '').
				append(this.dialog.msg).appendTo($modalFix);
				
			if (this.opts.full)
				this.dialog.overlay.
				css({
					height: w[0],
					width: w[1],
					position: 'fixed',
					left: 0,
					top: 0
				}).appendTo('body');
			else {
				this.dialog.overlay.css({
					bottom:'-' + this.opts.underlayBorder,
					top:'-' + this.opts.underlayBorder,
					left:'-' + this.opts.underlayBorder,
					right:'-' + this.opts.underlayBorder,
					height:'auto',
					width:'auto',
					overflow:'visible',
					position:'absolute'				
				}).prependTo($modalFix);
				
				if (ie6 || ieQuirks) {
					this.dialog.overlay.css({top: 0, bottom: 0, height: '100%'});
					this.dialog.overlayTop = this.dialog.overlay.clone().css(
						{
							height: this.opts.underlayBorder, 
							width: '100%',
							position: 'absolute',
							display: 'block',
							top:'-' + this.opts.underlayBorder,
							overflowY:'hidden',
							bottom: null
						});
					this.dialog.overlayTop.prependTo($modalFix);
					this.dialog.overlayBottom = 
						this.dialog.overlayTop.clone().css(
						{
							clear:'both',
							padding:0, margin:0,
							bottom:this.opts.underlayBorder,
							height: this.opts.underlayBorder,
							top:null,
							overflowY:'hidden',
							position: 'absolute'
						}).css('bottom',null).appendTo($modalFix);
					var overlay = this.dialog.overlay;
		            this.dialog.container.resize(function() { overlay.height($container.outerHeight()); });
					//$modalFix.resize(function() { overlay.height($container.outerHeight()); });
				}
			}
			this.dialog.container.append($modalFix).appendTo('body');
			this.setPosition();
            this.dialog.msg.append(this.dialog.data);//.after($('<div class="clear">&nbsp;</div>'));
			if (ie6 || ieQuirks) {
				if (!this.opts.full) overlay.height(this.dialog.container.outerHeight());
				this.fixIE();
            }
        },

        bindEvents: function() {
            var self = this;
            $('.' + this.opts.closeClass).bind('click.simplemodal', function(e) {
                e.preventDefault();
                self.close();
            });
			if (!this.opts.full) return false;
            $(window).bind('resize.simplemodal', function() {
                w = self.getDimensions();
                self.setPosition();
                if (ie6 || ieQuirks) {
                    self.fixIE();
                }
                else {
                    self.dialog.iframe && self.dialog.iframe.css({
                        height: w[0],
                        width: w[1]
                    });
                    self.dialog.overlay.css({
                        height: w[0],
                        width: w[1]
                    });
                }
            });
        },
        unbindEvents: function() {
            $('.' + this.opts.closeClass).unbind('click.simplemodal');
            $(window).unbind('resize.simplemodal');
        },
        fixIE: function() {
            var p = this.opts.position;
			if (!this.opts.full) {
				// fix underlay
				//alert(this.dialog.container.height());
				var width = 2*parseInt(this.opts.underlayBorder) + this.dialog.container.width() + 'px';
				this.dialog.overlay.width(width);
				this.dialog.overlayTop.width(width);
				this.dialog.overlayBottom.width(width);
				this.dialog.overlay.css({
					overflow: 'visible', bottom: 0, top: 0
				});
				//this.dialog.overlay.height(2*parseInt(this.opts.underlayBorder) + this.dialog.container.height() + 'px');
			}
            $.each([this.dialog.iframe || null, this.dialog.overlay, this.dialog.container], function(i, el) {
                if (el) {
                    var bch = 'document.body.clientHeight',
                    bcw = 'document.body.clientWidth',
                    bsh = 'document.body.scrollHeight',
                    bsl = 'document.body.scrollLeft',
                    bst = 'document.body.scrollTop',
                    bsw = 'document.body.scrollWidth',
                    ch = 'document.documentElement.clientHeight',
                    cw = 'document.documentElement.clientWidth',
                    sl = 'document.documentElement.scrollLeft',
                    st = 'document.documentElement.scrollTop',
                    s = el[0].style;
                    s.position = 'absolute';
                    if (i < 2) {
                        s.removeExpression('height');
                        s.removeExpression('width');
                        if (0) {
                            s.setExpression('height', '' + bsh + ' > ' + bch + ' ? ' + bsh + ' : ' + bch + ' + " px"');
                            s.setExpression('width', '' + bsw + ' > ' + bcw + ' ? ' + bsw + ' : ' + bcw + ' + " px"');
                        }
                    }
                    else {
                        var te, le;
                        if (p && p.constructor == Array) {
                            var top = p[0] ? typeof p[0] == 'number' ? p[0].toString() : p[0].replace(/px/, '') : el.css('top').replace(/px/, '');
                            te = top.indexOf('%') == -1 ? top + ' + (t = ' + st + ' ? ' + st + ' : ' + bst + ') + "px"': parseInt(top.replace(/%/, '')) + ' * ((' + ch + ' || ' + bch + ') / 100) + (t = ' + st + ' ? ' + st + ' : ' + bst + ') + "px"';
                            if (p[1]) {
                                var left = typeof p[1] == 'number' ? p[1].toString() : p[1].replace(/px/, '');
                                le = left.indexOf('%') == -1 ? left + ' + (t = ' + sl + ' ? ' + sl + ' : ' + bsl + ') + "px"': parseInt(left.replace(/%/, '')) + ' * ((' + cw + ' || ' + bcw + ') / 100) + (t = ' + sl + ' ? ' + sl + ' : ' + bsl + ') + "px"';
                            }
                        } else {
                            te = '(' + ch + ' || ' + bch + ') / 2 - (this.offsetHeight / 2) + (t = ' + st + ' ? ' + st + ' : ' + bst + ') + "px"';
                            le = '(' + cw + ' || ' + bcw + ') / 2 - (this.offsetWidth / 2) + (t = ' + sl + ' ? ' + sl + ' : ' + bsl + ') + "px"';
                        }
                        s.removeExpression('top');
                        s.removeExpression('left');
                        s.setExpression('top', te);
                        s.setExpression('left', le);
                    }
                }
            });
        },
        getDimensions: function() {
            var el = $(window);
            var h = $.browser.opera && $.browser.version > '9.5' && $.fn.jquery <= '1.2.6' ? document.documentElement['clientHeight'] : el.height();
            return [h, el.width()];
        },
        setPosition: function() {
            var top, left, hCenter = (w[0] / 2) - ((this.dialog.container.height() || this.dialog.data.height()) / 2),
            vCenter = (w[1] / 2) - ((this.dialog.container.width() || this.dialog.data.width()) / 2);
            if (this.opts.position && this.opts.position.constructor == Array) {
                top = this.opts.position[0] || hCenter;
                left = this.opts.position[1] || vCenter;
            } else {
                top = hCenter;
                left = vCenter;
            }
            this.dialog.container.css({
                left: left,
                top: top
            });
        },
        open: function() {
            this.dialog.iframe && this.dialog.iframe.show();
            if ($.isFunction(this.opts.onOpen)) {
                this.opts.onOpen.apply(this, [this.dialog]);
            } else {
                this.dialog.overlay.show();
                this.dialog.container.show();
                this.dialog.data.show();
            }
            this.bindEvents();
			if (!this.opts.full && (ie6 || ieQuirks)) this.dialog.container.triggerHandler('resize');
        },
        close: function(method) {
            if (!this.dialog.data) {
                return false;
            }
            if ($.isFunction(this.opts.onClose) && !this.occb) {
                this.occb = true;
                this.opts.onClose.apply(this, [this.dialog]);
            } else {
                if (this.dialog.parentNode) {
                    if (this.opts.persist) {
                        this.dialog.data.hide().appendTo(this.dialog.parentNode);
                    } else {
                        this.dialog.data.remove();
                        this.dialog.orig.appendTo(this.dialog.parentNode);
                    }
                } else {
                    this.dialog.data.remove();
                }
				if (method) $.fn[method].apply(this.dialog.container);
				else this.dialog.container.remove();
                this.dialog.overlay.remove();
                this.dialog.iframe && this.dialog.iframe.remove();
                this.dialog = {};
            }
            this.unbindEvents();
        }
    };
})(jQuery);
