/* Author: yangzeming
 * Date: 2013-12-10
 * Desc: 弹窗
 */
define(function (require, exports, module) {
    /**
    * 对话框
    * @class
    * @constructor
    * @param {Object} s 配置项
    * @param {String|HTMLElement|jQuery} s.html 浮层内容
    * @param {Boolean} [s.modal=true] 是否模态窗口
    * @param {Boolean} [s.showTitle=true] 是否显示标题
    * @param {String|Number} [s.width=300] 浮层宽度
    * @param {String|Number} [s.height] 浮层高度, 不指定时为自适应
    * @param {Boolean} [s.fixed] 当浏览器支持position:fix属性时是否使用该属性定位窗口,否则使用absolute
    * @param {String|Number} [s.left] 浮层距离浏览器左侧的位置
    * @param {String|Number} s.[top] 浮层距离浏览器顶部的位置
    * @param {Boolean} [s.show=true] 创建一个浮层后，是否自动显示
    * @param {Boolean} [s.closeable=true] 是否可关闭, 默认为true
    * @param {Boolean} [s.hideOnclose=false] 关闭时是否隐藏窗口
    * @param {Boolean} [s.draggable=true] 是否可拖拽, 默认为true
    * @param {String} [s.contentType] 浮层类型, 如果是"iframe",请指定url, 如果是"dom"，请指定dom
    * @param {Boolean} [s.resizeable=false] 是否可以通过鼠标改变浮层大小
    * @param {String} [s.closeTips] 鼠标停在关闭按钮上时显示的文字, 默认为 "关闭本窗口"
    * @param {String} [s.modalClassName] 浮层类名, 默认为空
    * @param {Boolean} [s.autoCenter=true] 窗口大小改变时，是否保持居中
    * @param {Number} [s.minWidth] 最小宽度, 默认为200, resizeable为true时有效
    * @param {Number} [s.minHeight] 最小高度, 默认为100, resizeable为true时有效
    * @param {Number} [s.maxWidth] 最大宽度, resizeable为true时有效
    * @param {Number} [s.maxHeight] 最大高度, resizeable为true时有效
    *
    * @alias $.dialog
    * @example
    * new $.dialog({
    *     "html" : "this is the first dialog", //内容
    *     "title" : "百度贴吧",  //标题
    *     "draggable" : false,  //不可以拖拽
    *     "closeable" : false  //没有关闭按钮
    * });
    *
    * new $.dialog({
    *     "contentType" : "dom", //内容为dom对象或者jquery dom对象
    *     "title" : "百度贴吧",  //标题
    *     "dom" : domobj  // 指定的dom对象
    * });
    */
    var isIE6 = $.browser.msie && $.browser.version < 7;
    var draggable = require("./draggable");
	var modal = require("./modal");
    var DialogINST = {};
    DialogINST.INST = [];
    var Dialog = _.Class({
        initial: function (options) {
            this._eventStack = {};
            DialogINST.INST.push(this);
            this.options = $.extend(true,{}, DialogINST.setting, options);
            this.$con = $(this.options.template);
            this.$wrapper = this.$con.find('[data-role="wrapper"]');
            this.$title = this.$con.find('[data-role="title"]');
            this.$closeBtn = this.$con.find('[data-role="closeBtn"]');
            this.$titleTxt = this.$con.find('[data-role="titleTxt"]');
            this.$content = this.$con.find('[data-role="content"]');
            if (!this.options.showTitle)
                this.options.draggable = false;
            if (this.options.top != null || this.options.left != null)
                this.options.autoCenter = false;

            var className = 'dialogJ';

            if (!isIE6 && this.options.fixed)
                this.$con.addClass("ui-dialog-fixed");
				
            //if (this.options.showShadow)
            //   this.$con.addClass('ui-dialog-shadow');
            var self = this;
            if (this.options.modal) {
                var cfg = {};
                if (this.options.modalClassName)
                    options.className = this.options.modalClassName;
                this.modal = new $.modal(cfg);
            }
            this.$con.css({ "zIndex": $.getzIndex(), "display": "none" }).appendTo(document.body);
            this._setupTitleBar();
            this.setTitle(this.options.title);
            if (this.options.contentType === 'iframe') {
                this.options.html = $("<iframe allowTransparency=\"true\"></iframe>").css({ width: "100%", height: "99%", "border": "none" }).attr({ "src": this.options.html, "frameBorder": 0 });
            }
            this._setupContent();
            this.setContent(this.options.html); //设置内容区域
            this.width(this.options.width);
            this.height(this.options.height);
            this.setPosition(this.options.left, this.options.top);
            this.options.show && this.show();
            this.options.autoCenter && $(window).bind("resize", _onResize);
            this._setScroll();
            //响应Esc键关闭窗口 已经实现escable配置 by Yao,Xiaoyi
            this.options.escable && this._setupEscKey();
            function _onResize() {
                if (self.dragged) return;
                self.trigger('onresize');
                if (self.sizeTimer) clearTimeout(self.sizeTimer);
                self.sizeTimer = setTimeout(function () {
                    self.setPosition();
                }, 5);
            }
            this.close = function () {
                self.trigger("onclose");

                $(window).unbind("resize", _onResize);
                self.modal && self.modal.remove();
                self.dragobj && self.dragobj.remove();
                self._setScroll(true);
                self.$con.remove();
                for (var i = 0, len = DialogINST.INST.length; i < len; i++) {
                    if (DialogINST.INST[i] == self) {
                        DialogINST.INST.splice(i, 1);
                        break;
                    }
                }

            }

        },
        /**
        * 设置标题
        * @param {String} title 标题
        *
        * @example
        * var obj = new $.dialog({
        *     "html" : "this is the first dialog", //内容
        *     "title" : "i贴吧"  //标题
        * });
        *
        * obj.setTitle("i贴吧");
        */
        setTitle: function (title) {
            this.$titleTxt.html(title || "");
        },
        /**
        * 设置窗口内容
        * @param {String|HTMLElement|jQuery} html 内容
        *
        * @example
        * var obj = new $.dialog({
        *     "html" : "hello world", //内容
        *     "title" : "百度贴吧"  //标题
        * });
        *
        * obj.setContent("hello world");
        */
        setContent: function (html) {
            if (html)
                this.$content.html(html);
        },
        /**
        * 设置/获取宽度
        * @param {String|Number} [width] 宽度
        * @return {Number}
        */
        width: function (width) {
            return this.$con.css("width", width);
        },
        /**
        * 设置/获取高度
        * @param {String|Number} [height] 高度
        * @return {Number}
        */
        height: function (height) {
            return this.$content.css("height", height);
        },
        /**
        * 设置位置
        * @param {Number} left
        * @param {Number} top
        */
        setPosition: function (left, top) {
            if ((left !== 0 & !left) && (top !== 0 && !top)) {
                //居中显示	
                var doc = $(document);
                var win = $(window);
                var o = this.options.fixed && !isIE6 ? [0, 0] : [doc.scrollLeft(), doc.scrollTop()];
                //考虑用户体验，top不能小于0
                left = o[0] + (win.width() - this.$con.outerWidth()) / 2;
                top = o[1] + (win.height() - this.$con.outerHeight()) / 2;
                top = (top >= 0) ? top : 0;
            }
            this.$con.css({ "left": left, "top": top });
            this.trigger('resize');
            /*			if(this.modal && this.modal.cfg.resizeable)
            this.modal && this.modal.triggerHandler('resize', this.modal.resizeFunc);
            */
        },
        /**
        * 获取标题
        * @return {String}
        */
        getTitle: function () {
            return this.$titleTxt.html();
        },
        /**
        * 获取内容
        * @return {String}
        */
        getContent: function () {
            return this.$content.html();
        },
        /**
        * 显示Dialog
        */
        show: function () {
            if (this.options.effect) {
                var ef = this.options.effect;
                var top = this.$con.css("top");
                this.$con.css("top", "0px").show().animate({
                    top: top
                }, ef.speed||500, function () {

                });
            }
            else {
                this.$con.show.apply(this.$con, arguments);
            }
            if (this.modal) {
                this.modal.cfg.safety = this.$con;
                this.modal.show.apply(this.modal, arguments);
            }
        },
        /**
        * 隐藏Dialog
        * @return {Boolean|void} 当隐藏成功时返回true，反之返回false
        */
        hide: function () {
            this.trigger("onhide");

            this.$con.hide.apply(this.$con, arguments);
            if (this.modal)
                this.modal.hide.apply(this.modal, arguments);
        },
        /**
        * 获取该Dialog的DOM对象
        * @return {HTMLElement}
        */
        getElement: function () {
            return this.$con[0];
        },
        /**
        * 获取Dialog中自带的按钮
        * @return {jQuery}
        */
        getButtons: function () {
            return this.buttons;
        },
        _setupTitleBar: function () {
            // 配置标题栏
            if (!this.options.showTitle)
                return;
            var self = this;

            var titleBar = self.$title;
            if (this.options.closeable) {
                self.$closeBtn && self.$closeBtn.attr("title", (this.options.closeTips || '关闭本窗口')).bind('mousedown', function (e) { e.stopPropagation(); }).bind("click",function (evt) {
                    if (self.options.hideOnclose)
                        self.hide();
                    else
                        self.close();
                    return false;
                });
            }
            if (this.options.draggable) {
			console.log(titleBar);
			console.log(titleBar[0]);
                titleBar[0].style.cssText = '-moz-user-select: none;cursor:move';
                var offset = null;

                this.dragobj = new draggable({
                    handle: titleBar,
                    target: self.$con,
                    onDown: function () {

                    },
                    onUp: function () {
                        self.dragged = true; //标记已经进行了拖拽操作            

                    }
                });
            }
        },

        //响应Esc键关闭窗口

        _setupEscKey: function () {
            var self = this;
            var func = function (event) {
                if (event.which == 27) {
                    // if (self.showTitle)
                    self.close();

                }
            };
            $(document).bind('keydown', func);

            $(self.element).bind('onclose', function () {
                $(document).unbind('keydown', func);
            });

        },
        _setupContent: function () {
            var wrap = this.$wrapper, self = this;
            if (this.options.contentScroll) {
                this.$content.css("overflow-y", "auto");
            }
            // @modify by yzm  
            if (this.options.resizeable) {
                var con = this.$content;
                this.options.minWidth = this.options.minWidth || 0;
                this.options.minHeight = this.options.minHeight || 0;
                $.each(['es'], function (k, v) {
                    var ele = $('<div class="resizable-' + v + '"><div></div></div>');
                    ele[0].style.cssText = "-moz-user-select:none;" + (k == 3 ? ("z-index:" + $.getzIndex()) : "");
                    // @modify by yzm
                    self.$wrapper.append(ele);
                    var val_W = null, val_H = null;
                    new draggable({
                        handle: ele,
                        onDown: function (event) {
                            val_W = parseInt(self.$con.width()); val_H = parseInt(con.height());
                        },
                        onMove: function (event, x, y) {
                            var width = val_W + x;
                            var height = val_H + y;
                            if (!((self.options.minWidth && width < self.options.minWidth && x < 0) || (self.options.maxWidth && (width > self.options.maxWidth) && x > 0)))
                                self.$con.width(width);
                            if (!((self.options.minHeight && (height < self.options.minHeight) && y < 0) || ((self.options.maxHeight) && (height > self.options.maxHeight) && y > 0)))
                                con.height(height);
                            var w = self.$con.outerWidth(),
							    h = self.$con.outerHeight();

                            if (self.onResize)
                                self.onResize.call(self, w, h);
                        },
                        onUp: function (event) {
                            self._setupHackDiv(0);
                        }
                    });
                });
            }
        },
        _setScroll: function (isCancel) {
            if (!this.options.modal || this.options.scrollable)
                return;
            var hNode = $('html');

            if (!hNode.length)
                return;

            var val = hNode[0].scrollTop;
            if (isCancel) {
                hNode.css({ 'overflow': this.$con.data('htmlof') || '', 'padding-right': '0px' });
            }
            else {
                if (hNode[0].style.overFlow)
                    this.$con.data('htmlof', hNode[0].style.overFlow);
                hNode.css({ 'overflow': 'hidden', 'padding-right': '17px' });
            }
            hNode[0].scrollTop = val;

        },
        setUnDraggable: function () {
            if (this.options.draggable) {
                this.dragobj.destroy();
            }
            return this;
        }
    });
    // 静态化方法
    $.extend(DialogINST, {
        /**
        * @default 默认配置项
        */
        setting: {
            modal: true, // 是否模态窗口
            showShadow: true, // 是否显示阴影
            showTitle: true, // 是否显示标题
            width: 300,
            height: null, //自适应
            fixed: false, //是否使用fix属性定位窗口
            left: null, //初始显示位置
            top: null,  //初始显示位置
            show: true, //是否自动显示
            closeable: true, //是否可关闭
            hideOnclose: false, //关闭时是否隐藏窗口
            draggable: true, //是否可拖拽
            contentType: null,  //如果是iframe,请指定url
            resizeable: false, //是否可以通过拖拽改变大小
            closeTips: null, //鼠标停在关闭按钮上时显示的文字
            escable: true, //按下Esc键执行close方法
            scrollable: true, //弹出窗口后页面是否可以滚动
            modalClassName: null, //模态窗口类名
            autoCenter: true, //窗口大小改变时，保持居中
            html: null, //内容
            minWidth: 200,
            minHeight: 100,
            contentScroll: true,
            template: '<div class="eui-dialog"><div class="alert_box" ><div class="alert_content" data-role="wrapper"><div class="a_tit" data-role="title"><i class="close_btn" data-role="closeBtn"></i><span data-role="titleTxt"></span></div> <div class="p_l10 p_r10" data-role="content" style="padding: 5px;"></div></div></div></div>',
            maxWidth: null,
            maxHeight: null
        },
        /**
        * 销毁所有页面中的Dialog元素
        */
        close: function () {
            for (var i = 0; i < this.INST.length; i++) {

                var res = this.INST[i].close();
                if (res !== false) {
                    i--;
                }
            }
        }

    });
    module.exports = Dialog;

});