﻿var Utils=new Utils();
function Utils()
{
 this.selectFile=function(obj,aExt)
 {
   if(obj.value=="")return;
   var fl=document.getElementById(obj.id+"_span");
   var fN=obj.value.substring(obj.value.lastIndexOf("\\")+1);
   var exName=fN.substring(fN.lastIndexOf(".")+1).toLowerCase();
   var ae=aExt.toLowerCase()+",";
   if(ae.indexOf(exName+",")==-1 && aExt!="*")
   {
      alert("Only allow '"+aExt+"'");
      obj.focus();
      
      document.execCommand("selectall"); 
      document.execCommand("Delete"); 
      fl.innerHTML="";
      return false;
   }
   
   fl.innerHTML=fN.substring(0,10);

};
this.addCss = function(ctl, css) {
    if (ctl.className == "") {
        ctl.className = css;
        return;
    }
    var str = new Array();
    str = ctl.className.split(' ');
    for (var i = 0; i < str.length; i++) {
        if (str[i].toLowerCase() == css.toLowerCase()) return;
    }
    ctl.className = ctl.className.trim() + " " + css;
};
this.removeCss=function(ctl,css)
{
    var str = new Array();
    str = ctl.className.split(' ');
    for (var i = 0; i < str.length; i++)
    {
        if (str[i].toLowerCase() == css.toLowerCase()) str[i] = "";
    }
    ctl.className =str.join(" ");
};
//以下設置行的runtimeStyle.backgroundColor
this.setBackColor = function(obj, color) {
    if (!document.all) return;
    if (color == null) {
        obj.runtimeStyle.backgroundColor = "#F1F1F1";
    }
    else
        obj.runtimeStyle.backgroundColor = color;
};

this.clearBackColor = function(obj, color) {
    if (!document.all) return;
    if (color == null) {
        obj.runtimeStyle.backgroundColor = "";
        obj.runtimeStyle.color = "";
    }
    else
        obj.runtimeStyle.backgroundColor = color;
};


this.expandSearch = function(obj, panelId) {
    var panelDiv = document.getElementById(panelId);
    if (panelDiv == null) return;
    var panelExpanded = document.getElementById(panelId + "_Expanded");
    if (panelExpanded.value.toLowerCase() == "true") {
        panelExpanded.value = "false";
        panelDiv.style.display = "none";
        obj.className = "BtnNormal";
        obj.title = "還原";
    }
    else {
        panelExpanded.value = "true";
        panelDiv.style.display = "";
        obj.className = "BtnMin";
        obj.title = "最小化";
    }

};
this.checkNumberFilter = function(objId, prov, oldValue) {
    var obj = document.getElementById(objId);
    if (obj.value == "") return;
    if (obj.value != obj.value.trim()) obj.value = obj.value.trim();
    var regAFloat = /^\d+(\.\d+)?$/g; //非負浮點數
    var regFloat = /^(-?\d+)(\.\d+)?$/g; //浮點數
    var regAInt = /^\d+$/g; //非負整數（正整數 + 0）
    var regInt = /^-?\d+$/g; //整數
    var dotPos = obj.value.indexOf(".");
    if (obj.value != oldValue) obj.onblur = obj.onchange;
    if (prov == "" || prov == "undefined")//沒有格式則默認為"非負浮點數"，小數位數最多4位
    {
        if (obj.value.indexOf(".") == obj.value.length - 1) return;
        if (obj.value.match(regAFloat) == null) {
            obj.value = oldValue;
            return;
        }
        if (dotPos > 0 && obj.value.length - dotPos > 3) {
            obj.value = oldValue;
            return;
        }
    }
    else {
        var provArr = prov.split(".");
        if (provArr.length == 1)//沒有點認為整數
        {
            if (prov.indexOf("-") != 0)//沒有負號時只能為正數
            {
                if (obj.value.match(regAInt) == null) { obj.value = oldValue; return; }
            }
            if (obj.value.match(regInt) == null && obj.value != "-") { obj.value = oldValue; return; }
        }
        else {
            if (obj.value.indexOf(".") == obj.value.length - 1) return;
            if (prov.indexOf("-") != 0)//沒有負號時只能為正數
            {
                if (obj.value.match(regAFloat) == null) { obj.value = oldValue; return; }
            }
            if (obj.value.match(regFloat) == null && obj.value != "-") { obj.value = oldValue; return; }
            if (obj.value.indexOf(".") < 0) return true;
            if (obj.value.split(".")[1].length > provArr[1].length) { obj.value = oldValue; return; }

        }

    }
};
this.checkPaste = function(obj, prov) {
    setTimeout("Utils.checkNumberFilter('" + obj.id + "','" + prov + "','" + obj.value + "')", 2);
};
 //檢測輸入框只能輸入數字
this.checkNumber = function(obj, prov) {
    if (obj == null) return;

    if (event.shiftKey) return false; //屏蔽shift
    switch (event.keyCode) {
        case 13:
            var btnGo = obj.id.replace("_pageGo", "_btnGo")
            document.getElementById(btnGo).focus();
            document.getElementById(btnGo).click();
            return true;
            break;
        default:
            break;
    }
    var allow = false;
    if (event.keyCode == 9 || event.keyCode == 8 || event.keyCode == 46 || event.keyCode == 37 || event.keyCode == 39) allow = true; //允許Tab、BackSpace和Delete及左右鍵
    if (event.ctrlKey) allow = true;
    if (event.keyCode == 110 || event.keyCode == 190) allow = true; //輸入小數點時
    if (event.keyCode == 109 || event.keyCode == 189) allow = true; //輸入負號時       

    setTimeout("Utils.checkNumberFilter('" + obj.id + "','" + prov + "','" + obj.value + "')", 2);
    if (allow) return true;

    //禁止非數字鍵
    if (!(window.event.keyCode >= 48 && window.event.keyCode <= 57) && !(window.event.keyCode >= 96 && window.event.keyCode <= 105)) {
        return false;
    }
    return true;
};
    //打開彈出頁面
this.openUrl = function(win, url, width, height) {
    if (width == null) width = 900;
    if (height == null) height = 600;
    var top = (screen.height - height) / 2 - 50;
    var left = (screen.width - width) / 2;
    var href = url;
    if (url.indexOf("?") == -1 || url == "") {
        href = url + "?" + this.getParam(location.search, "MenuId");
    }
    else {
        href = url + "&" + this.getParam(location.search, "MenuId");
    }
    win = window.open(href, "_blank", "width=" + width + ",height=" + height + ",menubar=no,location=no,toolbar=no,alwaysRaised=yes,resizable=yes,scrollbars=yes,left=" + left + ",top=" + top + "");
    return win;
};
this.getParam = function(url, param) {
    var index = url.indexOf(param + "=");
    if (index == -1) return "";
    var rtn = url.substr(index);
    index = rtn.indexOf("&");
    if (index == -1) return rtn;
    rtn = rtn.substring(0, index);
};
this.showModel = function(url, width, height) {

    var _width = 800, _height = 600;
    if (width != null) _width = width;
    if (height != null) _height = height;
    var href = "";

    if (url.indexOf("?") == -1 || url == "") {
        href = url + "?r=" + Math.random();
    }
    else {
        href = url + "&r=" + Math.random();
    }
    var returnValue = window.showModalDialog(href, self, "scroll:1;status:0;help:0;resizable:1;dialogWidth:" + _width + "px;dialogHeight:" + _height + "px;");
    return returnValue;
};

this.getParam = function(url, param) {
    var index = url.indexOf(param + "=");
    if (index == -1) return "";
    var rtn = url.substr(index);
    index = rtn.indexOf("&");
    if (index == -1) return rtn;
    rtn = rtn.substring(0, index);
};
this.getAltedHref = function(href, prms, vals) {
    var str = href;
    for (var i = 0; i < prms.length; i++) {
        if (vals[i] == null || typeof (vals[i]) == "undefined" || vals[i] == "null" || vals[i] == "undefined") continue;
        var reg = new RegExp("[\?\&]" + prms[i] + "=[^\&]*", "i");
        var ps = str.match(reg);
        if (ps != null) {
            str = str.replace(ps[0], ps[0].substring(0, 1) + prms[i] + "=" + escape(vals[i]));
        }
        else {
            if (str.indexOf("?") >= 0) {
                str = str + "&" + prms[i] + "=" + escape(vals[i]);
            } else {
                str = str + "?" + prms[i] + "=" + escape(vals[i]);
            }
        }

    }
    return str;
};
	//計算元素的絕對Top
this.getAbsoluteTop = function(obj) {
    var top = 0;
    while (obj.offsetParent) {
        if (obj.offsetParent != null) {
            top += obj.offsetTop;
            obj = obj.offsetParent;
        }
    }
    return top;
};
   //計算元素的絕對Left
this.getAbsoluteLeft = function(obj) {
    var left = 0;
    while (obj.offsetParent) {
        if (obj.offsetParent != null) {
            left += obj.offsetLeft;
            obj = obj.offsetParent;
        }
    }
    return left;
};
    //判斷元素是否在指定Id元素內
this.isInContainer = function(obj, containerId) {
    var element = obj;
    if (element.id == containerId) return true;
    while (element.parentNode) {
        if (element.id == containerId) return true;
        if (element.parentNode != null) {
            element = element.parentNode;
        }
    }
    return false;
};


    //----
    //---------------------------------------------------------根據url發請求拿數據
    /*如(參數3為失敗的自定義處理，可以省略)：
    wisdom.request("atttribute.aspx",function(data){alert(data);},function(ex){alert("error");});
    */
this.getArgument = function(args, type) {
    for (var i = 0; i < args.length; i++) {
        if (typeof (args[i]) == type) return args[i];
    }
    return null;
};

this.request = function(url, sfnc) {
    var p1 = null, p2 = null, p3 = null, p4 = null, ef = null, asy = true, dt = "json", mt = "GET", pd = null;
    var args = [];
    for (var i = 2; i < arguments.length; i++) {
        args.push(arguments[i]);
    }
    var p = null;
    p = wisdom.getArgument(args, "function");
    if (p != null) ef = p;
    p = wisdom.getArgument(args, "string");
    if (p != null) dt = p;
    p = wisdom.getArgument(args, "boolean");
    if (p != null) asy = p;
    p = wisdom.getArgument(args, "object");
    if (p != null) {
        mt = "POST";
        pd = p;
    }
    try {

        	$.ajax(
                {
                    url: url + ((url.indexOf("?") > -1) ? "&r=" : "?r=") + Math.random(),
                    async: asy,
                    type: mt,
                    data: ((pd == null) ? "" : "postData=" + encodeURIComponent(Utils.serialize(pd))),
                    dataType: dt,
                    timeout: 1000000,
                    beforeSend: function() {
                        //IsBusy(true);

                    },
                    success: sfnc,
                    error: ((ef == null) ? function(Xhr) {
                        if (Xhr != null) { SysMsg.expandMsg(Xhr.responseText); } else { SysMsg.expandMsg("Time out"); };
                    } : ef),
                    complete: function() {
                        //IsBusy(false);
                    }
                });
    } catch (e) {
        SysMsg.expandMsg(e);
    }
};
this.isEmpty = function(val) {//判斷對象是否是NULL或者時undefined
    if (typeof (val) == 'undefined') return true;
    if (val == null) return true;
    if ((val + "").trim() == "") return true;

};
 //以下方法處理字符串前後的空格
String.prototype.trim = function(){ return Trim(this);} 
String.prototype.lTrim = function(){return LTrim(this);} 
String.prototype.rTrim = function(){return RTrim(this);} 

String.prototype.startWith = function(seg){return StartWith(this,seg);} //判斷是否以..開頭
String.prototype.endWith = function(seg){return EndWith(this,seg);} //判斷是否以..結尾
//此處為獨立函數 
function LTrim(str) 
{ 
var i; 
for(i=0;i<str.length;i++) 
{ 
if(str.charAt(i)!=" "&&str.charAt(i)!="\r" && str.charAt(i)!="\n" &&str.charAt(i)!="\t")break; 
} 
str=str.substring(i,str.length); 
return str; 
} 
function RTrim(str) 
{ 
var i; 
for(i=str.length-1;i>=0;i--) 
{ 
if(str.charAt(i)!=" "&&str.charAt(i)!="\r" && str.charAt(i)!="\n" &&str.charAt(i)!="\t")break; 
} 
str=str.substring(0,i+1); 
return str; 
} 
function Trim(str) 
{ 
return LTrim(RTrim(str)); 
} 
function StartWith(str,seg)
{
  if(str.indexOf(seg)==0)return true;
  return false;
}
function EndWith(str,seg)
{
  if(str.lastIndexOf(seg)==str.length-seg.length)return true;
  return false;
}
this.deString=function (str)
 {
     var returnValue = str+"";     
     returnValue = returnValue.replace(/&quot;/g,"\"");
     returnValue = returnValue.replace(/&lt;/g,"<");
     returnValue = returnValue.replace(/&gt;/g,">");
     return returnValue;
}
 //序列化Json對象
this.serialize = function(obj) {
    if (obj == null) return '""';
    if (typeof (obj) == typeof (0)) return obj.toString();
    if (typeof (obj) == typeof (true)) return obj.toString();
    if (obj instanceof Date) {
        return '"'+obj+'"';
    }
    if (typeof (obj) == "function") return obj;
    if (typeof (obj) == typeof ('') || obj instanceof String) {
        if ((obj + "").indexOf("/Date(") == 0) {
            return '"'+(new Date(parseFloat(obj.substring(6, obj.length-2))).toString("yyyy-MM-dd hh:mm:ss"))+'"';
        }
        obj = obj.toString();
        obj = obj.replace(/\r\n/, '\\r\\n');
        obj = obj.replace(/\n/, '\\n');
        obj = obj.replace(/\"/, '\\"');
        return '"' + obj + '"';
    }
    var strRet;
    if (typeof (obj.join) == "function") {
        strRet = "[";
        for (var i = 0; i < obj.length; i++) {
            if (strRet.length > 1) strRet += ",";
            strRet += this.serialize(obj[i]);
        }
        strRet += "]";
        return strRet;
    }
    if (typeof (obj) == typeof ({})) {
        strRet = "{";
        for (var p in obj) {
            if (strRet.length > 1) strRet += ",";
            strRet += '"' + p + '":' + this.serialize(obj[p]);
        }
        strRet += "}";
        return strRet;
    }
};



}
function addEvent(handler, sender, triger) {
    var sdr = (sender == null) ? window : sender;
    var trg = triger;
    if (sdr.addEventListener) {
        switch (trg) {
            case "onclick":
                trg = "click";
                break;
            case "onsubmit":
                trg = "submit";
                break;
            default:
                trg = "load";
                break;
        }
        sdr.addEventListener(trg, handler, false);
        resizeBy;
    }
    if (sdr.attachEvent) {
        switch (trg) {
            case "onclick":
                trg = "onclick";
                break;
            case "onsubmit":
                trg = "onsubmit";
                break;
            case "onscroll":
                trg = "onscroll";
                break;
            case "onresize":
                trg = "onresize";
                break;
            default:
                trg = "onload";
                break;
        }
        sdr.attachEvent(trg, handler);
        return;
    }
}
/*格式化時間
formatStr:
yyyy:年
MM:月
dd:日
hh:小時
mm:分鐘
ss:秒
*/
Date.prototype.toString = function(formatStr) {
    var date = this;
    if (typeof (formatStr) == "undefined" && typeof (date.toLocaleString) != 'undefined') return date.toLocaleString();
    var timeValues = function() { };
    timeValues.prototype = {
        year: function() {
        if (formatStr.indexOf("yyyy") >= 0) {
                return date.getFullYear();
            }
            else {
                return date.getYear().toString().substr(2);
            }
        },
        elseTime: function(val, formatVal) {
            return formatVal >= 0 ? (val < 10 ? "0" + val : val) : (val);
        },
        month: function() {
            return this.elseTime(date.getMonth() + 1, formatStr.indexOf("MM"));
        },
        day: function() {
            return this.elseTime(date.getDate(), formatStr.indexOf("dd"));
        },
        hour: function() {
            return this.elseTime(date.getHours(), formatStr.indexOf("hh"));
        },
        minute: function() {
            return this.elseTime(date.getMinutes(), formatStr.indexOf("mm"));
        },
        second: function() {
            return this.elseTime(date.getSeconds(), formatStr.indexOf("ss"));
        }
    }
    var tV = new timeValues();
    var replaceStr = {
        year: ["yyyy", "yy"],
        month: ["MM", "M"],
        day: ["dd", "d"],
        hour: ["hh", "h"],
        minute: ["mm", "m"],
        second: ["ss", "s"]
    };
    for (var key in replaceStr) {
        formatStr = formatStr.replace(replaceStr[key][0], eval("tV." + key + "()"));
        formatStr = formatStr.replace(replaceStr[key][1], eval("tV." + key + "()"));
    }
    return formatStr;
};
//var split = new SplitBar("splitBar", "SplitBar");
//split.setImg("images/arr.gif", "images/arr2.gif");
function SplitBar(barId, css) {
    var bar = document.getElementById(barId);
    if (css != null) bar.className = css;
    bar.img1 = "";
    bar.img2 = "";
    bar.img = {};
    bar.allowSplit = true;
    this.setImg = function(img1, img2) {
        bar.img1 = img1;bar.img2 = img2;
        bar.innerHTML = "<img src=\"" + img1 + "\" style=\"cursor:hand;\">";
        bar.img = bar.getElementsByTagName("IMG")[0];
        bar.img.bar = bar;
        bar.img.onclick = function() {
            var bar = this.parentElement;
            var barLeft = bar.parentElement.cells[0];
            if (barLeft.style.display != "none") {
                bar.img.src = bar.img2;
                barLeft.style.display = "none";
            }
            else {
                bar.img.src = bar.img1;
                barLeft.style.display = ""
            }
        };
        bar.img.onmouseover = function() {
            var bar = this.parentElement;
            bar.allowSplit = false;
        };
        bar.img.onmouseout = function() {
            var bar = this.parentElement;
            bar.allowSplit = true;
        };
    };
    var sp = document.getElementById("$Sp");
    if (sp == null) {
        sp = document.createElement("DIV");
        sp.style.textAlign = "center";
        sp.innerHTML = "<iframe style=\"display:none;\" />";
        sp.className = "SplitBar";

        sp.id = "$Sp";
        sp.style.display = "none";
        sp.style.position = "absolute";
        sp.style.zIndex = "800";
        document.body.appendChild(sp);
    }

    bar.sp = sp;
    sp.bar = bar; ;
    sp.onselect = function() { return false; };

    var e = event;
    bar.onmousedown = bar.onmousemove = function(e) {
        if (this.parentElement.cells[0].style.display == "none") return;
        setTimeout(function() {
            var sp = document.getElementById("$Sp");
            if (sp.bar.allowSplit) sp.style.display = "";
        }, 2);
        this.sp.style.filter = "alpha(opacity=0)";
        this.sp.style.left = this.offsetLeft - 2;
        this.sp.style.top = this.offsetTop;
        this.sp.style.width = this.offsetWidth + 4;
        this.sp.style.height = this.offsetHeight;
        this.sp.style.cursor = "w-resize";
        this.sp.onmousedown = function(e) {
            this.style.filter = "alpha(opacity=20)";
            this.style.width = 100;
            this.style.left = this.bar.offsetLeft - 50;
            this.setCapture();
            var e = e || event;
            this.onmousemove = function() {
                var x = e.clientX, y = e.clientY;
                this.style.left = x - 50;
            };
            this.onmouseout = this.onmouseup = function() {
                this.style.display = "none";
                this.releaseCapture();
                this.bar.parentElement.cells[0].style.width = this.offsetLeft + 50;
                this.onmouseout = this.onmouseup = function() {
                    this.style.display = "none";
                };
                this.onmousemove = function() { };

            };
            this.bar.onmouseup = function() {
                this.sp.style.display = "none";
            };
        };
    };
}
