﻿/*
Common Javascript library    
editor : Bastian Choi / MedicalLogic
lastupdate : 2011.07.18

required parameter
var ROOT_PATH = "<%= ResolveClientUrl("~/") %>";
*/

; (function ($)
{
    // --------------------------------------------------------------------------------------------
    // 웹서비스 호출
    var POST_URL = ROOT_PATH + "Handlers/BizMate4.service";

    $.svc = {};

    $.svc.open = function (fn, args, target)
    {
        var url = POST_URL + "?jquery_post_fn_name=" + fn + "&" + $.param(args);
        window.open(url, target);
    };

    $.svc.call = function (fn, async, args, callback)
    {
        args["jquery_post_fn_name"] = fn;
        $.ajax({
            timeout: 60000,
            type: "POST",
            url: POST_URL,
            async: async,
            data: args,
            success: function (res) { this.base = callback; this.base(eval(res)); },
            error: function () { }
        });
    };

    $.svc.post = function (fn, args, callback, debug)
    {
        args["jquery_post_fn_name"] = fn;
        $.post(POST_URL, args, function (res) { if(debug) alert(res); this.base = callback; this.base(eval(res)); });
    };

    $.svc.submit = function (fn, args, callback)
    {
        param = args;
        jQuery.each($("form").serializeArray(), function (i, field) { param[field.name] = ((param[field.name]) ? param[field.name] + "," : "") + field.value; });
        param["jquery_post_fn_name"] = fn;
        $.post(POST_URL, param, function (res) { this.base = callback; this.base(eval(res)); });
    };

    $.svc.error = function (res, msg)
    {
        if (msg != '') msg = msg + "\n";
        if (res.err < 0) alert(msg + "[" + res.err + "] " + res.errmsg);
        return (res.err < 0);
    }

    // --------------------------------------------------------------------------------------------
    // 웹 파라메터 가져오는 함수
    function getParam(key, defaultVal)
    {
        if (defaultVal == null) defaultVal = "";
        key = key.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
        var regex = new RegExp("[\\?&]" + key + "=([^&#]*)");
        var qs = regex.exec(window.location.href);
        if (qs == null)
            return defaultVal;
        else
            return qs[1];
    };
    $.paramStr = function (key, defaultVal) { return getParam(key, defaultVal); };
    $.paramInt = function (key, defaultVal) { return parseInt(getParam(key, defaultVal)); };
    $.paramFloat = function (key, defaultVal) { return parseFloat(getParam(key, defaultVal)); };

    // --------------------------------------------------------------------------------------------
    // Date 관련 함수
    $.date = {};
    $.date.diff = function (type, date1, date2)
    {
        // Javascript 에서는 월이 0부터 시작한다.    
        var dt1 = new Date(date1.toString().split('-')[0], date1.toString().split('-')[1] - 1, date1.toString().split('-')[2]);
        var dt2 = new Date(date2.toString().split('-')[0], date2.toString().split('-')[1] - 1, date2.toString().split('-')[2]);
        var diff = parseInt(dt2.getTime() - dt1.getTime());
        switch (type)
        {
            case "y":
            case "year":
                diff = Math.ceil(diff / 1000 / 60 / 60 / 24 / 365);
                break;
            case "m":
            case "month":
                diff = Math.ceil(diff / 1000 / 60 / 60 / 24 / 30);
                break;
            case "d":
            case "day":
                diff = Math.ceil(diff / 1000 / 60 / 60 / 24);
                break;
        }
        return diff;
    }
    $.date.today = function ()
    {
        var date = new Date();
        var month = date.getMonth() + 1;
        return date.getFullYear() + "-" + month + "-" + date.getDate();
    }

    // --------------------------------------------------------------------------------------------
    // COOKIE 관련 함수
    $.cookie = function (name, value, expiredays)
    {
        if (value)
        {
            var todayDate = new Date();
            todayDate.setDate(todayDate.getDate() + expiredays);
            document.cookie = name + "=" + escape(value) + "; path=/;" + ((expiredays) ? " expires=" + todayDate.toGMTString() + ";" : "");
        }
        else
        {
            var search = name + "=";
            var cookie = document.cookie;

            if (cookie.length > 0)
            {
                startIndex = cookie.indexOf(name);
                if (startIndex != -1)
                {
                    startIndex += name.length;
                    endIndex = cookie.indexOf(";", startIndex);
                    if (endIndex == -1) endIndex = cookie.length;
                    return unescape(cookie.substring(startIndex + 1, endIndex));
                }
                else
                {
                    return null;
                }
            }
            else
            {
                return null;
            }
        }
    }

    // --------------------------------------------------------------------------------------------
    // XML 관련 함수
    $.xml = {};
    $.xml.load = function (url, callback)
    {
        $.ajax({
            timeout: 60000,
            type: "GET",
            url: url,
            async: false,
            datatype: "xml",
            success: function (xml) { this.base = callback; this.base($(xml)); },
            error: function () { }
        });
    };
    $.xml.makenode = function (name, attr, value, cdata)
    {
        var attrcode = [];
        for (var key in attr)
        {
            if (attr[key] != null)
                attrcode[attrcode.length] = " " + key + "=\"" + attr[key].toString().replace(/"/g, "'") + "\"";
        }

        var code = [];
        if (attr.length > 0)
            code[code.length] = "<" + name + attrcode.join('') + ">";
        else
            code[code.length] = "<" + name + attrcode.join('') + ">";
        if (cdata) code[code.length] = "<![CDATA[";
        code[code.length] = value;
        if (cdata) code[code.length] = "]]>";
        code[code.length] = "</" + name + ">";
        return code.join('');
    };
    $.xml.encode = function(xml)
    {
        if (!xml || xml == undefined || xml == null || xml == "") return "";
        xml = xml.replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/&nbsp;/g, "&amp;nbsp;");
        return xml;
    };
    $.xml.decode = function(xml)
    {
        if (!xml || xml == undefined || xml == null || xml == "") return "";
        xml = xml.replace(/&amp;/g, "&").replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&nbsp;/g, " ");
        return xml;        
    };
    $.xml.parse = function (xml)
    {
        if (xml == "" || xml == null || xml == undefined) return $($.parseXML("<blank></blank>"));
        return $($.parseXML(xml));
    };
    $.fn.node = function (path)
    {
        var node = $(this).find(path);
        if (node)
            return node;
        else
            return $("<NoData></NoData>");
    };

    // --------------------------------------------------------------------------------------------
    // File Upload
    $.filectrl = [];
    $.fn.uploadCtrl = function (callback, autosubmit)
    {
        var id = $(this).attr("id");
        var ctrl = $(this);

        var code = [];
        code[code.length] = "<table style='width:100%;'>";
        code[code.length] = "<form id='upload_frm_" + id + "' method='post' enctype='multipart/form-data' target='upload_result_frm_" + id + "' action='" + ROOT_PATH + "/Handlers/BizMate4.service'>";
        code[code.length] = "<input type='hidden' name='jquery_post_fn_name' value='BizMate4@FileCtrl.Upload' />";
        code[code.length] = "<input type='hidden' name='callback' value='" + callback + "' />";
        code[code.length] = "<tr><td><input type='file' id='file_select_ctrl' name='file_select_ctrl' style='width:100%;' /></td></tr>";
        code[code.length] = "</form>";
        code[code.length] = "</table>";
        code[code.length] = "<iframe id='upload_result_frm_" + id + "' name='upload_result_frm_" + id + "' style='display:none;'></iframe>";

        ctrl.append(code.join(''));

        if (autosubmit) ctrl.find("#file_select_ctrl").change(function () { ctrl.upload(); });
    };

    $.fn.upload = function ()
    {
        var id = $(this).attr("id");
        $("#upload_frm_" + id).submit();
        document.getElementById("upload_frm_" + id).reset();
    }

    $.filectrl.url = function (url, filename)
    {
        var args = { jquery_post_fn_name: "BizMate4@FileCtrl.Download", url: url, filename: encodeURI(filename) };
        return ROOT_PATH + "/Handlers/BizMate4.service?" + $.param(args);
    };
    $.filectrl.download = function (url, filename, target)
    {
        window.open($.filectrl.url(url, filename), ((target) ? target : "_self"));
    };

    // --------------------------------------------------------------------------------------------
    // TabMenu 관련 함수
    /*
    <table id="tabmenu" class="tabmenu_line" style="width:100%;">
    <tr>
    <td class="tabmenu" width="80">TAB MENU TITLE1</td>
    <td></td>
    </tr>
    </table>
    <div name="tabmenuBodyDiv" class="tabmenu_body" style="display: none;">
    </div>
    <script type="text/javascript">
    $("#tabmenu").tabmenu(0);
    </script>
    */
    $.tabmenu = {};
    $.tabmenu.selectTab = function (ctrl, idx)
    {
        ctrl.find("td:eq(" + idx + ")").click();
    };
    $.fn.selectTab = function (tabID)
    {
        $(this).find("td:eq(" + tabID + ")").click();
    };
    $.fn.tabmenu = function (defaultTabID, callback)
    {
        var tabmenu = $(this);
        var menuid = tabmenu.attr("id");
        if (!defaultTabID) defaultTabID = 0;

        $("#" + menuid + " td[class='tabmenu']").hover(
            function () { if ($(this).html() == "") return; if (!$(this).hasClass("tabmenu_selected")) $(this).addClass("tabmenu_hover"); },
            function () { $(this).removeClass("tabmenu_hover"); }
        );

        $("#" + menuid + " td[class='tabmenu']").click(function ()
        {
            if ($(this).html() == "") return;
            var idx = $(this).index();
            //$("div[class='tabmenu_body']").each(function () { $(this).css("display", "none"); });
            $("#" + menuid).parent().children("div[class='tabmenu_body']").css("display", "none");
            $("#" + menuid + " td").removeClass("tabmenu_selected");

            $("#" + menuid + " td:eq(" + idx + ")").addClass("tabmenu_selected");
            //$("div[class='tabmenu_body']:eq(" + idx + ")").css("display", "block");
            $("#" + menuid).parent().children("div[class='tabmenu_body']:eq(" + idx + ")").css("display", "block");

            if (callback)
            {
                this.base = callback;
                this.base(idx);
            }
        });

        //$("div[class='tabmenu_body']:eq(" + defaultTabID + ")").css("display", "none");
        $("#" + menuid).parent().children("div[class='tabmenu_body']").css("display", "none");
        $("#" + menuid + " td:eq(" + defaultTabID + ")").click();
    };


    // --------------------------------------------------------------------------------------------
    // Table List 관련 함수
    $.list = {};
    $.list.clearSelection = function (ctrl)
    {
        ctrl.data("selectedId", "");
        ctrl.find(".cell_selected").each(function () { $(this).removeClass("cell_selected"); });
    };

    $.list.select = function (ctrl, id)
    {
        var selectedCtrl = ctrl.find("[itemid='" + id + "']");
        if (selectedCtrl)
        {
            $.list.clearSelection(ctrl);
            selectedCtrl.addClass("cell_selected");
            ctrl.data("selectedId", id);
        }
    };

    $.list.selectedId = function (ctrl)
    {
        var obj = ctrl.data("selectedId");
        return (obj) ? obj : "";
    };

    $.fn.list = function (onClick, onPageChange, options)
    {
        var opts = $.extend({}, $.fn.list.defaults, options);

        var listctrl = $(this);
        listctrl.data("selectedId", "");
        //listctrl.data("options", opts);

        var selector = (opts.type == "grid") ? "td" : "tr" + ((listctrl.find("tbody").length > 0) ? ":gt(0)" : "");
        listctrl.find(selector).live("click", function (event, ui)
        {
            var idx = $(this).index();
            listctrl.data("selectedIndex", idx);
            listctrl.data("selectedId", $(this).attr("itemid"));
            listctrl.find(".cell_selected").each(function () { $(this).removeClass("cell_selected"); });
            $(this).addClass("cell_selected");

            if (onClick)
            {
                this.base = onClick;
                this.base(idx);
            }
        });

        listctrl.find(selector).live("touch", function () { listctrl.find(selector).click(); });

        listctrl.find(selector).live("mouseover", function () { if (!$(this).hasClass("cell_selected")) $(this).addClass("cell_hover"); });
        listctrl.find(selector).live("mouseout", function () { $(this).removeClass("cell_hover"); });

        if (opts.pagesize > 0)
        {
            $("#" + listctrl.attr("id") + "_pageer").remove();
            var pager = $("<div id='" + listctrl.attr("id") + "_pageer' style='width:100%;padding:4px 4px 4px 4px;'></div>");
            pager.paging(opts.pageno, opts.pagesize, opts.total, onPageChange, opts.imgpath);
            listctrl.after(pager);
        }
    };

    // Paging 함수
    $.fn.paging = function (pageno, pagesize, total, callback, imgpath)
    {
        var IMG_PATH = (imgpath) ? imgpath : ROOT_PATH + "/Images/Common";
        var last = parseInt(total / pagesize) + 1;

        var page1 = (pageno % 10 == 0) ? (pageno - 9) : parseInt(pageno) - (pageno % 10) + 1;
        var page2 = (pageno % 10 == 0) ? (pageno) : parseInt(pageno) + (10 - (pageno % 10));
        if (page2 > last) page2 = last;
        var prev = parseInt(pageno) - 1;
        var next = parseInt(pageno) + 1;
        //alert(pageno + "," + pagesize + "," + total + "," + imgpath);
        var code = "";
        code += "<table style='margin:5px;'><tr>";

        if (pageno > 1)
            code += "<td class='list_page' id='firstPageBtn'><img src='" + IMG_PATH + "/arrow_first.gif' alt='FIRST' style='cursor:pointer;' /></td>";
        else
            code += "<td class='list_page' disabled><img src='" + IMG_PATH + "/arrow_first.gif' alt='FIRST' /></td>";

        if ((pageno - 1) > 0)
            code += "<td class='list_page' id='prevPageBtn'><img src='" + IMG_PATH + "/arrow_prev.gif' alt='PREV' style='cursor:pointer;' /></td>";
        else
            code += "<td class='list_page' disabled><img src='" + IMG_PATH + "/arrow_prev.gif' alt='PREV' /></td>";

        for (var idx = page1; idx <= page2; idx++)
        {
            var cls = (idx == pageno) ? "list_page_selected" : "list_page";
            code += "<td class='" + cls + "'><span id='pageBtn' idx='" + idx + "' style='cursor:pointer;'>" + idx + "<span></a></td>";
        }

        if (pageno < last)
            code += "<td class='list_page' id='nextPageBtn'><img src='" + IMG_PATH + "/arrow_next.gif' alt='NEXT' style='cursor:pointer;' /></td>";
        else
            code += "<td class='list_page' disabled><img src='" + IMG_PATH + "/arrow_next.gif' alt='NEXT' /></td>";

        if (pageno < last)
            code += "<td class='list_page' id='lastPageBtn'><img src='" + IMG_PATH + "/arrow_last.gif' alt='LAST' style='cursor:pointer;' /></td>";
        else
            code += "<td class='list_page' disabled><img src='" + IMG_PATH + "/arrow_last.gif' alt='LAST' /></td>";

        code += "</tr></table>";
        $(this).html(code);

        $(this).find("#firstPageBtn").click(function () { this.base = callback; try { this.base(1); } catch (exception) { alert(exception); } });
        $(this).find("#prevPageBtn").click(function () { this.base = callback; try { this.base(prev); } catch (exception) { alert(exception); } });
        $(this).find("span[id='pageBtn']").click(function () { this.base = callback; try { this.base($(this).attr("idx")); } catch (exception) { alert(exception); } });
        $(this).find("#nextPageBtn").click(function () { this.base = callback; try { this.base(next); } catch (exception) { alert(exception); } });
        $(this).find("#lastPageBtn").click(function () { this.base = callback; try { this.base(last); } catch (exception) { alert(exception); } });
    };


    $.fn.list.defaults =
    {
        type: "list",   // list, grid
        pageno: 1,
        pagesize: 0,    // 0:no paging, 1~: use paging
        total: 0,
        imgpath: ROOT_PATH + "/Images/Common"
    };


})(jQuery);

// Debug Window
function DEBUG_WINDOW() { window.open(ROOT_PATH + "/Scripts/BizMate4/debug.htm", "_debug", "width=1000,height=800,top=0,left=0,scrollbars=yes,resizable=yes").focus(); }


