/**
 *************************************************************************************
 * [标题：ExmayUI JQuery Window 插件]<br>
 *************************************************************************************
 * [描述：ExmayUI JQuery Window 插件]<br>
 *************************************************************************************
 * @author Exmay Team / 亿美团队
 *************************************************************************************
 * @version Version 1.0.1 Beta / v1.0.1 测试版
 *************************************************************************************
 */

/*
 * ***********************************************************************************
 * 版权：Copyright © 2012 Exmay Inc. All Rights Reserved. 长沙亿美软件有限公司　版权所有
 * ***********************************************************************************
 * 企业文化：专注　创新　分享　共赢
 * ***********************************************************************************
 * 官方网站：http://www.exmay.com
 * ***********************************************************************************
 * 官方邮箱：service@exmay.com
 * ***********************************************************************************
 */

﻿﻿(function($) {
    
    // 初始化窗口
    function initExmayWindow(target) {
    	var body = null;
    	try{body = top.document.body}catch (err){body = "body"};
    	var $_window = $(".exmayui-window:last", body);
    	if($_window.html() != null) {
    		$.fn.exmayWindow.defaults.zIndex = $_window.css("z-index");
    	}
        var cache = $(target).data("exmayWindow");
		$(target).removeClass("exmayui-window");
        var $panel = $(target).exmayPanel($.extend({},
        cache.options, {
            /*border: false,*/
            doSize: true,
            closed: true,
            cls: "exmayui-window",
            headerCls: "exmayui-window-header",
            bodyCls: "exmayui-window-body",
            
            // 销毁前
            onBeforeDestroy: function() {
                if (cache.options.onBeforeDestroy.call(target) == false) {
                    return false;
                }
                if (cache.shadow) {
                    cache.shadow.remove();
                }
                if (cache.mask) {
                    cache.mask.remove();
                }
            },
            
            // 关闭
            onClose: function() {
                if (cache.shadow) {
                    cache.shadow.hide();
                }
                if (cache.mask) {
                    cache.mask.hide();
                }
                cache.options.onClose.call(target);
            },
            
            // 打开
            onOpen: function() {
                if (cache.mask) {
                    cache.mask.css({
                        display: "block",
                        zIndex: $.fn.exmayWindow.defaults.zIndex++
                    });
                }
                if (cache.shadow) {
                    cache.shadow.css({
                        display: "block",
                        zIndex: $.fn.exmayWindow.defaults.zIndex++,
                        left: cache.options.left,
                        top: cache.options.top,
                        width: cache.exmayWindow.outerWidth(),
                        height: cache.exmayWindow.outerHeight()
                    });
                 	if(cache.options.position){
						 cache.shadow.css({
							position : cache.options.position
						});
					}
                }
                cache.exmayWindow.css("z-index", $.fn.exmayWindow.defaults.zIndex++);
                cache.options.onOpen.call(target);
            },
            
            // 调整大小
            onResize: function(width, height) {
                var opts = $(target).exmayPanel("options");
                cache.options.width = opts.width;
                cache.options.height = opts.height;
                cache.options.left = opts.left;
                cache.options.top = opts.top;
                if (cache.shadow) {
                    cache.shadow.css({
                        left: cache.options.left,
                        top: cache.options.top,
                        width: cache.exmayWindow.outerWidth(),
                        height: cache.exmayWindow.outerHeight()
                    });
                }
                cache.options.onResize.call(target, width, height);
            },
            
            // 最小化
            onMinimize: function() {
                if (cache.shadow) {
                    cache.shadow.hide();
                }
                if (cache.mask) {
                    cache.mask.hide();
                }
                cache.options.onMinimize.call(target);
            },
            
			// 收缩前            
            onBeforeCollapse: function() {
                if (cache.options.onBeforeCollapse.call(target) == false) {
                    return false;
                }
                if (cache.shadow) {
                    cache.shadow.hide();
                }
            },
            
            // 展开
            onExpand: function() {
                if (cache.shadow) {
                    cache.shadow.show();
                }
                cache.options.onExpand.call(target);
            }
        }));
        cache.exmayWindow = $panel.exmayPanel("exmayPanel");
        if (cache.mask) {
            cache.mask.remove();
        }
        
        // 模态窗口
        if (cache.options.modal == true) {
//            cache.mask = $("<div class=\"exmayui-window-mask\"></div>").appendTo("body");
        	var $parent = $(top.document.body);
            cache.mask = $('<div class="exmayui-window-mask"></div>').appendTo($parent);
            cache.mask.css({
                width: getBodySize().width,
                height: getBodySize().height,
                display: "none"
            });
        }
        if (cache.shadow) {
            cache.shadow.remove();
        }
        if (cache.options.shadow == true) {
            cache.shadow = $('<div class="exmayui-window-shadow"></div>').insertAfter(cache.exmayWindow);
            cache.shadow.css({
                display: "none"
            });
        }
        
        
    	// 兼容框架页
        var _window = null;
        var _document = null;
        // 兼容跨域
        try{_window = top.window;_document=top.document}catch (err){_window = window;_document=document};
        if (cache.options.left == null) {
            var _width = cache.options.width;($(_window).width() - _width) / 2
            if (isNaN(_width)) {
                _width = cache.exmayWindow.outerWidth();
            }
        	cache.options.left = ($(_window).width() - _width) / 2;
            if(cache.options.position != "fixed") {
            	cache.options.left = cache.options.left + $(_document).scrollLeft();
            }
        }
        if (cache.options.top == null) {
            var _height = cache.exmayWindow.height;
            if (isNaN(_height)) {
                _height = cache.exmayWindow.outerHeight();
            }
        	cache.options.top = ($(_window).height() - _height) / 2;
            if(cache.options.position != "fixed") {
            	cache.options.top = cache.options.top + $(_document).scrollTop();
            }
        }
		if(cache.options.position){
			cache.exmayWindow.css({
				position : cache.options.position
			});
		}
        moveExmayWindow(target);

        if (cache.options.closed == false) {
            $panel.exmayWindow("open");
        }
    };
    
//    // 设置窗口绝对居中
//    function setWindowAbsoluteCenter(target) {
//    	var cache = $(target).data("exmayWindow");
//    	// 兼容框架页
//        var _window = top.window;
//        var _document = top.document;
//        if (cache.options.left == null) {
//            var _width = cache.options.width;
//            if (isNaN(_width)) {
//                _width = cache.window.outerWidth();
//            }
//            cache.options.left = ($(_window).width() - _width) / 2 + $(_document).scrollLeft();
//        }
//        if (cache.options.top == null) {
//            var _height = cache.window.height;
//            if (isNaN(_height)) {
//                _height = cache.window.outerHeight();
//            }
//            cache.options.top = ($(_window).height() - _height) / 2 + $(_document).scrollTop();
//        }
//        moveExmayWindow(target);
//    }
    
    // 绑定窗口事件
    function bindExmayWindowEvents(target) {
        var cache = $(target).data("exmayWindow");
        
        var $windowProxy = $('<div class="exmayui-window-proxy"><p class="exmayui-window-proxy-bg-logo"></p></div>');
        
        // 初始化窗口拖动
        cache.exmayWindow.exmayDraggable({
            handle: ">div.exmayui-panel-header>div.exmayui-panel-title-middle",
            disabled: cache.options.draggable == false,
            
            // 拖动前
            onStartDrag: function(e) {
                if (cache.mask) {
                    cache.mask.css("z-index", $.fn.exmayWindow.defaults.zIndex++);
                }
                if (cache.shadow) {
                    cache.shadow.css("z-index", $.fn.exmayWindow.defaults.zIndex++);
                }
                cache.exmayWindow.css("z-index", $.fn.exmayWindow.defaults.zIndex++);
                // 代理
                if (!cache.proxy) {
                    cache.proxy = $windowProxy.insertAfter(cache.exmayWindow);
                }
                cache.proxy.css({
                    display: "none",
                    zIndex: $.fn.exmayWindow.defaults.zIndex++,
                    left: e.data.left,
                    top: e.data.top,
                    width: ($.boxModel == true ? (cache.exmayWindow.outerWidth() - (cache.proxy.outerWidth() - cache.proxy.width())) : cache.exmayWindow.outerWidth()),
                    height: ($.boxModel == true ? (cache.exmayWindow.outerHeight() - (cache.proxy.outerHeight() - cache.proxy.height())) : cache.exmayWindow.outerHeight())
                });
                setTimeout(function() {
                    if (cache.proxy) {
                        cache.proxy.show();
                    }
                },
                500);
                // 兼容选择插件
                $(".exmayui-selectable").exmaySelectable({checkbox : true});
            },
            // 拖动中
            onDrag: function(e) {
//                cache.proxy.css({
            	var left = e.data.left;
            	var top = e.data.top;
                $windowProxy.css({
                    display: "block",
                    left: left,
                    top: top
                });
                
                //$("#tip").html(e.data.left + "/" + e.data.top + "/" + cache.window.width() + "/" + cache.window.height());
                
                // 开关控制，不让窗口出父容器，右侧与下侧对overflow=auto,允许滚动条的容器不生效
//                if(left <0) {
//	               	$windowProxy.css({ left: 0 });
//                }
                if(top < 0) {
               		$windowProxy.css({ top: 0 });
                }
//                var width = getBodySize().width;
				var height = getBodySize().height;
//                if(left + cache.window.width() > width) {
//                	$windowProxy.css({ left: width - cache.window.width() });
//                }
                if(top + cache.exmayWindow.height() > height) {
                	$windowProxy.css({ top: height - cache.exmayWindow.height() });
                }
                
                return false;
            },
            // 拖动后
            onStopDrag: function(e) {
                cache.options.left = e.data.left;
                cache.options.top = e.data.top;
                
                // 开关控制，不让窗口出父容器, 右侧与下侧对overflow=auto,允许滚动条的容器不生效
//                if(cache.options.left < 0) {
//                	cache.options.left = 0;
//                }
                if(cache.options.top < 0) {
                	cache.options.top = 0;
                }
//                var width = getBodySize().width;
				var height = getBodySize().height;
//                if(cache.options.left + cache.window.width() > width) {
//                	cache.options.left = width - cache.window.width();;
//                }
                if(cache.options.top + cache.exmayWindow.height() > height) {
                	cache.options.top = height - cache.exmayWindow.height();
                }
                
                $(target).exmayWindow("move");
//                cache.proxy.remove();
                $windowProxy.remove();
                cache.proxy = null;
                
                // 兼容选择插件
                $(".exmayui-selectable").exmaySelectable({checkbox : false});
            }
        });
        
        // 初始化窗口大小设置
        cache.exmayWindow.exmayResizable({
            disabled: cache.options.exmayResizable == false,
            onStartResize: function(e) {
        		// 代理
                if (!cache.proxy) {
                    cache.proxy = $('<div class="exmayui-window-proxy"></div>').insertAfter(cache.exmayWindow);
                }
                cache.proxy.css({
                    zIndex: $.fn.exmayWindow.defaults.zIndex++,
                    left: e.data.left,
                    top: e.data.top,
                    width: ($.boxModel == true ? (e.data.width - (cache.proxy.outerWidth() - cache.proxy.width())) : e.data.width),
                    height: ($.boxModel == true ? (e.data.height - (cache.proxy.outerHeight() - cache.proxy.height())) : e.data.height)
                });
            },
            onResize: function(e) {
                cache.proxy.css({
                    left: e.data.left,
                    top: e.data.top,
                    width: ($.boxModel == true ? (e.data.width - (cache.proxy.outerWidth() - cache.proxy.width())) : e.data.width),
                    height: ($.boxModel == true ? (e.data.height - (cache.proxy.outerHeight() - cache.proxy.height())) : e.data.height)
                });
                return false;
            },
            onStopResize: function(e) {
                cache.options.left = e.data.left;
                cache.options.top = e.data.top;
                cache.options.width = e.data.width;
                cache.options.height = e.data.height;
                resizeExmayWindow(target);
                cache.proxy.remove();
                cache.proxy = null;
            }
        });
        
        // 窗口大小改变时遮罩层大小自动适应
		// 兼容框架页
		var _window = null;
		// 兼容跨域
		try{_window = top.window;}catch (err){_window = window;};
		$(_window).resize(function() {
//			cache.options.left = null;
//			cache.options.top = null;
//			setWindowAbsoluteCenter(target);
			$(".exmayui-window-mask").css( {
				width : $(_window).width(),
				height : $(_window).height()
			});
			setTimeout(function() {
				//setWindowAbsoluteCenter(target);
				$(".exmayui-window-mask").css( {
					width : getBodySize().width,
					height : getBodySize().height
				});
			}, 50);
		});
        
    };
    
    // 获取页面尺寸
    function getBodySize() {
    	// 兼容框架页
    	var _document = null;
		// 兼容跨域
        try{_document=top.document}catch (err){_document=document};

        if (_document.compatMode == "BackCompat") {
            return {
                width: Math.max(_document.body.scrollWidth, _document.body.clientWidth),
                height: Math.max(_document.body.scrollHeight, _document.body.clientHeight)
            };
        } else {
            return {
                width: Math.max(_document.documentElement.scrollWidth, _document.documentElement.clientWidth),
                height: Math.max(_document.documentElement.scrollHeight, _document.documentElement.clientHeight)
            };
        }
    };
    
	// 设置窗口大小
    function resizeExmayWindow(target, data) {
        var opts = $(target).data("exmayWindow").options;
        if (data) {
            if (data.width) {
                opts.width = data.width;
            }
            if (data.height) {
                opts.height = data.height;
            }
            if (data.left != null) {
                opts.left = data.left;
            }
            if (data.top != null) {
                opts.top = data.top;
            }
        }
        $(target).exmayPanel("resize", opts);
    };
    
    // 移动窗口
    function moveExmayWindow(target, data) {
        var cache = $(target).data("exmayWindow");
        var opts = $(target).data("exmayWindow").options;
        if (data) {
 			    
        	if(data == "center"){
        		var size = getBodySize();
        		cache.options.left = (size.width - opts.width)/2;
        		cache.options.top = (size.height - opts.height)/2;
        	}
            if (data.left != null) {
                cache.options.left = data.left;
            }
            if (data.top != null) {
                cache.options.top = data.top;
            }
        }
        $(target).exmayPanel("move", cache.options);
        if (cache.shadow) {
            cache.shadow.css({
                left: cache.options.left,
                top: cache.options.top
            });
        }
    };
    
    // 定义窗口插件
    $.fn.exmayWindow = function(options, data) {
    	
        if (typeof options == "string") {
            var method = $.fn.exmayWindow.methods[options];
            if (method) {
                ////$("#exmay-debug").append("调用 " + options + " 方法 从[窗口]进入");
                return method(this, data);
            } else {
                //$("#exmay-debug").append("调用 " + options + " 方法 从[窗口]进入[面板]");
            	return this.exmayPanel(options, data);
            }
        }
        
        options = options || {};
        
        return this.each(function() {
        	var $this = $(this);
            var cache = $this.data("exmayWindow");
            if (cache) {
                $.extend(cache.options, options);
            } else {
                $this.data("exmayWindow", {
                    options: $.extend({}, $.fn.exmayWindow.defaults, $.fn.exmayWindow.parseOptions(this), options)
                });
	            initExmayWindow(this);
	            bindExmayWindowEvents(this);
            }
        });
    };
	
	// 窗口方法
    $.fn.exmayWindow.methods = {
        options: function(target) {
            var panelOpts = $(target).exmayPanel("options");
            var windowOpts = $(target).data("exmayWindow").options;
            return $.extend(windowOpts, {
                closed: panelOpts.closed,
                collapsed: panelOpts.collapsed,
                minimized: panelOpts.minimized,
                maximized: panelOpts.maximized
            });
        },
        exmayWindow: function(target) {
            return $(target).data("exmayWindow").exmayWindow;
        },
        resize: function(target, data) {
            return target.each(function() {
                resizeExmayWindow(this, data);
            });
        },
        move: function(target, data) {
            return target.each(function() {
                moveExmayWindow(this, data);
            });
        }
    };
	
	// 解析窗口选项
    $.fn.exmayWindow.parseOptions = function(target) {
        var $target = $(target);
        return $.extend({}, $.fn.exmayPanel.parseOptions(target), {
            draggable: ($target.attr("draggable") ? $target.attr("dr$targetgable") == "true": undefined),
            resizable: ($target.attr("resizable") ? $target.attr("resizable") == "true": undefined),
            shadow: ($target.attr("shadow") ? $target.attr("shadow") == "true": undefined),
            modal: ($target.attr("modal") ? $target.attr("modal") == "true": undefined),
            position: $target.attr("position")
        });
    };
	
	// 窗口属性
    $.fn.exmayWindow.defaults = $.extend({}, $.fn.exmayPanel.defaults, {
        zIndex: 9000,
        draggable: true,
        resizable: true,
        shadow: true,
        modal: false,
        title: "新窗口",
		fullScreen: true,
        collapsible: true,
        minimizable: true,
        maximizable: true,
        closable: true,
        closed: false,
        position : null
    });
	
})(jQuery);