﻿/// <reference path="mootools.js" />
/* 
MooStudio.js  基于 mootools 的插件扩展包基类
本js文件为插件包的基类包
Author : S.P    开源社区: studio.80y.cn     交流QQ群:1809084   转载请保留此段信息
*/
if (!window["UI"]) window["UI"] = new Object();

/*  调试  */
var traceIndex = 0;
function trace(msg) {
    var trace = $("trace");
    if (trace == null) return;
    var list = trace.getElements("div");
    if (list.length > 20) {
        list[0].dispose();
    }
    new Element("div", { html: traceIndex++ + msg }).inject($("trace"));
}

var $F = function (name) {
    /// <summary>
    /// 查找名字为name的控件
    /// </summary>
    /// <param name="name">String 名字</param>
    return $$("*[name=" + name + "]").getLast();
};

// 字符串扩展方法

String.prototype.get = function (key, ignoreCase) {
    /// <summary>
    /// 获取 query string 的键内容
    /// </summary>
    /// <param name="key">键</param>
    /// <param name="ignoreCase">是否区分大小写。 可选项，默认为false</param>
    /// <returns>值</returns>
    var str = this;
    ignoreCase = ignoreCase == undefined ? false : ignoreCase;
    if (str.indexOf("?") > -1) str = str.substr(str.indexOf('?') + 1);
    var value = null;
    str.split("&").each(function (item) {
        var name = item.split("=");
        if (name[0] == key || (!ignoreCase && name[0].toLowerCase() == key.toLowerCase())) {
            value = name[1];
        }
    });
    return value;
}

String.prototype.getBody = function (starTag, endTag) {
    /// <summary>
    /// 获取文本指定标签中的内容
    /// </summary>
    /// <param name="starTag">开始标签  可选参数 默认为 &lt;body&gt; </param>
    /// <param name="endTag">结束标签  可选参数 默认为 &lt;body&gt; </param>
    var html = this;
    if (starTag == undefined) starTag = "<body>";
    if (endTag == undefined) endTag = "</body>";
    if (html.indexOf(starTag) == -1 || html.substring(html.indexOf(starTag)).indexOf(endTag) == -1) return this;
    return html.substring(html.indexOf(starTag) + starTag.length, html.indexOf(starTag) + html.substring(html.indexOf(starTag)).indexOf(endTag));
}

String.prototype.toDate = function () {
    /// <summary>
    /// 把字符串转化成为日期对象 字符串格式为 yyyy(-|/)MM(-|/)dd 
    /// </summary>
    var str = this;
    var regex = /^(\d{4})[\-|\/](\d{1,2})[\-|\/](\d{1,2}).*?/;
    if (!regex.test(str)) return null;
    var matchs = str.match(regex);
    return new Date(matchs[1], matchs[2].toInt() - 1, matchs[3]);
};

String.prototype.StartWith = function (str, ignoreCase) {
    /// <summary>
    /// 确定此字符串实例的开头是否与指定的字符串匹配。
    /// </summary>
    /// <param name="str">String 要比较的字符串</param>
    /// <param name="ignoreCase">Boolean 是否区分大小写 可选参数，默认为false</param>
    if (ignoreCase == undefined) ignoreCase = false;
    var string = this;
    if (!ignoreCase) { string = string.toLowerCase(); str = str.toLowerCase(); }
    return string.indexOf(str) == 0;
}

String.prototype.EndWith = function (str, ignoreCase) {
    /// <summary>
    /// 确定此字符串实例的结尾是否与指定的字符串匹配。
    /// </summary>
    /// <param name="str">String 要比较的字符串</param>
    /// <param name="ignoreCase">Boolean 是否区分大小写 可选参数，默认为false</param>
    if (ignoreCase == undefined) ignoreCase = false;
    var string = this;
    if (!ignoreCase) { string = string.toLowerCase(); str = str.toLowerCase(); }
    return string.length == string.indexOf(str) + str.length;
}




// 日期扩展方法

Date.prototype.getLastDate = function () {
    /// <summary>
    /// 获取一个月的最后一天的日期
    /// </summary>
    var date = new Date(this.getFullYear(), this.getMonth() + 1, 0);
    return date.getDate();
};

Date.prototype.getFirstDay = function () {
    /// <summary>
    /// 获取当前月的第一天是星期几
    /// </summary>
    var date = new Date(this.getFullYear(), this.getMonth(), 1);
    return date.getDay();
};

Date.prototype.AddDays = function (value) {
    /// <summary>
    /// 返回一个新的 DateTime，它将指定的天数加到此实例的值上。
    /// </summary>
    /// <param name="value">Int 由整数组成的天数。value 参数可以是负数也可以是正数。</param>
    var date = this;
    date.setDate(date.getDate() + value);
    return date;
};

Date.prototype.ToShortDateString = function () {
    /// <summary>
    /// 将当前 System.DateTime 对象的值转换为其等效的短日期字符串表示形式。
    /// </summary>
    return this.getFullYear() + "-" + (this.getMonth() + 1) + "-" + this.getDate();
};


// 数字的扩展方法
Number.prototype.ToString = function (format) {
    /// <summary>
    /// 格式化数字
    /// </summary>
    /// <param name="format">String 格式化类型 c:货币</param>
    switch (format) {
        case "c":
            var number = Math.round(this * 100) / 100;
            if (number.toString().indexOf(".") == -1) number += ".00";
            return number.toString();
            break;
        default:
            return this.toString();
            break;
    }
};


// 数组扩展方法

Array.prototype.bind = function (el, option) {
    /// <summary>
    /// 把数组绑定到控件上
    /// </summary>
    var list = this;
    switch (el.get("tag")) {
        case "select":
            Element.clean(el);
            list.each(function (item) {
                var op = option;
                if (op == undefined) op = { text: "text", value: "value" };
                el.options.add(new Option(item[op.text], item[op.value]));
            });
            break;
    }
};

Array.prototype.sort = function () {
    /// <summary>
    /// 数组排序 从小到大
    /// </summary>
    return this;
    var list = this;
    for (var i = 0; i < list.length; i++) {
        for (var i2 = i + 1; i2 < list.length; i2++) {
            if (list[i].toInt() > list[i2].toInt()) {
                var n = list[i2];
                list[i2] = list[i];
                list[i] = n;
            }
        }
    }
    return list;
}


// DOM对象扩展方法

Element.clean = function (t) {
    /// <summary>
    /// 清空自身的元素
    /// </summary>
    switch (t.get("tag")) {
        case "select":
            for (var index = t.options.length - 1; index >= 0; index--) {
                t.options[index] = null;
            }
            break;
    }
}

Element.CheckBox = function (obj) {
    /// <summary>
    /// 在提交form的时候如果checkbox为空则设置该值为false而且选中
    /// </summary> 
    /// <param name="obj">checkbox 对象 </param>
    obj = $(obj);
    if (!obj.get("checked")) {
        obj.set("value", "false");
        obj.set("checked", true);
        obj.setStyle("visibility", "hidden");
    }
}

// 基类方法

UI.getSize = function () {
    /// <summary>
    /// 获取屏幕宽高 返回JSON对象 {x : ,y : , height , top }
    /// x 、 y 为网页可视区域的宽高。 height为网页全部内容的高  top为当前网页被卷去的高度
    /// </summary>

    var height = Math.max(document.documentElement.scrollHeight, document.documentElement.clientHeight);
    if (height > window.screen.availHeight) height = document.documentElement.clientHeight;
    var width = Math.max(document.documentElement.scrollWidth, document.documentElement.clientWidth);
    return { x: width, y: height,
        height: $(document.body).getSize().y,
        top: Math.max(document.body.scrollTop, document.documentElement.scrollTop)
    };
};

UI.center = function (obj, container) {
    /// <summary>
    /// 设置obj居中
    /// </summary> 
    /// <param name="obj">要居中的对象</param>
    /// <param name="container">相对居中的容器。可选项，不填表示body</param>
    obj = $(obj);
    if (container == undefined) container = document.body;
    container = $(container);
    var body = UI.getSize();
    var position = obj.getCoordinates();
    obj.setStyles({
        "left": (body.x - position.width) / 2,
        "top": (body.height - position.height) / 2 < 0 ? 0 : (body.height - position.height) / 2
    });
    return { x: (body.x - position.width) / 2, y: (body.height - position.height) / 2 };
};


/*  扩展mootools的方法   */

Object.get = function (obj, key, ignoreCase) {
    /// <summary>
    /// 获取object的指定key对象。
    /// </summary>
    /// <param name="obj">要进行查找的JSON对象</param>
    /// <param name="key">要获取的key。</param>
    /// <param name="ignoreCase">是否区分key的大小写，默认为不区分</param>
    ignoreCase = ignoreCase == undefined ? false : ignoreCase;
    var value = null;
    Object.each(obj, function (v, k) {
        if (key == k || (!ignoreCase && key.toLowerCase() == k.toLowerCase())) value = v;
    });
    return value;
};

// 已经加载的文件列表。
var _importList = new Array();

// 库文件根目录
var _gPath = (function () {
    var str = "/scripts/moostudio.js";
    var es = document.getElementsByTagName("script");
    for (var i = 0; i < es.length; i++) {
        var src = es[i].src;
        if (src.toLowerCase().substr(src.length - str.length) == str) {
            return src.substr(0, src.length - str.length);
        }
    }
    return "http://cn.t100.cn/Studio/resources";
})();

function $import(file, isSync, refresh) {
    /// <summary>
    /// 引用js或者样式库
    /// </summary>
    /// <param name="file">要引用的文件路径 如果无路径符号则引用公共库中的文件</param>
    /// <param name="isSync">Boolean 同步或者异步引用 默认为true</param>
    /// <param name="refresh">Boolean 重新加载时候是否主动刷新 默认为false</param>
    if (location.href.toLowerCase().contains("/demo/")) { _gPath = "/resources" }
    if (refresh == undefined) refresh = false;
    if (_importList.contains(file)) {
        if (refresh) {
            $$("head script").each(function (item) {
                if (item.get("src") == null) return;
                if (item.get("src").EndWith(file)) {
                    item.dispose();
                }
            });
        } else {
            return;
        }
    }

    _importList.push(file);
    if (isSync == undefined) isSync = true;
    if (!file.contains("/") && file.EndWith(".js")) file = _gPath + "/Scripts/" + file;
    if (!file.contains("/") && file.EndWith(".css")) file = _gPath + "/Styles/" + file;
    var header = document.getElementsByTagName("head")[0];
    var el = null;
    var fileExt = file.substring(file.lastIndexOf('.'));
    if (fileExt.StartWith(".js")) {
        el = isSync ? "<script language=\"javascript\" type=\"text/javascript\" src=\"" + file + "\"></script>" : new Element("script", {
            "language": "javascript",
            "type": "text/javascript",
            "src": file
        });
    } else if (fileExt.StartWith(".css")) {
        el = isSync ? "<link type=\"text/css\" rel=\"Stylesheet\" href=\"" + file + "\" />" : new Element("link", {
            "type": "text/css",
            "rel": "Stylesheet",
            "href": file
        });
    }
    isSync ? document.write(el) : el.inject($(header));
}

// 设为首页
function SetHome(obj, vrl) {
    try {
        obj.style.behavior = "url(#default#homepage)";
        obj.setHomePage(vrl);
    } catch (e) {
        if (window.netscape) {
            try {
                netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
            } catch (e) {
                alert("\u62B1\u6B49\uFF01\u60A8\u7684\u6D4F\u89C8\u5668\u4E0D\u652F\u6301\u76F4\u63A5\u8BBE\u4E3A\u9996\u9875\u3002\u8BF7\u5728\u6D4F\u89C8\u5668\u5730\u5740\u680F\u8F93\u5165\u201Cabout:config\u201D\u5E76\u56DE\u8F66\u7136\u540E\u5C06[signed.applets.codebase_principal_support]\u8BBE\u7F6E\u4E3A\u201Ctrue\u201D\uFF0C\u70B9\u51FB\u201C\u52A0\u5165\u6536\u85CF\u201D\u540E\u5FFD\u7565\u5B89\u5168\u63D0\u793A\uFF0C\u5373\u53EF\u8BBE\u7F6E\u6210\u529F\u3002");
            }
            var prefs = Components.classes['@mozilla.org/preferences-service;1'].getService(Components.interfaces.nsIPrefBranch);
            prefs.setCharPref("browser.startup.homepage", vrl);
        }
    }
}

// 加入收藏夹
function addBookmark(title) {
    var url = parent.location.href;
    if (window.sidebar) {
        window.sidebar.addPanel(title, url, "");
    } else if (document.all) {
        window.external.AddFavorite(url, title);
    } else if (window.opera && window.print) {
        return true;
    }
}
