/* Minification failed. Returning unminified contents.
(502,11-12): run-time error JS1003: Expected ':': (
(502,14-15): run-time error JS1100: Expected ',': {
(504,5-6): run-time error JS1002: Syntax error: }
(507,5-6): run-time error JS1002: Syntax error: }
(523,5-6): run-time error JS1002: Syntax error: }
(539,5-6): run-time error JS1002: Syntax error: }
(548,5-6): run-time error JS1002: Syntax error: }
(551,5-6): run-time error JS1002: Syntax error: }
(554,5-6): run-time error JS1002: Syntax error: }
(562,5-6): run-time error JS1002: Syntax error: }
(571,5-6): run-time error JS1002: Syntax error: }
(574,2-3): run-time error JS1197: Too many errors. The file might not be a JavaScript file: (
(570,9-66): run-time error JS1018: 'return' statement outside of function: return { width: e[a + 'Width'], height: e[a + 'Height'] }
(553,9-26): run-time error JS1018: 'return' statement outside of function: return this.value
(550,9-49): run-time error JS1018: 'return' statement outside of function: return this.replaceUrl(link, this.value)
(547,9-24): run-time error JS1018: 'return' statement outside of function: return url.href
 */
//function tamingselect(p_dropDownListID, p_scrollRecCount, p_widthPoint) {
//    if (!document.getElementById && !document.createTextNode) { return; }
//    
//    // Classes for the link and the visible dropdown
//    var ts_selectclass = 'turnintodropdown'; 	// class to identify selects
//    var ts_listclass = 'turnintoselect'; 	// class to identify ULs

//    var ts_boxclass = 'dropcontainer'; 		// parent element
//    var ts_triggeron = 'activetrigger'; 		// class for the active trigger link
//    var ts_triggeroff = 'trigger'; 		// class for the inactive trigger link
//    var ts_triggerBtnoff = 'triggerBtn'; 		// class for the inactive trigger link
//    var ts_dropdownclosed = 'dropdownhidden'; // closed dropdown
//    var ts_dropdownopen = 'dropdownvisible'; // open dropdown
//    var ts_table = 'dropdownTable';
//    var ts_cell = 'dropdownCell';
//    var isOnContainer = false;
//    /*
//    Turn all selects into DOM dropdowns
//    */
//    var count = 0;
//    var toreplace = new Array();
//    var sel = document.getElementById(p_dropDownListID);
//    var maxItemLength = 0;

//    if (ts_check(sel, ts_selectclass)) {
//        var hiddenfield = document.createElement('input');
//        hiddenfield.name = sel.name;
//        hiddenfield.type = 'hidden';
//        hiddenfield.id = sel.id;
//        hiddenfield.value = sel.options[0].value;
//        sel.parentNode.insertBefore(hiddenfield, sel)

//        var trigger = document.createElement('a');
//        ts_addclass(trigger, ts_triggeroff);
//        trigger.href = '#';
////        $(trigger).css('height', '22px');
// //       $(trigger).css('padding-top', '3px').css('padding-left', '5px').css('margin', '0px 0px 0px 2px');
//        trigger.onclick = function() {
//            f_closeAllDropDown(this);
//            ts_swapclass(this, ts_triggeroff, ts_triggeron)
//            ts_swapclass(this.parentNode.parentNode.parentNode.parentNode.parentNode.getElementsByTagName('ul')[0], ts_dropdownclosed, ts_dropdownopen);
//            return false;
//        }

//        trigger.onblur = function() {
//            $(this).next()
//            if (!isOnContainer) {
//                f_closeAllDropDown(null);
//            }
//        }
//        var triggerBtn = document.createElement('div');
//        var arrowImgUrl = g_root + 'image/arrow.gif';
//        ts_addclass(triggerBtn, ts_triggerBtnoff);    
//        
//        $(triggerBtn).css('background', 'url("' + arrowImgUrl + '")');        
//        $(triggerBtn).css('background-repeat', 'no-repeat');
////        $(triggerBtn).css('height', '22px');
//        
//        triggerBtn.onclick = function() {
//            f_closeAllDropDown($(this).parents('tr:first').find('a').get(0));
//            ts_swapclass($(this).parents('tr:first').find('a').get(0), ts_triggeroff, ts_triggeron);
//            ts_swapclass(this.parentNode.parentNode.parentNode.parentNode.parentNode.getElementsByTagName('ul')[0], ts_dropdownclosed, ts_dropdownopen);
//            try
//            {
//            $(this).parents('tr:first').find('a').get(0).focus();
//            }
//            catch(ex)
//            {
//            
//            }
//            return false;
//        }
//        triggerBtn.onmouseover = function() {
//            isOnContainer = true;
//        }
//        triggerBtn.onmouseout = function() {
//            isOnContainer = false;
//        }

//        trigger.appendChild(document.createTextNode(sel.options[0].text));

//        var ta1 = document.createElement('table');
//        ts_addclass(ta1, ts_table);
//        ta1.insertRow(0);
//        ta1.rows[0].insertCell(0);
//        ta1.rows[0].insertCell(1);
//        ta1.rows[0].cells[0].appendChild(trigger);
//        ta1.rows[0].cells[1].appendChild(triggerBtn);
//        ts_addclass(ta1.rows[0].cells[0], ts_cell);
//        ts_addclass(ta1.rows[0].cells[1], ts_cell);
//        
//        sel.parentNode.insertBefore(ta1, sel);
//        
////        sel.parentNode.insertBefore(trigger, sel);
////        sel.parentNode.insertBefore(triggerBtn, sel);
//        var replaceUL = document.createElement('ul');

//        for (var j = 0; j < sel.getElementsByTagName('option').length; j++) {
//            var v = sel.getElementsByTagName('option')[j].text.length * p_widthPoint;
//            if (maxItemLength < v) {
//                maxItemLength = v;
//            }
//        }

//        for (var j = 0; j < sel.getElementsByTagName('option').length; j++) {
//            var newli = document.createElement('li');
//            var newa = document.createElement('a');

//            newli.v = sel.getElementsByTagName('option')[j].value;
//            newli.elm = hiddenfield;
//            newli.istrigger = trigger;
//            newa.href = '#';
//            newa.appendChild(document.createTextNode(
//				sel.getElementsByTagName('option')[j].text));

//            $(newa).css('width', maxItemLength + 'px');

//            newli.onclick = function() {
//                this.elm.value = this.v;
//                ts_swapclass(this.istrigger, ts_triggeron, ts_triggeroff);
//                ts_swapclass(this.parentNode, ts_dropdownopen, ts_dropdownclosed)
//                this.istrigger.firstChild.nodeValue = this.firstChild.firstChild.nodeValue;
//                return false;
//            }

//            newli.appendChild(newa);
//            replaceUL.appendChild(newli);
//        }

//        if (sel.getElementsByTagName('option').length >= p_scrollRecCount) {
//            $(replaceUL).css('height', '240px');
//        }
//        
////        $(ta1).mouseout(function() {
////            ts_swapclass(this.parentNode.parentNode.parentNode.parentNode.parentNode.getElementsByTagName('ul')[0], ts_dropdownclosed, ts_dropdownopen);
////        });
//        
//        ts_addclass(replaceUL, ts_dropdownclosed);
//        var div = document.createElement('div');
//        
//        div.appendChild(replaceUL);
//        div.onmouseover = function() {
//            isOnContainer = true;
//        }
//        div.onmouseout = function() {
//            isOnContainer = false;
//        }
//        
//        ts_addclass(div, ts_boxclass);
//        $(div).css('overflow', 'visible');
//        sel.parentNode.insertBefore(div, sel)
//        toreplace[count] = sel;
//        count++;
//    }

//    /*
//    Turn all ULs with the class defined above into dropdown navigations
//    */

//    var uls = document.getElementsByTagName('ul');
//    for (var i = 0; i < uls.length; i++) {
//        if (ts_check(uls[i], ts_listclass)) {
//            var newform = document.createElement('form');
//            var newselect = document.createElement('select');
//            for (j = 0; j < uls[i].getElementsByTagName('a').length; j++) {
//                var newopt = document.createElement('option');
//                newopt.value = uls[i].getElementsByTagName('a')[j].href;
//                newopt.appendChild(document.createTextNode(uls[i].getElementsByTagName('a')[j].innerHTML));
//                newselect.appendChild(newopt);
//            }
//            newselect.onchange = function() {
//                window.location = this.options[this.selectedIndex].value;
//            }
//            newform.appendChild(newselect);
//            uls[i].parentNode.insertBefore(newform, uls[i]);
//            toreplace[count] = uls[i];
//            count++;
//        }
//    }
//    for (i = 0; i < count; i++) {
//        toreplace[i].parentNode.removeChild(toreplace[i]);
//    }
//    function ts_check(o, c) {
//        return new RegExp('\\b' + c + '\\b').test(o.className);
//    }
//    function ts_swapclass(o, c1, c2) {
//        var cn = o.className
//        o.className = !ts_check(o, c1) ? cn.replace(c2, c1) : cn.replace(c1, c2);
//    }
//    function ts_addclass(o, c) {
//        if (!ts_check(o, c)) { o.className += o.className == '' ? c : ' ' + c; }
//    }

//    function f_closeAllDropDown(p_element) {
//        $('[class$=activetrigger]').each(
//        function() {
//        if (this != p_element) {
//            ts_swapclass(this, ts_triggeroff, ts_triggeron)
//            ts_swapclass(this.parentNode.parentNode.parentNode.parentNode.parentNode.getElementsByTagName('ul')[0], ts_dropdownclosed, ts_dropdownopen);
//            }
//        }
//        );
//    }

//}
/**
* Adds and removes classes to a list of links to allow keyboard accessibility
*
* @param string dropDownId
* @param string hoverClass
* @param int mouseOffDelay
*/
$(document).ready(function() {
    f_menu_dropdown('uxMenuDropDown', 'hover', 200);
});

function f_menu_dropdown(dropdownId, hoverClass, mouseOffDelay) {
    if (dropdown = document.getElementById(dropdownId)) {
        var listItems = dropdown.getElementsByTagName('li');
        for (var i = 0; i < listItems.length; i++) {
            listItems[i].onmouseover = function() {
                resetFrame(this,true);
                this.className = addClass(this);
            }
            listItems[i].onmouseout = function() {
                var that = this;
                resetFrame(this, false);
                setTimeout(function() { that.className = removeClass(that); }, mouseOffDelay);
                this.className = that.className;
            }
            var anchor = listItems[i].getElementsByTagName('a');
            anchor = anchor[0];
            anchor.onfocus = function() {
            resetFrame(this.parentNode, true);
                tabOn(this.parentNode);
            }
            anchor.onblur = function() {
            resetFrame(this.parentNode, false);
                tabOff(this.parentNode);
            }
        }
    }

    function tabOn(li) {
        if (li.nodeName == 'LI') {
            li.className = addClass(li);
            tabOn(li.parentNode.parentNode);
        }
    }

    function tabOff(li) {
        if (li.nodeName == 'LI') {
            li.className = removeClass(li);
            tabOff(li.parentNode.parentNode);
        }
    }

    function addClass(li) { return li.className + ' ' + hoverClass; }
    function removeClass(li) { return li.className.replace(hoverClass, ""); }

    function resetFrame(li, v_init) {
        if (li.getElementsByTagName('ul').length == 1) {
            li.getElementsByTagName('li')[0].style.width = $(li).find('a')[0].offsetWidth + 160;
            li.getElementsByTagName('ul')[0].style.width = $(li).find('a')[0].offsetWidth + 160;
        }
        if (li.getElementsByTagName('iframe').length == 1) {
            if (v_init) {

                li.getElementsByTagName('iframe')[0].style.top = $(li).find('ul').position().top+2;
                li.getElementsByTagName('iframe')[0].style.width = $(li).find('a')[0].offsetWidth+160;
                li.getElementsByTagName('iframe')[0].style.height = $(li).find('ul')[0].offsetHeight-2;
                //li.getElementsByTagName('li')[0].style.height = $(li).find('ul')[0].offsetHeight;
            } else {
                li.getElementsByTagName('iframe')[0].style.width = 0;
                li.getElementsByTagName('iframe')[0].style.height = 0;
            }
        }
    }
}
;
function f_gridAddRow(p_tableID) {
    var v_table = document.getElementById(p_tableID + '_content');
    var v_root = v_table.getElementsByTagName('tr')[0].parentNode;
    var v_obj = v_root.getElementsByTagName('tr')[0].cloneNode(true);
    var v_rowCount;
    var v_cell = null;
    var v_controlType = null;
    var v_newID = null;
    var v_fieldValue = null;


    v_root.appendChild(v_obj);

    v_rowCount = v_table.rows.length;
    for (i = 0; i < v_table.rows[v_rowCount - 1].cells.length; i++) {
        v_cell = v_table.rows[v_rowCount - 1].cells[i];
        v_table.rows[v_rowCount - 1].cells[0].innerHTML = v_rowCount;
        for (j = 0; j < v_cell.childNodes.length; j++) {
            v_controlType = v_cell.childNodes[j].type;

            if (v_controlType != null) {
                v_newID = p_tableID + "_r" + String(v_rowCount - 1) + "_c" + String(i) + "_n" + String(j)
                v_cell.childNodes[j].id = v_newID;
                v_cell.childNodes[j].name = v_newID;
                if (v_controlType == 'checkbox') {        // return 'true' or 'false'
                    v_fieldValue = v_cell.childNodes[j].checked = false;
                }
                else if (v_controlType == 'text') {
                    v_fieldValue = v_cell.childNodes[j].value = "";
                }
                else if (v_controlType.indexOf('select') >= 0) {
                     v_fieldValue = v_cell.childNodes[j].selectedIndex = 0;
                }
            }
        }
    }

    eval(p_tableID + "_change_row()");
}

function f_resizeGridWithScroll(p_elementId, p_scrollNo, p_showHeader, p_showFooter, p_retry) {
    try {
        var v_table = document.getElementById(p_elementId + '_content');
        var v_rowNo = v_table.rows.length;
        document.getElementById(p_elementId + '_div').style.display = 'block';


        if (v_rowNo <= p_scrollNo || p_scrollNo == 0) {
            document.getElementById(p_elementId + '_div').style.overflowY = 'hidden';
        }
        else {

            document.getElementById(p_elementId + '_div').style.height = (g_rowHeight * p_scrollNo) + 1 + 'px';
            document.getElementById(p_elementId + '_div').style.overflowY = 'scroll';
        }
    }
    catch (Err) {
        if (p_retry)
            setTimeout("f_resizeGridWithScroll('" + p_elementId + "', " + v_rowNo + ", " + p_scrollNo + ", " + p_showHeader + ", " + p_showFooter + ", true); ", 1);
    }
}

function f_resizeGridChangeRow(p_elementId, p_scrollNo, p_showHeader, p_showFooter, p_retry) {
    var g_rowHeight = 25;
    try {
        var v_table = document.getElementById(p_elementId + '_content')
        var v_rowNo = v_table.rows.length;
        document.getElementById(p_elementId + '_div').style.display = 'block';

        if (v_rowNo <= p_scrollNo || p_scrollNo == 0) {
            document.getElementById(p_elementId + '_div').style.height = Math.round(document.getElementById(p_elementId + '_content').offsetHeight) + 1 + 'px';
            document.getElementById(p_elementId + '_div').style.overflowY = 'hidden';
            document.getElementById(p_elementId + '_div').style.height = document.getElementById(p_elementId + '_content').offsetHeight + 'px';
        }
        else {
            if (document.getElementById(p_elementId + '_div').style.overflowY != 'scroll') {
                document.getElementById(p_elementId + '_div').style.height = (g_rowHeight * p_scrollNo) + 1 + 'px';
                document.getElementById(p_elementId + '_div').style.overflowY = 'scroll';
            }
        }
    }
    catch (Err) {

    }
}

function f_gridDeleteRow(p_button) {
    var v_tr = p_button.parentNode.parentNode;
    var v_table = v_tr.parentNode;
    var v_cell = null;
    var v_controlType = null;
    var v_fieldValue = null;

    //Real Grid ID
    var v_tableID = v_table.parentNode.parentNode.parentNode.id;
    if (v_table.rows.length > 1) {
        $(v_tr).remove();

    } else {
        for (i = 0; i < v_table.rows[0].cells.length; i++) {
            v_cell = v_table.rows[0].cells[i];
            for (j = 0; j < v_cell.childNodes.length; j++) {
                v_controlType = v_cell.childNodes[j].type;
                if (v_controlType != null) {
                    if (v_controlType == 'checkbox') {        // return 'true' or 'false'
                        v_fieldValue = v_cell.childNodes[j].checked = false;
                    }
                    else if (v_controlType == 'text') {
                        v_fieldValue = v_cell.childNodes[j].value = "";
                    }
                    else if (v_controlType.indexOf('select') >= 0) {
                        v_fieldValue = v_cell.childNodes[j].selectedIndex = 0;
                    }
                }
            }
        }


    }
    f_gridResetIDandNum(v_table);
    eval(v_tableID + "_change_row()");
}

function f_gridResetIDandNum(p_table) {
    var v_tableID = p_table.parentNode.id;
    var v_row = null;
    var v_cell0 = null;
    var v_cell = null;
    var v_controlType = null;
    var v_newID = null;

    for (var i = 0; i < p_table.rows.length; i++) {
        v_row = p_table.rows[i];
        v_cell0 = v_row.cells[0];
        v_cell0.innerHTML = i + 1;
        for (j = 0; j < p_table.rows[i].cells.length; j++) {
            v_cell = p_table.rows[i].cells[j];
            for (k = 0; k < v_cell.childNodes.length; k++) {
                v_controlType = v_cell.childNodes[k].type;
                if (v_controlType != null) {
                    v_newID = v_tableID + "_r" + String(i) + "_c" + String(j) + "_n" + String(k);
                    v_cell.childNodes[k].id = v_newID;
                    v_cell.childNodes[k].name = v_newID;
                }
            }
        }
    }

}

function f_gridSubmit(p_dataSet, p_tableName, p_fieldName, p_dataValue) {
    var v_result = false;
    var v_valueJSON = JSON.stringify({ dataSet: p_dataSet,
        tableName: p_tableName,
        fieldName: p_fieldName,
        dataValue: p_dataValue
    });

    $.ajax({
        type: "POST",
        url: g_root + "/api/PostVacancy/SaveToSession",
        data: v_valueJSON,
        async: false,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(p_msg) {
            if (p_msg.d = 'true')
                v_result = true;
        },
        error: function(p_xhr) {
            v_result = false;
        }
    })
    return v_result;
}

//error: function(p_xhr, p_ajaxOptions, p_thrownError) {;
function f_msgTxt(p_msgCD) {

    return f_commonTxt(p_msgCD, "GetMsgText");

}

function f_labelTxt(p_msgCD) {

    return f_commonTxt(p_msgCD, "GetLabelText");

}

function f_commonTxt(p_msgCD, p_function) {

    var v_result = '';

    var req = { msgCd: p_msgCD };

    $.ajax({
        type: "POST",
        async: false,
        url: g_root + "/api/Language/" + p_function,
        contentType: "application/json; charset=utf-8",
        data: JSON.stringify(req),
        dataType: "json",
        success: function(response) {
            if (response.d != '') {
                v_result = response.d;
            }
        }
    });

    return v_result;

};
var v_flag;
var v_container;
var g_currentFontSize;
var g_commonCodeWSPage = '/api/CommonCode';
var windowMinWidth = 992;

var mb = {
    value: false,
    disabled: false,
    enable() {
        this.disabled = false;
    },
    disable() {
        this.disabled = true;
    },
    updateLinkForMobile() {
        $('header a[href]:not([data-disable-change-link])').each(function () {
            if ($(this).attr('href') != null && $(this).attr('href').toLowerCase().indexOf('\/jobseeker\/jobsearch\/quickview') >= 0) {
                var url = mb.replaceUrl($(this).attr('href'), true);
                $(this).attr('href', url);
            }
        });
        if (!this.disabled) {
            $('#content-div a[href]:not([data-disable-change-link])').each(function () {
                if ($(this).attr('href') != null && $(this).attr('href').toLowerCase().indexOf('\/jobseeker\/jobsearch\/quickview') >= 0) {
                    var url = mb.replaceUrl($(this).attr('href'), true);
                    $(this).attr('href', url);
                }
            });
        }
    },
    updateLinkForDesktop() {
        $('header a[href]:not([data-disable-change-link])').each(function () {
            if ($(this).attr('href') != null && $(this).attr('href').toLowerCase().indexOf('\/jobseeker\/jobsearch\/joblist') >= 0) {
                var url = mb.replaceUrl($(this).attr('href'), false);
                $(this).attr('href', url);
            }
        });
        if (!this.disabled) {
            $('#content-div a[href]:not([data-disable-change-link])').each(function () {
                if ($(this).attr('href') != null && $(this).attr('href').toLowerCase().indexOf('\/jobseeker\/jobsearch\/joblist') >= 0) {
                    var url = mb.replaceUrl($(this).attr('href'), false);
                    $(this).attr('href', url);
                }
            });
        }
    },
    replaceUrl(link, isMobile) {
        var url = new URL(link, document.baseURI);
        if (isMobile) {
            url.pathname = url.pathname.toLowerCase().replace('\/jobseeker\/jobsearch\/quickview', '\/jobseeker\/jobsearch\/joblist');
        } else {
            url.pathname = url.pathname.toLowerCase().replace('\/jobseeker\/jobsearch\/joblist', '\/jobseeker\/jobsearch\/quickview');
        }
        return url.href;
    },
    getQueryLink(link) {
        return this.replaceUrl(link, this.value);
    },
    get mobile() {
        return this.value;
    },
    set mobile(value) {
        if (value) {
            this.updateLinkForMobile();
        } else {
            this.updateLinkForDesktop();
        }
        this.value = value;
    },
    get viewport() {
        var e = window
            , a = 'inner';
        if (!('innerWidth' in window)) {
            a = 'client';
            e = document.documentElement || document.body;
        }
        return { width: e[a + 'Width'], height: e[a + 'Height'] }
    }
}

$(document).ready(function () {
    var lang_path = window.location.pathname.split("/")[1]
    switch (lang_path) {
        case "en":
            g_langOpt = 1;
            break;
        case "tc":
            g_langOpt = 2;
            break;
        case "cn":
            g_langOpt = 3;
            break;
    }

    checkIsMobileWidth();
    window.addEventListener("resize", checkIsMobileWidth);

    initTabindex();
    window.addEventListener("resize", handleChangeTabindex);

    f_highlightKeyword();
});

function checkIsMobileWidth() {
    if (window.innerWidth < windowMinWidth) {
        mb.mobile = true;
    } else {
        mb.mobile = false;
    }
}

function initTabindex() {
    $('a,button,input,select,textarea,[data-ies-tabindex],[data-ies-xs-tabindex],[data-ies-sm-tabindex],[data-ies-md-tabindex],[data-ies-lg-tabindex],[data-ies-xl-tabindex]')
        .each(function (index, element) {
            var baseTabindex = $(element).parents('[data-ies-base-tabindex]').toArray().reduce(function (prev, elem) {
                return prev + parseInt($(elem).attr('data-ies-base-tabindex'));
            }, 0);

            if ($(element).attr('data-ies-tabindex') || $(element).attr('data-ies-xs-tabindex') || $(element).attr('data-ies-sm-tabindex') || $(element).attr('data-ies-md-tabindex') || $(element).attr('data-ies-lg-tabindex') || $(element).attr('data-ies-xl-tabindex')) {
                var tabindex = parseInt($(element).attr('data-ies-tabindex'));
                tabindex = isNaN(tabindex) ? baseTabindex : (tabindex == -1) ? tabindex : tabindex + baseTabindex;

                var tabindex_xs = parseInt($(element).attr('data-ies-xs-tabindex'));
                tabindex_xs = isNaN(tabindex_xs) ? tabindex : (tabindex_xs == -1) ? tabindex_xs : tabindex_xs + baseTabindex;

                var tabindex_sm = parseInt($(element).attr('data-ies-sm-tabindex'));
                tabindex_sm = isNaN(tabindex_sm) ? tabindex_xs : (tabindex_sm == -1) ? tabindex_sm : tabindex_sm + baseTabindex;

                var tabindex_md = parseInt($(element).attr('data-ies-md-tabindex'));
                tabindex_md = isNaN(tabindex_md) ? tabindex_sm : (tabindex_md == -1) ? tabindex_md : tabindex_md + baseTabindex;

                var tabindex_lg = parseInt($(element).attr('data-ies-lg-tabindex'));
                tabindex_lg = isNaN(tabindex_lg) ? tabindex_md : (tabindex_lg == -1) ? tabindex_lg : tabindex_lg + baseTabindex;

                var tabindex_xl = parseInt($(element).attr('data-ies-xl-tabindex'));
                tabindex_xl = isNaN(tabindex_xl) ? tabindex_lg : (tabindex_xl == -1) ? tabindex_xl : tabindex_xl + baseTabindex;

                $(element).data('ies-tabindex-xs', tabindex_xs);
                $(element).data('ies-tabindex-sm', tabindex_sm);
                $(element).data('ies-tabindex-md', tabindex_md);
                $(element).data('ies-tabindex-lg', tabindex_lg);
                $(element).data('ies-tabindex-xl', tabindex_xl);
            } else {
                if ($(element).attr('tabindex') == "-1") {
                    $(element).data('ies-base-tabindex', baseTabindex);
                } else {
                    $(element).attr('tabindex', baseTabindex);
                }
            }
        });
    handleChangeTabindex();
}

var g_screenWidth = '';
function handleChangeTabindex() {
    var newScreenWidth;
    if (window.innerWidth >= 1200) {
        newScreenWidth = 'xl';
    } else if (window.innerWidth >= 992) {
        newScreenWidth = 'lg';
    } else if (window.innerWidth >= 768) {
        newScreenWidth = 'md';
    } else if (window.innerWidth >= 576) {
        newScreenWidth = 'sm';
    } else {
        newScreenWidth = 'xs';
    }

    if (newScreenWidth != g_screenWidth) {
        $('[data-ies-tabindex],[data-ies-xs-tabindex],[data-ies-sm-tabindex],[data-ies-md-tabindex],[data-ies-lg-tabindex],[data-ies-xl-tabindex]')
            .each(function (index, element) {
                var tabindex = $(element).data('ies-tabindex-' + newScreenWidth);
                $(element).attr('tabindex', tabindex);
            });
        g_screenWidth = newScreenWidth;
    }
}

function replaceUrlParam(uri, k, v) {
    var url = new URL(uri, document.baseURI);
    var found = false;
    url.searchParams.forEach(function (value, key) {
        if (key.toLowerCase() == k.toLowerCase()) {
            url.searchParams.set(key, v);
            found = true;
        }
    });
    if (!found) {
        url.searchParams.set(k, v);
    }
    return url.href;
}

//function f_switchStyleSheet(p_frSize, p_toSize) {
//    if (p_frSize != p_toSize) {
//        $("link[rel=stylesheet]").each(
//            function() {
//                $(this).attr('href', $(this).attr('href').replace('App_Themes/' + p_frSize + '/', 'App_Themes/' + p_toSize + '/'));
//            }
//        );
//    }
//}


function getCustomListItemTabIdx(id, baseIdx) {
    var tempidx = 0;
    $('#' + id + " ul").parents('[data-ies-base-tabindex]').each(function () {
        tempidx += $(this).data('ies-base-tabindex');
    });
    if (!isNaN(tempidx) && tempidx > 0) { baseIdx = tempidx };
    var tabidx = baseIdx;

    return tabidx;
}

function f_onError(arg) {
    alert(f_msgTxt('E092041') + ": " + arg._message); //error has occured
}

function f_showError(res) {

    if (typeof (v_container) == 'undefined') {
        v_container = '*';
    }
    v_flag = false;
    var result = res.d;

    if (result != null) {

        if (result.length == 0) {
            v_flag = true;
        }
        else {
            if (result[0][0] != '') {
                if ($(v_container).find('[id$=' + result[0][0] + ']').find('input[type="radio"]').length) {
                    f_getFocus($(v_container).find('[id$=' + result[0][0] + '_0]').eq(parseInt(result[0][3])));
                } else {
                    f_getFocus($(v_container).find('[id$=' + result[0][0] + ']').eq(parseInt(result[0][3])));
                }
            }

            for (var i = 0; i < result.length; i++) {
                var v_rowno = parseInt(result[i][3]);
                switch (v_rowno) {
                    case -1:
                        f_fillMessage($('span[id$=uxGeneralError]'), result[i][2]);
                        break;
                    default:
                        if (result[i][2] == 'ChangeTextColor') {
                            $('[id$=' + result[i][1] + ']').addClass('change-error-color');
                        } else {
                            f_fillMessage($(v_container).find('span[id$=' + result[i][1] + ']').eq(v_rowno), result[i][2]);
                        }
                        break;
                }
            }
        }
        f_focusErrorMessage();
    } else {
        window.location = g_root;
    }
}

function f_showMessage(res) {
    var result = res.d;
    if (typeof (v_container) == 'undefined') {
        v_container = '*';
    }

    //alert('result: ' + result);   
    for (var i = 0; i < result.length; i++) {
        var v_rowno = parseInt(result[i][3]);
        switch (v_rowno) {
            case -1:
                f_fillMessage($('span[id$=uxGeneralError]'), result[i][2]);
                break;
            default:
                f_fillMessage($(v_container).find('span[id$=' + result[i][1] + ']').eq(v_rowno), result[i][2]);
                break;
        }
    }
}

function f_fillMessage(control, errorMsg) {
    $(control).html(errorMsg).show();
}

function f_getFocus(control) {
    $(control).focus();
}

function f_clearAllErrorSpans() { f_clearAllSpans(); };
function f_clearAllSpans() {
    $('span.error').each(function () {
        $(this).html('');
    });
}

function f_clearAllErrorSpans(control) { f_clearAllSpans(control); };
function f_clearAllSpans(control) {
    $('[id$=uxGeneralError]').html('');
    $(control).find('span.error').each(function () {
        $(this).html('');
    });
    $(control).find('span.error-msg').each(function () {
        $(this).html('');
    });
}

function f_cleanAllErrorTxtColor(control) {
    $(control).find('.change-error-color').each(function () {
        $(this).removeClass('change-error-color');
    });
}

function f_clearError(control) {
    $(control).html('');
}

function f_initDropDownList(p_codeType, p_params, control) {
    var g_commonCodeWSPage = g_root + '/api/CommonCode';
    var request = {
        codeType: p_codeType,
        params: p_params,
        lang_opt: g_langOpt
    }


    this.v_target = control;
    $.ajax({
        type: "POST",
        async: false,
        url: g_commonCodeWSPage + "/GetCode",
        contentType: "application/json; charset=utf-8",
        data: JSON.stringify(request),
        dataType: "json",
        success: f_initSubComboBox,
        error: f_onError
    });
}

function f_initSubComboBox(res) {
    var result = res.d;
    var $x = $(v_target);
    var y = $x.get(0);
    while (y.hasChildNodes()) {
        y.removeChild(y.firstChild);
    }
    y.options[0] = new Option;
    y.options[0].text = '';
    y.options[0].value = '';
    //$(v_target).html('');
    //$(v_target).append($("<option></option>").attr("value", '').text(''));
    for (var i = 0; i < result.length; i++) {
        //$(v_target).append($("<option></option>").attr("value", result[i][0]).text(result[i][1]));               
        var z = $x.get(0)
        z.options[i + 1] = new Option;
        z.options[i + 1].text = result[i][1];
        z.options[i + 1].value = result[i][0];
    }
}
jQuery.fn.extend({
    customFadeIn: function (speed, callback) {
        $(this).fadeIn(speed, function () {
            if (navigator.userAgent.search("MSIE") >= 0)
                $(this).get(0).style.removeAttribute('filter');
            if (callback != undefined)
                callback();
        });
    },
    customFadeOut: function (speed, callback) {
        $(this).fadeOut(speed, function () {
            if (navigator.userAgent.search("MSIE") >= 0)
                $(this).get(0).style.removeAttribute('filter');
            if (callback != undefined)
                callback();
        });
    }
});
function f_initialVariable(p_commonCodeWSPage, p_langOpt) {

    g_commonCodeWSPage = p_commonCodeWSPage;
    g_langOpt = p_langOpt;

}
function f_getQueryString(p_key) {
    var AllVars = window.location.search.substring(1);
    var Vars = AllVars.split("&");

    for (i = 0; i < Vars.length; i++) {
        var Var = Vars[i].split("=");
        if (Var[0] == p_key) return Var[1];

    }
    return "";
}

function f_highlightKeyword() {
    //Highlight searched keyword after searching.
    //1. Keyword search (Simple and advanced search)
    //2. Job title search (Advanced search)

    $('*[id$=job_list_table]').removeHighlight();
    $('*[id$=order_div]').removeHighlight();
    $('*[id$=jobCardHeader]').removeHighlight();
    $('*[id$=jobOrderTable]').removeHighlight();

    if (($('*[id$=uxSearchKeyword]').val() != undefined &&
        $('*[id$=uxSearchKeyword]').val() != NaN)) {

        if ($('*[id$=uxSearchKeyword]').val().trim() != '') {

            var v_simpleSearchKeyword = $('*[id$=uxSearchKeyword]').val();
            var v_simpleSearchKeywordList = v_simpleSearchKeyword.split(',');

            for (i = 0; i < v_simpleSearchKeywordList.length; i++) {
                if (v_simpleSearchKeywordList[i] != '' &&
                    v_simpleSearchKeywordList[i] != undefined &&
                    v_simpleSearchKeywordList[i] != NaN) {

                    $('*[id$=job_list_table]').highlight(v_simpleSearchKeywordList[i], false);
                    $('*[id$=order_div]').highlight(v_simpleSearchKeywordList[i], false);
                    $('*[id$=jobCardHeader]').highlight(v_simpleSearchKeywordList[i], false);
                    $('*[id$=jobOrderTable]').highlight(v_simpleSearchKeywordList[i], false);

                }
            }

        }
    }
}

function f_onKeyPressEnter(p_event, p_id) {
    var v_browserName = navigator.appName;
    var v_event = (window.event) ? window.event : p_event;
    var v_keyCode = (v_event.keyCode) ? v_event.keyCode : v_event.charCode;
    if (v_keyCode == 13) {
        var src = v_event.srcElement || v_event.target;
        if (src &&
            (src.tagName.toLowerCase() == "input") &&
            ((src.type.toLowerCase() == "text") || (src.type.toLowerCase() == "password") || (src.type.toLowerCase() == "radio"))
        ) {
            $('#' + p_id)[0].focus();
            $('#' + p_id)[0].click();
        }
    }
}

/*Scroll to top when arrow up clicked BEGIN*/
$(window).scroll(function () {
    var height = $(window).scrollTop();
    if (height > 70) {
        $('#backtotop').fadeIn();
    } else {
        $('#backtotop').fadeOut();
    };
});

$(document).ready(function () {


    $("#backtotop").click(function (event) {
        event.preventDefault();
        $("html, body").animate({ scrollTop: 0 }, "slow");
        return false;
    });

});
/*Scroll to top when arrow up clicked END*/


/* Set Global lang Var start*/

/* Set Global lang Var End*/

function getUrlVars() {
    var vars = {};
    var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function (m, key, value) {
        vars[key] = value;
    });
    return vars;
}


function f_getQueryString(p_key) {
    var AllVars = window.location.search.substring(1);
    var Vars = AllVars.split("&");

    for (i = 0; i < Vars.length; i++) {
        var Var = Vars[i].split("=");
        if (Var[0] == p_key) return Var[1];

    }
    return "";
}

function f_uxSiteSearch_onKeyPress(p_event) {
    var v_browserName = navigator.appName;
    var v_event = (window.event) ? window.event : p_event;
    var v_keyCode = (v_event.keyCode) ? v_event.keyCode : v_event.charCode;

    switch (v_keyCode) {
        case 13:
            if (v_browserName == 'Microsoft Internet Explorer') {
                window.event.returnValue = false;
            } else {
                v_event.preventDefault();
                v_event.stopPropagation();
            }
            f_uxSiteSearch_onClick();
            return false;
    }
}
function f_uxSiteSearch_onClick() {
    $('input[id$=uxGoToBtn]')[0].click();
}

function f_uxGoToBtn_onClick() {
    var v_message = '';
    var v_keyword = $('input[name$=uxSiteSearch]').val();
    var v_uiLang = "";

    if (v_keyword == null || v_keyword == '') {
        if (g_langOpt.toString() == "1") {
            v_message = "Please enter keyword!";
        } else if (g_langOpt.toString() == "2") {
            v_message = "請輸入關鍵字。";
        } else {
            v_message = "请输入关键字。";
        }

        alert(v_message);
        return false;
    }
    switch (g_langOpt) {
        case 1:
            v_uiLang = "en";
            break;
        case 2:
            v_uiLang = "zh-hk";
            break;
        case 3:
            v_uiLang = "zh-cn";
            break;
    }

    window.location.href = "http://search.gov.hk/search.html?gp1=jobs_home&gp0=jobs_home&web=this&query=" + v_keyword + "&tpl_id=stdsearch&ui_lang=" + v_uiLang;
    return true;
}
function loadModal(url, element_id) {
    if ($('#' + element_id).find(".modal-content").html().trim() == "") {
        $.ajax({
            url: url,
            success: function (result) {
                $('#' + element_id).find(".modal-content").append(result);
            }
        });
    }
}

function copytext(e) {
    var W = window;
    var T = W.document;
    var support = T?.queryCommandSupported && T?.queryCommandSupported('copy');

    if (!typeof p === 'string') {
        console.log('argument is not string type');
        return !1;
    }

    if (!support) {
        console.log('not support copy');
        return !1;
    }

    let o = T.createElement("textarea");
    o.textContent = e,
        T.body.appendChild(o),
        o.select();
    let success = !0;
    if (!navigator.clipboard)
        try {
            return T.execCommand("copy")
        } catch {
            return !1;
        } finally {
            T.body.removeChild(o);
        }

    return navigator.clipboard.writeText(e).then(() => {
        T.body.removeChild(o);
    },
        () => {
            T.body.removeChild(o);
            success = !1;
        }),
        success
}
;
/*
#############################################
########## Data Validation Library ##########
#############################################
*/


//Check about the input that is fufill the length requirement
function f_checkLength(input, lengthReq) {
    if (input.length == lengthReq)
        return true;
    else
        return false;

}

//Check about the date that is a valid format
function f_checkIsValidDate(input, formatStyle) {

    var re = "";
    var result = false;

    switch (formatStyle) {
        case 'dd':
        case 'mm':

            re = /^\d{1,2}$/
            if (re.test(input))
                result = true;
            else
                result = false;

            break;

        case 'dd/mm':

            re = /^\d{1,2}\/\d{1,2}$/
            if (re.test(input))
                result = true;
            else
                result = false;

            break;

        case 'mm/yyyy':

            re = /^\d{1,2}\/\d{4}$/
            if (re.test(input))
                result = true;
            else
                result = false;

            break;

        case 'dd/mm/yyyy':
            //Advanced Reference Link: http://www.rodsdot.com/ee/dateValidate.asp; http://www.the-art-of-web.com/javascript/validate-date/
            re = /^\d{1,2}\/\d{1,2}\/\d{4}$/
            if (re.test(input))
                result = true;
            else
                result = false;

            break;
    }

    return result;
}

//Check about the time that is a valid format
function f_checkIsValidTime(input, formatStyle) {

    var re = "";
    var result = false;

    switch (formatStyle) {
        case 'mm':
        case 'hh':

            re = /^\d{1,2}$/
            if (re.test(input))
                result = true;
            else
                result = false;

            break;

        case 'hh:mm':

            re = /^\d{1,2}\:\d{1,2}$/
            if (re.test(input))
                result = true;
            else
                result = false;

            break;

        case 'hh:mm:ss':

            re = /^\d{1,2}\:\d{1,2}\:\d{1,2}$/
            if (re.test(input))
                result = true;
            else
                result = false;

            break;
    }

    return result;
}

//Check about the email that is a valid format
function f_checkIsValidEmail(input) {

    //    apos = input.indexOf("@");
    //    dotpos = input.lastIndexOf(".");
    //    if (apos < 1 || dotpos - apos < 2)
    //        return false;
    //    else
    //        return true;
    var pattern = /^([a-zA-Z0-9_.+-])+@([a-zA-Z0-9_.+-])+\.([a-zA-Z0-9])+([a-zA-Z0-9])+$/;
    if (!pattern.test(input)) {
        return false;
    }

    // check index of  (consecutive ..)
    if (input.indexOf("..") >= 0) {
        return false;
    }

    if (f_checkWithSpace(input)) {
        return false;
    }
    return true;

}

//Check about the number that has a valid digits after point
function f_checkIsValidFloatNumber(input, maxDigitsAfterPoint) {

    input = input.toString();

    if (input.lastIndexOf('.') > 0) {

        var diff = input.length - input.lastIndexOf('.') - 1;

        if (diff <= maxDigitsAfterPoint)
            return true;
        else
            return false;

    } return true;

}

//Check about the number that has a negative number
function f_checkIsNegativeNumber(input) {

    if (input >= Number.NEGATIVE_INFINITY && input < 0)
        return true;
    else
        return false;

}

//Check about the number that has a positive number
function f_checkIsPositiveNumber(input) {

    if (input <= Number.POSITIVE_INFINITY && input >= 0)
        return true;
    else
        return false;

}

//Check about the input that is equal another value
function f_checkIsEqual(input1, input2) {

    if (input1.toString() == input2.toString())
        return true;
    else
        return false;

}

//Check about the input that is NOT equal another value
function f_checkIsNotEqual(input1, input2) {

    if (input1.toString() != input2.toString())
        return true;
    else
        return false;

}

//Check about the input that is greater than another value
function f_checkIsGreaterThan(input1, input2) {

    if (input1 > input2)
        return true;
    else
        return false;

}

//Check about the input that is greater and equal another value
function f_checkIsGreaterThanOrEqual(input1, input2) {

    if (input1 >= input2)
        return true;
    else
        return false;

}

//Check about the input that is lower than another value
function f_checkIsLessThan(input1, input2) {

    if (input1 < input2)
        return true;
    else
        return false;

}

//Check about the input that is lower and equal another value
function f_checkIsLessThanOrEqual(input1, input2) {

    if (input1 <= input2)
        return true;
    else
        return false;

}

//Check about the input that is between valueA and ValueB
function CheckIsBetween(input1, input2, input3) {

    if ((input1 >= input2) && (input1 <= input3))
        return true;
    else
        return false;

}

//Check about the input that is contained selected values
function f_checkIsContain(input1, input2Array) {

    var isFound = false;

    var i = 0;
    for (i = 0; i < input2Array.length; i++) {
        if (input1 == input2Array[i])
            isFound = true;
    }

    return isFound;

}

//Check about the input that is not contained selected values
function f_checkIsNotContain(input1, input2Array) {

    var isFound = false;

    var i = 0;
    for (i = 0; i < input2Array.length; i++) {
        if (input1 == input2Array[i])
            isFound = true;
    }

    return !isFound;

}


//Get the value length from target textbox
function f_getTextBoxValueLength(controlID) {

    return document.getElementById(controlID).value.length;

}

//Get the value from target textbox
function f_getTextBoxValue(controlID) {

    return document.getElementById(controlID).value;

}

//Get the selected value from target drop down list
function f_getDropDownListSelectedValue(controlID) {

    var dlist = document.getElementById(controlID);
    return dlist.options[dlist.selectedIndex].value;

}

//Get the selected values from target radio button list
function f_getRadioButtonListSelectedValue(controlID) {

    var rbtn = document.getElementById(controlID).getElementsByTagName('input');

    var result = "";

    for (var i = 0; i < rbtn.length; i++) {
        if (rbtn[i].checked) {
            result = rbtn[i].value;
        }
    }

    return result;

}

//Get the selected index from target checkbox list
function f_getCheckBoxListSelectedIndex(controlID) {

    var clist = document.getElementById(controlID).getElementsByTagName('input');

    var result = new Array();
    var resultIndex = 0;

    for (var i = 0; i < clist.length; i++) {
        if (clist[i].checked) {
            result[resultIndex] = i;
            resultIndex++;
        }
    }

    return result;

}

//Get the selected value from target checkbox
function f_getCheckBoxSelectedValue(controlID) {

    var c = document.getElementById(controlID);
    var result = false;

    if (c.checked)
        result = true;

    return result;

}

//Set the selected value from target drop down list
function f_setDropDownListSelectedIndex(controlID, selectedIndex) {

    var dlist = document.getElementById(controlID);
    dlist.selectedIndex = selectedIndex;

}

//Set the selected values from target radio button list
function f_setRadioButtonListSelectedIndex(controlID, selectedIndex) {

    var rbtn = document.getElementById(controlID).getElementsByTagName('input');
    rbtn[selectedIndex].checked = true;

}

//Set the selected index from target checkbox list
function f_setCheckBoxListSelectedIndex(controlID, selectedIndex, isChecked) {

    var clist = document.getElementById(controlID).getElementsByTagName('input');
    clist[selectedIndex].checked = isChecked;

}

//Set the selected value from target checkbox
function f_setCheckBoxSelectedValue(controlID, isChecked) {

    var c = document.getElementById(controlID);
    c.checked = isChecked;

}

//Set the target control as enabled or disabled
function f_setEnable(controlID, isEnabled, tabIndex) {

    if (document.getElementById(controlID).type == "text" || document.getElementById(controlID).type == "textarea") {
        document.getElementById(controlID).readOnly = !isEnabled;
        if (!isEnabled) {
            document.getElementById(controlID).tabIndex = -1;
        } else {
            document.getElementById(controlID).tabIndex = tabIndex;
        }
    }else{
        document.getElementById(controlID).disabled = !isEnabled;
        document.getElementById(controlID).readOnly = !isEnabled;
        if (!isEnabled) {
            document.getElementById(controlID).tabIndex = -1;
        } else {
            document.getElementById(controlID).tabIndex = tabIndex;
        }
    }
    if (document.getElementById(controlID).type != "submit" && document.getElementById(controlID).type != "checkbox") {
        if (isEnabled) {
            document.getElementById(controlID).style.backgroundColor = "White";
        }
        else {
            document.getElementById(controlID).style.backgroundColor = "#E6E6E6";
        }
    }
}

//Not test
//Set the target control as visibled or invisibled
function f_setVisible(controlID, isVisibled) {

    if (isVisibled)
        document.getElementById(controlID).style.display = "block";
    else
        document.getElementById(controlID).style.display = "none";

}

//Set the target control value
function f_setValue(controlID, input) {

    document.getElementById(controlID).value = input;

}

//Set the focus at target control
function f_setFocus(controlID) {
    if (document.getElementById(controlID) != null) {
        document.getElementById(controlID).focus();
    }
    else {
        controlID.focus();
    }
}

//Set the selection highlight at target control
function f_setSelect(controlID) {

    document.getElementById(controlID).select();

}



//f_checkIsEqual + customized error messange + f_setFocus
function f_checkRequiredField(controlID, ifErrorShowAlert, errorMessage) {

    var c = document.getElementById(controlID);

    if (f_checkIsEqual(c.value, '')) {

        if (ifErrorShowAlert)
            alert(errorMessage);

        return false;
    } else return true;

}
//-------------------------------------------------------------------
// f_isBlank(value)
//   Returns true if value only contains spaces
//-------------------------------------------------------------------
function f_isBlank(val) {
    if (val == null) { return true; }
    for (var i = 0; i < val.length; i++) {
        if ((val.charAt(i) != ' ') && (val.charAt(i) != "\t") && (val.charAt(i) != "\n") && (val.charAt(i) != "\r")) { return false; }
    }
    return true;
}


//Check about the date that is a valid format
function f_checkIsDigits(input) {
    var string = "1234567890";
    if (f_isBlank(input)) {
        return false;
    }
    for (var i = 0; i < input.length; i++) {
        if (string.indexOf(input.charAt(i)) == -1) {
            return false;
        }
    }

    return true;
}
//Check string contain alphanumerical characters only
function f_checkIsLetterOrDigits(input) {
    var string = "1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    if (f_isBlank(input)) {
        return false;
    }
    for (var i = 0; i < input.length; i++) {
        if (string.indexOf(input.charAt(i)) == -1) {
            return false;
        }
    }

    return true;
}

function f_setRadioButtonListEnable(controlID, selectedIndex, enable) {
    var rbtn = document.getElementById(controlID + "_" + selectedIndex);
    rbtn.disabled = !enable;
    var result = "";
}

//DeSelect the selected values from target radio button list
function f_setRadioButtonListToDeselect(controlID, selectedIndex) {

    var rbtn = document.getElementById(controlID).getElementsByTagName('input');
    rbtn[selectedIndex].checked = false;

}
//Get the target control maxlength
function f_getMaxLength(controlID) {

    return document.getElementById(controlID).getAttribute("maxLength");

}
// rtrim
function rtrim(stringToTrim) {
    return stringToTrim.replace(/\s+$/, "");
}

// ltrim
function ltrim(str, chars) {
    chars = chars || "\\s";
    return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}


// trim
function trim(str, chars) {
    return ltrim(rtrim(str, chars), chars);
}

function f_checkWithSpace(input) {
    var string = " ";
    if (f_isBlank(input)) {
        return false;
    }
    if (input.indexOf(string) != -1) {
        return true;
    }
    return false;
}

//function f_checkMaxLength(Object, MaxLen) {
//    var value = Object.value;
//    var totalLength = 0;
//    for (var i = 0; i < value.length; i++) {
//        if (value.charCodeAt(i) > 126){
//            totalLength += 2;
//        }else{
//            totalLength += 1;
//        }
//        if (totalLength > MaxLen) {
//            Object.value = Object.value.substring(0, i);           
//            break;
//        }
//    }
//}
function f_checkMaxLength_onkeypress(p_object, p_event) {
    //return false;
    var v_event = (window.event) ? window.event : p_event;
    var v_keyCode = (v_event.keyCode) ? v_event.keyCode : v_event.charCode;
    var lastValue = f_getTextBoxValue(p_object.id);
    if ((v_keyCode >= 48 && v_keyCode <= 59) // 1-9
        || (v_keyCode >= 65 && v_keyCode <= 90) // A-Z
        || (v_keyCode >= 96 && v_keyCode <= 111) // 1-9
        || (v_keyCode >= 187 && v_keyCode <= 192)
        || (v_keyCode >= 219 && v_keyCode <= 222)
        || (v_keyCode == 229)) {
        var lSize = f_getMaxLength(p_object.id);
        var newValue = f_getTextBoxValue(p_object.id);
        var totalLength = 0;
        for (var i = 0; i < newValue.length; i++) {
            if (newValue.charCodeAt(i) > 126 || newValue.charCodeAt(i) == 10) {
                 totalLength += 2;
            } else {
                totalLength += 1;
            }
            if (totalLength > lSize) {
                return false;
            }
        }

    }
   return true;
}

function f_checkMaxLength_onblur(p_object) {
    var v_fields = new Array();
    var lSize = f_getMaxLength(p_object.id);
    var newValue = f_getTextBoxValue(p_object.id);
    if (!g_isClosed) return false;
    var totalLength = 0;
    for (var i = 0; i < newValue.length; i++) {
        if (newValue.charCodeAt(i) > 126 || newValue.charCodeAt(i) ==10) {
            totalLength += 2;
        } else {
            totalLength += 1;
        }
    }
    if (totalLength > lSize) {
        v_fields = new Array();
        v_fields[0] = 'The length of input is over the limitation.';
        f_errorMessageShow('99997', p_object.id, v_fields);
    }
}

function f_checkMaxLength(p_object) {
    var lastValue = f_getTextBoxValue(p_object.id);
    lastValue = lastValue.replace(/\'/g, '\\\'');
    lastValue = lastValue.replace(/\"/g, '\\"');
    lastValue = lastValue.replace(/\n/g, '\\n');
    lastValue = lastValue.replace(/\r/g, '')
    setTimeout("f_checkNextMaxLength('" + p_object.id + "', '" + lastValue + "');", 1);

}

function f_checkNextMaxLength(p_objectID, p_lastValue) {
    var lSize = f_getMaxLength(p_objectID);
    var newValue = f_getTextBoxValue(p_objectID);
    var totalLength = 0;
    for (var i = 0; i < newValue.length; i++) {
        if (newValue.charCodeAt(i) > 126 || newValue.charCodeAt(i) == 10) {
            totalLength += 2;
        } else {
            totalLength += 1;
        }
        if (totalLength > lSize) {
           
            f_setValue(p_objectID, p_lastValue);
            f_setValue(p_objectID, p_lastValue.substring(0, i));
            break;
        }
    }
}

function f_focusErrorMessage() {
    //$('.error:visible[innerHTML!=""]').eq(0).attr('tabindex', 0);
    $('.error:visible').not('[innerHTML=""]').eq(0).focus();
    $('.error-msg:visible').not('[innerHTML=""]').eq(0).focus();
};
/*
 * jQuery Autocomplete plugin 1.2.3
 *
 * Copyright (c) 2009 Jörn Zaefferer
 *
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 *
 * With small modifications by Alfonso Gómez-Arzola.
 * See changelog for details.
 *
 */

;(function($) {

$.fn.extend({
	autocomplete: function(urlOrData, options) {
		var isUrl = typeof urlOrData == "string";
		options = $.extend({}, $.Autocompleter.defaults, {
			url: isUrl ? urlOrData : null,
			data: isUrl ? null : urlOrData,
			delay: isUrl ? $.Autocompleter.defaults.delay : 10,
			max: options && !options.scroll ? 10 : 150,
		}, options);

		// if highlight is set to false, replace it with a do-nothing function
		options.highlight = options.highlight || function(value) { return value; };

		// if the formatMatch option is not specified, then use formatItem for backwards compatibility
		options.formatMatch = options.formatMatch || options.formatItem;

		return this.each(function() {
			new $.Autocompleter(this, options);
		});
	},
	result: function(handler) {
		return this.bind("result", handler);
	},
	search: function(handler) {
		return this.trigger("search", [handler]);
	},
	flushCache: function() {
		return this.trigger("flushCache");
	},
	setOptions: function(options){
		return this.trigger("setOptions", [options]);
	},
	unautocomplete: function() {
		return this.trigger("unautocomplete");
	}
});

$.Autocompleter = function(input, options) {

	var KEY = {
		UP: 38,
		DOWN: 40,
		DEL: 46,
		TAB: 9,
		RETURN: 13,
		ESC: 27,
		COMMA: 188,
		PAGEUP: 33,
		PAGEDOWN: 34,
		BACKSPACE: 8
	};

	var globalFailure = null;
	if(options.failure != null && typeof options.failure == "function") {
	  globalFailure = options.failure;
	}

	// Create $ object for input element
	var $input = $(input).attr("autocomplete", "off").addClass(options.inputClass);

	var timeout;
	var previousValue = "";
	var cache = $.Autocompleter.Cache(options);
	var hasFocus = 0;
	var lastKeyPressCode;
	var config = {
		mouseDownOnSelect: false
	};
	var select = $.Autocompleter.Select(options, input, selectCurrent, config);

	var blockSubmit;

	// prevent form submit in opera when selecting with return key
  navigator.userAgent.indexOf("Opera") != -1 && $(input.form).bind("submit.autocomplete", function() {
		if (blockSubmit) {
			blockSubmit = false;
			return false;
		}
	});

	// older versions of opera don't trigger keydown multiple times while pressed, others don't work with keypress at all
	$input.bind((navigator.userAgent.indexOf("Opera") != -1 && !'KeyboardEvent' in window ? "keypress" : "keydown") + ".autocomplete", function(event) {
		// a keypress means the input has focus
		// avoids issue where input had focus before the autocomplete was applied
		hasFocus = 1;
		// track last key pressed
		lastKeyPressCode = event.keyCode;
		switch(event.keyCode) {

			case KEY.UP:
				if ( select.visible() ) {
					event.preventDefault();
					select.prev();
				} else {
					onChange(0, true);
				}
				break;

			case KEY.DOWN:
				if ( select.visible() ) {
					event.preventDefault();
					select.next();
				} else {
					onChange(0, true);
				}
				break;

			case KEY.PAGEUP:
				if ( select.visible() ) {
  				event.preventDefault();
					select.pageUp();
				} else {
					onChange(0, true);
				}
				break;

			case KEY.PAGEDOWN:
				if ( select.visible() ) {
  				event.preventDefault();
					select.pageDown();
				} else {
					onChange(0, true);
				}
				break;

			// matches also semicolon
			case options.multiple && $.trim(options.multipleSeparator) == "," && KEY.COMMA:
			case KEY.TAB:
			case KEY.RETURN:
				if( selectCurrent() ) {
					// stop default to prevent a form submit, Opera needs special handling
					event.preventDefault();
					blockSubmit = true;
					return false;
				}
				break;

			case KEY.ESC:
				select.hide();
				break;

			default:
				clearTimeout(timeout);
				timeout = setTimeout(onChange, options.delay);
				break;
		}
	}).focus(function(){
		// track whether the field has focus, we shouldn't process any
		// results if the field no longer has focus
		hasFocus++;
	}).blur(function() {
	  hasFocus = 0;
		if (!config.mouseDownOnSelect) {
			hideResults();
		}
	}).click(function() {
		// show select when clicking in a focused field
		// but if clickFire is true, don't require field
		// to be focused to begin with; just show select
		if( options.clickFire ) {
		  if ( !select.visible() ) {
  			onChange(0, true);
  		}
		} else {
		  if ( hasFocus++ > 1 && !select.visible() ) {
  			onChange(0, true);
  		}
		}
	}).bind("search", function() {
		// TODO why not just specifying both arguments?
		var fn = (arguments.length > 1) ? arguments[1] : null;
		function findValueCallback(q, data) {
			var result;
			if( data && data.length ) {
				for (var i=0; i < data.length; i++) {
					if( data[i].result.toLowerCase() == q.toLowerCase() ) {
						result = data[i];
						break;
					}
				}
			}
			if( typeof fn == "function" ) fn(result);
			else $input.trigger("result", result && [result.data, result.value]);
		}
		$.each(trimWords($input.val()), function(i, value) {
			request(value, findValueCallback, findValueCallback);
		});
	}).bind("flushCache", function() {
		cache.flush();
	}).bind("setOptions", function() {
		$.extend(true, options, arguments[1]);
		// if we've updated the data, repopulate
		if ( "data" in arguments[1] )
			cache.populate();
	}).bind("unautocomplete", function() {
		select.unbind();
		$input.unbind();
		$(input.form).unbind(".autocomplete");
	});


	function selectCurrent() {
		var selected = select.selected();
		if( !selected )
			return false;

		var v = selected.result;
		previousValue = v;

		if ( options.multiple ) {
			var words = trimWords($input.val());
			if ( words.length > 1 ) {
				var seperator = options.multipleSeparator.length;
				var cursorAt = $(input).selection().start;
				var wordAt, progress = 0;
				$.each(words, function(i, word) {
					progress += word.length;
					if (cursorAt <= progress) {
						wordAt = i;
						return false;
					}
					progress += seperator;
				});
				words[wordAt] = v;
				// TODO this should set the cursor to the right position, but it gets overriden somewhere
				//$.Autocompleter.Selection(input, progress + seperator, progress + seperator);
				v = words.join( options.multipleSeparator );
			}
			v += options.multipleSeparator;
		}

		$input.val(v);
		hideResultsNow();
		$input.trigger("result", [selected.data, selected.value]);
		return true;
	}

	function onChange(crap, skipPrevCheck) {
		if( lastKeyPressCode == KEY.DEL ) {
			select.hide();
			return;
		}

		var currentValue = $input.val();

		if ( !skipPrevCheck && currentValue == previousValue )
			return;

		previousValue = currentValue;

		currentValue = lastWord(currentValue);
		if ( currentValue.length >= options.minChars) {
			$input.addClass(options.loadingClass);
			if (!options.matchCase)
				currentValue = currentValue.toLowerCase();
			request(currentValue, receiveData, hideResultsNow);
		} else {
			stopLoading();
			select.hide();
		}
	};

	function trimWords(value) {
		if (!value)
			return [""];
		if (!options.multiple)
			return [$.trim(value)];
		return $.map(value.split(options.multipleSeparator), function(word) {
			return $.trim(value).length ? $.trim(word) : null;
		});
	}

	function lastWord(value) {
		if ( !options.multiple )
			return value;
		var words = trimWords(value);
		if (words.length == 1)
			return words[0];
		var cursorAt = $(input).selection().start;
		if (cursorAt == value.length) {
			words = trimWords(value)
		} else {
			words = trimWords(value.replace(value.substring(cursorAt), ""));
		}
		return words[words.length - 1];
	}

	// fills in the input box w/the first match (assumed to be the best match)
	// q: the term entered
	// sValue: the first matching result
	function autoFill(q, sValue){
		// autofill in the complete box w/the first match as long as the user hasn't entered in more data
		// if the last user key pressed was backspace, don't autofill
		if( options.autoFill && (lastWord($input.val()).toLowerCase() == q.toLowerCase()) && lastKeyPressCode != KEY.BACKSPACE ) {
			// fill in the value (keep the case the user has typed)
			$input.val($input.val() + sValue.substring(lastWord(previousValue).length));
			// select the portion of the value not typed by the user (so the next character will erase)
			$(input).selection(previousValue.length, previousValue.length + sValue.length);
		}
	};

	function hideResults() {
		clearTimeout(timeout);
		timeout = setTimeout(hideResultsNow, 200);
	};

	function hideResultsNow() {
		var wasVisible = select.visible();
		select.hide();
		clearTimeout(timeout);
		stopLoading();
		if (options.mustMatch) {
			// call search and run callback
			$input.search(
				function (result){
					// if no value found, clear the input box
					if( !result ) {
						if (options.multiple) {
							var words = trimWords($input.val()).slice(0, -1);
							$input.val( words.join(options.multipleSeparator) + (words.length ? options.multipleSeparator : "") );
						}
						else {
							$input.val( "" );
							$input.trigger("result", null);
						}
					}
				}
			);
		}
	};

	function receiveData(q, data) {
		if ( data && data.length && hasFocus ) {
			stopLoading();
			select.display(data, q);
			autoFill(q, data[0].value);
			select.show();
		} else {
			hideResultsNow();
		}
	};

	function request(term, success, failure) {
		if (!options.matchCase)
			term = term.toLowerCase();
		var data = cache.load(term);
		// recieve the cached data
		if (data) {
			if(data.length)	{
				success(term, data);
			}
			else{
				var parsed = options.parse && options.parse(options.noRecord) || parse(options.noRecord);	
				success(term,parsed);
			}
		// if an AJAX url has been supplied, try loading the data now
		} else if( (typeof options.url == "string") && (options.url.length > 0) ){

			var extraParams = {
				timestamp: +new Date()
			};
			$.each(options.extraParams, function(key, param) {
				extraParams[key] = typeof param == "function" ? param() : param;
			});

			$.ajax({
				// try to leverage ajaxQueue plugin to abort previous requests
				mode: "abort",
				// limit abortion to this input
				port: "autocomplete" + input.name,
				dataType: options.dataType,
				url: options.url,
				data: $.extend({
					q: lastWord(term),
					limit: options.max
				}, extraParams),
				success: function(data) {
					var parsed = options.parse && options.parse(data) || parse(data);
					cache.add(term, parsed);
					success(term, parsed);
				}
			});
		} else {
			// if we have a failure, we need to empty the list -- this prevents the the [TAB] key from selecting the last successful match
			select.emptyList();
			if(globalFailure != null) {
        globalFailure();
      }
      else {
        failure(term);
			}
		}
	};

	function parse(data) {
		var parsed = [];
		var rows = data.split("\n");
		for (var i=0; i < rows.length; i++) {
			var row = $.trim(rows[i]);
			if (row) {
				row = row.split("|");
				parsed[parsed.length] = {
					data: row,
					value: row[0],
					result: options.formatResult && options.formatResult(row, row[0]) || row[0]
				};
			}
		}
		return parsed;
	};

	function stopLoading() {
		$input.removeClass(options.loadingClass);
	};

};

$.Autocompleter.defaults = {
	inputClass: "ac_input",
	resultsClass: "ac_results",
	loadingClass: "ac_loading",
	minChars: 1,
	delay: 400,
	matchCase: false,
	matchSubset: true,
	matchContains: true,
	cacheLength: 100,
	max: 100,
	mustMatch: false,
	extraParams: {},
	selectFirst: true,
	formatItem: function(row) { return row[0]; },
	formatMatch: null,
	autoFill: false,
	width: 0,
	multiple: false,
	multipleSeparator: ", ",
	inputFocus: true,
	clickFire: false,
	highlight: function(value, term) {
		return value.replace(new RegExp("(?![^&;]+;)(?!<[^<>]*)(" + term.replace(/([\^\$\(\)\[\]\{\}\*\.\+\?\|\\])/gi, "\\$1") + ")(?![^<>]*>)(?![^&;]+;)", "gi"), "<strong>$1</strong>");
	},
    scroll: true,
    scrollHeight: 180,
    scrollJumpPosition: true
};

$.Autocompleter.Cache = function(options) {

	var data = {};
	var length = 0;

	function matchSubset(s, sub) {
		if (!options.matchCase)
			s = s.toLowerCase();
		var i = s.indexOf(sub);
		if (options.matchContains == "word"){
			i = s.toLowerCase().search("\\b" + sub.toLowerCase());
		}
		if (i == -1) return false;
		return i == 0 || options.matchContains;
	};

	function add(q, value) {
		if (length > options.cacheLength){
			flush();
		}
		if (!data[q]){
			length++;
		}
		data[q] = value;
	}

	function populate(){
		if( !options.data ) return false;
		// track the matches
		var stMatchSets = {},
			nullData = 0;

		// no url was specified, we need to adjust the cache length to make sure it fits the local data store
		if( !options.url ) options.cacheLength = 1;

		// track all options for minChars = 0
		stMatchSets[""] = [];

		// loop through the array and create a lookup structure
		for ( var i = 0, ol = options.data.length; i < ol; i++ ) {
			var rawValue = options.data[i];
			// if rawValue is a string, make an array otherwise just reference the array
			rawValue = (typeof rawValue == "string") ? [rawValue] : rawValue;

			var value = options.formatMatch(rawValue, i+1, options.data.length);
			if ( typeof(value) === 'undefined' || value === false )
				continue;

			var firstChar = value.charAt(0).toLowerCase();
			// if no lookup array for this character exists, look it up now
			if( !stMatchSets[firstChar] )
				stMatchSets[firstChar] = [];

			// if the match is a string
			var row = {
				value: value,
				data: rawValue,
				result: options.formatResult && options.formatResult(rawValue) || value
			};

			// push the current match into the set list
			stMatchSets[firstChar].push(row);

			// keep track of minChars zero items
			if ( nullData++ < options.max ) {
				stMatchSets[""].push(row);
			}
		};

		// add the data items to the cache
		$.each(stMatchSets, function(i, value) {
			// increase the cache size
			options.cacheLength++;
			// add to the cache
			add(i, value);
		});
	}

	// populate any existing data
	setTimeout(populate, 25);

	function flush(){
		data = {};
		length = 0;
	}

	return {
		flush: flush,
		add: add,
		populate: populate,
		load: function(q) {
			if (!options.cacheLength || !length)
				return null;
			/*
			 * if dealing w/local data and matchContains than we must make sure
			 * to loop through all the data collections looking for matches
			 */
			if( !options.url && options.matchContains ){
				// track all matches
				var csub = [];
				// loop through all the data grids for matches
				for( var k in data ){
					// don't search through the stMatchSets[""] (minChars: 0) cache
					// this prevents duplicates
					if( k.length > 0 ){
						var c = data[k];
						$.each(c, function(i, x) {
							// if we've got a match, add it to the array
							if (matchSubset(x.value, q)) {
								csub.push(x);
							}
						});
					}
				}
				return csub;
			} else
			// if the exact item exists, use it
			if (data[q]){
				return data[q];
			} else
			if (options.matchSubset) {
				for (var i = q.length - 1; i >= options.minChars; i--) {
					var c = data[q.substr(0, i)];
					if (c) {
						var csub = [];
						$.each(c, function(i, x) {
							if (matchSubset(x.value, q)) {
								csub[csub.length] = x;
							}
						});
						return csub;
					}
				}
			}
			return null;
		}
	};
};

$.Autocompleter.Select = function (options, input, select, config) {
	var CLASSES = {
		ACTIVE: "ac_over"
	};

	var listItems,
		active = -1,
		data,
		term = "",
		needsInit = true,
		element,
		list;

	// Create results
	function init() {
		if (!needsInit)
			return;
		element = $("<div/>")
		.hide()
		.addClass(options.resultsClass)
		.css("position", "absolute")
		.appendTo(document.body)
		.hover(function(event) {
		  // Browsers except FF do not fire mouseup event on scrollbars, resulting in mouseDownOnSelect remaining true, and results list not always hiding.
		  if($(this).is(":visible")) {
		    input.focus();
		  }
		  config.mouseDownOnSelect = false;
		});

		list = $("<ul/>").appendTo(element).mouseover( function(event) {
			if(target(event).nodeName && target(event).nodeName.toUpperCase() == 'LI') {
	            active = $("li", list).removeClass(CLASSES.ACTIVE).index(target(event));
			    $(target(event)).addClass(CLASSES.ACTIVE);
	        }
		}).click(function(event) {
			$(target(event)).addClass(CLASSES.ACTIVE);
			select();
			if( options.inputFocus )
			  input.focus();
			return false;
		}).mousedown(function() {
			config.mouseDownOnSelect = true;
		}).mouseup(function() {
			config.mouseDownOnSelect = false;
		});

		if( options.width > 0 )
			element.css("width", options.width);

		needsInit = false;
	}

	function target(event) {
		var element = event.target;
		while(element && element.tagName != "LI")
			element = element.parentNode;
		// more fun with IE, sometimes event.target is empty, just ignore it then
		if(!element)
			return [];
		return element;
	}

	function moveSelect(step) {
		listItems.slice(active, active + 1).removeClass(CLASSES.ACTIVE);
		movePosition(step);
        var activeItem = listItems.slice(active, active + 1).addClass(CLASSES.ACTIVE);
        if(options.scroll) {
            var offset = 0;
            listItems.slice(0, active).each(function() {
				offset += this.offsetHeight;
			});
            if((offset + activeItem[0].offsetHeight - list.scrollTop()) > list[0].clientHeight) {
                list.scrollTop(offset + activeItem[0].offsetHeight - list.innerHeight());
            } else if(offset < list.scrollTop()) {
                list.scrollTop(offset);
            }
        }
	};

	function movePosition(step) {
		if (options.scrollJumpPosition || (!options.scrollJumpPosition && !((step < 0 && active == 0) || (step > 0 && active == listItems.size() - 1)) )) {
			active += step;
			if (active < 0) {
				active = listItems.size() - 1;
			} else if (active >= listItems.size()) {
				active = 0;
			}
		}
	}


	function limitNumberOfItems(available) {
		return options.max && options.max < available
			? options.max
			: available;
	}

	function fillList() {
		list.empty();
		var max = limitNumberOfItems(data.length);
		for (var i=0; i < max; i++) {
			if (!data[i])
				continue;
			var formatted = options.formatItem(data[i].data, i+1, max, data[i].value, term);
			if ( formatted === false )
				continue;
			var li = $("<li/>").html( options.highlight(formatted, term) ).addClass(i%2 == 0 ? "ac_even" : "ac_odd").appendTo(list)[0];
			$.data(li, "ac_data", data[i]);
		}
		listItems = list.find("li");
		if ( options.selectFirst ) {
			listItems.slice(0, 1).addClass(CLASSES.ACTIVE);
			active = 0;
		}
		// apply bgiframe if available
		if ( $.fn.bgiframe )
			list.bgiframe();
	}

	return {
		display: function(d, q) {
			init();
			data = d;
			term = q;
			fillList();
		},
		next: function() {
			moveSelect(1);
		},
		prev: function() {
			moveSelect(-1);
		},
		pageUp: function() {
			if (active != 0 && active - 8 < 0) {
				moveSelect( -active );
			} else {
				moveSelect(-8);
			}
		},
		pageDown: function() {
			if (active != listItems.size() - 1 && active + 8 > listItems.size()) {
				moveSelect( listItems.size() - 1 - active );
			} else {
				moveSelect(8);
			}
		},
		hide: function() {
			element && element.hide();
			listItems && listItems.removeClass(CLASSES.ACTIVE);
			active = -1;
		},
		visible : function() {
			return element && element.is(":visible");
		},
		current: function() {
			return this.visible() && (listItems.filter("." + CLASSES.ACTIVE)[0] || options.selectFirst && listItems[0]);
		},
		show: function() {
			var offset = $(input).offset();
			element.css({
				width: typeof options.width == "string" || options.width > 0 ? options.width : $(input).width(),
				top: offset.top + input.offsetHeight,
				left: offset.left
			}).show();
            if(options.scroll) {
                list.scrollTop(0);
                list.css({
					maxHeight: options.scrollHeight,
					overflow: 'auto'
				});

                if(navigator.userAgent.indexOf("MSIE") != -1 && typeof document.body.style.maxHeight === "undefined") {
					var listHeight = 0;
					listItems.each(function() {
						listHeight += this.offsetHeight;
					});
					var scrollbarsVisible = listHeight > options.scrollHeight;
                    list.css('height', scrollbarsVisible ? options.scrollHeight : listHeight );
					if (!scrollbarsVisible) {
						// IE doesn't recalculate width when scrollbar disappears
						listItems.width( list.width() - parseInt(listItems.css("padding-left")) - parseInt(listItems.css("padding-right")) );
					}
                }

            }
		},
		selected: function() {
			var selected = listItems && listItems.filter("." + CLASSES.ACTIVE).removeClass(CLASSES.ACTIVE);
			return selected && selected.length && $.data(selected[0], "ac_data");
		},
		emptyList: function (){
			list && list.empty();
		},
		unbind: function() {
			element && element.remove();
		}
	};
};

$.fn.selection = function(start, end) {
	if (start !== undefined) {
		return this.each(function() {
			if( this.createTextRange ){
				var selRange = this.createTextRange();
				if (end === undefined || start == end) {
					selRange.move("character", start);
					selRange.select();
				} else {
					selRange.collapse(true);
					selRange.moveStart("character", start);
					selRange.moveEnd("character", end);
					selRange.select();
				}
			} else if( this.setSelectionRange ){
				this.setSelectionRange(start, end);
			} else if( this.selectionStart ){
				this.selectionStart = start;
				this.selectionEnd = end;
			}
		});
	}
	var field = this[0];
	if ( field.createTextRange ) {
		var range = document.selection.createRange(),
			orig = field.value,
			teststring = "<->",
			textLength = range.text.length;
		range.text = teststring;
		var caretAt = field.value.indexOf(teststring);
		field.value = orig;
		this.selection(caretAt, caretAt + textLength);
		return {
			start: caretAt,
			end: caretAt + textLength
		}
	} else if( field.selectionStart !== undefined ){
		return {
			start: field.selectionStart,
			end: field.selectionEnd
		}
	}
};

})(jQuery);
;
/*
jQuery Masked Input Plugin
Copyright (c) 2007 - 2015 Josh Bush (digitalbush.com)
Licensed under the MIT license (http://digitalbush.com/projects/masked-input-plugin/#license)
Version: 1.4.1
*/
!function(factory) {
    "function" == typeof define && define.amd ? define(["jquery"], factory) : factory("object" == typeof exports ? require("jquery") : jQuery);
} (function($) {
    var caretTimeoutId, ua = navigator.userAgent, iPhone = /iphone/i.test(ua), chrome = /chrome/i.test(ua), android = /android/i.test(ua);
    $.mask = {
        definitions: {
            "9": "[0-9]",
            a: "[A-Za-z]",
            "*": "[A-Za-z0-9]"
        },
        autoclear: !0,
        dataName: "rawMaskFn",
        placeholder: "_"
    }, $.fn.extend({
        caret: function(begin, end) {
            var range;
            if (0 !== this.length && !this.is(":hidden")) return "number" == typeof begin ? (end = "number" == typeof end ? end : begin,
            this.each(function() {
                this.setSelectionRange ? this.setSelectionRange(begin, end) : this.createTextRange && (range = this.createTextRange(),
                range.collapse(!0), range.moveEnd("character", end), range.moveStart("character", begin),
                range.select());
            })) : (this[0].setSelectionRange ? (begin = this[0].selectionStart, end = this[0].selectionEnd) : document.selection && document.selection.createRange && (range = document.selection.createRange(),
            begin = 0 - range.duplicate().moveStart("character", -1e5), end = begin + range.text.length),
            {
                begin: begin,
                end: end
            });
        },
        unmask: function() {
            return this.trigger("unmask");
        },
        mask: function(mask, settings) {
            var input, defs, tests, partialPosition, firstNonMaskPos, lastRequiredNonMaskPos, len, oldVal;
            if (!mask && this.length > 0) {
                input = $(this[0]);
                var fn = input.data($.mask.dataName);
                return fn ? fn() : void 0;
            }
            return settings = $.extend({
                autoclear: $.mask.autoclear,
                placeholder: $.mask.placeholder,
                completed: null
            }, settings), defs = $.mask.definitions, tests = [], partialPosition = len = mask.length,
            firstNonMaskPos = null, $.each(mask.split(""), function(i, c) {
                "?" == c ? (len--, partialPosition = i) : defs[c] ? (tests.push(new RegExp(defs[c])),
                null === firstNonMaskPos && (firstNonMaskPos = tests.length - 1), partialPosition > i && (lastRequiredNonMaskPos = tests.length - 1)) : tests.push(null);
            }), this.trigger("unmask").each(function() {
                function tryFireCompleted() {
                    if (settings.completed) {
                        for (var i = firstNonMaskPos; lastRequiredNonMaskPos >= i; i++) if (tests[i] && buffer[i] === getPlaceholder(i)) return;
                        settings.completed.call(input);
                    }
                }
                function getPlaceholder(i) {
                    return settings.placeholder.charAt(i < settings.placeholder.length ? i : 0);
                }
                function seekNext(pos) {
                    for (; ++pos < len && !tests[pos]; );
                    return pos;
                }
                function seekPrev(pos) {
                    for (; --pos >= 0 && !tests[pos]; );
                    return pos;
                }
                function shiftL(begin, end) {
                    var i, j;
                    if (!(0 > begin)) {
                        for (i = begin, j = seekNext(end); len > i; i++) if (tests[i]) {
                            if (!(len > j && tests[i].test(buffer[j]))) break;
                            buffer[i] = buffer[j], buffer[j] = getPlaceholder(j), j = seekNext(j);
                        }
                        writeBuffer(), input.caret(Math.max(firstNonMaskPos, begin));
                    }
                }
                function shiftR(pos) {
                    var i, c, j, t;
                    for (i = pos, c = getPlaceholder(pos); len > i; i++) if (tests[i]) {
                        if (j = seekNext(i), t = buffer[i], buffer[i] = c, !(len > j && tests[j].test(t))) break;
                        c = t;
                    }
                }
                function androidInputEvent() {
                    var curVal = input.val(), pos = input.caret();
                    if (oldVal && oldVal.length && oldVal.length > curVal.length) {
                        for (checkVal(!0); pos.begin > 0 && !tests[pos.begin - 1]; ) pos.begin--;
                        if (0 === pos.begin) for (; pos.begin < firstNonMaskPos && !tests[pos.begin]; ) pos.begin++;
                        input.caret(pos.begin, pos.begin);
                    } else {
                        for (checkVal(!0); pos.begin < len && !tests[pos.begin]; ) pos.begin++;
                        input.caret(pos.begin, pos.begin);
                    }
                    tryFireCompleted();
                }
                function blurEvent() {
                    checkVal(), input.val() != focusText && input.change();
                }
                function keydownEvent(e) {
                    if (!input.prop("readonly")) {
                        var pos, begin, end, k = e.which || e.keyCode;
                        oldVal = input.val(), 8 === k || 46 === k || iPhone && 127 === k ? (pos = input.caret(),
                        begin = pos.begin, end = pos.end, end - begin === 0 && (begin = 46 !== k ? seekPrev(begin) : end = seekNext(begin - 1),
                        end = 46 === k ? seekNext(end) : end), clearBuffer(begin, end), shiftL(begin, end - 1),
                        e.preventDefault()) : 13 === k ? blurEvent.call(this, e) : 27 === k && (input.val(focusText),
                        input.caret(0, checkVal()), e.preventDefault());
                    }
                }
                function keypressEvent(e) {
                    if (!input.prop("readonly")) {
                        var p, c, next, k = e.which || e.keyCode, pos = input.caret();
                        if (!(e.ctrlKey || e.altKey || e.metaKey || 32 > k) && k && 13 !== k) {
                            if (pos.end - pos.begin !== 0 && (clearBuffer(pos.begin, pos.end), shiftL(pos.begin, pos.end - 1)),
                            p = seekNext(pos.begin - 1), len > p && (c = String.fromCharCode(k), tests[p].test(c))) {
                                if (shiftR(p), buffer[p] = c, writeBuffer(), next = seekNext(p), android) {
                                    var proxy = function() {
                                        $.proxy($.fn.caret, input, next)();
                                    };
                                    setTimeout(proxy, 0);
                                } else input.caret(next);
                                pos.begin <= lastRequiredNonMaskPos && tryFireCompleted();
                            }
                            e.preventDefault();
                        }
                    }
                }
                function clearBuffer(start, end) {
                    var i;
                    for (i = start; end > i && len > i; i++) tests[i] && (buffer[i] = getPlaceholder(i));
                }
                function writeBuffer() {
                    input.val(buffer.join(""));
                }
                function checkVal(allow) {
                    var i, c, pos, test = input.val(), lastMatch = -1;
                    for (i = 0, pos = 0; len > i; i++) if (tests[i]) {
                        for (buffer[i] = getPlaceholder(i); pos++ < test.length; ) if (c = test.charAt(pos - 1),
                        tests[i].test(c)) {
                            buffer[i] = c, lastMatch = i;
                            break;
                        }
                        if (pos > test.length) {
                            clearBuffer(i + 1, len);
                            break;
                        }
                    } else buffer[i] === test.charAt(pos) && pos++, partialPosition > i && (lastMatch = i);
                    return allow ? writeBuffer() : partialPosition > lastMatch + 1 ? settings.autoclear || buffer.join("") === defaultBuffer ? (input.val() && input.val(""),
                    clearBuffer(0, len)) : writeBuffer() : (writeBuffer(), input.val(input.val().substring(0, lastMatch + 1))),
                    partialPosition ? i : firstNonMaskPos;
                }
                var input = $(this), buffer = $.map(mask.split(""), function(c, i) {
                    return "?" != c ? defs[c] ? getPlaceholder(i) : c : void 0;
                }), defaultBuffer = buffer.join(""), focusText = input.val();
                input.data($.mask.dataName, function() {
                    return $.map(buffer, function(c, i) {
                        return tests[i] && c != getPlaceholder(i) ? c : null;
                    }).join("");
                }), input.one("unmask", function() {
                    input.off(".mask").removeData($.mask.dataName);
                }).on("focus.mask", function() {
                    if (!input.prop("readonly")) {
                        clearTimeout(caretTimeoutId);
                        var pos;
                        focusText = input.val(), pos = checkVal(), caretTimeoutId = setTimeout(function() {
                            input.get(0) === document.activeElement && (writeBuffer(), pos == mask.replace("?", "").length ? input.caret(0, pos) : input.caret(pos));
                        }, 10);
                    }
                }).on("blur.mask", blurEvent).on("keydown.mask", keydownEvent).on("keypress.mask", keypressEvent).on("input.mask paste.mask", function() {
                    input.prop("readonly") || setTimeout(function() {
                        var pos = checkVal(!0);
                        input.caret(pos), tryFireCompleted();
                    }, 0);
                }), chrome && android && input.off("input.mask").on("input.mask", androidInputEvent),
                checkVal();
            });
        }
    });
});;
