var preURL = '/schedule_console/schedule-manager?responseType=json&action=';
//var preURL = '/volcs_vg/schedule-web?responseType=json&action=';
var stateSelectOption = '0:変更無し;1:初期(I);4:正常終了(N);5:異常終了(F);9:無効化(D)';
var controlStateSelectOption = '0:変更無し;2:一時停止(P);3:再開(R);4:中断(A)';
var stateSearchOption = ':すべて;1:初期(I);2:投入(E);3:実行中(R);4:正常終了(N);5:異常終了(F);6:一時停止(P);7:中断(A);8:リトライ(T);9:無効化(D);-1:不明(U)';
var checkStateSearchOption = ':すべて;1:初期状態(I);2:タイムオーバー(O);-1:不明(U)';
var controlStateSearchOption = ':すべて;1:初期状態(I);2:一時停止(P);3:再開(R);4:中断(A);5:制御失敗(F);-1:不明(U)';
var booleanSearchOption = ':すべて;true:○;false:☓'
var timeSearchOption = ":すべて;start:一発;repeat:繰返し;retry:リトライ;none:その他"
var masterDivId = '';
var masterPagerDivId = '';
var scheduleDivId = '';
var schedulePagerDivId = '';
var dependsDivId = '';
var dependsPagerDivId = '';
var dependedDivId = '';
var dependedPagerDivId = '';
var dateTimeFormatter = 'YYYYMMDDhhmmssSSS';
var setFrozenColumns = 'setFrozenColumns'; 
var masterId = '';
var fromStr = '';
var toStr = '';
var selectedScheduleRow = null;

function isBlank(str){
    return str == undefined || str == null || str.length == 0 ? true : false;
}

function toNull(str){
    return isBlank(str) ? 'null' : str;
}

function unformatTime(beforeStr){
    if(isBlank(beforeStr)){
        return 'null';
    }
    return beforeStr.split(':').join('');
}

function unformatDateTime(beforeStr){
    if(isBlank(beforeStr)){
        return 'null';
    }
    var unformate = beforeStr.split(' ');
    return unformate[0].split('/').join('') + unformate[1].split(':').join('');
}

function timeFormatSource(datetime){
    return isBlank(datetime)?'':datetime.substr(8, 2) + ':' + datetime.substr(10, 2) + ':' + datetime.substr(12, 2);
}

function getHourSource(datetime){
    return isBlank(datetime)?'':datetime.substr(8, 2);
}

function getMinuteSource(datetime){
    return isBlank(datetime)?'':datetime.substr(10, 2);
}

function dateTimeFormat(cellvalue){
    return isBlank(cellvalue)?'':cellvalue.substr(0, 4) + '/' + cellvalue.substr(4, 2) + '/' + cellvalue.substr(6, 2) + ' ' + cellvalue.substr(8, 2) + ':' + cellvalue.substr(10, 2) + ':' + cellvalue.substr(12, 2) + ':' + cellvalue.substr(14, 3);
}

function getRunTime(start, end){
    var startTime,endTime;
    if(!isBlank(start)){
    }
    if(!isBlank(end)){
        endTime = moment(end,dateTimeFormatter);
    }
    var diff = 0;
    if(endTime != null && startTime != null){
        diff = (endTime.valueOf() - startTime.valueOf()) / 1000 //seconds
    }
    return diff;
}
function getBooleanStr(cellvalue, options, cell){
    return isBlank(cellvalue)?'':cellvalue == 'true' || cellvalue == true? '◯' : '☓';
}

function getTimeRange(time){
    var tmpH,tmpM,tmpS;
    if(!isBlank(time) && time != '0'){
        var result = Math.round(time / 1000);
        tmpM = Math.round(result / 60);
        tmpS = result % 60;
        tmpH = Math.round(tmpM / 60);
        tmpM = tmpM % 60;
        return ('0' + tmpH).slice(-2) + ':' + ('0' + tmpM).slice(-2)+ ':' + ('0' + tmpS).slice(-2);
    }
    return '00:00:00';
}

function changeTimeRange(timeStr){
    var hourtime = timeStr.split('.');
    return (hourtime[0] * 3600 + hourtime[1] * 60 + hourtime[0]) * 1000;
}

function getStateName(cellvalue, options, cell) {
    var temp='';
    var color = 'transparent';
    if (cellvalue == 1) {
        temp = '初期(I)';
        color = 'LightSteelBlue';
    }else if (cellvalue == 2) {
        temp = '投入(E)';
        color = 'yellow';
    }else if (cellvalue == 3) {
        temp = '実行中(R)';
        color = 'yellow';
    }else if (cellvalue == 4) {
        temp = '正常終了(N)';
        color = 'Chartreuse';
    }else if (cellvalue == 5) {
        temp = '異常終了(F)';
        color = 'Red';
    }else if (cellvalue == 6) {
        temp = '一時停止(P)';
        color = 'yellow';
    }else if (cellvalue == 7) {
        temp = '中断(A)';
        color = 'yellow';
    }else if (cellvalue == 8) {
        temp = 'リトライ(T)';
        color = 'yellow';
    }else if (cellvalue == 9) {
        temp = '無効化(D)';
        color = 'DarkGray';
    }else if (cellvalue == -1) {
        temp = '不明(U)';
    }
    return "<span class='none' style='background-color:" + color + ";'>" + temp + '</span>';
}
function getStateCode(name) {
    var temp=-1;
    if (name.indexOf('初期') != -1) {
        temp = 1;
    }else if (name.indexOf('投入') != -1) {
        temp = 2;
    }else if (name.indexOf('実行中') != -1) {
        temp = 3;
    }else if (name.indexOf('正常終了') != -1) {
        temp = 4;
    }else if (name.indexOf('異常終了') != -1) {
        temp = 5;
    }else if (name.indexOf('一時停止') != -1) {
        temp = 6;
    }else if (name.indexOf('中断') != -1) {
        temp = 7;
    } else if (name.indexOf('リトライ') != -1) {
        temp = 8;
    }
    return temp;
}

function getCheckStateName(cellvalue, options, cell) {
    var temp='';
    if (cellvalue == 1) {
        temp = '初期状態(I)';
    }else if (cellvalue == 2) {
        temp = 'タイムオーバー(O)';
    }else if (cellvalue == -1) {
        temp = '不明(U)';
    }
    return temp;
}

function getControlStateName(cellvalue, options, cell) {
    var temp='';
    if (cellvalue == 1) {
        temp = '初期状態(I)';
    }else if (cellvalue == 2) {
        temp = '一時停止(P)';
    }else if (cellvalue == 3) {
        temp = '再開(R)';
        startTime = moment(start,dateTimeFormatter);
    }else if (cellvalue == 4) {
        temp = '中断(A)';
    }else if (cellvalue == 5) {
        temp = '制御失敗(F)';
    }else if (cellvalue == -1) {
        temp = '不明(U)';
    }
    return temp;
}

function getControlStateCode(name) {
    var temp=-1;
    if (name.indexOf('初期状態') != -1) {
        temp = 1;
    }else if (name.indexOf('一時停止') != -1) {
        temp = 2;
    }else if (name.indexOf('再開') != -1) {
        temp = 3;
    }else if (name.indexOf('中断') != -1) {
        temp = 4;
    }else if (name.indexOf('制御失敗') != -1) {
        temp = 5;
    }
    return temp;
}

function loadMasterTab1(){
    masterDivId = '#mastertable_tab1';
    masterPagerDivId = '#masterpager_tab1';
    scheduleDivId = '#scheduletable_tab1';
    schedulePagerDivId = '#schedulepager_tab1';
    dependsDivId = '#dependstable_tab1';
    dependsPagerDivId = '#dependspager_tab1';
    dependedDivId = '#dependedtable_tab1';
    dependedPagerDivId = '#dependedpager_tab1';
    loadMaster();
    loadSchedule();
    loadDependMst([]);
    loadDependSchedule(dependsDivId,dependsPagerDivId,'','先行ジョブ');
    loadDependSchedule(dependedDivId,dependedPagerDivId,'','後続ジョブ');
    return true;
}
function datePick(elem){
    $(elem).datepicker({dateFormat:'yymmdd'});
}
function loadMaster(){
    var mygrid;
    mygrid = jQuery(masterDivId).jqGrid({
        width: 895,
        height: 260,
        hidegrid: false,
        url: preURL + 'scheduleMaster',
        datatype: 'json',
        regional: 'ja',
        gridModel: true,
        rowNum: 10,
        rowList: [10, 20, 30],
        colNames: ['ID', 'グループID', '登録日', 'タスク名', '有効フラグ', '開始時間', '終了時間', 'インプット', 'テンプレートフラグ', 'リトライ間隔時間', 'リトライ終了時間', '最大遅延時間', '再実行間隔時間', '実行タイプ', 'スケジュールタイプ', '実行キー', '依存先'],
        colModel: [
            {name: 'id', index: 'id', width: 200, frozen: true, sortable: true},
            {name: 'groupId', index: 'groupId', width: 100, frozen: true, editable: true, sortable: true},
            {
                name: 'date',
                index: 'date',
                hidden: true,
                editable: true,
                editrules: {edithidden: true},
                editoptions: {dataInit: datePick}
            },
            {name: 'taskName', index: 'taskName', width: 250, sortable: true},
            {
                name: 'enabled',
                index: 'enabled',
                width: 100,
                align: 'center',
                formatter: getBooleanStr,
                stype: 'select',
                searchoptions: {sopt: ['eq'], value: booleanSearchOption},
                sortable: true
            },
            {
                name: 'startTime',
                index: 'startTime',
                width: 100,
                sortable: true,
                editable: true,
                align: 'right',
                searchoptions: {searchOperators: true, sopt: ['lt ', 'le', 'gt', 'ge', 'eq', 'ne']}
            },
            {
                name: 'endTime',
                index: 'endTime',
                width: 100,
                editable: true,
                sortable: true,
                align: 'right',
                searchoptions: {searchOperators: true, sopt: ['lt ', 'le', 'gt', 'ge', 'eq', 'ne']}
            },
            {name: 'input', index: 'input', width: 200, sortable: true, edittype: 'textarea', editable: true},
            {
                name: 'template',
                index: 'template',
                width: 100,
                align: 'center',
                formatter: getBooleanStr,
                stype: 'select',
                searchoptions: {sopt: ['eq'], value: booleanSearchOption},
                sortable: true
            },
            {
                name: 'retryInterval',
                index: 'retryInterval',
                width: 100,
                sortable: true,
                align: 'right',
                searchoptions: {searchOperators: true, sopt: ['lt ', 'le', 'gt', 'ge', 'eq', 'ne']}
            },
            {
                name: 'retryEndTime',
                index: 'retryEndTime',
                width: 150,
                sortable: true,
                editable: true,
                searchoptions: {searchOperators: true, sopt: ['lt ', 'le', 'gt', 'ge', 'eq', 'ne']}
            },
            {
                name: 'maxDelayTime',
                index: 'maxDelayTime',
                width: 100,
                sortable: true,
                align: 'right',
                searchoptions: {searchOperators: true, sopt: ['lt ', 'le', 'gt', 'ge', 'eq', 'ne']}
            },
            {
                name: 'repeatInterval',
                index: 'repeatInterval',
                width: 100,
                sortable: true,
                align: 'right',
                searchoptions: {searchOperators: true, sopt: ['lt ', 'le', 'gt', 'ge', 'eq', 'ne']}
            },
            {name: 'executorType', index: 'executorType', width: 100, align: 'center', editable: true, sortable: true},
            {name: 'scheduleType', index: 'scheduleType', width: 100, align: 'center', sortable: true},
            {name: 'executorKey', index: 'executorKey', width: 100, editable: true, sortable: true},
            {name: 'depends', index: 'depends', width: 100, hidden: true}
        ],
        pager: masterPagerDivId,
        viewrecords: true,
        sortname: 'id',
        sortorder: 'asc',
        onSelectRow: function (id) {
            if (id == null) {
                id = 0;
            }
            var rowData = jQuery(masterDivId).jqGrid('getRowData', id);
            var dependsData = rowData.depends != null && rowData.depends.length > 0 ? JSON.parse(rowData.depends) : "";
            jQuery('#masterdependstable_tab1').jqGrid("GridUnload");
            loadDependMst(dependsData);
            jQuery(scheduleDivId).setGridParam({
                url: preURL + 'schedule&masterId=' + encodeURI(rowData.id),
                datatype: 'json',
                page: 1
            });
            jQuery(scheduleDivId).jqGrid('setCaption', '登録中ジョブ: ' + rowData.id).trigger('reloadGrid');
            masterId = rowData.id;
            jQuery(dependsDivId).setGridParam({
                url: preURL + 'depends&id=0',
                datatype: 'json',
                page: 1
            }).trigger('reloadGrid');
            jQuery(dependedDivId).setGridParam({
                url: preURL + 'depends&id=0',
                datatype: 'json',
                page: 1
            }).trigger('reloadGrid');
        },
        beforeProcessing: function (data) {
            var i, rows = data.scheduleMasters;
            for (i = 0; i < rows.length; i++) {
                rows[i].startTime = timeFormatSource(rows[i].startTime);
                rows[i].endTime = timeFormatSource(rows[i].endTime);
                rows[i].retryEndTime = timeFormatSource(rows[i].retryEndTime);
                rows[i].retryInterval = getTimeRange(rows[i].retryInterval);
                rows[i].maxDelayTime = getTimeRange(rows[i].maxDelayTime);
                rows[i].repeatInterval = getTimeRange(rows[i].repeatInterval);
                rows[i].depends = typeof rows[i].depends === 'string' || rows[i].depends == null ? rows[i].depends : JSON.stringify(rows[i].depends);
            }
        },
        rownumbers: true,
        shrinkToFit: false,
        loadonce: true,
        caption: 'スケジュールマスター',
        jsonReader: {

            root: 'scheduleMasters',
            repeatitems: false
        }
    }).navGrid(masterPagerDivId, {edit: false, add: false, del: false, view: true, search: false}
        /* add:true,addtext:'マスターからのジョブ登録'
         {
         mtype: 'GET',
         onclickSubmit: function(rp_ge, postdata) {
         rp_ge.url =  preURL + 'addFromMaster&masterId='+ toNull(encodeURI(postdata.mastertable_tab1_id)) + '&groupId=' + toNull(encodeURI(postdata.groupId)) + '&input=' + toNull(encodeURI(postdata.input)) + '&date=' + toNull(postdata.date) + '&startTime=' + unformatTime(postdata.startTime) + '&endTime=' + unformatTime(postdata.endTime) + '&retryEndTime=' + unformatTime(postdata.retryEndTime) + '&executorKey=' + toNull(postdata.executorKey);
         },
         serializeEditData: function (postdata) { return ''; },
         reloadAfterSubmit: false,
         closeOnEscape: true,
         closeAfterEdit: true
         }
         */
    ).jqGrid('filterToolbar', {searchOperators: true, defaultSearch: 'cn'}).jqGrid(setFrozenColumns);
}

function loadDependMst(dependsMasterData){
    jQuery('#masterdependstable_tab1').jqGrid({
        width:195,
        height:288,
        regional : 'ja',
        data: dependsMasterData,
        datatype: 'local',
        colNames: ['マスターID','失敗無視フラグ'],
        colModel: [
            {name:'masterId',index:'masterId',width:145,sortable:true},
            {name:'ignoreError',index:'ignoreError',width:120,sortable:true,formatter:getBooleanStr,stype: 'select', searchoptions:{ sopt:['eq'], value: booleanSearchOption}}
        ],
        rowNum: 100,
        gridModel: true,
        shrinkToFit: false,
        //pager: '#masterdependspager_tab1',
        viewrecords: true,
        caption: '先行ジョブ',
        loadonce: true
    }).jqGrid('filterToolbar',{searchOperators: true,defaultSearch:'cn'});
}
function formatCheck(value, colname){
    if(colname.indexOf('予定開始時間') != -1 || colname.indexOf('予定終了時間') != -1){
        if (value.length > 0 && value.length != 12){
            return [false,colname + ' must input like this format.(HH:mm:ss:SSS)'];
        } else {
            return [true,''];
        }
    }else if(colname.indexOf('リトライ終了時間')!= -1){
        if(scheduleDivId == '#scheduletable_tab1'){
            if (value.length > 0 && value.length != 12){
                return [false,colname + ' must input like this format.(HH:mm:ss:SSS)'];
            } else {
                return [true,''];
            }
        }else{
            if (value.length > 0 && value.length != 23){
                return [false,colname + ' must input like this format.(yyyy/MM/dd HH:mm:ss:SSS)'];
            } else {
                return [true,''];
            }
        }
    }else if(scheduleDivId != '#scheduletable_tab1' &&( colname.indexOf('タスク名') != -1 || colname.indexOf('マスターID') != -1 )){
        if (value.length == 0 ){
                return [false,colname + ' must be required.'];
            } else {
                return [true,''];
            }
    }else if(colname.indexOf('予定時間') != -1){
        if (value.length > 0 && value.length != 23){
            return [false,colname + ' must input like this format.(yyyy/MM/dd HH:mm:ss:SSS)'];
        } else {
            return [true,''];
        }
    }else{
        return [true,''];
    }
}
function loadScheduleTab2(){
    scheduleDivId = '#scheduletable_tab2';
    schedulePagerDivId = '#schedulepager_tab2';
    dependsDivId = '#dependstable_tab2';
    dependsPagerDivId = '#dependspager_tab2';
    dependedDivId = '#dependedtable_tab2';
    dependedPagerDivId = '#dependedpager_tab2';
    var id = '#reportrange_tab2';
    var from= moment().add(-3, 'days').hour(0).minute(0);
    var to = moment();
    fromStr = isBlank(fromStr) ? from.format('YYYYMMDDHHmm')+'00000' : fromStr;
    toStr = isBlank(toStr) ? to.format('YYYYMMDDHHmm')+'59999' : toStr;
    initDateTimePicker(from,to);
    loadSchedule();
    jQuery(scheduleDivId).setGridParam({url:preURL + 'schedule&from='+fromStr +'&to=' + toStr + '&state=' + $('#multiple-optgroups').val(),datatype:'json', page:1}).trigger('reloadGrid');
    loadDependSchedule(dependsDivId,dependsPagerDivId,'','先行ジョブ');
    loadDependSchedule(dependedDivId,dependedPagerDivId,'','後続ジョブ');
    jQuery(dependsDivId).setGridParam({url:preURL + 'depends&id=0',datatype:'json', page:1}).trigger('reloadGrid');
    jQuery(dependedDivId).setGridParam({url:preURL + 'depends&id=0',datatype:'json', page:1}).trigger('reloadGrid');
    return true;
}


function initDateTimePicker(from,to){
    $('#datetimepicker6').datetimepicker({format: 'YYYY/MM/DD HH:mm',locale: moment.locale('ja'),defaultDate: from});
    $('#datetimepicker7').datetimepicker({format: 'YYYY/MM/DD HH:mm',locale: moment.locale('ja'),defaultDate: to});
    $("#datetimepicker6").on("dp.change", function (e) {
        $('#datetimepicker7').data("DateTimePicker").minDate(e.date);
    });
    $("#datetimepicker7").on("dp.change", function (e) {
        $('#datetimepicker6').data("DateTimePicker").maxDate(e.date);
    });
    $('#multiple-optgroups').multiselect({
            enableClickableOptGroups: true
        });
}

function reloadSchedule(){
    fromStr = unformatDateTime($("#datetimepicker6").find("input").val()) + '00000';
    toStr = unformatDateTime($("#datetimepicker7").find("input").val()) + '59999';
    jQuery(scheduleDivId).setGridParam({url:preURL + 'schedule&from='+fromStr +'&to=' + toStr + '&state=' + $('#multiple-optgroups').val(),datatype:'json', page:1}).trigger('reloadGrid');
    jQuery(dependsDivId).setGridParam({url:preURL + 'depends&id=0',datatype:'json', page:1}).trigger('reloadGrid');
    jQuery(dependedDivId).setGridParam({url:preURL + 'depends&id=0',datatype:'json', page:1}).trigger('reloadGrid');
}

function loadSchedule(){
    jQuery(scheduleDivId).jqGrid({
        width: 1095,
        hidegrid: false,
        height: 260,
        regional : 'ja',
        gridModel: true,
        url : '',
        loadonce: true,
        datatype: 'local',
        colNames: ['ID', 'マスターID','タスク名','ステータス', '登録日', '予定開始時間','予定終了時間', '予定時間','インプット','アウトプット','実行時間(秒)','開始時間','終了時刻','チェックステータス', 'コントロールステータス',  '実行キー', '実行タイプ', 'グループID',  '初期開始時間',  'グループマスターID', '最大遅延時間',  'リトライ', 'リトライ終了時間', 'リトライ間隔','依存先'],
        colModel: [
                {name:'id',index:'id',width:120,frozen:true,sortable:true,searchoptions:{searchOperators: true,sopt: ['lt ','le','gt','ge','eq','ne']}},
                {name:'masterId',index:'masterId',width:150,frozen:true,sortable:true,editrules:{custom: true, custom_func:formatCheck}},
                {name:'taskName',index:'taskName',width:150,frozen:true,sortable:true,editrules:{custom: true, custom_func:formatCheck}}, //editrules:{required:true},
                {name:'state',index:'state',width:100,frozen:true,align:'center',formatter:getStateName,editable:true, edittype:'select',editoptions:{value:stateSelectOption},stype: 'select', searchoptions:{ sopt:['eq'], value: stateSearchOption},sortable:true},
                {name:'date',index:'date',hidden:true,editable:true,editrules:{edithidden:true},editoptions:{dataInit:datePick}},
                {name:'startTime',index:'startTime',hidden:true,sortable:true,editable:true,editrules:{custom: true, custom_func:formatCheck}},
                {name:'endTime',index:'endTime',hidden:true,sortable:true,editable:true,editrules:{custom: true, custom_func:formatCheck}},
                {name:'time',index:'time',width:150,editable:true,sortable:true,searchoptions:{searchOperators: true,sopt: ['lt ','le','gt','ge','eq','ne']},editrules:{custom: true, custom_func:formatCheck}},
                {name:'input',index:'input',width:150,editable:true,edittype:'textarea',sortable:true},
                {name:'output',index:'output',width:150,editable:true,edittype:'textarea',sortable:true},
                {name:'runTime',index:'runTime',width:100,sorttype:'float',sortable:true,align:'right',searchoptions:{searchOperators: true,sopt: ['lt ','le','gt','ge','eq','ne']}},
                {name:'executeStartTime',index:'executeStartTime',width:140,sortable:true,searchoptions:{searchOperators: true,sopt: ['lt ','le','gt','ge','eq','ne']}},
                {name:'executeEndTime',index:'executeEndTime',width:140,sortable:true,searchoptions:{searchOperators: true,sopt: ['lt ','le','gt','ge','eq','ne']}},
                {name:'checkState',index:'checkState',width:100,align:'center',formatter:getCheckStateName,stype: 'select', searchoptions:{ sopt:['eq'], value: checkStateSearchOption},sortable:true},
                {name:'controlState',index:'controlState',width:100,align:'center',formatter:getControlStateName,editable:true,edittype:'select',editoptions:{value:controlStateSelectOption},stype: 'select', searchoptions:{ sopt:['eq'], value: controlStateSearchOption},sortable:true},
                {name:'executorKey',index:'executorKey',width:100,editable:true,sortable:true},
                {name:'executorType',index:'executorType',width:100,align:'center',editable:true,sortable:true},
                {name:'groupId',index:'groupId',width:100,editable:true,sortable:true},
                {name:'initialTime',index:'initialTime',width:150,sortable:true,searchoptions:{searchOperators: true,sopt: ['lt ','le','gt','ge','eq','ne']}},
                {name:'masterGroupId',index:'masterGroupId',width:150,sortable:true},
                {name:'maxDelayTime',index:'maxDelayTime',width:100,editable:true,sorttype:'float',align:'right',sortable:true,searchoptions:{searchOperators: true,sopt: ['lt ','le','gt','ge','eq','ne']}},
                {name:'retry',index:'retry',width:100,formatter:getBooleanStr,stype: 'select', searchoptions:{ sopt:['eq'], value: booleanSearchOption},sortable:true},
                {name:'retryEndTime',index:'retryEndTime',width:100,editable:true,sortable:true,searchoptions:{searchOperators: true,sopt: ['lt ','le','gt','ge','eq','ne']}, editrules:{custom: true, custom_func:formatCheck}},
                {name:'retryInterval',index:'retryInterval',width:100,editable:true,sorttype:'float',sortable:true,align:'right',searchoptions:{searchOperators: true,sopt: ['lt ','le','gt','ge','eq','ne']}},
                {name:'depends',index:'depends',width:200,hidden:true,editable:true,edittype:'textarea'}
        ],
        rowNum: 100,
        rowList: [100, 200, 300],
        pager: schedulePagerDivId,
        sortname: 'id',
        sortorder: 'asc',
        viewrecords: true,
        shrinkToFit: false,
        multiselect: true,
        multiboxonly: true,
        caption: '登録中ジョブ',
        jsonReader : {
            root:'schedules',
            repeatitems:false
        },
        beforeProcessing: function (data) {
            var i, rows = data.schedules;
            for (i = 0; i < rows.length; i++) {
                rows[i].runTime = getRunTime(rows[i].executeStartTime,rows[i].executeEndTime);
                rows[i].executeStartTime = dateTimeFormat(rows[i].executeStartTime);
                rows[i].executeEndTime = dateTimeFormat(rows[i].executeEndTime);
                rows[i].time = dateTimeFormat(rows[i].time);
                rows[i].initialTime = dateTimeFormat(rows[i].initialTime);
                rows[i].retryEndTime = dateTimeFormat(rows[i].retryEndTime);
                rows[i].maxDelayTime = getTimeRange(rows[i].maxDelayTime);
                rows[i].retryInterval = getTimeRange(rows[i].retryInterval);
                rows[i].input = typeof rows[i].input==='string'||rows[i].input==null?rows[i].input:JSON.stringify(rows[i].input);
                rows[i].depends = typeof rows[i].depends==='string'||rows[i].depends==null?rows[i].depends:JSON.stringify(rows[i].depends);
            }
        },
        loadComplete: function () {
            var val_time = jQuery(scheduleDivId).jqGrid('getCol', 'runTime', false, '');
            var time = 0.0,cnt = 0;
            for(var i = 0; i < val_time.length; i++){
                var temp = Number(val_time[i]);
                if(temp > 0){
                    time += temp;
                    cnt = cnt + 1;
                }
            }
            var avg = cnt > 0 ? time/cnt : 0;
            jQuery(scheduleDivId).footerData('set',{output: '平均実行時間(秒)', runTime: myRound(avg,3)});
        },
        onSelectRow:function(ids){
            if(ids == null) {
                ids=0;
            }
            selectedScheduleRow = jQuery(scheduleDivId).jqGrid('getRowData', ids);
            jQuery(dependsDivId).setGridParam({url:preURL + 'depends&id='+ids,datatype:'json', page:1}).trigger('reloadGrid');
            jQuery(dependedDivId).setGridParam({url:preURL + 'depended&id='+ids,datatype:'json', page:1}).trigger('reloadGrid');
        }
    }).navGrid(schedulePagerDivId, { edit: true,edittext:'変更', add: true, addtext:'新規', del: true, deltext:'削除', search: false, refresh: true, view:true ,
        beforeRefresh: function(){
            jQuery(scheduleDivId).jqGrid('setGridParam',{datatype:'json', page:1}).trigger('reloadGrid');
        }},
        // edit options
        {
            mtype: 'GET',
            beforeShowForm: function(frm) {
                chageEditableColForEdit(frm);
            },
            onclickSubmit: function(rp_ge, postdata) {
                onclickSubmitForEdit (postdata);
                rp_ge.url = preURL + 'changeExecutorKey&id=' + toNull(postdata[scheduleDivId.substring(1,scheduleDivId.length) + '_id']) + '&executorKey=' + toNull(postdata.executorKey);
            },
            serializeEditData: function (postdata) { return ''; },
            reloadAfterSubmit: true,
            closeOnEscape: true,
            closeAfterEdit: true,
            afterSubmit: function (response, postdata) {
                jQuery(scheduleDivId).jqGrid('setGridParam',{datatype:'json', page:1}).trigger('reloadGrid');
                $(".ui-icon-closethick").trigger('click');
            }
        },
        // add options
        {
            mtype: 'GET',
            beforeShowForm: function(frm) {
                chageEditableColForAdd(frm);
            },
            onclickSubmit: function(rp_ge, postdata) {
                if(scheduleDivId == '#scheduletable_tab1'){
                    rp_ge.url =  preURL + 'addFromMaster&masterId='+ toNull(encodeURI(masterId)) + '&groupId=' + toNull(encodeURI(postdata.groupId)) + '&input=' + toNull(encodeURI(postdata.input)) + '&date=' + toNull(postdata.date) + '&startTime=' + unformatTime(postdata.startTime) + '&endTime=' + unformatTime(postdata.endTime) + '&retryEndTime=' + unformatTime(postdata.retryEndTime) + '&executorKey=' + toNull(postdata.executorKey);
                }else{
                    rp_ge.url =  preURL + 'add&masterId='+ toNull(encodeURI(postdata.masterId)) + '&groupId=' + toNull(encodeURI(postdata.groupId)) + '&time=' + unformatTime(postdata.time) + '&taskName=' + toNull(postdata.taskName) + '&input=' + toNull(encodeURI(postdata.input))  + '&depends=' + toNull(encodeURI(postdata.depends))  + '&executorKey=' + toNull(postdata.executorKey) + '&executorType=' + toNull(postdata.executorType) + '&retryInterval=' + toNull(postdata.retryInterval) + '&retryEndTime=' + unformatTime(postdata.retryEndTime) + '&maxDelayTime=' + changeTimeRange(postdata.maxDelayTime);
                }
            },
            serializeEditData: function (postdata) { return ''; },
            reloadAfterSubmit: true,
            closeOnEscape: true,
            closeAfterAdd: true,
            afterSubmit: function (response, postdata) {
                jQuery(scheduleDivId).jqGrid('setGridParam',{datatype:'json', page:1}).trigger('reloadGrid');
                $(".ui-icon-closethick").trigger('click');
            }
        }   ,
        //del options
        {
            mtype: 'GET',
                onclickSubmit: function(rp_ge, postdata) {
                rp_ge.url = preURL + 'remove&id=' + postdata;
            },
            serializeDelData: function (postdata) { return ''; },
            reloadAfterSubmit: true,
            closeOnEscape: true
        }
    ).jqGrid('filterToolbar',{searchOperators: true,defaultSearch:'cn'}).jqGrid(setFrozenColumns);
}

function loadDependSchedule(tableId,pagerId,url,caption){
    jQuery(tableId).jqGrid({
        width: 545,
        hidegrid: false,
        height: 260,
        regional : 'ja',
        gridModel: true,
        url : url,
        loadonce: true,
        datatype: 'local',
        colNames: ['ID','マスターID','タスク名','ステータス', '予定時間','インプット','アウトプット','実行時間(秒)','開始時間','終了時刻','チェックステータス', 'コントロールステータス',  '実行キー', '実行タイプ', 'グループID',  '初期開始時間',  'グループマスターID', '最大遅延時間',  'リトライ', 'リトライ終了時間', 'リトライ間隔','失敗無視フラグ','依存先'],
        colModel: [
                {name:'id',index:'id',width:120,frozen:true,sortable:true,searchoptions:{searchOperators: true,sopt: ['lt ','le','gt','ge','eq','ne']}},
                {name:'masterId',index:'masterId',width:150,editable:true,frozen:true,sortable:true},
                {name:'taskName',index:'taskName',width:150,editable:true,editrules:{required:true},sortable:true},
                {name:'state',index:'state',width:100,align:'center',formatter:getStateName,editable:true, edittype:'select',editoptions:{value:stateSelectOption},stype: 'select', searchoptions:{ sopt:['eq'], value: stateSearchOption},sortable:true},
                {name:'time',index:'time',width:150,editable:true,sortable:true,searchoptions:{searchOperators: true,sopt: ['lt ','le','gt','ge','eq','ne']}},
                {name:'input',index:'input',width:150,editable:true,edittype:'textarea',sortable:true},
                {name:'output',index:'output',width:150,editable:true,edittype:'textarea',sortable:true},
                {name:'runTime',index:'runTime',width:100,sorttype:'float',sortable:true,align:'right',searchoptions:{searchOperators: true,sopt: ['lt ','le','gt','ge','eq','ne']}},
                {name:'executeStartTime',index:'executeStartTime',width:140,sortable:true,searchoptions:{searchOperators: true,sopt: ['lt ','le','gt','ge','eq','ne']}},
                {name:'executeEndTime',index:'executeEndTime',width:140,sortable:true,searchoptions:{searchOperators: true,sopt: ['lt ','le','gt','ge','eq','ne']}},
                {name:'checkState',index:'checkState',width:100,align:'center',formatter:getCheckStateName,stype: 'select', searchoptions:{ sopt:['eq'], value: checkStateSearchOption},sortable:true},
                {name:'controlState',index:'controlState',width:100,align:'center',formatter:getControlStateName,editable:true,edittype:'select',editoptions:{value:controlStateSelectOption},stype: 'select', searchoptions:{ sopt:['eq'], value: controlStateSearchOption},sortable:true},
                {name:'executorKey',index:'executorKey',width:100,editable:true,sortable:true},
                {name:'executorType',index:'executorType',width:100,align:'center',editable:true,sortable:true},
                {name:'groupId',index:'groupId',width:100,editable:true,sortable:true},
                {name:'initialTime',index:'initialTime',width:150,sortable:true,searchoptions:{searchOperators: true,sopt: ['lt ','le','gt','ge','eq','ne']}},
                {name:'masterGroupId',index:'masterGroupId',width:150,sortable:true},
                {name:'maxDelayTime',index:'maxDelayTime',width:100,editable:true,sorttype:'float',align:'right',sortable:true,searchoptions:{searchOperators: true,sopt: ['lt ','le','gt','ge','eq','ne']}},
                {name:'retry',index:'retry',width:100,sortable:true},
                {name:'retryEndTime',index:'retryEndTime',width:100,editable:true,sortable:true,searchoptions:{searchOperators: true,sopt: ['lt ','le','gt','ge','eq','ne']}},
                {name:'retryInterval',index:'retryInterval',width:100,editable:true,sorttype:'float',sortable:true,align:'right',searchoptions:{searchOperators: true,sopt: ['lt ','le','gt','ge','eq','ne']}},
                {name:'ignoreError',index:'ignoreError',width:60,sortable:true,formatter:getBooleanStr,stype: 'select', searchoptions:{ sopt:['eq'], value: booleanSearchOption}},
                {name:'depends',index:'depends',width:200,hidden:true,editable:true,edittype:'textarea'}
        ],
        rowNum: 10,
        rowList: [10, 20, 30],
        pager: pagerId,
        sortname: 'id',
        sortorder: 'asc',
        viewrecords: true,
        shrinkToFit: false,
        rownumbers: true,
        caption: caption,
        jsonReader : {
            root:'schedules',
            repeatitems:false
        },
        beforeProcessing: function (data) {
            var i, rows = data.schedules;
            for (i = 0; i < rows.length; i++) {
                rows[i].runTime = getRunTime(rows[i].executeStartTime,rows[i].executeEndTime);
                rows[i].executeStartTime = dateTimeFormat(rows[i].executeStartTime);
                rows[i].executeEndTime = dateTimeFormat(rows[i].executeEndTime);
                rows[i].time = dateTimeFormat(rows[i].time);
                rows[i].initialTime = dateTimeFormat(rows[i].initialTime);
                rows[i].retryEndTime = dateTimeFormat(rows[i].retryEndTime);
                rows[i].maxDelayTime = getTimeRange(rows[i].maxDelayTime);
                rows[i].retryInterval = getTimeRange(rows[i].retryInterval);
                rows[i].input = typeof rows[i].input==='string'||rows[i].input==null?rows[i].input:JSON.stringify(rows[i].input);
                rows[i].depends = typeof rows[i].depends==='string'||rows[i].depends==null?rows[i].depends:JSON.stringify(rows[i].depends);
                rows[i].ignoreError = getErrorIgnoreFlag(tableId,rows[i]);
            }
        },
        loadComplete: function () {
            var val_time = jQuery(this).jqGrid('getCol', 'runTime', false, '');
            var time = 0.0,cnt = 0;
            for(var i = 0; i < val_time.length; i++){
                var temp = Number(val_time[i]);
                if(temp > 0){
                    time += temp;
                    cnt = cnt + 1;
                }
            }
            var avg = cnt > 0 ? time/cnt : 0;
            jQuery(this).footerData('set',{output: '平均実行時間(秒)', runTime: myRound(avg,3)});
        },
        onSelectRow:function(id){
        }
    }).navGrid(pagerId, { edit: false, add: false, del: false, search: false, refresh: true, view:true }).jqGrid('filterToolbar',{searchOperators: true,defaultSearch:'cn'}).jqGrid(setFrozenColumns);
}

function getErrorIgnoreFlag(tableId,row){
   if(tableId.indexOf('dependstable') != -1){
       var depends = JSON.parse(selectedScheduleRow.depends);
       for(var i=0; depends!=null&&i< depends.length; i++){
           if(depends[i].masterId == row.masterId){
               return depends[i].ignoreError;
           }
       }
   }else if(tableId.indexOf('dependedtable') != -1)
       var depended = JSON.parse(row.depends);
       for(var i=0; depended!=null&&i< depended.length; i++){
           if(depended[i].masterId == selectedScheduleRow.masterId){
               return depended[i].ignoreError;
           }
       }
    return false;
}

function chageEditableColForAdd(form){
    if(scheduleDivId == '#scheduletable_tab1'){
        $('#tr_groupId', form).show();
        $('#tr_input', form).show();
        $('#tr_date', form).show();
        $('#tr_startTime', form).show();
        $('#tr_endTime', form).show();
        $('#tr_retryEndTime', form).show();
        $('#tr_executorKey', form).show();
        
        $('#tr_time', form).hide();
        $('#tr_maxDelayTime', form).hide();
        $('#tr_retryInterval', form).hide();
        $('#tr_taskName', form).hide();
        $('#tr_depends', form).hide();
        $('#tr_executorType', form).hide();
        $('#tr_masterId', form).hide();
    }else{
        $('#tr_groupId', form).show();
        $('#tr_executorType', form).show();
        $('#tr_input', form).show();
        $('#tr_masterId', form).show();
        $('#tr_maxDelayTime', form).show();
        $('#tr_retryEndTime', form).show();
        $('#tr_retryInterval', form).show();
        $('#tr_taskName', form).show();
        $('#tr_depends', form).show();
        $('#tr_executorKey', form).show();
        $('#tr_time', form).show();
        
        $('#tr_date', form).hide();
        $('#tr_startTime', form).hide();
        $('#tr_endTime', form).hide();
    }

    $('#tr_state', form).hide();
    $('#tr_output', form).hide();
    $('#tr_controlState', form).hide();
}

function chageEditableColForEdit(form){
    $('#tr_input', form).hide();
    $('#tr_executorType', form).hide();
    $('#tr_groupId', form).hide();
    $('#tr_masterId', form).hide();
    $('#tr_retryInterval', form).hide();
    $('#tr_taskName', form).hide();
    $('#tr_depends', form).hide();

    $('#tr_maxDelayTime', form).show();
    $('#tr_retryEndTime', form).show();
    $('#tr_executorKey', form).show();
    $('#tr_state', form).show();
    $('#tr_time', form).show();
    $('#tr_output', form).show();
    $('#tr_controlState', form).show();
}

function onclickSubmitForEdit (postdata) {
    var selectedId = jQuery(scheduleDivId).jqGrid('getGridParam', 'selrow');
    var rowData = jQuery(scheduleDivId).jqGrid('getRowData', selectedId);
    var before = getStateCode(rowData.state);
    if(postdata.state != '0' && before != postdata.state){
        var output = rowData.output == postdata.output || postdata.output.length > 500 ? '' : '&output=' + toNull(postdata.output);
        $.ajax({
          type: 'GET',
          async: false,
          url: preURL + 'changeState&id=' + rowData.id + '&oldState=' + before + '&newState=' + postdata.state + output ,
          success: function(data, status, xhr){
          },
          error: function(xhr, status, err) {
            alert(status + ': ' + err);
          }
        });
    }
    var beforeControl = getControlStateCode(rowData.controlState);
    if(postdata.controlState != '0' && beforeControl != postdata.controlState){
        $.ajax({
          type: 'GET',
          async: false,
          url: preURL + 'changeControlState&id=' + rowData.id + '&oldState=' + beforeControl + '&newState=' + postdata.controlState ,
          success: function(data, status, xhr){
          },
          error: function(xhr, status, err) {
            alert(status + ': ' + err);
          }
        });
    }
    if(rowData.time != postdata.time){
        var output = rowData.output == postdata.output || postdata.output.length > 500 ? '' : '&output=' + toNull(encodeURI(postdata.output));
        $.ajax({
          type: 'GET',
          async: false,
          url: preURL + 'reschedule&id=' + rowData.id + '&time=' + unformatDateTime(rowData.time) + output,
          success: function(data, status, xhr){
          },
          error: function(xhr, status, err) {
            alert(status + ': ' + err);
          }
        });
    }
    if(rowData.retryEndTime != postdata.retryEndTime){
        $.ajax({
          type: 'GET',
          async: false,
          url: preURL + 'changeRetryEndTime&id=' + rowData.id + '&retryEndTime=' + unformatDateTime(rowData.retryEndTime),
          success: function(data, status, xhr){
          },
          error: function(xhr, status, err) {
            alert('Server does not support this action (changeRetryEndTime).' + status + ': ' + err);
          }
        });
    }
    if(rowData.maxDelayTime != postdata.maxDelayTime){
        $.ajax({
          type: 'GET',
          async: false,
          url: preURL + 'changeMaxDelayTime&id=' + rowData.id + '&maxDelayTime=' + changeTimeRange(rowData.maxDelayTime),
          success: function(data, status, xhr){
          },
          error: function(xhr, status, err) {
            alert('Server does not support this action (changeMaxDelayTime). ' + status + ': ' + err);
          }
        });
    }
}

function loadCreatingTab3(){
    var from= moment();
    var to = moment().add(6, 'days');
    var id = '#reportrange_tab3';
    initDateRange(from,to,id);
    $(id).on('apply.daterangepicker', function (ev, picker) {
        loadCreating(picker.startDate,picker.endDate);
    });
    loadCreating(from,to);
}

function initDateRange(from, to, id) {
    var cb = function (start, end, label) {
        $(id + ' span').html(start.format('YYYY/MM/DD') + ' - ' + end.format('YYYY/MM/DD'));
    };

    var optionSet = {
        startDate: from,
        endDate: to,
        minDate: '1970/01/01',
        maxDate: '2999/12/31',
        dateLimit: {days: 62},
        showDropdowns: true,
        showWeekNumbers: true,
        timePicker: false,
        timePickerIncrement: 1,
        timePicker12Hour: true,
        ranges: {
            '今日': [moment(), moment()],
            '明日': [moment().add(1, 'days'), moment().add(1, 'days')],
            '昨日': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
            '今週': [moment().startOf('week'), moment().endOf('week')],
            '過去７日': [moment().subtract(6, 'days'), moment()],
            '直近７日': [moment(), moment().add(6, 'days')],
            '今月': [moment().startOf('month'), moment().endOf('month')]
        },
        opens: 'right',
        buttonClasses: ['btn btn-default'],
        applyClass: 'btn-sm btn-primary',
        cancelClass: 'btn-sm',
        format: 'YYYY/MM/DD',
        separator: ' ～ ',
        locale: {
            applyLabel: '確定',
            cancelLabel: 'キャンセル',
            fromLabel: '開始日',
            toLabel: '終了日',
            customRangeLabel: 'カレンダー',
            daysOfWeek: ['日', '月', '火', '水', '木', '金', '土'],
            monthNames: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月'],
            firstDay: 1
        }
    };
    $(id + ' span').html(moment().format('YYYY/MM/DD') + ' - ' + moment().format('YYYY/MM/DD'));
    $(id).daterangepicker(optionSet, cb);
    return true;
}

function loadCreating(from, to){
    var url = preURL + 'isMakeSchedule&from=' + from.format('YYYYMMDD') + '&to=' + to.format('YYYYMMDD');
    var mname = ['ID'];
    var weekname = ['日','月','火','水','木','金','土'];
    var mmod = [{name: 'id', index: 'id', width: 250, frozen:true,jsonmap:'masterId',sortable:true}];
     for(var i = 0; i <= 30; i++){
        var dateStr = from.format('YYYYMMDD');
        mname.push(from.format('YYYY/MM/DD') + '(' +weekname[from.day()] + ')');
        mmod.push({name:dateStr, index:dateStr,width:120,align:'center',formatter:getBooleanStr,stype: 'select', searchoptions:{ sopt:['eq'], value: booleanSearchOption},jsonmap:'result.'+ i +'.isMake',sortable:true});
        if(to.diff(from,'day') <= 0){
            break;
        }
        from.add(1, 'days');
     }

      jQuery('#mastertable_tab3').GridUnload().trigger('reloadGrid');
      jQuery('#mastertable_tab3').jqGrid({
            width: 1095,
            hidegrid: false,
            height: 550,
            url:url,
            datatype: 'json',
            rowNum: '30',
            rowList: [30, 50, 100],
            colNames: mname,
            colModel: mmod,
            regional : 'ja',
            shrinkToFit: false,
            pager: '#masterpager_tab3',
            viewrecords: true,
            caption: 'ジョブ登録確認',
            jsonReader : {
                root:'result',
                repeatitems:false
            },
            loadonce: true
        }).navGrid('#masterpager_tab3', { edit: false, add: false, del: false, search: false, refresh: true, view:true }).jqGrid('filterToolbar').jqGrid(setFrozenColumns);
}

function updateState(){
    var selected = $('#state').val();
    var ids = jQuery(scheduleDivId).jqGrid('getGridParam','selarrrow');
    var beforeState =[];
    var afterState =[];
    if(isBlank(ids)){
        alert('変更対象を選択してください。')
    }else{
        if(window.confirm('ステータスを一括変更しますか。')){
            for (var i= 0; i<ids.length; i++) {
                var rowData = jQuery(scheduleDivId).jqGrid('getRowData', ids[i]);
                beforeState.push(getStateCode(rowData.state));
                afterState.push(selected);
            }
            var url = preURL + 'changeState&id=' + ids + '&oldState=' + beforeState + '&newState=' + afterState;
            $.ajax({
            type: 'GET',
            url: url,
            async: false,
            dataType: 'json',
            success: function (response) {
                jQuery(scheduleDivId).setGridParam({url:preURL + 'schedule&from='+fromStr +'&to=' + toStr,datatype:'json', page:1}).trigger('reloadGrid');
              },
              error: function(xhr, status, err) {
                alert(status + ': ' + err);
              }
           })
        }
    }
}

function myRound(val, precision)
{
     digit = Math.pow(10, precision);
     val = val * digit;
     val = Math.round(val);
     val = val / digit;
     return val;
}

function loadChartTab4(){
    $.ajax({
      type: 'GET',
      async: false,
      url: preURL + 'scheduleMaster',
      success: function(data, status, xhr){
          if(data != undefined && data != null){
              loadChart(data.scheduleMasters);
          }
      },
      error: function(xhr, status, err) {
        alert(status + ': ' + err);
      }
    });
    return true;
}

function loadChart(rows){
    var mname = ['ID'];
    var mmod = [{name: 'id', index: 'id', width: 250, frozen:true,sortable:true}];
     for(var i = 0; i <= 23; i++){
        var dateStr = ('0' + i).slice(-2);
        var hour = dateStr + ':00~';
        var half = dateStr + ':30~';
        mname.push(hour);
        mmod.push({name:hour, index:hour,width:40,align:'center',editable:true,sortable:true,stype: 'select', searchoptions:{ sopt:['cn'], value: timeSearchOption}});
        mname.push(half);
        mmod.push({name:half, index:half,width:40,align:'center',editable:true,sortable:true,stype: 'select', searchoptions:{ sopt:['cn'], value: timeSearchOption}});
     }

    var data = [];
    for (i = 0; i < rows.length; i++) {
        var item = [];
        item['id'] = rows[i].id;
        var start = getHourSource(rows[i].startTime) + ':' +  getMinuteSource(rows[i].startTime);
        var end = '';
        if(!isBlank(rows[i].endTime)){
            end = getHourSource(rows[i].endTime) + ':' +  getMinuteSource(rows[i].endTime);
        }else if(!isBlank(rows[i].retryEndTime)){
            end = getHourSource(rows[i].retryEndTime) + ':' +  getMinuteSource(rows[i].retryEndTime);
        }
        for(var j = 0; j <= 23; j++){
            var dateStr = ('0' + j).slice(-2);
            var hourStr = dateStr + ':00~';
            var halfStr = dateStr + ':30~';
            item[hourStr] = "<span class='none'>" + ' ' + "</span>" ;
            item[halfStr] = "<span class='none'>" + ' '+ "</span>";
            if(isBlank(rows[i].startTime) && isBlank(rows[i].endTime)){
                if(!isBlank(rows[i].retryInterval) &&  rows[i].retryInterval > 0){
                    item[hourStr] = "<span class='retry'>" + ' ' + "</span>" ;
                    item[halfStr] = "<span class='retry'>" + ' '+ "</span>";
                }else if(!isBlank(rows[i].repeatInterval) &&  rows[i].repeatInterval > 0){
                    item[hourStr] = "<span class='repeat'>" + ' ' + "</span>" ;
                    item[halfStr] = "<span class='repeat'>" + ' '+ "</span>";
                } 
            }
            if(dateStr >= getHourSource(rows[i].startTime)){
                if(dateStr == getHourSource(rows[i].startTime) && isBlank(rows[i].endTime) && isBlank(rows[i].retryEndTime)){
                    item[hourStr] = "<span class='start'>" + start + "</span>" ;
                }else if(dateStr <= getHourSource(rows[i].endTime)){
                    if(dateStr == getHourSource(rows[i].startTime) && dateStr < getHourSource(rows[i].endTime)){
                        item[hourStr] = "<span class='repeat'>" + start + "</span>" ;
                        item[halfStr] = "<span class='repeat'>" + ' '+ "</span>";
                    }else if(dateStr < getHourSource(rows[i].endTime)){
                        item[hourStr] = "<span class='repeat'>" + ' '+ "</span>";
                        if(('0' + (j +1)).slice(-2) == getHourSource(rows[i].endTime ) && getMinuteSource(rows[i].endTime) == '00'){
                            item[halfStr] = "<span class='repeat'>" + end + "</span>";
                        }else{
                            item[halfStr] = "<span class='repeat'>" + ' '+ "</span>";
                        }
                    }else{
                        if(getMinuteSource(rows[i].endTime) > '30' ){
                            item[hourStr] = "<span class='repeat'>" + ' '+ "</span>";
                            item[halfStr] = "<span class='repeat'>" + end + "</span>";
                        }else if(getMinuteSource(rows[i].endTime) > '00'){
                            item[hourStr] = "<span class='repeat'>" + end + "</span>";
                        }
                    }
                }else if(dateStr <= getHourSource(rows[i].retryEndTime)){
                    if(dateStr == getHourSource(rows[i].startTime) && dateStr < getHourSource(rows[i].retryEndTime)){
                        item[hourStr] = "<span class='retry'>" + start + "</span>" ;
                        item[halfStr] = "<span class='retry'>" + ' '+ "</span>";
                    }else if(dateStr < getHourSource(rows[i].retryEndTime)){
                        item[hourStr] = "<span class='retry'>" + ' ' + "</span>";
                        if(('0' + (j +1)).slice(-2) == getHourSource(rows[i].retryEndTime) && getMinuteSource(rows[i].retryEndTime) == '00' ){
                            item[halfStr] = "<span class='retry'>" + end + "</span>";
                        }else{
                            item[halfStr] = "<span class='retry'>" + ' '+ "</span>";
                        }
                    }else{
                        if(getMinuteSource(rows[i].retryEndTime) > '30'){
                            item[hourStr] = "<span class='retry'>" + "</span>";
                            item[halfStr] = "<span class='retry'>" + end + "</span>";
                        }else if(getMinuteSource(rows[i].retryEndTime) > '00'){
                            item[hourStr] = "<span class='retry'>" + end + "</span>";
                        }
                    }
                }
            }
        }
        data.push(item);
    }

    jQuery('#mastertable_tab4').jqGrid({
        width: 1095,
        hidegrid: false,
        height: 580,
        data:data,
        datatype: 'local',
        rowNum: '100',
        rowList: [100, 200, 500],
        colNames: mname,
        colModel: mmod,
        regional : 'ja',
        shrinkToFit: false,
        rownumbers: true,
        pager: '#masterpager_tab4',
        viewrecords: true,
        caption: 'ジョブ実行時間確認',
        shrinkToFit: false,
        loadonce: true
    }).navGrid('#masterpager_tab4', { edit: false, add: false, del: false, search: false, refresh: true, view:false }).jqGrid('filterToolbar').jqGrid(setFrozenColumns);
}
