﻿
// 這是當使用者的瀏覽器沒有安裝 Silverlight 時，要顯示的替代內容（如果用 JavaScript 動態產生 Silverlight 物件，就會用得到）
var altSilverlightHtml = "<a href='{1}' style='text-decoration: none;'><img src='{2}' alt='{3}' style='border-style: none'/></a>";
altSilverlightHtml = altSilverlightHtml.replace('{1}', "javascript:Silverlight.getSilverlight('4.0.50401.0');");
altSilverlightHtml = altSilverlightHtml.replace('{2}', "http://go.microsoft.com/fwlink/?LinkId=161376");
altSilverlightHtml = altSilverlightHtml.replace('{3}', "Get Microsoft Silverlight");



function resizeSilverlight(height) {
    /// <summary>
    /// 提供 Silverlight 呼叫的函數，用意是當 Silverlight 外掛自己改變大小時，Html 中的父項目也要跟著改變大小
    /// </summary>
    var sl = document.getElementById("silverlightControlHost");
    sl.style.height = height + "px";
}


function onSilverlightError(sender, args) {
    var appSource = "";
    if (sender != null && sender != 0) {
        appSource = sender.getHost().Source;
    }

    var errorType = args.ErrorType;
    var iErrorCode = args.ErrorCode;

    if (errorType == "ImageError" || errorType == "MediaError") {
        return;
    }

    var errMsg = "Unhandled Error in Silverlight Application " + appSource + "\n";

    errMsg += "Code: " + iErrorCode + "    \n";
    errMsg += "Category: " + errorType + "       \n";
    errMsg += "Message: " + args.ErrorMessage + "     \n";

    if (errorType == "ParserError") {
        errMsg += "File: " + args.xamlFile + "     \n";
        errMsg += "Line: " + args.lineNumber + "     \n";
        errMsg += "Position: " + args.charPosition + "     \n";
    }
    else if (errorType == "RuntimeError") {
        if (args.lineNumber != 0) {
            errMsg += "Line: " + args.lineNumber + "     \n";
            errMsg += "Position: " + args.charPosition + "     \n";
        }
        errMsg += "MethodName: " + args.methodName + "     \n";
    }

    throw new Error(errMsg);
}



var Ar = {};
Ar.Ajax = {};

Ar.Ajax.XMLHttpRequest = (window.XMLHttpRequest) ?
    new XMLHttpRequest() :  // Gecko
        ((window.ActiveXObject) ? new ActiveXObject("MsXml2.XmlHttp") : null);  // IE


Ar.loadScriptFileAsync = function(scriptSrc) {
    /// <summary>
    /// 以非同步的方式動態載入 JavaScript 檔案，若要等到 script 載入完畢才繼續執行，請改用 loadScriptFile
    /// </summary>

    var script = document.createElement("script");
    script.type = "text/javascript";
    script.src = scriptSrc;
    document.getElementsByTagName("head")[0].appendChild(script);
}


Ar.loadScriptFile = function(scriptSrc) {
    /// <summary>
    /// 以同步的方式動態載入 JavaScript 檔案，利用 XMLHttpRequest 同步要求的特性，確定 script 完全載入後，才會繼續執行
    /// </summary>
    var xhr = Ar.Ajax.XMLHttpRequest;
    xhr.open('GET', scriptSrc, false);
    xhr.send(null);

    if (xhr.status == 200)
        window.eval(xhr.responseText);
}


Ar.loadCSSFile = function (cssSrc) {
    /// <summary>
    /// 以非同步的方式動態載入 CSS 檔案
    /// </summary>

    var css = document.createElement("link");
    css.type = "text/css";
    css.rel = "stylesheet";
    css.href = cssSrc;
    document.getElementsByTagName("head")[0].appendChild(css);
}


Ar.QueryString = function (name) {
    /// <summary>
    /// 找出網址中的查詢字串
    /// </summary>

    name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regexS = "[\\?&]" + name + "=([^&#]*)";
    var regex = new RegExp(regexS);
    var results = regex.exec(window.location.href);
    if (results == null)
        return "";
    else
        return results[1];
}



// -------------------- UI --------------------
Ar.UI = {};
Ar.UI.checkAllInTable = function (checkAllButton, tableId, columnIndex) {
    /// <summary>
    /// 對一個 Table 裡面所有 CheckBox 同時打勾或取消打勾
    /// </summary>
    var query;
    if ($ != undefined) query = $;
    else query = $telerik.$;

    var checked = checkAllButton.checked;
    var grid = $find(tableId);
    if (grid != null && grid.get_masterTableView) { // 這邊是針對 RadGrid 的 Script
        var masterTable = grid.get_masterTableView();
        var rowsLength = masterTable.get_dataItems().length;
        var dataItems = masterTable.get_dataItems();
        for (var i = 0; i < rowsLength; i++)
            if (checked) masterTable.selectItem(i); else dataItems[i].set_selected(false);
    }
    else if (columnIndex)   // 以下是一般的 DataGrid / GridView 或 Table
        query('#' + tableId + ' tr').each(function () {
            query(this).children("td").eq(columnIndex).find('input:checkbox').attr('checked', checked);
        });
    else
        query('#' + tableId + ' input:checkbox').attr('checked', checked);
}



// -------------------- Image --------------------
Ar.Image = {};
/// <summary>
/// 根據原始寬高，以及目標寬高，計算出不會讓圖變形的最佳尺寸
/// </summary>
Ar.Image.getProperSize = function (originWidth, originHeight, targetWidth, targetHeight) {
    var w0 = originWidth;
    var h0 = originHeight;
    var w1 = targetWidth;
    var h1 = targetHeight;
    var w, h;
    if (w0 > w1 && h0 <= h1)
    { w = w1; h = w1 * h0 / w0 }
    else if (w0 <= w1 && h0 > h1)
    { h = h1; w = h1 * w0 / h0 }
    else if (w0 > w1 && h0 > h1) {
        var delta = w1 / w0 - h1 / h0;
        if (delta >= 0) {
            h = h1;
            w = w0 * h1 / h0;
        }
        else {
            w = w1;
            h = h0 * w1 / w0;
        }
    }

    return { "width": w, "height": h };
}



function CountDown(spanID, TargetTimeInSec, spanHeader) {
    var daysms = 24 * 60 * 60;
    var hoursms = 60 * 60;
    var Secondms = 60;
    var BaseTime = new Date("Janu 1, 2000 0:0:0");
    var CurrentTime = new Date();
    var CurrentTimeInSec = Math.floor((CurrentTime.getTime() - BaseTime.getTime()) / 1000);
    //            window.alert(TargetTimeInSec + "-" + CurrentTimeInSec);

    Diff = TargetTimeInSec - CurrentTimeInSec;
    if (Diff < 0) Diff = 0;
    var dDay = Math.floor(Diff / daysms); Diff -= dDay * daysms;
    var dHour = Math.floor(Diff / hoursms); Diff -= dHour * hoursms;
    var dMinute = Math.floor(Diff / Secondms); Diff -= dMinute * Secondms;
    var dSecond = Math.floor(Diff);
    var countStr = spanHeader // "剩餘:&nbsp"
    if (dDay > 0) countStr += "<b>" + dDay + "</b>&nbsp;天";
    countStr += "&nbsp;<b>" + dHour + "</b>&nbsp;時";
    countStr += "&nbsp;<b>" + dMinute + "</b>&nbsp;分";
    countStr += "&nbsp;<b>" + dSecond + "</b>&nbsp;秒";
    document.getElementById(spanID).innerHTML = countStr;
    setTimeout("CountDown('" + spanID + "', '" + TargetTimeInSec + "', '" + spanHeader + "')", 1000);
}



function VSWindowLoad() {

    var viewportwidth;
    var viewportheight;
    var wndWidth;

    // the more standards compliant browsers (mozilla/netscape/opera/IE7) use window.innerWidth and window.innerHeight 

    if (typeof window.innerWidth != 'undefined') {
        viewportwidth = window.innerWidth;
        viewportheight = window.innerHeight;

    }

    // IE6 in standards compliant mode (i.e. with a valid doctype as the first line in the document) 

    else if (typeof document.documentElement != 'undefined'
     && typeof document.documentElement.clientWidth !=
     'undefined' && document.documentElement.clientWidth != 0) {
        viewportwidth = document.documentElement.clientWidth;
        viewportheight = document.documentElement.clientHeight;
    }

    // older versions of IE 

    else {
        viewportwidth = document.getElementsByTagName('body')[0].clientWidth;
        viewportheight = document.getElementsByTagName('body')[0].clientHeight;
    }

    wndWidth = viewportwidth - 60;
    if (wndWidth < 1008) wndWidth = 750;
    if (wndWidth > 1008) wndWidth = 750;
    if (viewportheight < 60) viewportheight = 60;

    window.radopen(null, 'VSWindow');
    var oWnd = GetRadWindowManager().GetWindowByName('VSWindow');

    oWnd.MoveTo((viewportwidth - wndWidth) / 2, 30);
    oWnd.SetSize(wndWidth, viewportheight - 60);


    window.scrollTo(0, 0);
    oWnd.togglePin();

}

function EDWindowLoad() {

    var viewportwidth;
    var viewportheight;
    var wndWidth;

    // the more standards compliant browsers (mozilla/netscape/opera/IE7) use window.innerWidth and window.innerHeight 

    if (typeof window.innerWidth != 'undefined') {
        viewportwidth = window.innerWidth;
        viewportheight = window.innerHeight;
    }

    // IE6 in standards compliant mode (i.e. with a valid doctype as the first line in the document) 

    else if (typeof document.documentElement != 'undefined'
     && typeof document.documentElement.clientWidth !=
     'undefined' && document.documentElement.clientWidth != 0) {
        viewportwidth = document.documentElement.clientWidth;
        viewportheight = document.documentElement.clientHeight;
    }


    // older versions of IE 

    else {
        viewportwidth = document.getElementsByTagName('body')[0].clientWidth;
        viewportheight = document.getElementsByTagName('body')[0].clientHeight;
    }

    wndWidth = viewportwidth;
    if (wndWidth < 700) wndWidth = 700;
    if (wndWidth > 1024) wndWidth = 1024;
    // 編輯區要盡量寬敞，暫時這樣修改，看看大家反應
    //            wndWidth = 1000
    if (viewportheight < 50) viewportheight = 50;

    window.radopen(null, 'EDWindow');
    var oWnd = GetRadWindowManager().GetWindowByName('EDWindow');

    //            oWnd.MoveTo((viewportwidth - wndWidth) / 2, 30);
    //            oWnd.SetSize(wndWidth, viewportheight - 35);

    oWnd.MoveTo((viewportwidth - wndWidth) / 2, 0);
    oWnd.SetSize(wndWidth, viewportheight);
    window.scrollTo(0, 0);
    oWnd.togglePin();

}



function CEWindowLoad() {

    var viewportwidth;
    var viewportheight;
    var wndWidth;

    // the more standards compliant browsers (mozilla/netscape/opera/IE7) use window.innerWidth and window.innerHeight 

    if (typeof window.innerWidth != 'undefined') {
        viewportwidth = window.innerWidth;
        viewportheight = window.innerHeight;
    }

    // IE6 in standards compliant mode (i.e. with a valid doctype as the first line in the document) 

    else if (typeof document.documentElement != 'undefined'
     && typeof document.documentElement.clientWidth !=
     'undefined' && document.documentElement.clientWidth != 0) {
        viewportwidth = document.documentElement.clientWidth;
        viewportheight = document.documentElement.clientHeight;
    }


    // older versions of IE 

    else {
        viewportwidth = document.getElementsByTagName('body')[0].clientWidth;
        viewportheight = document.getElementsByTagName('body')[0].clientHeight;
    }

    wndWidth = viewportwidth;
    if (wndWidth < 700) wndWidth = 700;
    if (wndWidth > 1024) wndWidth = 1024;
    // 編輯區要盡量寬敞，暫時這樣修改，看看大家反應
    //            wndWidth = 1000
    if (viewportheight < 50) viewportheight = 50;

    window.radopen(null, 'CEWindow');
    var oWnd = GetRadWindowManager().GetWindowByName('CEWindow');

    //            oWnd.MoveTo((viewportwidth - wndWidth) / 2, 30);
    //            oWnd.SetSize(wndWidth, viewportheight - 35);

    oWnd.MoveTo((viewportwidth - wndWidth) / 2, 0);
    oWnd.SetSize(wndWidth, viewportheight);
    window.scrollTo(0, 0);
    oWnd.togglePin();

}

