﻿/* ===================================================
* ais.webform.js v1.0.0
* javascript library for AIS WebForm
* ==================================================== */
var _DocumentTitle = document.title;
var _Timer = 10;
var _RootPath = "__ROOTPATH";  // 網站根目錄
var _GridClientID = "__GRIDCLIENTID";  // 表身 GridView 的 ClientID 集合字串
var _ValueChangeID = "__VALUECHANGEID";  // 記錄欄位值變更的成員識別
var _FlowRevoke = "__FLOWREVOKE";  // 撤銷是否執行送審

// 傳入網站相對路徑，取得完整網址
function $getUrl(path) {
    var rootPath = document.getElementById(_RootPath).value;
    return rootPath + path;
}

// 執行 PostBack 動作
function $doPostBack(eventTarget, eventArgument) {
    __doPostBack(eventTarget, eventArgument);
}

// 父頁面執行 PostBack 動作
function $doParentPostBack(eventTarget, eventArgument) {
    var oFrame;
    var oParent;
    // 先判斷是否為 RWD 的 iFrame
    oFrame = top.document.getElementById("PageContent_FrameContent");
    if (oFrame != null) {
        oParent = oFrame.contentWindow;
        if (oParent.__doPostBack != null) {
            oParent.$showLoading();   // 顯示等待圖示
            oParent.__doPostBack(eventTarget, eventArgument);
        }
    }
    else if (window.opener) {
        if (window.opener.__doPostBack != null)
            window.opener.__doPostBack(eventTarget, eventArgument);
    }
    else {
        if (parent.__doPostBack != null)
            parent.__doPostBack(eventTarget, eventArgument);
    }

    // 隱藏強制回應視窗
    parent.$hideModal();
}

// 要求 EditForm 執行 PostBack 動作
function $doEditFormPostBack(eventTarget, eventArgument) {
    window.parent.frames[1].__doPostBack(eventTarget, eventArgument);
}

// 要求 ListForm 執行 PostBack 動作
function $doListFormPostBack(eventTarget, eventArgument) {
    window.parent.frames[0].__doPostBack(eventTarget, eventArgument);
}

// 使用 DevCallback 呼叫
function $doCallback() {
    callbackControl.PerformCallback();
}

// 使用 DevCallback 取回資訊
function doCallbackComplete(s, e) {
    var obj = $.parseJSON(e.result);

    $.each(obj.UpdateFields, function (i, item) {
        var ObjName;
        if (item.TableName != "") {
            ObjName = item.TableName + "." + item.FieldName;
        } else {
            ObjName = item.FieldName;
        }

        if (window[ObjName] instanceof ASPxClientTextBox || window[ObjName] instanceof ASPxClientDateEdit) {
            window[ObjName].SetText(item.FieldValue);
        }
        else if (window[ObjName] instanceof ASPxClientCheckBoxList) {
            window[ObjName].SelectValues(item.FieldValue);
        }
        else if (window[ObjName] instanceof ASPxClientCheckBox || window[ObjName] instanceof ASPxClientRadioButton) {
            window[ObjName].SetChecked(item.FieldValue); //FieldValue = (True 或 False)
        }
        else if (window[ObjName] instanceof ASPxClientDropDownEdit) {
            $DDC_GetName(ObjName);
            var texts = $DDC_GetTextsByValues(item.FieldValue.split(DDC_textSeparator));
            window[ObjName].SetKeyValue(item.FieldValue);
            window[ObjName].SetValue(texts);
        }
        else {
            window[ObjName].SetValue(item.FieldValue);
        }
    });

    eval(obj.ClientScript);
}

//使用 CallBack 回呼時，取得用戶端引發 PageCommand 事件的引數
function $getPageCommandArgument(commnadName, value) {
    //用戶端物件執行 JSON 序列化
    var sArgument = JSON.stringify(value);
    return "PageCommand$" + commnadName + '$' + sArgument;
}

//執行 CallBack 回呼時，處理伺服端傳回的資料
function $processCallBackResult(value) {
    //將伺服端傳回的 JSON 字串反序列化為 CallBackResult 物件
    var oResult = JSON.parse(value);
    if (oResult.ClientScript != '') {
        eval(oResult.ClientScript);
    }
}

//開新視窗
function $openWindow(url, target, features) {
    var oWidnow = window.open(url, target, features);
    if (oWidnow != null) {
        oWidnow.opener = window;
        //開啟新視窗後，對此新視窗做Focus的動作
        setTimeout(function () { oWidnow.focus(); }, 300);
    }
}

// 開新視窗
function $openWindowEx(url, target, width, height, resizable, scrollbars, features) {
    var sFeatures = "";
    var sScrollbars = "yes";
    var sResizable = "yes";

    if (features != "")
        sFeatures = features + ",";

    if ((width > 0) && (height > 0)) {
        var iLeft = (screen.width) ? (screen.width - width) / 2 : 100;
        var iTop = (screen.height) ? (screen.height - height) / 2 : 100;
        sFeatures = sFeatures + "width=" + width + ",height=" + height + ",top=" + iTop + ",left=" + iLeft;
    }

    if (scrollbars == false)
        sScrollbars = "no";
    if (resizable == false)
        sResizable = "no";

    sFeatures = sFeatures + "menubar=no,toolbar=no,location=no,scrollbars=" + sScrollbars + ",resizable=" + sResizable;

    $openWindow(url, target, sFeatures);
}

// 頁面限時關閉
function $timerClose() {
    _Timer = _Timer - 1;
    document.title = _DocumentTitle + " [" + _Timer + ' sec]';
    if (_Timer > 0)
        setTimeout("$timerClose();", 1000);
    else {
        window.opener = null;
        window.close();
    }
}

// 關閉視窗
function $windowClose(message) {
    if (message != '') { alert(message); }
    window.opener = null;
    window.close();

    // 隱藏強制回應視窗
    parent.$hideModal();
}

// 子視窗回傳值給父視窗的控制項
function $ReturnValue(id, value) {
    var oControl;
    var oFrame;

    if (id == "Search") {
        $doParentPostBack("EditForm$Move", value);
    }
    else {
        // 先判斷是否為 RWD 的 iFrame 中的控制項
        oFrame = top.document.getElementById("PageContent_FrameContent");
        if (oFrame != null) {
            oControl = oFrame.contentWindow.document.getElementById(id);
        } else {
            if (opener != undefined)
                oControl = opener.window.document.getElementById(id);
            else
                oControl = parent.document.getElementById(id);
        }

        oControl.value = value;
        if (oControl.onchange != null)
            oControl.onchange();
    }

    // 隱藏強制回應視窗
    parent.$hideModal();

    if (opener != undefined)
        window.close();
    else
        parent.jQuery.colorbox.close();

    return false;
}

// GridView 右鍵選單 Click 事件處理方法
function $gridviewContextMenuItemClick(s, e) {
    if (e.item.name == "ExportXlsx" || e.item.name == "ImportExcelTemplate" || e.item.name == "ImportFromExcel" ||
        e.item.name == "SaveUserLayout" || e.item.name == "SaveCompanyLayout") {
        e.processOnServer = true;
        e.usePostBack = true;
    }

}

// GridView ValueChanged 導向方法
function $gridviewValueChanged(s, gridview, fieldName) {
    var oNewValue;
    var sArgs;

    oNewValue = s.GetValue();
    sArgs = "FieldValueChange|" + fieldName + '|' + oNewValue;
    gridview.PerformCallback(sArgs);
}

// GridView ButtonClick 導向方法
function $gridviewButtonClick(gridview, fieldName, buttonIndex) {
    var sArgs;

    sArgs = "ButtonClick|" + fieldName + "|" + buttonIndex;
    gridview.PerformCallback(sArgs);
}

// GridView RowClick 導向方法
function $gridviewRowClick(s, e) {
    // 設定焦點列
    s.SetFocusedRowIndex(e.visibleIndex);
    // 資料列設為編輯模式
    s.StartEditRow(e.visibleIndex);
}

// 記錄 GridView 垂直軸捲位置
var _gvVerticalScrollPosition = 0;

// GridView BeginCallback 導向方法
function $gridviewBeginCallback(s, e) {
    // alert(e.command);
    // 儲存垂直軸捲位置
    _gvVerticalScrollPosition = s.GetVerticalScrollPosition();
    if (e.command == "ADDNEWROW") {
        _gvVerticalScrollPosition = 10000;  // 新增時設垂直軸捲位置為極大值，使其移至新增列
    }
}

// GridView EndCallback 導向方法
function $gridviewEndCallback(s, e) {
    //alert("EndCallback");
    // 還原垂直軸捲位置
    if (_gvVerticalScrollPosition > 0) {
        s.SetVerticalScrollPosition(_gvVerticalScrollPosition);
    }
    if (s.cpScript) {
        eval(s.cpScript);
    }
    if (s.cpFocusEditor) {
        s.FocusEditor(s.cpFocusEditor);
    }
}

// 判斷 GridView 是否於編輯狀態，若為編輯狀態則執行 EndUpdate 做資料更新
function $gridviewEndUpdate() {
    var oGridView;
    var sNames;
    var oNames;

    sNames = $("#" + _GridClientID).val();
    if (typeof sNames == "undefined") { return false; }
    if (sNames == "") { return false; }

    // GridView 若為編輯狀態則執行 EndUpdate
    oNames = sNames.split(",");
    for (i = 0; i < oNames.length; i++) {
        try {
            oGridView = eval(oNames[i]);
            if (oGridView.IsEditing()) {
                oGridView.UpdateEdit();
                return true;
            }
        } catch (e) {
            // 無法取得 GridView 則略過錯誤
        }
    }
    return false;
}

// 頁面初始化
function $pageInitialize() {
    var prm = Sys.WebForms.PageRequestManager.getInstance();
    prm.add_initializeRequest($InitializeRequest);
    prm.add_pageLoaded($pageLoaded);
}

function $InitializeRequest(sender, args) {
    if (typeof LoadingPanel != "undefined")
        LoadingPanel.Show();  // 顯示等待圖示
}

function $pageLoaded(sender, args) {
    var panels = args.get_panelsUpdated();
    if ((panels.length > 0) && (typeof LoadingPanel != "undefined")) {
        LoadingPanel.Hide();  // 隱藏等待圖示
    }
}

// 顯示等待圖示
function $showLoading() {
    if (typeof LoadingPanel != "undefined")
        LoadingPanel.Show();
}

// 設定 IFrame 顯示網頁
function $setFrameUrl(url) {
    var oFrame;

    oFrame = window.parent.document.getElementById("FrameMain");
    if (oFrame != null) {
        // 若為 EditForm 則顯示捲軸，反之不顯示捲軸
        if (url.indexOf('TEditForm.aspx') != -1) {
            oFrame.scrolling = "yes";
        } else {
            oFrame.scrolling = "no";
        }
        oFrame.src = url;
    }
}

// EditForm 調整控制項大小
function $editFormAdjustSize(tableDefineHeight) {
    var iHeight;
    var iDocHeight;
    var oGridView;
    var sNames;
    var oNames;
    var oDefintHeight;
    var oTableHeight;
    var sDefineHeight;

    sNames = $("#" + _GridClientID).val();
    if (typeof sNames == "undefined") { return false; }
    if (sNames == "") { return; }

    oDefintHeight = tableDefineHeight.split(",");

    // 計算頁面高度
    iDocHeight = Math.max(0, document.documentElement.clientHeight);
    // 計算 GridView 高度
    iHeight = iDocHeight - $("#tabGroup").offset().top - 70;
    // 設定 GridView 高度
    oNames = sNames.split(",");
    for (i = 0; i < oNames.length; i++) {
        oGridView = eval(oNames[i]);

        sDefineHeight = "";
        for (j = 0; j < oDefintHeight.length; j++) {
            if (oDefintHeight[j] != "") {
                oTableHeight = oDefintHeight[j].split(":");
                if (oTableHeight[0] == oNames[i]) {
                    sDefineHeight = oTableHeight[1];
                    break;
                }
            }
        }

        if (sDefineHeight != "") {
            if (parseInt(sDefineHeight) == NaN)
                oGridView.SetHeight(iHeight);
            else
                oGridView.SetHeight(sDefineHeight);
        }
        else {
            oGridView.SetHeight(iHeight);
        }
    }
}

// 表單結束編輯，傳回 true 表示欄位需先異動更新，中斷存檔動作
function $endUpdate() {
    var sValueChangeID;

    // 若 GridView 為編輯狀態則需先異動更新
    if ($gridviewEndUpdate()) {
        return true;
    }
    // 存檔前檢查是否有欄位異動需回呼伺服端
    sValueChangeID = $("#" + _ValueChangeID).val();
    if (sValueChangeID != '') {
        $ValueChangedReset(); // 清除 ValueChanged 記錄值
        return true;
    }
    return false;
}

// EditForm 工具列按鈕 Click 導向方法
function $editFormToolbarItemClick(s, e) {
    var sKey;
    var sValueChangeID;

    sKey = e.item.name;

    if (sKey == 'Save') {
        // 若 GridView 為編輯狀態則需先異動更新
        if ($gridviewEndUpdate()) {
            e.processOnServer = false;
            return;
        }
        // 存檔前檢查是否有欄位異動需回呼伺服端
        sValueChangeID = $("#" + _ValueChangeID).val();
        if (sValueChangeID != '') {
            e.processOnServer = false;
            $ValueChangedReset(); // 清除 ValueChanged 記錄值
            return;
        }
    } else if (sKey == 'Delete') {
        if (confirm(Language_0001) == false)  // 是否確定要刪除?
            e.processOnServer = false;
    } else if (sKey == 'Invalid') {
        if (confirm(Language_0002) == false)  // 是否確定要作廢?
            e.processOnServer = false;
    } else if (sKey == 'Approve') {
        if (confirm(Language_0005) == false)  // 是否確定要核准?
            e.processOnServer = false;
    } else if (sKey == 'Revoke') {
        // 若需要撤銷送審，則直接回伺服端處理彈出送審視窗
        var sFlowRevoke = $("#" + _FlowRevoke).val();
        if (sFlowRevoke == "true") { return; }

        if (confirm(Language_0006) == false)  // 是否確定要撤銷?
            e.processOnServer = false;
    } else if (sKey == "FormStatus") {
        e.processOnServer = false;
        return;
    } else if (sKey == 'First' || sKey == 'Previous' || sKey == 'Next' || sKey == 'Last') {
        e.processOnServer = false;
        $doListFormPostBack("ListForm$" + sKey, "");
        return;
    }
}

// 開啟簽核頁面
// flowWaitID : 流程等待識別
function $openFlowApprove(flowWaitID) {
    var url = $getUrl("Forms/FlowApprove.aspx?FlowWaitID=" + flowWaitID);
    $openWindowEx(url, '_blank', 1024, 768, true, true, '');
    return false;
}

// 開啟唯譯簽核頁面
// flowInstanceID : 流程實體識別
function $openFlowView(flowInstanceID) {
    var url = $getUrl("Forms/FlowApprove.aspx?FlowInstanceID=" + flowInstanceID + "&ViewMode=true");
    $openWindowEx(url, '_blank', 1024, 768, true, true, '');
    return false;
}

// 欄位 ValueChanged 事件導向方法
function $ValueChanged(s, e) {
    // s.lastChangedValue - 最後異動值
    // s.globalName - 全域名稱，同欄位名稱
    $("#" + _ValueChangeID).val(s.name);
}

// 清除 ValueChanged 記錄值
function $ValueChangedReset() {
    $("#" + _ValueChangeID).val('');
}

// ASPxPopupControl Shown 事件導向方法
function $onPopupShown(s, e) {
    var windowInnerWidth = window.innerWidth;
    if (s.GetWidth() > windowInnerWidth) {
        s.SetWidth(windowInnerWidth - 4);
        s.UpdatePosition();
    }
}

/**
 * 顯示強制回應視窗
 * @param {string} url 網址
 * @param {string} headerText 抬頭文字
 * @param {number} width 寬度
 * @param {number} height 高度
 * @param {string} closeReturnKey 關閉視窗引發父頁面 FormReutrnValue 事件的識別鍵值
 */
function $showModal(url, headerText, width, height, closeReturnKey) {
    if (width > window.innerWidth)
        width = window.innerWidth;
    if (height > window.innerHeight)
        height = window.innerHeight;

    if (width > 0)
        popupHelper.SetWidth(width);
    if (height > 0)
        popupHelper.SetHeight(height);

    popupHelper.SetHeaderText(headerText);
    //popupHelper.RefreshContentUrl();
    popupHelper.Show();
    popupHelper.SetContentUrl(url);
    popupHelper.CloseUp.ClearHandlers();
    if (closeReturnKey && (closeReturnKey != ""))
        popupHelper.CloseUp.AddHandler(function (s, e) { $closeReturn(e, closeReturnKey); });
}

/**
 * 關閉強制回應視窗引發父頁面 FormReutrnValue 事件
 * @param {any} e CloseUp 事件引數，ASPxClientPopupWindowCloseUpEventArgs 型別
 * @param {string} key 識別鍵值
 */
function $closeReturn(e, key) {
    if (e.closeReason == "CloseButton")
        $doParentPostBack("__Page", "PageCommand$FormReteurn$" + key);
}

/**
 * 隱藏強制回應視窗
 */
function $hideModal() {
    if (typeof popupHelper != "undefined") {
        popupHelper.Hide();
    }
}

// DropDownCheckList 控制項相關方法
var DDC_textSeparator = ",";
var DDC_Name = "";
var DDC_CheckListName = "";

function $DDC_GetName(name) {
    var oName = $("[id^='" + name + "']");
    DDC_Name = name;
    DDC_CheckListName = oName.find('.dxeListBox').attr('id');
}
function $DDC_SureDropDown() {
    $DDC_UpdateText();
    $DDC_HideDropDown();
}
function $DDC_HideDropDown() {
    window[DDC_Name].HideDropDown();
}
function $DDC_UpdateSelectAllItemState() {
    $CCD_IsAllSelected() ? window[DDC_CheckListName].SelectIndices([0]) : window[DDC_CheckListName].UnselectIndices([0]);
}
function $CCD_IsAllSelected() {
    var selectedDataItemCount = window[DDC_CheckListName].GetItemCount() - (window[DDC_CheckListName].GetItem(0).selected ? 0 : 1);
    return window[DDC_CheckListName].GetSelectedItems().length == selectedDataItemCount;
}
function $DDC_Changed(listBox, args) {
    if (args.index == 0)
        args.isSelected ? listBox.SelectAll() : listBox.UnselectAll();
    $DDC_UpdateSelectAllItemState();
    $DDC_UpdateText();
}
function $DDC_UpdateText() {
    var selectedItems = window[DDC_CheckListName].GetSelectedItems();
    var values = $DDC_GetItemsValue(selectedItems).split(DDC_textSeparator);
    window[DDC_Name].SetText($DDC_GetItemsText(selectedItems));
    window[DDC_Name].SetKeyValue(values);
}
function $DDC_SynListBoxValues(dropDown, args) {
    $DDC_GetName(dropDown.name);
    window[DDC_CheckListName].UnselectAll();
    var texts = window[DDC_Name].GetText().split(DDC_textSeparator);
    var values = $DDC_GetValuesByTexts(texts);
    window[DDC_CheckListName].SelectValues(values);
    $DDC_UpdateSelectAllItemState();
    $DDC_UpdateText(); // for remove non-existing texts
}

function $DDC_GetItemsValue(items) {
    var values = [];
    for (var i = 0; i < items.length; i++)
        if (items[i].index != 0)
            values.push(items[i].value);
    return values.join(DDC_textSeparator);
}
function $DDC_GetItemsText(items) {
    var texts = [];
    for (var i = 0; i < items.length; i++)
        if (items[i].index != 0)
            texts.push(items[i].text);
    return texts.join(DDC_textSeparator);
}

// 值轉換為顯示文字
function $DDC_GetTextsByValues(values) {
    var actualValues = [];
    var item;
    for (var i = 0; i < values.length; i++) {
        item = window[DDC_CheckListName].FindItemByValue(values[i]);
        if (item != null) {
            actualValues.push(item.text);
        }
    }
    return actualValues;
}

// 顯示文字轉換為值
function $DDC_GetValuesByTexts(texts) {
    var actualValues = [];
    var item;
    for (var i = 0; i < texts.length; i++) {
        item = window[DDC_CheckListName].FindItemByText(texts[i]);
        if (item != null)
            actualValues.push(item.value);
    }
    return actualValues;
}

function $initInp(inpId)
{
    var inp = document.getElementById(inpId);
	var sCaption; 
	sCaption = $("#Lang_CloseSearch").val();
	
    if (typeof inp !== 'undefined' && inp != null)
    {
        inp.value = sCaption;
    }
}

function $show(aiinId, inpId)
{
	var sCaption; 
    var aiin = document.getElementById(aiinId);
    var inp = document.getElementById(inpId);
    if (aiin.style.display != 'none')
    {
        aiin.style.display = 'none';
		sCaption = $("#Lang_ExtendSearch").val();
        inp.value = sCaption;
    }
    else
    {
        aiin.style.display = 'block';
		sCaption = $("#Lang_CloseSearch").val();
        inp.value = sCaption;
    }
    AdjustSize();
}