/**
* 各種 POPUP 用視窗應用
*/
// 設定 POPUP 視窗，自動置左上或右上
var popupAdminWin;
function openWin(url, winName, w, h, pos)
{
  var pos = (pos === (void 0)) ? '0' : (screen.availWidth - w - 10);
  if (!popupAdminWin) {
    popupAdminWin = window.open(url, winName, 'width=' + w + ',height=' + h + ',scrollbars=no,top=0,left=' + pos + ',resizable=1');
  } else if (!popupAdminWin.closed) {
    popupAdminWin.location.href = url;
  } else {
    popupAdminWin = window.open(url, winName, 'width=' + w + ',height=' + h + ',scrollbars=no,top=0,left=' + pos + ',resizable=1');
  }
  popupAdminWin.focus();
}

// 客製決定上下左右位置，沒設定的話就置中
function openWin2(url, winName, w, h, t, l, s)
{
  var cTop  = screen.height/2 - (h/2);
  var cLeft = screen.width/2 - (w/2);
  var t = (t === (void 0)) ? cTop : t;
  var l = (l === (void 0)) ? cLeft : l;
  var s = (s === (void 0)) ? 'no' : 'yes';
  if (!popupAdminWin) {
    popupAdminWin = window.open(url, winName, 'width=' + w + ',height=' + h + ',scrollbars=' + s + ',top=' + t + ',left=' + l + ',resizable=1');
  } else if (!popupAdminWin.closed) {
    popupAdminWin.location.href = url;
  } else {
    popupAdminWin = window.open(url, winName, 'width=' + w + ',height=' + h + ',scrollbars=' + s + ',top=' + t + ',left=' + l + ',resizable=1');
  }
  popupAdminWin.focus();
}

// 設定可由 cookie 控制的視窗
function openCookieWin(url, winName, w, h, pos)
{
  var favorite = GetCookie('switch');
  if (favorite != 'off') {
    openWin(url, winName, w, h, pos);
  }
}

// 螢幕置中視窗
function openCenterWin(url, nameW, w, h, scroll)
{
  var s = (scroll === (void 0)) ? 0 : 1;
  if (navigator.appVersion.indexOf('4') != -1) {
    var cTop  = screen.height/2 - (h/2);
    var cLeft = screen.width/2 - (w/2);
    popupAdminWin = window.open(url, nameW, 'height=' + h + ',width=' + w + ',scrollbars=' + s + ',resizable=1,menubar=0,toolbar=0,status=0,location=0,directories=0,left=' + cLeft + ',top=' + cTop);
  }
  else {
    popupAdminWin = window.open(url, nameW, 'height=' + h + ',width=' + w + ',scrollbars=' + s + ',resizable=1,menubar=0,toolbar=0,status=0,location=0,directories=0,left=150,top=200');
  }
  popupAdminWin.focus();
}

// 全螢幕視窗
function openFullWin(url, winname)
{
  var strFeatures = "left=0,screenX=0,top=0,screenY=0,resizable,location,menubar,scrollbars,status,toolbar";
  if (window.screen) {
    var maxh = screen.availHeight - 146;
    var maxw = screen.availWidth - 10;
    strFeatures += ",height=" + maxh;
    strFeatures += ",innerHeight=" + maxh;
    strFeatures += ",width=" + maxw;
    strFeatures += ",innerWidth=" + maxw;
  }
  winID = window.open(url, winname, strFeatures);
}

/**
* 設定 Browser 狀態列訊息，用以隱藏預設狀態訊息
*
* @param string the message to show on status bar of window
*/
window.defaultStatus = "";
function winStatus(msg)
{
  window.status = msg;
}

/**
* 刪除時確認用函式 (機車版)
*
* @return boolean true or false
*/
function really()
{
  var flag = false;
  var A = prompt("若確定要刪除這筆資料，\n請輸入英文大寫字母：YES，然後按「確定」。", "No!");

  if (A == "yes") {
    alert("您輸入的是小寫喔。\n\n若您真的非刪除不可，請輸入大寫 YES 好嗎？");
  }
  else if (A == "Yes" || A == "YEs" || A == "YeS" || A == "yeS" || A == "yES" || A == "yEs") {
    alert("若您真的非刪除不可，YES 必須全部大寫才行！");
  }
  else if (A != "YES" && A != "No!") {
    alert("拜託∼，請勿跟程式開玩笑！");
  }
  else if (A == "YES") {
    alert("遵命，小的這就刪除！");
    flag = true;
  }

  return flag;
}

/**
* 表單輸入欄位 MouseFouse 時，清除預設提示文字
*
* Here is an inline example:
* <code>
* <input type="text" name="k" value="請輸入關鍵字" style="width:90px;"
*        onfocus="clearMe(this);" onblur="restore(this, '請輸入關鍵字');" />
* </code>
*
* 預設的提示文字 ('請輸入關鍵字')，可在 submit 查詢後，由程式動態變化
*
* @param object the form input element object
*/
function clearMe(control)
{
  control.value = '';
}

/**
* 表單輸入欄位 MouseBlur 時，回復預設提示文字
*
* @param object the form input element object
* @param string the string to prompt
*/
function restore(control, str)
{
  if (control.value == '') control.value = str;
}

/**
* 過濾欄位字串前後空白用方法(並去除不合法字元)
* 此函式將在稍後宣告為 String Object's prototype method
*/
function trim()
{
  if (!this) return this;

  // 濾掉字串前後的空白
  for (var begin = 0; begin < this.length; begin++) {
    if (this.charAt(begin) != " ") break;
  }
  for (var end = this.length; end > 0; end--) {
    if (this.charAt(end - 1) != " ") break;
  }

  return this.slice(begin, end);
}

/**
* 檢查欄位是否只包含空白字元
* 此函式將在稍後宣告為 String Object's prototype method
*/
function isEmpty()
{
  if (!this) return true;

  for (var len = 0; len < this.length; len++) {
    if (this.charAt(len) != " ") return false;
  }

  return true;
}

// 將以上 trim 及 isEmpty 兩函式宣告為 String 的屬性
String.prototype.trim = trim;
String.prototype.isEmpty = isEmpty;

/**
* 單純過濾字串前後空白用函式
*
* @param string the string to trim
*/
function trim2(str)
{
  // Immediately return if no trimming is needed
  if ((str.charAt(0) != ' ') && (str.charAt(str.length - 1) != ' ')) {
    return str;
  }
  // Trim leading spaces
  while (str.charAt(0) == ' ') {
    str = '' + str.substring(1, str.length);
  }
  // Trim trailing spaces
  while (str.charAt(str.length - 1)  == ' ') {
    str = '' + str.substring(0, str.length - 1);
  }

  return str;
}

/**
* 顯示管理訊息，可選用 Alert 或寫檔模式
*
* @param string the message to show
* @param string the mode of show message: 'alert' or else
*/
var _console = null;
function adminAlt(msg, type)
{
  if (msg != null && trim2(msg) != "") {
    if (type == 'alert') {
      alert(msg);
    }
    else {
      if ((_console == null) || (_console.closed)) {
        var width = 640;
        var height = 480;
        var left = screen.width/2 - (width/2);
        var top = screen.height/2 - (height/2);
        _console = window.open("", "console", "top=" + top + ",left=" + left + ",width=" + width + ",height=" + height + ",resizable,scrollbars");
        _console.document.open("text/html");
      }
      _console.focus();
      _console.document.writeln('<pre>');
      _console.document.writeln(msg);
      _console.document.writeln('</pre>');
      _console.document.writeln('<hr style="height: 1px; color: #333;" />');
      _console.document.writeln('<div align="center"><form action="" style="margin: 0;">');
      _console.document.writeln('<input type="button" value="關閉此視窗" style="font: 12px/17px Arial, sans-serif; color: #333;" onclick="window.close();" />');
      _console.document.writeln('</form></div>');
      _console.document.close();
    }
  }
}

/**
* 核取所有 checkbox 用於大量處理資料
*
* 可用於大量複製、搬移或刪除等功能
* 本函式假設所有 checkbox 同時用於單一用途
* 並設定觸發的 checkbox 名稱為 'selectAll'
*
* @param object the form object
*/
function selectAllBox(fm)
{
  var size = fm.elements.length;
  if (fm.selectAll.checked) {
    for (var i = 0; i < size; i++) {
      var tempobj = fm.elements[i];
      if (tempobj.type.toLowerCase() == "checkbox" && !tempobj.checked) {
        tempobj.checked = true;
      }
    }
  }
  else {
    for (var i = 0; i < size; i++) {
      var tempobj = fm.elements[i];
      if (tempobj.type.toLowerCase() == "checkbox" && tempobj.checked) {
        tempobj.checked = false;
      }
    }
  }
  // 最後讓焦點由 checkbox 轉移到頁面上
  document.body.focus();
}

/**
* 模仿 Win32's UI or HTML alt 功能，即時產生提示訊息
*
* Here is an inline example:
* <code>
* <style type="text/css">
* <!--
* .alt { position: absolute; visibility: hidden; background: #FFFFDD;
*        border: 1px solid; padding: 3px 4px; z-index: 300;
*        font: 11px Arial, sans-serif; text-align: center; vertical-align: middle; }
* -->
* </style>
* <div id="tag1" class="alt" style="width: 118px;">Here is Hint Alt!</div>
* <div onmouseover="chipHelp('tag1', 'visible', event.x, event.y);" 
*      onmouseout="chipHelp('tag1', 'hidden', 0, 0);">Here is Front-End Object!</div>
* </code>
*
* @param string the div element id name
* @param string visible or hidden
* @param object event.x position
* @param object event.y position
*/
function chipHelp(tagname, types, x, y)
{
  if (document.layers) {
    //document.layers[tagname].x  = document.body.scrollTop + x;
    //document.layers[tagname].y  = document.body.scrollLeft + y;
    document.layers[tagname].x  = x;
    document.layers[tagname].y  = y;
    document.layers[tagname].visibility  = types;
  }
  if (document.all) {
    theRealTop = parseInt(document.body.scrollTop);
    theTrueTop = y + theRealTop;
    document.all[tagname].style.top = theTrueTop + 10;
    theRealLeft = parseInt(document.body.scrollLeft);
    theTrueLeft = x + theRealLeft;
    document.all[tagname].style.left = theTrueLeft - 60;
    document.all(tagname).style.visibility = types;
  }
}

/**
* 清除 Multi-Select 的選擇
*
* @deprecated 建議改用下方 setSelectOptions() 取代本功能
* @param object the form object
* @param string the element name
*/
function clearSelect(fm, name)
{
  var maxSize = fm.length;

  for (var i = 0; i < maxSize; i++) {
    if (eval('fm.elements[' + i + '].type') == 'select-multiple') {
      if (eval('fm.elements[' + i + '].name').indexOf(name) != -1) {
        eval('fm.elements[' + i + '].selectedIndex = 1000000000;');
      }
    }
  }
}

/**
* Checks/unchecks all options of a <select> element
*
* 對 Multi-Select 作【全部選擇】或【清除選擇】
*
* @param  object  the form object
* @param  string  the element name
* @param  boolean whether to check or to uncheck the element
*
* @return boolean always true
*/
function setSelectOptions(fm, the_select, do_check)
{
    var selectObject = fm.elements[the_select];
    var selectCount  = selectObject.length;

    for (var i = 0; i < selectCount; i++) {
        selectObject.options[i].selected = do_check;
    } // end for

    return true;
} // end of the 'setSelectOptions()' function

/**
* Submit 防呆功能
*
* 在送出表單且 JS 驗證無誤後，
* 將送出及重置的按鈕 disable 起來，
* 以防止傳輸時間過久，使用者懷疑未送出，
* 再重覆送一次資料給程式。
*
* @param object the form object
*/
function submitOnce(fm)
{
    // if IE 4+ or NS 6+
    if (document.all || document.getElementById) {
        // hunt down "submit" and "reset"
        for (var i = 0; i < fm.length; i++) {
            var tempobj = fm.elements[i];
            if (tempobj.type && (tempobj.type.toLowerCase() == "submit"
                                    || tempobj.type.toLowerCase() == "reset")) {
                //disable it
                tempobj.value = '傳輸中…';
                tempobj.disabled = true;
            }
        }
    }
}

/**
* Format selected string to HTML style tag.
*
* Format string that be selected by user
* to bold <b></b> or italic <i></i> or underline <u></u> HTML style tag.
*
* @param string the string to format
*/
function formatStr(v)
{
    if (!document.selection) return;
    var str = document.selection.createRange().text;
    if (!str) return;
    document.selection.createRange().text = '<' + v + '>' + str + '</' + v + '>';
}

/**
* Insert link string to HTML style tag.
*
* Insert link string that be selected by user
* to HTML style tag.
*/
function insertLink()
{
    if (!document.selection) return;
    var str = document.selection.createRange().text;
    if (!str) return;
    var my_link = prompt('請輸入網址:', 'http://');
    if (my_link != null)
        document.selection.createRange().text = '<a href="' + my_link + '">' + str + '</a>';
}

/**
* 檢查公司統一編號格式是否正確
*/
function isCompID(compID)
{
    var cx = new Array();
    var cy = new Array();
    var cm = 0;
    var cs = 0;

    if (!compID.match(/^[0-9]{8}$/)) { return false; }
    if (compID.match(/^0{8}$/)) { return false; }

    cx[0] = parseInt(compID.substr(0, 1), 10) * 1;
    cx[1] = parseInt(compID.substr(1, 1), 10) * 2;
    cx[2] = parseInt(compID.substr(2, 1), 10) * 1;
    cx[3] = parseInt(compID.substr(3, 1), 10) * 2;
    cx[4] = parseInt(compID.substr(4, 1), 10) * 1;
    cx[5] = parseInt(compID.substr(5, 1), 10) * 2;
    cx[6] = parseInt(compID.substr(6, 1), 10) * 4;
    cx[7] = parseInt(compID.substr(7, 1), 10) * 1;
    
    cy[0] = parseInt(cx[1] / 10, 10);
    cy[1] = cx[1] % 10;
    cy[2] = parseInt(cx[3] / 10, 10);
    cy[3] = cx[3] % 10;
    cy[4] = parseInt(cx[5] / 10, 10);
    cy[5] = cx[5] % 10;
    cy[6] = parseInt(cx[6] / 10, 10);
    cy[7] = cx[6] % 10;

    cs = cx[0] + cx[2] + cx[4] + cx[7] + cy[0] + cy[1] + cy[2] + cy[3] + cy[4] + cy[5] + cy[6] + cy[7];
    cm = cs % 10;

    if (7 == parseInt(compID.substr(6, 1), 10))
    {
        if (0 == cm)
        {
            return true;
        }
        else
        {
            cm = (++cs) % 10;

            return (0 == cm) ? true : false;
        }
    }
    else
    {
        return (0 == cm) ? true : false;
    }
}

/**
* 取得 DHTML 操作物件
*/
var DHTML = (document.getElementById || document.all || document.layers);

function getLayerObj(name)
{
    if (document.getElementById)
    {
        return document.getElementById(name);
    }
    else if (document.all)
    {
        return document.all(name);
    }
    else if (document.layers)
    {
        return document.layers[name];
    }
}

/**
* 檢查是否為中文字元
*/
function isBig5(str)
{
    var strlen, c, cc
    strlen = str.length;

    if (strlen > 0)
    {
        for (var i = 0; i < strlen; i++)
        {
            c = escape(str.charAt(i));
            if ('%' == c.charAt(0))
            {
                cc = c.charAt(1);
                // IE~u, NS~A
                if ('A' == cc || 'u' == cc)
                {
                    return true;
                }
            }
        }

        return false;
    }
    else
    {
        return false;
    }
}

function isLetter(str)
{
    var chk_result = true;

    for (var i = 0; i < str.length; i++)
    {
        if (str.charAt(i).toLowerCase() < "a" || str.charAt(i).toLowerCase() > "z")
        {
            chk_result = false;
            break;
        }
    }

    return chk_result;
}

function isNumber(str)
{
    var chk_result = true;

    for (var i = 0; i < str.length; i++)
    {
        if (str.charAt(i) < "0" || str.charAt(i) > "9")
        {
            chk_result = false;
            break;
        }
    }

    return chk_result;
}

var ns6 = document.getElementById && !document.all;
var previous = '';
var eventobj;
var intended = /INPUT|TEXTAREA|SELECT|OPTION/;
var highlightcolor = 'FFFFAA';

function checkel(which)
{
    if (which.style && intended.test(which.tagName))
    {
        if (ns6 && eventobj.nodeType == 3) { eventobj = eventobj.parentNode.parentNode; }
        return true;
    }
    else
    {
        return false;
    }
}

function highlight(e)
{
    eventobj = ns6 ? e.target : event.srcElement;

    if (previous != '')
    {
        if (checkel(previous)) { previous.style.backgroundColor = ''; }
        previous = eventobj;
        if (checkel(eventobj)) { eventobj.style.backgroundColor = highlightcolor; }
    }
    else
    {
        if (checkel(eventobj)) { eventobj.style.backgroundColor = highlightcolor; }
        previous = eventobj;
    }
}

// Pop up a new window during waiting for loading the next page
var wchild;
var bWin = 0;
function openwait(url, w, h)
{
  if (!wchild) {
    wchild = window.open(url, "wait", "top=0,left=60,toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no,width=" + w + ",height=" + h);
  } else if (!wchild.closed) {
    wchild.location.href = url;
  } else {
    wchild = window.open(url, "wait", "top=0,left=60,toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no,width=" + w + ",height=" + h);
  }
  bWin = 1;
  wchild.focus();
}

function closewait()
{
  if (bWin == 1) {
    wchild.close();
  }
}

/**
 * This array is used to remember mark status of rows in browse mode
 */
var marked_row = new Array;

/**
 * Sets/unsets the pointer and marker in browse mode
 *
 * @param   object    the table row
 * @param   integer  the row number
 * @param   string    the action calling this script (over, out or click)
 * @param   string    the default background color
 * @param   string    the color to use for mouseover
 * @param   string    the color to use for marking a row
 *
 * @return  boolean  whether pointer is set or not
 */
function setPointer(theRow, theRowNum, theAction, theDefaultColor, thePointerColor, theMarkColor)
{
    var theCells = null;

    // 1. Pointer and mark feature are disabled or the browser can't get the
    //    row -> exits
    if ((thePointerColor == '' && theMarkColor == '')
        || typeof(theRow.style) == 'undefined') {
        return false;
    }

    // 2. Gets the current row and exits if the browser can't get it
    if (typeof(document.getElementsByTagName) != 'undefined') {
        theCells = theRow.getElementsByTagName('td');
    }
    else if (typeof(theRow.cells) != 'undefined') {
        theCells = theRow.cells;
    }
    else {
        return false;
    }

    // 3. Gets the current color...
    var rowCellsCnt  = theCells.length;
    var domDetect    = null;
    var currentColor = null;
    var newColor     = null;
    // 3.1 ... with DOM compatible browsers except Opera that does not return
    //         valid values with "getAttribute"
    if (typeof(window.opera) == 'undefined'
        && typeof(theCells[0].getAttribute) != 'undefined') {
        currentColor = theCells[0].getAttribute('bgcolor');
        domDetect    = true;
    }
    // 3.2 ... with other browsers
    else {
        currentColor = theCells[0].style.backgroundColor;
        domDetect    = false;
    } // end 3

    // 3.3 ... Opera changes colors set via HTML to rgb(r,g,b) format so fix it
    if (currentColor.indexOf("rgb") >= 0)
    {
        var rgbStr = currentColor.slice(currentColor.indexOf('(') + 1,
                                     currentColor.indexOf(')'));
        var rgbValues = rgbStr.split(",");
        currentColor = "#";
        var hexChars = "0123456789ABCDEF";
        for (var i = 0; i < 3; i++)
        {
            var v = rgbValues[i].valueOf();
            currentColor += hexChars.charAt(v/16) + hexChars.charAt(v%16);
        }
    }

    // 4. Defines the new color
    // 4.1 Current color is the default one
    if (currentColor == ''
        || currentColor.toLowerCase() == theDefaultColor.toLowerCase()) {
        if (theAction == 'over' && thePointerColor != '') {
            newColor              = thePointerColor;
        }
        else if (theAction == 'click' && theMarkColor != '') {
            newColor              = theMarkColor;
            marked_row[theRowNum] = true;
            // Garvin: deactivated onclick marking of the checkbox because it's also executed
            // when an action (like edit/delete) on a single item is performed. Then the checkbox
            // would get deactived, even though we need it activated. Maybe there is a way
            // to detect if the row was clicked, and not an item therein...
            // document.getElementById('id_rows_to_delete' + theRowNum).checked = true;
        }
    }
    // 4.1.2 Current color is the pointer one
    else if (currentColor.toLowerCase() == thePointerColor.toLowerCase()
             && (typeof(marked_row[theRowNum]) == 'undefined' || !marked_row[theRowNum])) {
        if (theAction == 'out') {
            newColor              = theDefaultColor;
        }
        else if (theAction == 'click' && theMarkColor != '') {
            newColor              = theMarkColor;
            marked_row[theRowNum] = true;
            // document.getElementById('id_rows_to_delete' + theRowNum).checked = true;
        }
    }
    // 4.1.3 Current color is the marker one
    else if (currentColor.toLowerCase() == theMarkColor.toLowerCase()) {
        if (theAction == 'click') {
            newColor              = (thePointerColor != '')
                                  ? thePointerColor
                                  : theDefaultColor;
            marked_row[theRowNum] = (typeof(marked_row[theRowNum]) == 'undefined' || !marked_row[theRowNum])
                                  ? true
                                  : null;
            // document.getElementById('id_rows_to_delete' + theRowNum).checked = false;
        }
    } // end 4

    // 5. Sets the new color...
    if (newColor) {
        var c = null;
        // 5.1 ... with DOM compatible browsers except Opera
        if (domDetect) {
            for (c = 0; c < rowCellsCnt; c++) {
                theCells[c].setAttribute('bgcolor', newColor, 0);
            } // end for
        }
        // 5.2 ... with other browsers
        else {
            for (c = 0; c < rowCellsCnt; c++) {
                theCells[c].style.backgroundColor = newColor;
            }
        }
    } // end 5

    return true;
} // end of the 'setPointer()' function

/*
* Checks if a value exists in an array
*
* Input: strVal [string] -> the value wanna find
*        objArr [array]  -> search target array data
*
* Return: searches objArr for strVal and returns True
*         if it is found in the array, False otherwise
*/
function inArray(strVal, objArr)
{
    var hasVal = false;
    var size = objArr.length;
    
    if (size > 0)
    {
        for (var i = 0; i < size; i++)
        {
            if (strVal == objArr[i])
            {
                hasVal = true;
                break;
            }
        }
    }

    return hasVal;
}