﻿/// <reference path="jquery-1.4.1-vsdoc.js" />
/*******************************************************************************
*  @UnitName    : CRWScript.JS                                                 *
*  @Project     :                                                              *
*  @Purpose     :                                                              *
*  @Status      :                                                              *
*  @Copyright   : 陈瑞玮                                                       *
*  @LastUpdate  : 2011/04/12 19:6 by CRW                                       *
*  @Comment     :                                                              *
*  @Description :                                                              *
*  @History     :                                                              *
*******************************************************************************/

//变量声明
var const_DivName_Waitting = "Div_Waitting_Content";
var const_DivName_Background = "Div_CRWBackground";
var const_zIndexBase = 10;

//***************************************************************************************************************************************************
//按ID取对象
//function $(obj) {
//    return typeof (obj) == "object" ? obj : document.getElementById(obj);
//}

//按字节获取对象长度
String.prototype.getsize = function () {
    var i = 0,
    bL = 0,
    sLen = this.length;
    while (i < sLen) bL += this.charCodeAt(i++) > 127 ? 2 : 1;
    return bL;
}

//按字节截取
String.prototype.sliceByByte = function (len) {
    var i = 0,
    bL = 0,
    sLen = this.length;
    while (bL < len && i < sLen) bL += this.charCodeAt(i++) > 127 ? 2 : 1;
    return this.slice(0, bL > len ? (i - 1) : i);
}
String.prototype.trim = function () {
    return $.trim(this);
}
//***************************************************************************************************************************************************
CRWPublic = {
    IsObject: function (obj) {
        return obj != null && typeof (obj) != 'undefined';
    },
    //删除对象
    Free: function (obj) {
        var array = $(obj);
        array.remove();
        array.empty();
    },
    GetEvent: function () {
        if (document.all) return window.event;
        func = CRWPublic.GetEvent.caller;
        while (func != null) {
            var arg0 = func.arguments[0];
            if (arg0) {
                if ((arg0.constructor == Event || arg0.constructor == MouseEvent) || (typeof (arg0) == "object" && arg0.preventDefault && arg0.stopPropagation)) {
                    return arg0;
                }
            }
            func = func.caller;
        }
        return null;
    },
    //截断消息，不向上传递
    DropEvent: function (event) {
        e = event ? event : CRWPublic.GetEvent();
        if (e) {
            try {
                try {
                    e.returnValue = false;
                    e.cancelBubble = true;
                }
                finally {
                    e.stopPropagation();
                    e.preventDefault();
                }
            }
            catch (ex) { }
        }
    },
    //获取Url参数
    GetUrlParam: function (name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
        var r = window.location.search.substr(1).match(reg);
        if (r != null) return unescape(r[2]);
        return null;
    },
    //获取页面实际大小 
    GetPageSize: function () {
        var pageWidth = $(document).width(); //document.body.scrollWidth > document.documentElement.scrollWidth ? document.body.scrollWidth : document.documentElement.scrollWidth;
        var pageHeight = $(document).height(); //document.body.scrollHeight > document.documentElement.scrollHeight ? document.body.scrollHeight : document.documentElement.scrollHeight;

        var windowWidth = $(window).width();
        var windowHeight = $(window).height();
        //        var obj = document.createElement("div");
        //        obj.style.position = "absolute";
        //        document.body.appendChild(obj);
        //        obj.style.top = "50%";
        //        obj.style.left = "50%";
        //        windowWidth = (obj.offsetLeft * 2) - 1;
        //        windowHeight = (obj.offsetTop * 2) - 1;
        //        document.body.removeChild(obj);
        //        obj = null;

        pageWidth = pageWidth > windowWidth ? pageWidth : windowWidth;
        pageHeight = pageHeight > windowHeight ? pageHeight : windowHeight;

        var scrollTop = document.body.scrollTop > document.documentElement.scrollTop ? document.body.scrollTop : document.documentElement.scrollTop;
        var scrollLeft = document.body.scrollLeft > document.documentElement.scrollLeft ? document.body.scrollLeft : document.documentElement.scrollLeft;
        return {
            pageWidth: pageWidth,
            pageHeight: pageHeight,
            windowWidth: windowWidth,
            windowHeight: windowHeight,
            scrollTop: scrollTop,
            scrollLeft: scrollLeft
        };
    },
    AddFavorite: function () {
        var url = window.location.href;
        try {
            window.external.addFavorite(url, document.title);
        } catch (e) {
            try {
                window.sidebar.addPanel(document.title, url, "");
            } catch (e) {
                alert("加入收藏操作被浏览器拒绝，请手动进行添加。");
            }
        }
        return false;
    },
    SetHomePage: function (obj) {
        var url = window.location.href;
        if (document.all) {
            obj.style.behavior = 'url(#default#homepage)';
            obj.setHomePage(url);
            obj.style.behavior = '';
        } else if (window.sidebar) {
            if (window.netscape) {
                try {
                    netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
                } catch (e) {
                    alert("该操作被浏览器拒绝，如果想启用该功能，请在地址栏内输入 about:config,然后将项 signed.applets.codebase_principal_support 值该为true");
                }
            }
            var prefs = Components.classes['@mozilla.org/preferences-service;1'].getService(Components.interfaces.nsIPrefBranch);
            prefs.setCharPref('browser.startup.homepage', url);
        }
    },
    EnterFocusControl: function (obj) {
        evt = CRWPublic.GetEvent();
        keyCode = evt.keyCode ? evt.keyCode : (evt.which ? evt.which : evt.charCode);
        if (keyCode == 13) {
            CRWPublic.DropEvent(evt);
            $(obj).focus();
        }
    },
    //    GetElementByClassName: function (obj, classname) {
    //        obj = $(obj);
    //        for (var i = 0; i < obj.childNodes.length; i++) if (obj.childNodes[i].className == classname) return obj.childNodes[i];
    //        return null;
    //    },
    OpenWindow: function (url, name, width, height) {
        var top = (window.screen.availHeight - 30 - height) / 2;
        var left = (window.screen.availWidth - 10 - width) / 2;
        return window.open(url, name, "width=" + width + ",height=" + height + ",top=" + top + ",left=" + left + ",toolbar=no, menubar=no, scrollbars=yes, resizable=no, location=no, status=no");
    },
    addEventListener: function (object, eventName, func) {
        object.addEventListener(eventName, func, false);
    },
    WaitForObject: function (object, func) {
        var timer = setInterval(function () {
            if ($(object).length == 0) {
                clearInterval(timer);
                func();
            }
        }, 1);
    }
}
//***************************************************************************************************************************************************
CRWDivControler = {
    //设置对象的透明度(Opacity)值
    SetOpacity: function (obj, value) {
        obj = $(obj).fadeTo("normal", value / 100);
        //        try {
        //            obj.style.filter = "Alpha(opacity=" + value + ")";
        //        } finally {
        //            try {
        //                obj.style.MozOpacity = value / 100;
        //            } finally {
        //                try {
        //                    obj.style.KhtmlOpacity = value / 100;
        //                } finally {
        //                    try {
        //                        obj.style.opacity = value / 100
        //                    } finally { }
        //                }
        //            }
        //        }
    },
    //设置对象大小为全页
    SetFullPage: function (obj, resizeWidth, resizeHeight) {
        if (!CRWPublic.IsObject(resizeWidth)) resizeWidth = 0;
        if (!CRWPublic.IsObject(resizeHeight)) resizeHeight = 0;
        var pagesize = CRWPublic.GetPageSize();
        obj.style.top = "0px";
        obj.style.left = "0px";
        obj.style.width = pagesize.pageWidth + resizeWidth + "px";
        obj.style.height = pagesize.pageHeight + resizeHeight + "px";
    },
    //设置对象到屏幕居中
    SetScreenCenter: function (obj) {
        var pagesize = CRWPublic.GetPageSize();
        //obj.parentNode.removeChild(obj);
        //document.body.appendChild(obj);
        obj.style.position = "absolute";
        obj.style.top = pagesize.scrollTop + Math.max((pagesize.windowHeight - obj.clientHeight) / 2, 0) + "px";
        obj.style.left = pagesize.scrollLeft + Math.max((pagesize.windowWidth - obj.clientWidth) / 2, 0) + "px";
    },
    //显示对象
    ShowObject: function (obj, setCenter, zIndex) {
        if (!CRWPublic.IsObject(setCenter)) setCenter = true;
        if (!CRWPublic.IsObject(zIndex)) zIndex = const_zIndexBase + 1;
        obj.style.zIndex = zIndex;
        $(obj).fadeIn();
        if (setCenter) CRWDivControler.SetScreenCenter(obj);
    },
    //隐藏对象
    HideObject: function (obj) {
        $(obj).fadeOut();
    },
    //显示背景
    ShowBackground: function (zIndex, parent) {
        if (!CRWPublic.IsObject(zIndex)) zIndex = const_zIndexBase;
        if (!CRWPublic.IsObject(parent)) parent = document.body;
        var bgDiv = $("#" + const_DivName_Background);
        if (bgDiv.length == 0) {
            bgDiv = document.createElement("div");
            bgDiv.id = const_DivName_Background;
            bgDiv.style.position = "absolute";
            bgDiv.style.background = "#000000";
            CRWDivControler.SetOpacity(bgDiv, 10);
            parent.appendChild(bgDiv);
        } else bgDiv = bgDiv[0];
        bgDiv.style.zIndex = zIndex;
        CRWDivControler.SetFullPage(bgDiv);
    },
    //隐藏背景
    HideBackground: function () {
        CRWPublic.Free("#" + const_DivName_Background);
    },
    ShowWaitting: function () {
        CRWDivControler.ShowBackground();
        var contentDiv = $("#" + const_DivName_Waitting);
        if (contentDiv.length == 0) {
            contentDiv = document.createElement("div");
            contentDiv.id = const_DivName_Waitting;
            contentDiv.style.width = "200px";
            contentDiv.style.height = "100px";
            contentDiv.style.display = "none";
            contentDiv.innerHTML = "<center><img src=\"/Images/loading.gif\" /><br /><br />正在操作中，请稍侯……</center>";
            document.body.appendChild(contentDiv);
        } else contentDiv = contentDiv[0];
        CRWDivControler.ShowObject(contentDiv);
    },
    HideWaitting: function () {
        CRWPublic.Free("#" + const_DivName_Waitting);
        CRWDivControler.HideBackground();
    },
    DragBind: function (handle, target) {
        var moveable = false;
        handle.onmousedown = function () {
            e = CRWPublic.GetEvent();
            x0 = e.clientX;
            y0 = e.clientY;
            x1 = parseInt(target.offsetLeft);
            y1 = parseInt(target.offsetTop);
            moveable = true;
            document.body.onmousemove = function () {
                if (moveable) {
                    window.getSelection ? window.getSelection().removeAllRanges() : document.selection.empty();
                    e = CRWPublic.GetEvent();
                    target.style.left = (x1 + e.clientX - x0) + "px";
                    target.style.top = (y1 + e.clientY - y0) + "px";
                }
            }
            document.body.onmouseup = function () {
                if (moveable) {
                    moveable = false;
                    document.body.onmousemove = null;
                    document.body.onmouseup = null;
                }
            }
        };
    },
    message_Div: null,
    message_CallBackFunc: null,
    message_activeElement: null,
    ShowMessage: function (message, icontype, autohide, callbackfunc, hidetime) {
        if (!CRWPublic.IsObject(arguments[1])) icontype = 0;
        if (!CRWPublic.IsObject(arguments[2])) autohide = false;
        if (!CRWPublic.IsObject(arguments[3])) callbackfunc = null;
        if (!CRWPublic.IsObject(arguments[4])) hidetime = 1500;
        CRWDivControler.ShowBackground();
        if (CRWDivControler.message_Div == null) {
            CRWDivControler.message_Div = document.createElement("div");
            CRWDivControler.message_Div.id = 'information-box';
            CRWDivControler.message_Div.style.display = "none";
            document.body.appendChild(CRWDivControler.message_Div);
        }
        CRWDivControler.message_CallBackFunc = callbackfunc;
        CRWDivControler.message_Div.innerHTML = '<div class="header">提示</div><div class="content"></div><div class="buttonbar"><input type="button" value="确定" onclick="this.disabled=true;CRWDivControler.HideMessage();"/></div>';
        var iconaddress;
        switch (icontype) {
            case 1:
                iconaddress = "/Images/icon-success.png";
                break;
            case 2:
                iconaddress = "/Images/icon-error.png";
                break;
            default:
                iconaddress = "/Images/icon-info.png";
                break;
        }
        var fDivs = CRWDivControler.message_Div.getElementsByTagName("div");
        var confirmButton = null;
        for (var i = 0; i < fDivs.length; i++) {
            if (fDivs[i].className == "header") {
                CRWDivControler.DragBind(fDivs[i], CRWDivControler.message_Div);
            } else if (fDivs[i].className == "content") {
                fDivs[i].innerHTML = '<table><tr><td class="td-img" valign="top"><img src="' + iconaddress + '"/></td><td valign="top">' + message + '</td></tr></table>';
            } else if (fDivs[i].className == "buttonbar") {
                if (autohide) fDivs[i].innerHTML = "";
                else confirmButton = fDivs[i].childNodes[0];
            }
        }
        CRWDivControler.ShowObject(CRWDivControler.message_Div);
        this.message_activeElement = document.activeElement;
        if (confirmButton) {
            confirmButton.focus(); //按钮获取焦点
        }
        if (autohide) {
            setTimeout(function () {
                CRWDivControler.HideMessage();
            },
            hidetime);
        }
    },
    HideMessage: function () {
        $(CRWDivControler.message_Div).fadeOut("normal", function () {
            CRWPublic.Free(CRWDivControler.message_Div);
            CRWDivControler.message_Div = null;
            CRWDivControler.HideBackground();
            $(CRWDivControler.message_activeElement).focus();
            if (CRWDivControler.message_CallBackFunc) {
                eval(CRWDivControler.message_CallBackFunc);
                CRWDivControler.message_CallBackFunc = null;
            }
        });
    }
}
//***************************************************************************************************************************************************
CRWAjax = {
    //Ajax处理
    Post: function (url, data, callbackFunc, async) //url:指定页面;data:POST的数据;callbackFunc:回调函数;needwait:是否显示等待界面
    {
        if (!CRWPublic.IsObject(arguments[2])) callbackFunc = null;
        if (!CRWPublic.IsObject(arguments[3])) async = false;
        if (!async) CRWDivControler.ShowWaitting();
        $.ajax({
            type: "post",
            async: async,
            url: url,
            data: data,
            success: function (content) { if (!async) CRWDivControler.HideWaitting(); if (callbackFunc) callbackFunc(content); },
            error: function (XMLHttpRequest, textStatus, errorThrown) { if (!async) CRWDivControler.HideWaitting(); CRWDivControler.ShowMessage("操作失败，请重试。", 2); }
        });
        /*var xmlHttpRequest = null;
        //创建XMLHttp请求对象
        try {
        xmlHttpRequest = new XMLHttpRequest();
        } catch (e) {
        try {
        xmlHttpRequest = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
        try {
        xmlHttpRequest = new ActiveXObject("Microsoft.XMLHTTP");
        } catch (e) {
        alert("您的浏览器不支持XMLHTTP操作。本次操作失败！")
        }
        }
        }
        //判断是否显示等待界面
        if (showwait) CRWDivControler.ShowWaitting();
        xmlHttpRequest.onreadystatechange = function () {
        switch (xmlHttpRequest.readyState) {
        case 0:
        //(未初始化)： (xmlHttpRequest)对象已经创建，但还没有调用open()方法。
        {
        break;
        }
        case 1:
        //(载入)：已经调用open() 方法，但尚未发送请求。
        {
        break;
        }
        case 2:
        //(载入完成)： 请求已经发送完成。
        {
        break;
        }
        case 3:
        //(交互)：可以接收到部分响应数据。
        {
        break;
        }
        case 4:
        //(完成)：已经接收到了全部数据，并且连接已经关闭。
        {
        if (showwait) CRWDivControler.HideWaitting();
        if (xmlHttpRequest.status == 200) {
        if (callbackFunc) callbackFunc(xmlHttpRequest.responseText);
        } else {
        //alert("操作失败，请重试。");
        }
        break;
        }
        }
        }
        xmlHttpRequest.open("post", url, true);
        xmlHttpRequest.setRequestHeader("content-length", data.length);
        xmlHttpRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        xmlHttpRequest.send(data);*/
    }
}
//***************************************************************************************************************************************************

