﻿// ************************************************************************
// 文件名: loader.js
// 版 权: Copyright @ 2009 广联达软件
// 作 者: Yangzh
// 日 期: 2009年12月01日
// 功 能: 动态加载javascript，css文件
// 描 述: 在html中引用loader.js引用,其它js及css将由此模块根据需要动态加载
// ************************************************************************

var oLoadingMsg = null;
var ReadyFiles = null;
var JS_PATH = null;


function using(filename, hint, isAsync) {
    // / <summary>引入文件javascript和style文件</summary>
    // / <param name="filename" type="String">.js或.css文件的url地址</param>
    // / <param name="hint" type="String">文件加载时的提示文本</param>

    if (!ReadyFiles) {
        ReadyFiles = new Array()
    }

    if (filename.toString().substring(0, 1) != '/') {
        filename = JS_PATH ? JS_PATH + filename : filename; // JS_PATH功能模块按不同文件夹分类时，请指定默认加载目录，不指定时表示从页面当前路径加载
    }

    if (ReadyFiles.toString().indexOf(filename.toLowerCase()) != -1) {
        return;
    }

    showLoading(filename, hint);
    if (filename.toLowerCase().indexOf('.js') != -1) {
        if (!isAsync) {
            loadScript(filename, ajaxQuery(filename), true);
        } else {
            asyncLoading(filename, hint)
        }
    } else if (filename.toLowerCase().indexOf('.css') != -1) {
        loadStyle(filename);
    }
    hiddenLoading();
    ReadyFiles.push(filename.toLowerCase());
}

function loadScript(filename, source, defer) {
    if (source) {
        var oHead = document.getElementsByTagName('HEAD').item(0);
        if (filename.toLowerCase().indexOf('.js') != -1) {
            var oScript = document.createElement('script');
            oScript.language = 'javascript';
            oScript.type = 'text/javascript';
            oScript.defer = defer;
            oScript.text = source;
            oHead.appendChild(oScript);
        }
    }
}
function loadStyle(filename) {
    // / <summary>动态加载样式</summary>
    // / <param name="filename" type="String">css文件名，此处为url地址</param>
    var oHead = document.getElementsByTagName('HEAD').item(0);
    var oStyle = document.createElement('link');
    oStyle.setAttribute("rel", "stylesheet");
    oStyle.setAttribute("type", "text/css");
    oStyle.setAttribute("href", filename);
    oHead.appendChild(oStyle);
}

function ajaxQuery(url, isDisableCache) {
    // / <summary>异步获取数据</summary>
    // / <param name="url" type="String">数据所在的url地址</param>
    // / <param name="isAllowCache" type="Boolean">是否允许使用缓存</param>

    if (isDisableCache) {
        var date = new Date();
        url += (url.indexOf("?") != -1 ? "&" : "?") + "_timeStamp=" + date;
    }
    var oXmlHttp = getHttpRequest();
    oXmlHttp.open('GET', url, false);
    oXmlHttp.send(null);
    var data = oXmlHttp.responseText;
    oXmlHttp = null;
    if (data.indexOf("{success") == 0) {
        // 返回值:json
        return eval('(' + data + ')');
    } else {
        // 返回普通String
        return data;
    }
}

function asyncLoading(url, msg) {
    var oXmlHttp = getHttpRequest();
    oXmlHttp.onreadystatechange = function () {
        switch (oXmlHttp.readyState) {
            case 4:
                if (oXmlHttp.status == 200) {
                    loadScript(url, oXmlHttp.responseText, false);
                    hiddenLoading();
                } else {
                    hiddenLoading();
                }
                break;
            case 1:
                showLoading(url, msg);
                break;
        }
    };
    oXmlHttp.open('GET', url, true);
    oXmlHttp.send(null);
}

function showLoading(url) {

}

function getHttpRequest() {
    if (window.XMLHttpRequest)
        return new XMLHttpRequest();
    else if (window.ActiveXObject)
        return new ActiveXObject('MsXml2.XmlHttp');
}

function _$(id, top) {
    // / <summary>获取DOM对象</summary>
    // / <param name="id" type="String">id</param>
    // / <param name="top" type="String">iframe时,是否从顶级document中查找</param>
    top = top ? top : "";
    if (typeof (id) == "object")
        return id;
    if (document.getElementById) {
        return eval(top + 'document.getElementById("' + id + '")');
    } else if (document.layers) {
        return eval(top + "document.layers['" + id + "']");
    } else {
        return eval(top + 'document.all.' + id);
    }
}

function showLoading(filename, hint) {
    // / <summary>显示加载信息</summary>
    // / <param name="filename" type="String">.js或.css文件的url地址</param>
    // / <param name="hint" type="String">文件加载时的提示文本</param>
    if (!oLoadingMsg)
        return;

    oLoadingMsg = _$('loadingStatus');
    oLoadingMsg.style.display = '';
    oLoadingMsg.innerHTML = hint;
}

function hiddenLoading() {
    // / <summary>隐藏加载信息</summary>
    if (!oLoadingMsg)
        return;
    oLoadingMsg.style.display = 'none';
}

var IsReady_Extjs = false;
function InitExtjs(isAsync) {
    // / <summary>载入Extjs库</summary>

    if (IsReady_Extjs)
        return;
    var path = '/sdk/ext3.1/';
    using(path + 'resources/css/ext.css', '正在加载样式 ...');
    //using(path + 'resources/css/ext-patch.css', '正在加载基础样式补丁 ...');
    using(path + 'adapter/ext/ext-base.js', '正在加载核心库 ...', isAsync);
    using(path + 'ext.js', '正在加载Ext库...', isAsync);
    //using(path + 'ext-lang-zh_CN.js', '正在加载中文支持...',isAsync);
    //using('/js/Ext_Patch.js', '正在加载Ext补丁...',isAsync)
    if (!isAsync) {
        Ext.BLANK_IMAGE_URL = path + 'resources/images/default/s.gif';
    }
    IsReady_Extjs = true;
}

function InitSWFjs() {
    // / <summary>载入SWFjs库</summary>
    var path = '/js/upload/';
    using(path + 'swfupload.js');
    using(path + 'swfupload.queue.js');
    using(path + 'fileprogress.js');
    using(path + 'handlers.js');
    using(path + 'setting.js');
    using(path + 'default.css')
}

function InitSWFjs_ext(isAsync) {
    // / <summary>载入SWFjs库</summary>
    var path = '/js/upload/';
    using(path + 'upload.js', '正在加载上传库文件', isAsync);
    using(path + 'default.css')
}

// =============以下为常用代码,开发后期单独放到独立的公共文件中===============
function ShowFailureMsg(msg, IsErrorIcon, title) {
    // / <summary>显示操作失败后的提示信息</summary>
    // / <param name="msg" type="String">显示内容</param>
    // / <param name="IsErrorIcon" type="Boolean">True: Ext.Msg.WARNING</param>
    // / <param name="title" type="String">标题</param>
    Ext.MessageBox.show({
        title: title ? title : '操作失败',
        msg: msg ? msg : '网络故障或服务器异常！',
        modal: true,
        style: 'text-align:left',
        width: 360,
        height: 270,
        buttons: Ext.Msg.OK,
        icon: IsErrorIcon ? Ext.Msg.ERROR : Ext.Msg.WARNING
    })

}

function ShowSuccessMsg(message) {
    // / <summary>提交数据成功时，弹出显示msg内容的对话框</summary>
    // / <param name="message" type="String">提示信息正文</param>
    // / <param name="form" type="Object"></param>
    // / <param name="action" type="Object"></param>
    Ext.MessageBox.show({
        title: '操作成功',
        msg: message,
        modal: true,
        style: 'text-align:left',
        width: 360,
        height: 270,
        buttons: Ext.Msg.OK,
        icon: Ext.Msg.INFO
    })
}

function GetTenderProject(tenderProjectID) {
    // / <summary>返回招标项目</summary>
    var conn = Ext.lib.Ajax.getConnectionObject().conn;
    conn.open("GET",
			'/Tender/GetTenderProject.json?tenderProjectID=' + tenderProjectID,
			false);
    conn.send(null);
    var oResult = Ext.util.JSON.decode(conn.responseText);
    if (oResult) {
        if (oResult.success) {
            return oResult.data;
        }
    } else {
        ShowFailureMsg();
        return null;
    }
}

function GetData(url, isString) {
    // / <summary>以同步方式从服务器端返回实体对象，注使用此代码，需先加载Ext</summary>
    // return ajaxQuery(url, true);
    // if (!isString) { data = Ext.util.JSON.decode(data) };
    // return data;
    url += (url.indexOf('?') == -1 ? '?' : '&') + '_dc='
			+ (new Date()).getTime(); // 解决缓存问题
    var oXmlHttp = getHttpRequest();
    oXmlHttp.open('GET', url, false);
    oXmlHttp.send(null);
    var responseText = oXmlHttp.responseText;
    oXmlHttp = null;
    try {
        if (!isString) {
            var oResult = Ext.util.JSON.decode(responseText);
            if (oResult) {
                if (oResult.data && oResult.data.msg) {
                    if (oResult.success) {
                        return oResult.data;
                    } else {
                        ShowFailureMsg(oResult.data.msg);
                    }
                } else {
                    return oResult
                }
            } else {
                // ShowFailureMsg();
                return null;
            }
        } else {
            return responseText;
        }
    } catch (e) {
        return null
    }
}

// 复选框(只读)
function CheckBox(val) {
    var k = "1";
    if (!val || val == 0 || val.toString().toLowerCase() == "false") {
        k = "0";
    }
    return '<b class="icon check-' + k + '"></b>'
}

// 星级
function Star(val) {
    val = val ? parseInt(val) : 0;
    return '<b class="star" style="width:' + (val * 18) + 'px"></b>';
}

// 可编辑列表的编辑框加边框
function InputBox(value) {
    return '<div style="border:solid 1px #cccccc;width:100%; height:100%; text-align:right; line-height:21px" title="双点修改">' + (value ? value
			: 0) + '</div>';
}

// ***********************仅用于调试时***************************
function ObjectToJson(o) {
    // / <summary>Object转Json</summary>
    // / <param name='o' type="Object">对象</param>
    var r = [];
    if (typeof o == "string")
        return "\""
				+ o.replace(/([\'\"\\])/g, "\\$1").replace(/(\n)/g, "\\n")
						.replace(/(\r)/g, "\\r").replace(/(\t)/g, "\\t") + "\"";
    if (typeof o == "undefined")
        return "undefined";
    if (typeof o == "object") {
        if (o === null)
            return "null";
        else if (!o.sort) {
            for (var i in o)
                r.push(i + ":" + (o[i]))
            r = "{" + r.join() + "}"
        } else {
            for (var i = 0; i < o.length; i++)
                r.push((o[i]))
            r = "[" + r.join() + "]"
        }
        return r;
    }
    return o.toString();
};

// 数组添加IndexOf方法
[ ].indexOf || (Array.prototype.indexOf = function (v) {
    for (var i = this.length; i-- && this[i] !== v; )
        ;
    return i;
});

// 数组添加append方法
[ ].append || (Array.prototype.append = function () {
    for (var i = 0; i < arguments.length; i++)
        this.push(arguments[i])
});

function JsonToObject(data) {
    // / <summary>将String转换为Object
    var o = null;
    try {
        o = eval('(' + data + ')');
    } catch (e) {
    }
    return o;
}
// *********************

function Print(doc, title) {
    // / <summary>打印</summary>
    doc = doc.replace(/paper /g, "");
    var style = GetData('/css/report.css', true);
    doc = '\r<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"><style type="text/css">'
			+ style
			+ '</style></head><body>'
			+ doc
			+ '</body></html>\n';

    var winname = window.open('', '_blank',
			'height=600,width=800,top=200,left=300,resizable=yes,scrollbars=yes');
    winname.document.open('text/html', 'replace');
    winname.document.writeln(doc);
    winname.document.title = title ? title + '打印' : '打印';
    winname.document.close();
    winname.print();
    //winname.close();   
}
function PreviewPage(url, pamas) {
    // / <summary>打印</summary>
    var p = 'height=600,width=800,top=200,left=300,scrollbars=yes, resizable=yes';
    if (pamas)
        p = pamas;
    window.open(url + '&print=true', '_blank', p);

}

function Preview(doc, title) {
    // / <summary>预览</summary>
    // doc = doc.replace(/paper /g, "");
    var style = GetData('/css/report.css', true);
    doc = '\r<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"><style type="text/css">'
			+ style + '</style></head><body>' + doc + '</body></html>\n';
    var winname = window
			.open('', '_blank', 'height=1,width=1,top=200,left=300');
    winname.document.open('text/html', 'replace');
    winname.document.writeln(doc);
    winname.document.title = title ? title + '预览' : '预览';
}

function GetPrintDocument(o) {
    var items = Ext.query('div.paper', o);
    var doc = '';
    for (var i = 0; i < items.length; i++) {
        doc += doc != '' ? '<br style="page-break-before:always" />' : '';
        doc += '<div class="report">' + items[i].innerHTML + '</div>';
    }
    return doc;
}

function IsDate(value) {
    // 检验是否是有效的日期
    var r = value.match(/^(\d{1,4})(-|\/)(\d{1,2})\2(\d{1,2})$/);
    if (r == null) {
        return false;
    } else {
        var d = new Date(r[1], r[3] - 1, r[4]);
        return (d.getFullYear() == r[1] && (d.getMonth() + 1) == r[3] && d
				.getDate() == r[4]);
    }
}

function IsTime(value) {
    // 检验是否是有效的时间
    var a = value.match(/^(\d{1,2})(:)?(\d{1,2})\2(\d{1,2})$/);
    if (a == null) {
        return false;
    }
    if (a[1] > 24 || a[3] > 60 || a[4] > 60) {
        return false
    }
    return true;
}


function parseObj(strData) {
    return (new Function("return " + strData))();
}

function getFormData(form) {
    //获取表单值对象   
    var data = {};
    $("input[type=text],input[type=password],textarea,select", form).each(function () {
        if (this.name || this.id) {
            data[this.name ? this.name : this.id] = $(this).val();
        }
    });
    return data;
}
