/* global GetData, Functions, $, DIRECT_LEVEL, SetData, document, sessionStorage, navigator, window, spotfire, handleAlerts, DivisorFieldCell, TextFieldCell, SwitchFieldCell, DateFieldCell, DropdownFieldCell, BootstrapFunctions, mUtil, DateFunctions, arrows, mApp, getCurrentMonth, createtasks, updateVisible, filterdata, console, DUrl */
/* eslint-disable no-unused-vars, no-redeclare, no-console*/

var MENU = "";
var LEVEL1 = [];
var LEVEL2 = [];
var LEVEL3 = [];
var LEVEL4 = [];
var ID;
var RET;
var LEGEND = "";
var QUESTIONS;
var PAGETITLE = "";
var REFRESHPAGE = false;
var FIELDS = {};
var TODAY = new Date();
var START = '';
var END = '';

GetData.SingleSqlValue("*", "OS_Question", "1 = 1", true, true, function (ret) {
    QUESTIONS = ret;
});

function buildMenu() {
    LEVEL1 = [];
    LEVEL2 = [];
    LEVEL3 = [];
    LEVEL4 = [];
    MENU = "";
    var i;

    GetData.SingleSqlValue("id_Catalog, Name", "OS_Catalog", "Category = 35 AND CatActive = 1", true, true, function (ret) {
        for (i = 0; i < ret.length; i++) {
            var PUSH = {
                "ID": ret[i].id_Catalog,
                "BelongTo": ret[i].Name.split("|")[0],
                "Title": Functions.LanguageSelect(ret[i].Name.split("|")[2], ret[i].Name.split("|")[1]),
                "Icon": ret[i].Name.split("|")[3],
                "SubMenu": ret[i].Name.split("|")[5],
                "OrderNumber": ret[i].Name.split("|")[6]
            };

            switch (ret[i].Name.split("|")[4]) {
                case "1":
                    if (PUSH.BelongTo == GetData.localStorage("Current_Page")) {
                        PUSH["Level"] = "Level1";
                        LEVEL1.push(PUSH);
                    }
                    break;
                case "2":
                    PUSH["Level"] = "Level2";
                    LEVEL2.push(PUSH);
                    break;
                case "3":
                    PUSH["Level"] = "Level3";
                    LEVEL3.push(PUSH);
                    break;
                case "4":
                    PUSH["Level"] = "Level4";
                    LEVEL4.push(PUSH);
                    break;
                default:
                    break;
            }
        }
        Functions.sortArray(LEVEL1, "OrderNumber", true);
        Functions.sortArray(LEVEL2, "OrderNumber", true);
        Functions.sortArray(LEVEL3, "OrderNumber", true);
        Functions.sortArray(LEVEL4, "OrderNumber", true);
        for (var l1 = 0; l1 < LEVEL1.length; l1++) {
            if (GetData.localStorage("Current_Page") == LEVEL1[l1].BelongTo) {
                MENU +=
                    '<li id="MENU_' + LEVEL1[l1].ID + '" class="m-menu__item m-menu__item--submenu m-menu__item--tabs ' + ((LEVEL1[l1].ID == DIRECT_LEVEL[1] || (DIRECT_LEVEL[0] == 0 && l1 == 0)) ? ' m-menu__item--active  m-menu__item--active-tab ' : '') + '" m-menu-submenu-toggle="tab" aria-haspopup="true"><a href="javascript:;" ' + (LEVEL1[l1].SubMenu == '0' ? 'onClick="PAGETITLE = \'' + LEVEL1[l1].Title + '\';ID = ' + LEVEL1[l1].ID + ';menuClick(1);"' : '') + ' class="m-menu__link m-menu__toggle" title=""><span class="m-menu__link-text" id="LINK_' + LEVEL1[l1].ID + '">' + LEVEL1[l1].Title + '</span><i' +
                    'class="m-menu__hor-arrow la la-angle-down"></i><i class="m-menu__ver-arrow la la-angle-right"></i></a>' +
                    '<div class="m-menu__submenu m-menu__submenu--classic m-menu__submenu--left m-menu__submenu--tabs"><span class="m-menu__arrow m-menu__arrow--adjust"></span>' +
                    '<ul class="m-menu__subnav">';
                for (var l2 = 0; l2 < LEVEL2.length; l2++) {
                    if (LEVEL1[l1].ID == LEVEL2[l2].BelongTo) {
                        var HASMENU2 = (Functions.indexOfObject(LEVEL3, "BelongTo", LEVEL2[l2].ID) != -1 ? true : false);
                        MENU += '<li id="MENU_' + LEVEL2[l2].ID + '" class="m-menu__item ' + (HASMENU2 ? 'm-menu__item--submenu m-menu__item--submenu-tabs" m-menu-submenu-toggle="click"' : ' m-menu-link-redirect="1"') + ' aria-haspopup="true"><a href="javascript:;" ' + (LEVEL2[l2].SubMenu == '0' ? 'onClick="PAGETITLE = \'' + LEVEL2[l2].Title + '\';ID = ' + LEVEL2[l2].ID + ';menuClick(2);"' : '') + ' class="m-menu__link "><i class="m-menu__link-icon flaticon-' + LEVEL2[l2].Icon + '"></i><span class="m-menu__link-text' + (HASMENU2 ? ' m-menu__toggle' : '') + '" id="LINK_' + LEVEL2[l2].ID + '">' + LEVEL2[l2].Title + '</span>' + (HASMENU2 ? '<i class="m-menu__hor-arrow la la-angle-down"></i><i class="m-menu__ver-arrow la la-angle-right"></i>' : '') + '</a>';
                        if (HASMENU2) {
                            MENU += '<div class="m-menu__submenu m-menu__submenu--classic m-menu__submenu--left"><span class="m-menu__arrow m-menu__arrow--adjust"></span>' +
                                '<ul class="m-menu__subnav">';
                        }
                        for (var l3 = 0; l3 < LEVEL3.length; l3++) {
                            if (LEVEL2[l2].ID == LEVEL3[l3].BelongTo) {
                                var HASMENU3 = (Functions.indexOfObject(LEVEL4, "BelongTo", LEVEL3[l3].ID) != -1 ? true : false);
                                MENU +=
                                    '<li id="MENU_' + LEVEL3[l3].ID + '" class="m-menu__item ' + (HASMENU3 ? 'm-menu__item--submenu " m-menu-submenu-toggle="hover"' : '') + ' m-menu-link-redirect="1" aria-haspopup="true"><a href="javascript:;" ' + (LEVEL3[l3].SubMenu == '0' ? 'onClick="PAGETITLE = \'' + LEVEL3[l3].Title + '\';ID = ' + LEVEL3[l3].ID + ';menuClick(3);"' : '') + ' class="m-menu__link ' + (HASMENU3 ? ' m-menu__toggle' : '') + '"><i class="m-menu__link-icon flaticon-' + LEVEL3[l3].Icon + '"></i><span class="m-menu__link-' + (HASMENU3 ? 'title"> <span class="m-menu__link-wrap"> <span class="m-menu__link-text' : 'text') + '" id="LINK_' + LEVEL3[l3].ID + '">' + LEVEL3[l3].Title + '</span>' + (HASMENU3 ? '<i class="m-menu__hor-arrow la la-angle-right"></i><i class="m-menu__ver-arrow la la-angle-right"></i></span></span>' : '') +
                                    //                                        '<span class="m-menu__link-badge"><span class="m-badge m-badge--success">2</span></span>' + 
                                    '</a>';
                                if (HASMENU3) {
                                    MENU += '<div class="m-menu__submenu m-menu__submenu--classic m-menu__submenu--right"><span class="m-menu__arrow "></span>' +
                                        '<ul class="m-menu__subnav">';
                                }
                                for (var l4 = 0; l4 < LEVEL4.length; l4++) {
                                    if (LEVEL3[l3].ID == LEVEL4[l4].BelongTo) {
                                        MENU +=
                                            '<li id="MENU_' + LEVEL4[l4].ID + '" class="m-menu__item " m-menu-link-redirect="1" aria-haspopup="true"><a href="javascript:;" ' + (LEVEL4[l4].SubMenu == '0' ? 'onClick="PAGETITLE = \'' + LEVEL4[l4].Title + '\';ID = ' + LEVEL4[l4].ID + ';menuClick(4);"' : '') + ' class="m-menu__link "><span class="m-menu__link-text" id="LINK_' + LEVEL4[l4].ID + '">' + LEVEL4[l4].Title + '</span></a></li>';
                                    }
                                }
                                if (HASMENU3) {
                                    MENU += '</ul></div>';
                                }
                                '</li>';
                            }
                        }
                        if (HASMENU2) {
                            MENU += '</ul></div>';
                        }
                        MENU += '</li>';
                    }
                }
                MENU += '</ul></div></li>';
            }
        }
        $('.m-menu__nav--submenu-arrow').html(MENU);

        if (GetData.UrlParameter("page") == undefined) {
            var START_MENU_1 = LEVEL1;
            var START_MENU_2 = Functions.filterArray(LEVEL2, {BelongTo: function (value) {return value == START_MENU_1[0].ID;}});
            var START_MENU_3 = (START_MENU_2.length > 0 ? Functions.filterArray(LEVEL3, {BelongTo: function (value) {return value == START_MENU_2[0].ID;}}) : []);
            var START_MENU_4 = (START_MENU_3.length > 0 ? Functions.filterArray(LEVEL4, {BelongTo: function (value) {return value == START_MENU_3[0].ID;}}) : []);

            if (START_MENU_4.length > 0) {
                PAGETITLE = START_MENU_4[0].Title;
                ID = START_MENU_4[0].ID;
                menuClick(4);
            } else if (START_MENU_3.length > 0) {
                PAGETITLE = START_MENU_3[0].Title;
                ID = START_MENU_3[0].ID;
                menuClick(3);
            } else if (START_MENU_2.length > 0) {
                PAGETITLE = START_MENU_2[0].Title;
                ID = START_MENU_2[0].ID;
                menuClick(2);
            } else if (START_MENU_1.length > 0) {
                PAGETITLE = START_MENU_1[0].Title;
                ID = START_MENU_1[0].ID;
                menuClick(1);
            }
        } else {
            for (i = 0; i < DIRECT_LEVEL.length; i++) {
                if (DIRECT_LEVEL[i] == 0) {
                    PAGETITLE = $("#LINK_" + DIRECT_LEVEL[i-1]).html();
                    ID = DIRECT_LEVEL[i-1];
                    menuClick(i - 1);
                    SetData.UrlParameter("page","{DELETE}");
                    break;
                }
            }
        }
    });

    GetData.SingleSqlValue('Name', 'OS_Catalog', 'id_Catalog = ' + GetData.localStorage("Current_Page"), true, true, function (ret) {
        document.title = 'Osiris - ' + Functions.LanguageSelect(ret[0].Name.split("|")[1], ret[0].Name.split("|")[0])
    });

}

function menuClick(LEVEL) {
    $('.m-subheader__breadcrumbs').html('<li class="m-nav__item m-nav__item--home"> <a href="#" class="m-nav__link m-nav__link--icon"> <i class="m-nav__link-icon la la-home"></i> </a> </li>');
    var MENULEVEL4 = (LEVEL >= 4 ? LEVEL4[Functions.indexOfObject(LEVEL4, "ID", ID)] : []);
    var MENULEVEL3 = (LEVEL >= 3 ? LEVEL3[Functions.indexOfObject(LEVEL3, "ID", (LEVEL == 3 ? ID : MENULEVEL4.BelongTo))] : []);
    var MENULEVEL2 = (LEVEL >= 2 ? LEVEL2[Functions.indexOfObject(LEVEL2, "ID", (LEVEL == 2 ? ID : MENULEVEL3.BelongTo))] : []);
    var MENULEVEL1 = (LEVEL >= 1 ? LEVEL1[Functions.indexOfObject(LEVEL1, "ID", (LEVEL == 1 ? ID : MENULEVEL2.BelongTo))] : []);
    $('.m-subheader__title').html(MENULEVEL1.Title);
    $('.m-menu__item--active').removeClass('m-menu__item--active');
    $('#MENU_' + MENULEVEL1.ID).addClass('m-menu__item--active');
    $('#MENU_' + MENULEVEL2.ID).addClass('m-menu__item--active');
    $('#MENU_' + MENULEVEL3.ID).addClass('m-menu__item--active');
    $('#MENU_' + MENULEVEL4.ID).addClass('m-menu__item--active');
    if (LEVEL >= 2) {
        $('.m-subheader__breadcrumbs').append('<li class="m-nav__separator">-</li>');
        $('.m-subheader__breadcrumbs').append('<li class="m-nav__item"> <a href="javascript:;" class="m-nav__link"> <span class="m-nav__link-text">' + MENULEVEL2.Title + '</span> </a> </li>');
    }
    if (LEVEL >= 3) {
        $('.m-subheader__breadcrumbs').append('<li class="m-nav__separator">-</li>');
        $('.m-subheader__breadcrumbs').append('<li class="m-nav__item"> <a href="javascript:;" class="m-nav__link"> <span class="m-nav__link-text">' + MENULEVEL3.Title + '</span> </a> </li>');
    }
    if (LEVEL >= 4) {
        $('.m-subheader__breadcrumbs').append('<li class="m-nav__separator">-</li>');
        $('.m-subheader__breadcrumbs').append('<li class="m-nav__item"> <a href="javascript:;" class="m-nav__link"> <span class="m-nav__link-text">' + MENULEVEL4.Title + '</span> </a> </li>');
    }
    //    $('.m-content .row').html('');
    showPage();
}

function showPage() {
    $('.inRow').hide();
    GetData.SingleSqlValue("Name", "OS_Catalog", "(Category = 36) AND (CatActive = 1) AND (SUBSTRING(Name, 0, CHARINDEX('|', Name)) = '" + ID + "')", true, true, function (ret) {
        if (ret != undefined && ret.length > 0) {
            RET = ret;
            viewSpotfire();
        }
    });
    GetData.SingleSqlValue("Name", "OS_Catalog", "(Category = 37) AND (CatActive = 1) AND (SUBSTRING(Name, 0, CHARINDEX('|', Name)) = '" + ID + "')", true, true, function (ret) {
        if (ret != undefined && ret.length > 0) {
            RET = ret;
            viewReport();
        }
    });
    GetData.SingleSqlValue("Name", "OS_Catalog", "(Category = 39) AND (CatActive = 1) AND (SUBSTRING(Name, 0, CHARINDEX('|', Name)) = '" + ID + "')", true, true, function (ret) {
        if (ret != undefined && ret.length > 0) {
            RET = ret;
            viewForm();
        }
    });
    GetData.SingleSqlValue("Name", "OS_Catalog", "(Category = 40) AND (CatActive = 1) AND (SUBSTRING(Name, 0, CHARINDEX('|', Name)) = '" + ID + "')", true, true, function (ret) {
        if (ret != undefined && ret.length > 0) {
            RET = ret;
            viewCalendar();
        }
    });
    GetData.SingleSqlValue("Name", "OS_Catalog", "(Category = 41) AND (CatActive = 1) AND (SUBSTRING(Name, 0, CHARINDEX('|', Name)) = '" + ID + "')", true, true, function (ret) {
        if (ret != undefined && ret.length > 0) {
            RET = ret;
            eshCalendar();
        }
    });
}

function viewSpotfire() {
    //handleAlerts.ShowLoading('Validating User in Spotfire...Please Wait. (' + timerOpen + ')');
    //newWindow = window.open("http://spotfire-app.monsanto.com/spotfire/wp/", "connectWindow", "top=100000,left=100000,menubar=0,width=1,height=1,status=0,titlebar=0");
    if (sessionStorage.getItem("spotfireSession") == undefined || sessionStorage.getItem("spotfireSession") == null || new Date(sessionStorage.getItem("spotfireSession")) < new Date()) {
        if (navigator.platform.toUpperCase().indexOf('WIN') >= 0 || (sessionStorage.getItem("spotfireNotWindowsSession") != undefined && sessionStorage.getItem("spotfireNotWindowsSession") != null && new Date(sessionStorage.getItem("spotfireNotWindowsSession")) > new Date())) {
            var d = new Date();
            d.setMinutes(d.getMinutes() + 5);
            sessionStorage.setItem("spotfireSession", d);

            if (navigator.platform.toUpperCase().indexOf('WIN') == -1) {
                var d = new Date();
                d.setMinutes(d.getMinutes() + 60);
                sessionStorage.setItem("spotfireNotWindowsSession", d);
            }

            $('#spotfireIframe').attr('src', "http://spotfire-app.monsanto.com/spotfire/wp/");
            Functions.onTimer(5, 'Validating User in Spotfire...Please Wait.', function () {
                showDashboardPortlet(ID);
            }, $('.m-grid__item.m-grid__item--fluid.m-wrapper'));
        } else {
            if ($('.Spotfire').length > 0) {
                $('.Spotfire').remove();
            }
            $('.m-content').append('<div id="OPage_' + ID + '_Spotfire" class="inRow Spotfire" style="width: 100%; text-align: center;"><button type="button" onclick="handleAlerts.OkCancel(\'Once you login into Spotfire please close the tab and return to the Osiris Tab.\',function(){openSpotfirePage(' + ID + ')})" class="btn m-btn--pill btn-danger">Login to Spotfire</button></div>');
        }
    } else {
        var d = new Date();
        d.setMinutes(d.getMinutes() + 5);
        sessionStorage.setItem("spotfireSession", d);

        if (navigator.platform.toUpperCase().indexOf('WIN') == -1) {
            var d = new Date();
            d.setMinutes(d.getMinutes() + 60);
            sessionStorage.setItem("spotfireNotWindowsSession", d);
        }

        showDashboardPortlet(ID);
    }
}

function openSpotfirePage(IDs) {
    var d = new Date();
    d.setMinutes(d.getMinutes() + 5);
    sessionStorage.setItem("spotfireSession", d);

    var d = new Date();
    d.setMinutes(d.getMinutes() + 60);
    sessionStorage.setItem("spotfireNotWindowsSession", d);
    window.open('http://spotfire-app.monsanto.com/spotfire/wp/', '_blank');
    $('#OPage_' + IDs + '_Spotfire').html('<div id="OPage_' + IDs + '_Spotfire" class="inRow Spotfire" style="width: 100%; text-align: center;"><button type="button" onclick="showDashboardPortlet(' + IDs + ');" name="openSpotfire" class="btn m-btn--pill btn-success">Open Spotfire</button></div>');
}

function showDashboardPortlet(IDs) {
    if ($('.Spotfire').length > 0) {
        $('.Spotfire').remove();
    }

    if ($('#OPage_' + IDs).length > 0 && REFRESHPAGE == false) {
        $('#OPage_' + IDs).show();
    } else {
        if (REFRESHPAGE) {
            $('#OPage_' + IDs).remove();
            REFRESHPAGE = false;
        }
        $('.m-content').append('<div id="OPage_' + IDs + '" class="inRow row"></div>');
        for (var i = 0; i < RET.length; i++) {
            if (IDs == RET[i].Name.split('|')[0]) {
                $('#OPage_' + IDs).append(
                    '<div class="col-xl-' + RET[i].Name.split("|")[3] + '">' +
                    '<!--begin:: Widgets/Top Products-->' +
                    '<div class="m-portlet m-portlet--bordered-semi m-portlet--full-height ">' +
                    '<div class="m-portlet__head">' +
                    '<div class="m-portlet__head-caption">' +
                    '<div class="m-portlet__head-title">' +
                    '<h3 class="m-portlet__head-text">' +
                    Functions.LanguageSelect(RET[i].Name.split("|")[2], RET[i].Name.split("|")[1]) +
                    '</h3>' +
                    '</div>' +
                    '</div>' +
                    '<div class="m-portlet__head-tools"><ul class="m-portlet__nav"><li class="m-portlet__nav-item"><a href="javascript:void(0)" class="m-portlet__nav-link m-portlet__nav-link--icon" onclick="openSpotfire(\'Portlet' + i + '-' + IDs + '\',\'' + RET[i].Name.split('|')[4].split('$')[0] + '\',\'' + RET[i].Name.split('|')[4].split('$')[1] + '\')"><i class="la la-refresh"></i></a></li></ul></div>' +
                    '</div>' +
                    '<div class="m-portlet__body">' +
                    '<div id="Portlet' + i + '-' + IDs + '">' +
                    '</div>' +
                    '</div>' +
                    '</div>' +
                    '</div>');
                openSpotfire('Portlet' + i + '-' + IDs, RET[i].Name.split("|")[4].split('$')[0], RET[i].Name.split("|")[4].split('$')[1]);
            }
        }
    }
}

function openSpotfire(PORTLET, PATH, PAGE) {
    //    newWindow.close();
    var c_serverUrl = "http://spotfire-app.monsanto.com/spotfire/wp/";
    var c_analysisPath = PATH;

    //var c_serverUrl = "https://spotfire.cloud.tibco.com/spotfire/wp/";
    //var c_analysisPath = "/users/MattMurdock/Public/Mashup";

    var c_parameters = ""; //Optional configuration block
    var customization = new spotfire.webPlayer.Customization(); //Optional configuration settings

    var app;

    var c_reloadAnalysisInstance = false;

    app = new spotfire.webPlayer.Application(c_serverUrl, customization, c_analysisPath, c_parameters, c_reloadAnalysisInstance);

    //Hide UI elements
    customization.showDodPanel = true;
    customization.showStatusBar = true;
    customization.showToolBar = true;
    customization.showPageNavigation = true;
    customization.showClose = true;
    customization.showAnalysisInfo = true;
    customization.showExportFile = true;
    customization.showExportVisualization = true;
    customization.showUndoRedo = true;
    customization.showFilterPanel = true;

    //var viewOne = app.openDocument("iframeReport", "IndividualExp", customization);
    var viewOne = app.openDocument(PORTLET, PAGE, customization);

    $('#' + PORTLET).css('height', ($(window).height() - 230).toString() + 'px');
    //    $('#Portlet1').show();
}

function viewReport() {

    var RepTable;
    if ($('#OPage_' + ID).length > 0 && REFRESHPAGE == false) {
        $('#OPage_' + ID).show();
    } else {
        if (REFRESHPAGE) {
            $('#OPage_' + ID).remove();
            REFRESHPAGE = false;
        }
        $('.m-content').append('<div id="OPage_' + ID + '" class="inRow" style="width: 100%;"><div id="Legend"></div></div>');
        handleAlerts.BlockElement({
            MESSAGE: 'Processing Report.  Please Wait.',
            ELEMENT: $('.m-grid__item.m-grid__item--fluid.m-wrapper')
        });
        var Param = RET[0].Name.split('|')[1];

        if (Param != "") {
            GetData.SingleSqlValue("Script,Legend", "OS_Reports", "RepId = '" + Param + "'", true, true, function (ret) {
                LEGEND = ret[0].Legend;
                if (ret[0].Script.substr(0, 1) == "@") {
                    RepTable = GetData.storedProdReport(ret[0].Script.substr(1));
                } else {
                    var SCRIPT = ret[0].Script.replace(/\[SEASON\]/g, GetData.localStorage("Season")).replace(/\[SITE\]/g, GetData.localStorage("Classification"));
                    GetData.SqlValue(SCRIPT.substr(0, SCRIPT.length - 1), true, false, function (ret2) {
                        showReport(ret2);
                    });
                }
            });
        }
    }
}

function showReport(REPTABLE) {
    if (QUESTIONS != undefined) {
        processReport(REPTABLE);
    } else {
        GetData.SingleSqlValue("*", "OS_Question", "1 = 1", true, true, function (ret) {
            QUESTIONS = ret;
            processReport(REPTABLE);
        });
    }
}

function processReport(REPTABLE) {
    var InputDat;
    var DataTable;
    
    if (REPTABLE.length > 0) {
        DataTable = REPTABLE;
        var b;
        var Headers = "";
        var TableKeys = [];
        for (var tableKey in REPTABLE[0]) {
            var HeadTitle = "";
            var Terms = ['@', '$', '*'];
            TableKeys.push(tableKey);

            for (var Term in Terms) {
                if (tableKey.indexOf(Terms[Term]) !== -1) {
                    if (tableKey.indexOf(Terms[Term]) == 0) {
                        HeadTitle = tableKey.substr(1);
                    } else {
                        HeadTitle = tableKey.substr(0, tableKey.indexOf(Terms[Term]));
                    }
                    break;
                } else {
                    HeadTitle = tableKey;
                }
            }

            Headers += '<th>' + (Functions.LanguageSelectItem(Functions.indexOfObject(QUESTIONS, 'Name', HeadTitle, 'Title', true)) == undefined || Functions.indexOfObject(QUESTIONS, 'Name', HeadTitle, 'Title', true) == -1 ? HeadTitle.replace(/[_]/g, " ") : Functions.LanguageSelectItem(Functions.indexOfObject(QUESTIONS, 'Name', HeadTitle, 'Title', true))) + '</th>';
        }

        InputDat = '<table class="table table-striped table-hover table-bordered DataTable" id="sample_editable_1">';
        if (TableKeys.searchFor('MasterID') >= 0) {
            InputDat += '<thead><tr><th>View</th><th>Edit</th>' + Headers + '</tr></thead>';
            InputDat += '<tfoot><tr><th>View</th><th>Edit</th>' + Headers + '</tr></tfoot>';
        } else {
            InputDat += '<thead><tr>' + Headers + '</tr></thead>';
            InputDat += '<tfoot><tr>' + Headers + '</tr></tfoot>';
        }
        InputDat += '<tbody>';

        for (b = 1; b < REPTABLE.length; b++) { //Rows
            InputDat += '<tr>';
            if (TableKeys.searchFor('MasterID') >= 0) {
                var MasterIDText = TableKeys[TableKeys.searchFor('MasterID')];
                InputDat += '<td style="text-align: center;"><a href="viewfrm.html?MasterId=' + REPTABLE[b][MasterIDText] + '&Form=' + MasterIDText.substr(MasterIDText.indexOf('@') + 1) + '" style="text-decoration: none;"><span aria-hidden="true" class="flaticon-search"></span></a></td>';
                InputDat += '<td style="text-align: center;"><a href="frm.html?MasterId=' + REPTABLE[b][MasterIDText] + '&Form=' + MasterIDText.substr(MasterIDText.indexOf('@') + 1) + '" style="text-decoration: none;"><span aria-hidden="true" class="flaticon-edit"></span></a></td>';
            }
            //var QData = GetData.LocalStorageJSONData('Question', 'Name', DataTable[0][b], '', 'ä', 'Name', 'InputType', 'PlaceHolder').split('ä');

            for (var e in REPTABLE[b]) { //Columns
                //            for (var e = 0; e < DataTable[b].length; e++) { //Columns
                //var DATA = GetData.LocalStorageJSON('Question', 'Name', DataTable[0][e]);
                var TD = '';
                var Switch = false;
                var Placeholder = '';

                //if (DataTable[0][0].indexOf('MasterID') >= 0) {
                //for (var o = 0; o < QData.length; o++) {
                //if (QData[o].split('|')[0] == DataTable[0][e]) {
                if (REPTABLE[b][e] == null) {
                    REPTABLE[b][e] = "";
                }
                if (REPTABLE[b][e].toString().indexOf('*') != -1) {
                    var QData = GetData.LocalStorageJSONData(QUESTIONS, 'Name', REPTABLE[b][e].substr(0, REPTABLE[b][e].indexOf('*')), '', 'ä', 'Name', 'InputType', 'PlaceHolder').split('ä');

                    //if (QData[o].split('|')[1] == '24' || QData[o].split('|')[1] == '54' || QData[o].split('|')[1] == '59') {
                    Switch = true;
                    Placeholder = QData[0].split('|')[2];
                    //}
                    //break;
                }

                //}
                //}

                if (Switch) {
                    if (REPTABLE[b][e] == "1") {
                        TD = Placeholder.split(',')[0];
                    } else {
                        TD = Placeholder.split(',')[1];
                    }
                } else {
                    TD = REPTABLE[b][e];
                }

                InputDat += '<td ' + (REPTABLE[0][e].toString().indexOf('$') > 0 ? 'style="background-color: ' + REPTABLE[0][e].substr(REPTABLE[0][e].toString().indexOf('$') + 1) + ';">' : '>') + TD + '</td>';
            }
            //InputDat += '<td><a class="edit" href="javascript:;">Edit </a></td><td><a class="delete" href="javascript:;">Delete </a></td></tr>';
            //InputDat += '<td><a class="delete" href="javascript:;">Delete </a></td></tr>';
            InputDat += '</tr>';
        }
        InputDat += '</tbody>' +
            '</table>';

        $('#OPage_' + ID).prepend(InputDat);

        //        $('#sample_editable_1 thead th').each(function () {
        //            var title = $(this).text();
        //            if (title != 'View' && title != 'Edit') {
        //                $(this).html('<p name="headerTitle">' + $(this).html() + '</p><input type="text" placeholder="Search ' + title + '" style="width: 100%;" />');
        //            } else {
        //                $(this).html('');
        //            }
        //        });
        $('#sample_editable_1 thead tr').clone(true).appendTo('#sample_editable_1 thead');
        $('#sample_editable_1 thead tr:eq(1) th').each(function (i) {
            var title = $(this).text();
            $(this).html('<input type="text" placeholder="Search ' + title + '" />');

            $('input', this).on('keyup change', function () {
                if (table.column(i).search() !== this.value) {
                    table
                        .column(i)
                        .search(this.value)
                        .draw();
                }
            });
        });

        var color_Col = 99;
        var thArray = [];
        var table = $('#sample_editable_1').DataTable({
            //buttons: true
            orderCellsTop: true,
            fixedHeader: true,
            "scrollX": true,
            buttons: ['copy', 'csv',
                {
                    extend: 'excel',
                    messageTop: PAGETITLE
                    //                },
                    //                {
                    //                    extend: 'pdfHtml5',
                    //                    orientation: 'landscape',
                    //                    pageSize: 'LETTER',
                    //                    title: 'TIC TICKET REPORT',
                    //                    action: function (e, dt, node, config) {
                    //                        ///update title property based on the added input field
                    //                        config.title = PAGETITLE + ($($('.dataTables_filter').find('input')).val() == "" ? "" : " - " + $($('.dataTables_filter').find('input')).val());
                    //
                    //                        ///procede with the export
                    //                        $.fn.dataTable.ext.buttons.pdfHtml5.action(e, dt, node, config);
                    //                    }
                }, {
                    extend: 'print',
                    customize: function (win) {
                        var last = null;
                        var current = null;
                        var bod = [];

                        var css = '@page { size: landscape; }',
                            head = win.document.head || win.document.getElementsByTagName('head')[0],
                            style = win.document.createElement('style');

                        style.type = 'text/css';
                        style.media = 'print';

                        if (style.styleSheet) {
                            style.styleSheet.cssText = css;
                        } else {
                            style.appendChild(win.document.createTextNode(css));
                        }

                        head.appendChild(style);

                        $(win.document.body)
                            .css('font-size', '10pt'); //.prepend('<img src="http://datatables.net/media/images/logo-fade.png" style="position:absolute; top:0; left:0;" />');

                        $(win.document.body).find('table')
                            .addClass('compact')
                            .css('font-size', 'inherit');
                    }
                }
            ],

            "fnRowCallback": function (nRow, aData, iDisplayIndex, iDisplayIndexFull) {
                thArray = [];

                for (var i = 0; i < $('#sample_editable_1').DataTable().columns()[0].length; i++) {
                    thArray.push($($('#sample_editable_1').DataTable().column(i).header()).text());
                }

                if (thArray.indexOf('COLOR') >= 0) {
                    color_Col = thArray.indexOf('COLOR');
                    if ($('#sample_editable_1').DataTable().row(nRow).data()[color_Col] == 'red' || $('#sample_editable_1').DataTable().row(nRow).data()[color_Col] == 'indianred' || $('#sample_editable_1').DataTable().row(nRow).data()[color_Col] == 'green') {
                        $('td', nRow).css('color', 'white');
                    }
                    $('td', nRow).css('background-color', $('#sample_editable_1').DataTable().row(nRow).data()[color_Col]);
                }
            }
        });

        table.on('search.dt', function () {
            $('#filterInfo').html('Currently applied global search: ' + table.search());
        });

        for (var i = 0; i < $('#sample_editable_1').DataTable().columns()[0].length; i++) {
            thArray.push($($('#sample_editable_1').DataTable().column(i).header()).text());
        }

        if (thArray.indexOf('COLOR') >= 0) {
            $('#sample_editable_1').DataTable().column(thArray.indexOf('COLOR')).visible(false);
        }

        var headerSize = 0;
        for (var i = 0; i < $('[name="headerTitle"]').length; i++) {
            if ($($('[name="headerTitle"]')[i]).height() > headerSize) {
                headerSize = $($('[name="headerTitle"]')[i]).height();
            }
        }
        $('[name="headerTitle"]').css('height', headerSize + 'px');

        table.buttons().container().appendTo('#sample_editable_1_wrapper .col-md-6:eq(0)');

        table.columns().every(function () {
            var that = this;

            $('input', this.footer()).on('keyup change', function () {
                if (that.Search() !== this.value) {
                    that
                        .Search(this.value)
                        .draw();
                }
            });
        });

        //var table = $('#sample_editable_1').DataTable();
        //var column;
        //table.columns().visible(true);
        //column = table.column(1);
        //column.visible(false);
        //
        //    } else {
        //        $('#OPage_' + ID).html('');
    }

    if (LEGEND != undefined) {
        var Legend = LEGEND.split(',');

        for (var i = 0; i < Legend.length; i++) {
            $('#Legend').append('<div><span style="border: 1px solid #ccc; float: left; width: 12px; height: 12px; margin: 2px; background-color: ' + Legend[i].split('|')[0] + '"></span>' + Legend[i].split('|')[1] + '</div>');
        }
    }
    handleAlerts.UnblockElement($('.m-grid__item.m-grid__item--fluid.m-wrapper'));
}

function viewForm() {
    if ($('#OPage_' + ID).length > 0 && REFRESHPAGE == false) {
        $('#OPage_' + ID).show();
    } else {
        if (REFRESHPAGE) {
            $('#OPage_' + ID).remove();
            REFRESHPAGE = false;
        }
        $('.m-content').append('<div id="OPage_' + ID + '" class="inRow" style="width: 100%;"></div>');
        //        GetData.SingleSqlValue("*", "OS_Question", "FormName = '" + RET[0].Name.split("|")[3] + "'", true, true, function (ret) {
        ////            debugger;
        //        });
        $('#OPage_' + ID).html('<form class="m-form m-form--fit m-form--label-align-right" autocomplete="nope">' +
            '<input name="fake_email" class="visually-hidden" type="text"><input name="fake_password" class="visually-hidden" type="password">' +
            '<div class="m-portlet__body">' +
            '<div class="form-group m-form__group m--margin-top-10">' +
            '</div>' +
            '</div>' +
            '</form>');
        
        FIELDS[ID] = [
            new DivisorFieldCell({"ID": "Divisor1",
                                  "TITLE1":"The example form below demonstrates common HTML form elements in pill and air(box shadowed) styles:",
                                  "TITLE2":"The example form below demonstrates common HTML form elements in pill and air(box shadowed) styles:"
                                 }),
            new TextFieldCell({"ID": "Hola",
                               "TITLE1":"Si",
                               "TITLE2":"Yes",
                               "PLACEHOLDER":"Entre la data"
                              }),
            new SwitchFieldCell({"ID": "Hola",
                            "TITLE1":"Si",
                            "TITLE2":"Yes",
                            "VALUE":"True",
                            "COLOR": "info"
                           }),
            new SwitchFieldCell({"ID": "Hola",
                            "TITLE1":"Si",
                            "TITLE2":"Yes",
                            "VALUE":"false", 
                            "ONTEXT": "Ok", 
                            "OFFTEXT": "Not Ok", 
                            "isONOFF": true, 
                            "COLOR": "info"
                           }),
            new TextFieldCell({"ID": "Hola",
                               "TITLE1":"Si",
                               "TITLE2":"Yes",
                               "PLACEHOLDER":"Password", 
                               "isPASSWORD": true
                              }),
            new DateFieldCell({"ID": "Hola",
                               "TITLE1":"Si",
                               "TITLE2":"Yes",
                               "PLACEHOLDER":"Password", 
                               "isPASSWORD": true
                              }),
            new DropdownFieldCell({"ID": "Hola",
                               "TITLE1":"Si",
                               "TITLE2":"Yes",
                               "PLACEHOLDER":"Password", 
                               "OPTIONS": "1,2,3,4,5"
                              }),
            new DropdownFieldCell({"ID": "Hola",
                               "TITLE1":"Si",
                               "TITLE2":"Yes",
                               "PLACEHOLDER":"Password", 
                               "OPTIONS": "1,2,3,4,5",
                               "isSELECTMULTIPLE": true
                              }),
            new DropdownFieldCell({"ID": "Hola",
                               "TITLE1":"Si",
                               "TITLE2":"Yes",
                               "OPTIONS": "1,2,3,4,5", 
                               "isSELECT2": true
                              })
        ];

        $('#OPage_' + ID + ' .m-portlet__body').append(FIELDS[ID].map(function(e) { return e.getHtml();}).join(''));
        $('#OPage_' + ID + ' .m-portlet__body').append(
            
            //Textarea
            '<div class="form-group m-form__group">' +
            '<label for="exampleTextarea">Example textarea</label>' +
            '<textarea class="form-control m-input m-input--air m-input--pill textarea-autosize" id="exampleTextarea" rows="3"></textarea>' +
            '</div>' +
            '</div>' +
            '<div class="m-portlet__foot m-portlet__foot--fit">' +
            '<div class="m-form__actions">' +
            '<button type="reset" class="btn btn-brand">Submit</button>' +
            '<button type="reset" class="btn btn-secondary">Cancel</button>' +
            '</div>' +
            '</div>' +
            //Checkbox
            '<div class="m-form__group form-group">' +
            '<label>Checkbox States</label>' +
            '<div class="m-checkbox-list">' +
            '<label class="m-checkbox m-checkbox--success">' +
            '<input type="checkbox"> Success state' +
            '<span></span>' +
            '</label>' +
            '<label class="m-checkbox m-checkbox--brand">' +
            '<input type="checkbox"> Brand state' +
            '<span></span>' +
            '</label>' +
            '<label class="m-checkbox m-checkbox--primary">' +
            '<input type="checkbox"> Primary state' +
            '<span></span>' +
            '</label>' +
            '</div>' +
            '<span class="m-form__help">Some help text goes here</span>' +
            '</div>' +
            //Inline Checkbox
            '<div class="m-form__group form-group">' +
            '<label for="">Inline Checkboxes</label>' +
            '<div class="m-checkbox-inline">' +
            '<label class="m-checkbox m-checkbox--success">' +
            '<input type="checkbox"> Option 1' +
            '<span></span>' +
            '</label>' +
            '<label class="m-checkbox m-checkbox--brand">' +
            '<input type="checkbox"> Option 2' +
            '<span></span>' +
            '</label>' +
            '<label class="m-checkbox m-checkbox--primary">' +
            '<input type="checkbox"> Option 3' +
            '<span></span>' +
            '</label>' +
            '</div>' +
            '<span class="m-form__help">Some help text goes here</span>' +
            '</div>' +
            //Radio button
            '<div class="m-form__group form-group">' +
            '<label>Radio Checked States</label>' +
            '<div class="m-radio-list">' +
            '<label class="m-radio m-radio--success">' +
            '<input type="radio" name="example_2" value="1"> Success state' +
            '<span></span>' +
            '</label>' +
            '<label class="m-radio m-radio--brand">' +
            '<input type="radio" name="example_2" value="2"> Brand state' +
            '<span></span>' +
            '</label>' +
            '<label class="m-radio m-radio--primary">' +
            '<input type="radio" name="example_2" value="3"> Primary state' +
            '<span></span>' +
            '</label>' +
            '</div>' +
            '<span class="m-form__help">Some help text goes here</span>' +
            '</div>' +
            //Inline Radio button
            '<div class="m-form__group form-group">' +
            '<label for="">Inline Radios</label>' +
            '<div class="m-radio-inline">' +
            '<label class="m-radio">' +
            '<input type="radio" name="example_3" value="1"> Option 1' +
            '<span></span>' +
            '</label>' +
            '<label class="m-radio">' +
            '<input type="radio" name="example_3" value="2"> Option 2' +
            '<span></span>' +
            '</label>' +
            '<label class="m-radio">' +
            '<input type="radio" name="example_3" value="3"> Option 3' +
            '<span></span>' +
            '</label>' +
            '</div>' +
            '<span class="m-form__help">Some help text goes here</span>' +
            '</div>' +
            //Datebox
            '<div class="form-group m-form__group">' +
            '<label>Enable Helper Buttons</label>' +
            '<div class="m-input-list">' +
            '<div class="input-group date">' +
            '<input type="text" class="form-control m-input m-date m-input--air m-input--pill" readonly value="05/20/2017" id="m_datepicker_3" />' +
            '<div class="input-group-append">' +
            '<span class="input-group-text btn m-btn--pill disabled btn-outline-metal">' +
            '<i class="la la-calendar"></i>' +
            '</span>' +
            '</div>' +
            '</div>' +
            '<span class="m-form__help">Enable clear and today helper buttons</span>' +
            '</div>' +
            '</div>' +
            //Simple DateRange
            '<div class="form-group m-form__group">' +
            '<label>Range Picker</label>' +
            '<div class="m-input-list">' +
            '<div class="input-daterange input-group m-date">' +
            '<input type="text" class="form-control m-input" name="start" />' +
            '<div class="input-group-append">' +
            '<span class="input-group-text"><i class="la la-ellipsis-h"></i></span>' +
            '</div>' +
            '<input type="text" class="form-control" name="end" />' +
            '</div>' +
            '<span class="m-form__help">Linked pickers for date range selection</span>' +
            '</div>' +
            '</div>' +
            //Datetime
            '<div class="form-group m-form__group">' +
            '<label>Meridian Format</label>' +
            '<div class="m-input-list">' +
            '<div class="input-group date">' +
            '<input type="text" class="form-control m-datetime" placeholder="Select date and time" />' +
            '<div class="input-group-append">' +
            '<span class="input-group-text">' +
            '<i class="la la-calendar glyphicon-th"></i>' +
            '</span>' +
            '</div>' +
            '</div>' +
            '<span class="m-form__help">Linked pickers for date range selection</span>' +
            '</div>' +
            '</div>' +
            //DateRange
            '<div class="form-group m-form__group">' +
            '<label>Input Group Setup</label>' +
            '<div class="m-input-list">' +
            '<div class="input-group">' +
            '<input type="text" class="form-control m-daterange" readonly placeholder="Select date range" />' +
            '<div class="input-group-append">' +
            '<span class="input-group-text"><i class="la la-calendar-check-o"></i></span>' +
            '</div>' +
            '</div>' +
            '</div>' +
            '</div>' +
            //Timebox
            '<div class="form-group m-form__group">' +
            '<label>Default Time</label>' +
            '<div class="m-input-list">' +
            '<div class="input-group timepicker">' +
            '<div class="input-group-prepend">' +
            '<span class="input-group-text">' +
            '<i class="la la-clock-o"></i>' +
            '</span>' +
            '</div>' +
            '<input class="form-control m-time" readonly placeholder="Select time" type="text" />' +
            '</div>' +
            '</div>' +
            '</div>' +
            //MaxLength
            '<div class="form-group m-form__group">' +
            '<label>Custom Text</label>' +
            '<div class="m-input-list">' +
            '<input type="text" class="form-control m-maxlength" maxlength="8" placeholder="" type="text" />' +
            '<span class="m-form__help">Display custom text on input focus</span>' +
            '</div>' +
            '</div>' +
            //Switch
            '<div class="form-group m-form__group">' +
            '<label>Custom Label</label>' +
            '<div class="m-switch-list">' +
            '<input data-switch="true" type="checkbox" checked="checked" data-on-text="True" data-handle-width="50" data-off-text="False" data-on-color="success">' +
            '<input data-switch="true" type="checkbox" checked="checked" data-on-text="" data-off-text="" data-on-color="info">' +
            '<input data-switch="true" type="checkbox" checked="checked" data-on-text="Enabled" data-off-text="Disabled" data-on-color="brand">' +
            '</div>' +
            '</div>' +
            //Repeat
            '<div class="m-repeat">' +
            '<div class="form-group  m-form__group no-padding_bottom">' +
            '<label>Contact:</label>' +
            '<div data-repeater-list="">' +
            '<div data-repeater-item class="m--margin-bottom-10">' +
            '<div class="input-group">' +
            '<input type="email" class="form-control form-control-danger m-input m-input--air m-input--pill" name="TestRepeat" aria-describedby="emailHelp" placeholder="Enter test">' +
            '<div class="col-sm-1 text-sm-right no-padding">' +
            '<div data-repeater-delete="" class="btn-md btn btn-danger m-btn m-btn--icon m-btn--pill">' +
            '<span>' +
            '<i class="la la-trash-o"></i>' +
            '<span>Delete</span>' +
            '</span>' +
            '</div>' +
            '</div>' +
            '</div>' +
            '</div>' +
            '</div>' +
            '</div>' +
            '<div class="form-group m-form__group no-padding_top">' +
            '<div data-repeater-create="" class="btn btn btn-brand m-btn m-btn--icon m-btn--pill m-btn--wide">' +
            '<span>' +
            '<i class="la la-plus"></i>' +
            '<span>Add</span>' +
            '</span>' +
            '</div>' +
            '</div>');
    }
    BootstrapFunctions.init();
}

function viewCalendar() {
    if ($('#OPage_' + ID).length > 0 && REFRESHPAGE == false) {
        $('#OPage_' + ID).show();
    } else {
        if (REFRESHPAGE) {
            $('#OPage_' + ID).remove();
            REFRESHPAGE = false;
        }
        $('.m-content').append('<div id="OPage_' + ID + '" class="inRow" style="width: 100%;"></div>');
        //        GetData.SingleSqlValue("*", "OS_Question", "FormName = '" + RET[0].Name.split("|")[3] + "'", true, true, function (ret) {
        ////            debugger;
        //        });
        $('#OPage_' + ID).html('<div class="m-portlet" id="m_portlet">' +
            '<div class="m-portlet__head">' +
            '<div class="m-portlet__head-caption">' +
            '<div class="m-portlet__head-title">' +
            '<span class="m-portlet__head-icon">' +
            '<i class="flaticon-calendar-2"></i>' +
            '</span>' +
            '<h3 class="m-portlet__head-text">' +
//            'Background Events' +
            '</h3>' +
            '</div>' +
            '</div>' +
            '<div class="m-portlet__head-tools">' +
            '<ul class="m-portlet__nav">' +
            '<li class="m-portlet__nav-item">' +
            '<a href="javascript:;" class="btn btn-accent m-btn m-btn--custom m-btn--icon m-btn--pill m-btn--air addEventCalendar">' +
            '<span>' +
            '<i class="la la-plus"></i>' +
            '<span>Add Event</span>' +
            '</span>' +
            '</a>' +
            '</li>' +
            '</ul>' +
            '</div>' +
            '</div>' +
            '<div class="m-portlet__body">' +
            '<div id="' + ID + '_m_calendar"></div>' +
            '</div>' +
            '</div>');
        
        $('.addEventCalendar').on('click',function(){
            var messageBody = '<h2 class="title">' + Functions.LanguageSelect('Nuevo Evento', 'New Event') + '</h2></br>';
            FIELDS[ID] = [
                    new TextFieldCell({
                        "ID": "FormId",
                        "PARENT": ID,
                        "INDEX": 0,
                        "isHIDDEN": true
                    }),
                    new TextFieldCell({
                        "ID": "eventTitle",
                        "TITLE1":"Titulo",
                        "TITLE2":"Title",
                        "PLACEHOLDER":"Escriba aqui",
                        "PARENT": ID,
                        "INDEX": 1
                    }),
                    new SwitchFieldCell({
                        "ID": "eventRepeating",
                        "TITLE1":"Evento Repetitivo",
                        "TITLE2":"Repeating Event",
                        "onCHANGE": "if ($(this)[0].checked) {$('#eventRepeatType_Div').show();$('#eventRepeatEndDay_Div').show();} else {$('#eventRepeatType_Div').hide();$('#eventRepeatEndDay_Div').hide();}",
                        "PARENT": ID,
                        "INDEX": 2
                    }),
                    new DropdownFieldCell({
                        "ID": "eventRepeatType",
                        "TITLE1":"Tipo de Evento Repetitivo",
                        "TITLE2":"Repeating Event Type",
                        "isSELECT2": true,
                        "PLACEHOLDER": "Select Type",
                        "OPTIONS": "daily,weekly,monthly,annually",
                        "PARENT": ID,
                        "INDEX": 3,
                        "isHIDDEN": true
                    }),
                    new DateFieldCell({
                        "ID": "eventRepeatEndDay",
                        "TITLE1":"Fecha de Terminaci&oacute;n",
                        "TITLE2":"End Day",
                        "PARENT": ID,
                        "INDEX": 4,
                        "isHIDDEN": true
                    }),
                    new SwitchFieldCell({
                        "ID": "eventAllDay",
                        "TITLE1":"Evento de todo el Dia",
                        "TITLE2":"All Day Event",
                        "PARENT": ID,
                        "INDEX": 5
                    }),
                    new DateFieldCell({
                        "ID": "eventStartDate",
                        "TITLE1":"Fecha de Comienzo",
                        "TITLE2":"Start Day",
                        "PARENT": ID,
                        "INDEX": 6
                    }),
                    new DateFieldCell({
                        "ID": "eventEndDate",
                        "TITLE1":"Fecha de Terminaci&oacute;n",
                        "TITLE2":"End Day",
                        "PARENT": ID,
                        "INDEX": 7
                    }),
                    new TextFieldCell({
                        "ID": "eventDescription",
                        "TITLE1":"Descripci&oacute;n",
                        "TITLE2":"Desciption",
                        "PLACEHOLDER":"Escriba aqui",
                        "isTEXTAREA": true,
                        "PARENT": ID,
                        "INDEX": 8
                    })
                ];
                
                messageBody += FIELDS[ID].map(function(e) { return e.getHtml();}).join('');
                handleAlerts.CustomDialog({
                    buttons: {
                        danger: {
                            label: "Cancel",
                            className: "btn-primary m-btn--pill pull-left",
                            callback: function () {}
                        },
                        main: {
                            label: "Ok",
                            className: "btn-warning m-btn--pill pull-right",
                            callback: function () {
                                Functions.SendAnswers(GetData.localStorage('UserId') + '’eventCalendar’1’' + ID + '|' + Functions.AleatoryCode(15) + '’' + GetData.localStorage('Classification') + '’' + GetData.localStorage('Season') + '*' + (FIELDS[ID].filter(function(e) {if (e["ID"] != "FormId") return e})).map(function(e) {return e["ID"] + "|" + e["VALUE"]}).join('„'),function(ret) {console.log(ret);});
                            }
                        }
                    },
                    closeButton: true,
                    message: messageBody,
                    modalClose: undefined,
                    onEsc: null,
//                    position: "center",
                    size: "large",
                    init: function() {
                        
                        $('[name="eventRepeatType"]').select2({
                            placeholder: $('[name="eventRepeatType"]').attr('data-placeholder'),
                            allowClear : true
                        });
                        $('[name="eventRepeatEndDay"]').datepicker({
                            format: "mm/dd/yyyy",
                            autoclose: true,
                            rtl: mUtil.isRTL(),
                            todayBtn: "linked",
                            clearBtn: true,
                            todayHighlight: true,
                            templates: arrows
                        });
                        
                        if ($('[name="eventAllDay"]')[0].checked) {
                            $('[name="eventStartDate"],[name="eventEndDate"]').datepicker({
                                 format: "mm/dd/yyyy",
                                 autoclose: true,
                                 rtl: mUtil.isRTL(),
                                 todayBtn: "linked",
                                 clearBtn: true,
                                 todayHighlight: true,
                                 templates: arrows
                             });
                        } else {
                            $('[name="eventStartDate"],[name="eventEndDate"]').datetimepicker({
                                 format: "mm/dd/yyyy - HH:ii P",
                                 showMeridian: true,
                                 todayHighlight: true,
                                 autoclose: true,
                                 todayBtn: true,
                                 pickerPosition: 'bottom-left'
                            });
                        }
                        $('[name="eventAllDay"]').on("click",function() {
                            if ($('[name="eventAllDay"]')[0].checked) {
                                $('[name="eventStartDate"],[name="eventEndDate"]').datetimepicker("remove");
                                $('[name="eventStartDate"]').val(DateFunctions.FormatDate(($('[name="eventStartDate"]').val().indexOf("-") > 0 ? $('[name="eventStartDate"]').val().substring(0,10) : new Date($('[name="eventStartDate"]').val())),"MM/dd/yyyy"));
                                $('[name="eventEndDate"]').val(DateFunctions.FormatDate(($('[name="eventEndDate"]').val().indexOf("-") > 0 ? $('[name="eventEndDate"]').val().substring(0,10) : new Date($('[name="eventEndDate"]').val())),"MM/dd/yyyy"));
                                $('[name="eventStartDate"],[name="eventEndDate"]').datepicker({
                                     format: "mm/dd/yyyy",
                                     autoclose: true,
                                     rtl: mUtil.isRTL(),
                                     todayBtn: "linked",
                                     clearBtn: true,
                                     todayHighlight: true,
                                     templates: arrows
                                 });
                            } else {
                                $('[name="eventStartDate"],[name="eventEndDate"]').datepicker("remove");
                                $('[name="eventStartDate"]').val(DateFunctions.FormatDate(new Date($('[name="eventStartDate"]').val()),"MM/dd/yyyy - HH:mm T"));
                                $('[name="eventEndDate"]').val(DateFunctions.FormatDate(new Date($('[name="eventEndDate"]').val()),"MM/dd/yyyy - HH:mm T"));
                                $('[name="eventStartDate"],[name="eventEndDate"]').datetimepicker({
                                     format: "mm/dd/yyyy - HH:ii P",
                                     showMeridian: true,
                                     todayHighlight: true,
                                     autoclose: true,
                                     todayBtn: true,
                                     pickerPosition: 'bottom-left'
                                });
                            }
                        })
                    }
                });
        });
        
        $("#" + ID + "_m_calendar").fullCalendar({
            isRTL: mUtil.isRTL(),
            header: {
                left: "prev,next today",
                center: "title",
                right: "month,agendaWeek,agendaDay,listYear"
            },
            timezone : 'local',
//            disableDragging: true,
            selectable: true,
//            editable: !0,
//            eventLimit: !0,
//            navLinks: !0,
            dayClick: function(date, allDay, jsEvent) {
              if (allDay) {
                jsEvent.calendar.gotoDate(date);
//                jsEvent.calendar.changeView('agendaDay');
              }
            },
            select: function(startDate, endDate,a,b,c) {
              console.log('selected ' + startDate.format() + ' to ' + endDate.format());  
            },
            businessHours: {
                start: '7:00',
                end: '16:00'
            },
            eventClick: function(eventObj) {
                var startingH = DateFunctions.FormatDate(eventObj.start.valueOf(),"UTC+");
                var endingH = (eventObj.end == null ? "" : DateFunctions.FormatDate(eventObj.end.valueOf(),"UTC+"));
                var repeatEndingH = (eventObj.repeatEndDay == null ? endingH : DateFunctions.FormatDate(eventObj.repeatEndDay.valueOf(),"UTC+"));
                var messageBody = '<h2 class="title">' + Functions.LanguageSelect('Evento', 'Event') + ': ' + eventObj.title + '</h2></br>';

                FIELDS[ID] = [
                    new TextFieldCell({
                        "ID": "FormId",
                        "VALUE": eventObj.id,
                        "PARENT": ID,
                        "INDEX": 0,
                        "isHIDDEN": true
                    }),
                    new TextFieldCell({
                        "ID": "eventTitle",
                        "TITLE1":"Titulo",
                        "TITLE2":"Title",
                        "PLACEHOLDER":"Escriba aqui",
                        "VALUE": eventObj.title,
                        "PARENT": ID,
                        "INDEX": 1,
                        "isREADONLY": eventObj.isReadOnly
                    }),
                    new SwitchFieldCell({
                        "ID": "eventRepeating",
                        "TITLE1":"Evento Repetitivo",
                        "TITLE2":"Repeating Event",
                        "VALUE": eventObj.repeating,
                        "onCHANGE": "if ($(this)[0].checked) {$('#eventRepeatType_Div').show();$('#eventRepeatEndDay_Div').show();} else {$('#eventRepeatType_Div').hide();$('#eventRepeatEndDay_Div').hide();}",
                        "PARENT": ID,
                        "INDEX": 2,
                        "isREADONLY": eventObj.isReadOnly
                    }),
                    new DropdownFieldCell({
                        "ID": "eventRepeatType",
                        "TITLE1":"Tipo de Evento Repetitivo",
                        "TITLE2":"Repeating Event Type",
                        "VALUE": eventObj.repeatType,
                        "isSELECT2": true,
                        "PLACEHOLDER": "Select Type",
                        "OPTIONS": "daily,weekly,monthly,annually",
                        "isHIDDEN": (eventObj.repeating ? false : true),
                        "PARENT": ID,
                        "INDEX": 3,
                        "isREADONLY": eventObj.isReadOnly
                    }),
                    new DateFieldCell({
                        "ID": "eventRepeatEndDay",
                        "TITLE1":"Fecha de Terminaci&oacute;n",
                        "TITLE2":"End Day",
                        "VALUE":DateFunctions.FormatDate((new Date(repeatEndingH)).addDays(-1),"MM/dd/yyyy"),
                        "isHIDDEN": (eventObj.repeating ? false : true),
                        "PARENT": ID,
                        "INDEX": 4,
                        "isREADONLY": eventObj.isReadOnly
                    }),
                    new SwitchFieldCell({
                        "ID": "eventAllDay",
                        "TITLE1":"Evento de todo el Dia",
                        "TITLE2":"All Day Event",
                        "VALUE":eventObj.allDay,
                        "PARENT": ID,
                        "INDEX": 5,
                        "isREADONLY": eventObj.isReadOnly
                    }),
                    new DateFieldCell({
                        "ID": "eventStartDate",
                        "TITLE1":"Fecha de Comienzo",
                        "TITLE2":"Start Day",
                        "VALUE":(eventObj.allDay ? DateFunctions.FormatDate(startingH,"MM/dd/yyyy") : DateFunctions.FormatDate(startingH, 'MM/dd/yyyy hh:mm T')),
                        "PARENT": ID,
                        "INDEX": 6,
                        "isREADONLY": eventObj.isReadOnly
                    }),
                    new DateFieldCell({
                        "ID": "eventEndDate",
                        "TITLE1":"Fecha de Terminaci&oacute;n",
                        "TITLE2":"End Day",
                        "VALUE":(eventObj.allDay ? DateFunctions.FormatDate((new Date(endingH)).addDays(-1),"MM/dd/yyyy") : DateFunctions.FormatDate(endingH,'MM/dd/yyyy hh:mm T')),
                        "PARENT": ID,
                        "INDEX": 7,
                        "isREADONLY": eventObj.isReadOnly
                    }),
                    new TextFieldCell({
                        "ID": "eventDescription",
                        "TITLE1":"Descripci&oacute;n",
                        "TITLE2":"Desciption",
                        "PLACEHOLDER":"Escriba aqui",
                        "isTEXTAREA": true,
                        "VALUE": eventObj.description,
                        "PARENT": ID,
                        "INDEX": 8,
                        "isREADONLY": eventObj.isReadOnly
                    })
                ];
                
                messageBody += FIELDS[ID].map(function(e) { return e.getHtml();}).join('');
                handleAlerts.CustomDialog({
                    buttons: {
                        danger: {
                            label: "Cancel",
                            className: "btn-primary m-btn--pill pull-left",
                            callback: function () {}
                        },
                        main: {
                            label: "Ok",
                            className: "btn-warning m-btn--pill pull-right",
                            callback: function () {
                                Functions.SendAnswers(GetData.localStorage('UserId') + '’eventCalendar’1’' + ID + '|' + Functions.AleatoryCode(15) + '’' + GetData.localStorage('Classification') + '’' + GetData.localStorage('Season') + '*eventTitle|' + 'Repeating Event' + '„eventRepeating|' + 'true' + '„eventAllDay|' + 'false' + '„eventStart|' + '01/26/2019 03:30 PM' + '„eventEnd|' + '01/26/2019 05:30 PM' + '„eventRepeatEndDay|' + '02/02/2019' + '„eventDescription|' + 'Lorem ipsum dolor incid idunt ut labore' + '„eventColor|' + 'primary',function(ret) {console.log(ret);});
                            }
                        }
                    },
                    closeButton: true,
                    message: messageBody,
                    modalClose: undefined,
                    onEsc: null,
//                    position: "center",
                    size: "large",
                    init: function() {
                        
                        $('[name="eventRepeatType"]').select2({
                            placeholder: $('[name="eventRepeatType"]').attr('data-placeholder'),
                            allowClear : true
                        });
                        $('[name="eventRepeatEndDay"]').datepicker({
                            format: "mm/dd/yyyy",
                            autoclose: true,
                            rtl: mUtil.isRTL(),
                            todayBtn: "linked",
                            clearBtn: true,
                            todayHighlight: true,
                            templates: arrows
                        });

//                        if ($('[name="eventRepeating"]')[0].checked) {
//                            $('#eventRepeatType_Div').show();
//                            $('#eventRepeatEndDay_Div').show();
//                        } else {
//                            $('#eventRepeatType_Div').hide();
//                            $('#eventRepeatEndDay_Div').hide();
//                        }
                        
                        if ($('[name="eventAllDay"]')[0].checked) {
                            $('[name="eventStartDate"],[name="eventEndDate"]').datepicker({
                                 format: "mm/dd/yyyy",
                                 autoclose: true,
                                 rtl: mUtil.isRTL(),
                                 todayBtn: "linked",
                                 clearBtn: true,
                                 todayHighlight: true,
                                 templates: arrows
                             });
                        } else {
                            $('[name="eventStartDate"],[name="eventEndDate"]').datetimepicker({
                                 format: "mm/dd/yyyy - HH:ii P",
                                 showMeridian: true,
                                 todayHighlight: true,
                                 autoclose: true,
                                 todayBtn: true,
                                 pickerPosition: 'bottom-left'
                            });
                        }
                        $('[name="eventAllDay"]').on("click",function() {
                            if ($('[name="eventAllDay"]')[0].checked) {
                                $('[name="eventStartDate"],[name="eventEndDate"]').datetimepicker("remove");
                                $('[name="eventStartDate"]').val(DateFunctions.FormatDate(($('[name="eventStartDate"]').val().indexOf("-") > 0 ? $('[name="eventStartDate"]').val().substring(0,10) : new Date($('[name="eventStartDate"]').val())),"MM/dd/yyyy"));
                                $('[name="eventEndDate"]').val(DateFunctions.FormatDate(($('[name="eventEndDate"]').val().indexOf("-") > 0 ? $('[name="eventEndDate"]').val().substring(0,10) : new Date($('[name="eventEndDate"]').val())),"MM/dd/yyyy"));
                                $('[name="eventStartDate"],[name="eventEndDate"]').datepicker({
                                     format: "mm/dd/yyyy",
                                     autoclose: true,
                                     rtl: mUtil.isRTL(),
                                     todayBtn: "linked",
                                     clearBtn: true,
                                     todayHighlight: true,
                                     templates: arrows
                                 });
                            } else {
                                $('[name="eventStartDate"],[name="eventEndDate"]').datepicker("remove");
                                $('[name="eventStartDate"]').val(DateFunctions.FormatDate(new Date($('[name="eventStartDate"]').val()),"MM/dd/yyyy - HH:mm T"));
                                $('[name="eventEndDate"]').val(DateFunctions.FormatDate(new Date($('[name="eventEndDate"]').val()),"MM/dd/yyyy - HH:mm T"));
                                $('[name="eventStartDate"],[name="eventEndDate"]').datetimepicker({
                                     format: "mm/dd/yyyy - HH:ii P",
                                     showMeridian: true,
                                     todayHighlight: true,
                                     autoclose: true,
                                     todayBtn: true,
                                     pickerPosition: 'bottom-left'
                                });
                            }
                        })
                    }
                });
            },
            eventRender: function (e, t) {
                t.hasClass("fc-day-grid-event") ? (t.data("content", e.description), t.data("placement", "top"), mApp.initPopover(t)) : t.hasClass("fc-time-grid-event") ? t.find(".fc-title").append('<div class="fc-description">' + e.description + "</div>") : 0 !== t.find(".fc-list-item-title").length && t.find(".fc-list-item-title").append('<div class="fc-description">' + e.description + "</div>")
            }
        });
        
        $.ajax({
            type: "POST",
            data: "StringJSON=eventCalendar|" + GetData.localStorage("Classification"),
            dataType: "xml",
            url: DUrl + "WebServiceOsiris.asmx/Get_Answer_with_Form_Report",
//            cache: false,
            async: true,
            success: function (data) {

                var title = $(data).find('string').first().text();

                if (title != "[[]]") {
                    var updatedEvents = Functions.ArrayToObject(JSON.parse(title));
                    var EVENTS = [];
                    
                    for(var i = 0; i < updatedEvents.length; i++) {
                        var inEVENTS = {};
                        if(updatedEvents[i]["eventCreatedBy"] != undefined && updatedEvents[i]["eventCreatedBy"] == GetData.localStorage('UserId')) {inEVENTS["isReadOnly"] = false;} else {inEVENTS["isReadOnly"] = true;}
                        if(updatedEvents[i]["eventTitle"] != undefined) {inEVENTS["title"] = updatedEvents[i]["eventTitle"];}
                        if(updatedEvents[i]["eventAllDay"] != undefined) {inEVENTS["allDay"] = Functions.isTrue(updatedEvents[i]["eventAllDay"]);}
//                        if(updatedEvents[i]["eventColor"] != undefined) {inEVENTS["color"] = mApp.getColor(updatedEvents[i]["eventColor"]);}
                        inEVENTS["color"] = mApp.getColor("accent");
                        if(updatedEvents[i]["eventDescription"] != undefined) {inEVENTS["description"] = updatedEvents[i]["eventDescription"];}
                        if(updatedEvents[i]["eventEnd"] != undefined) {inEVENTS["originalEnd"] = updatedEvents[i]["eventEnd"]; inEVENTS["end"] = (Functions.isTrue(updatedEvents[i]["eventAllDay"]) ? DateFunctions.FormatDate((new Date(updatedEvents[i]["eventEnd"])).addDays(1),'UTC-') : DateFunctions.FormatDate(updatedEvents[i]["eventEnd"],'UTC-'));}
                        if(updatedEvents[i]["eventStart"] != undefined) {inEVENTS["originalStart"] = updatedEvents[i]["eventStart"]; inEVENTS["start"] = DateFunctions.FormatDate(updatedEvents[i]["eventStart"],'UTC-');}
                        inEVENTS["id"] = updatedEvents[i]["Form_Id"];
                        
                        if (Functions.isTrue(updatedEvents[i]["eventRepeating"])) {
                            var repeatTimes = 0;
                            var repeatType = "";
                            if (updatedEvents[i].eventRepeatType == "daily") {
                                repeatType = "Day";
                                repeatTimes = DateFunctions.CompareDates(updatedEvents[i].eventStart,updatedEvents[i].eventRepeatEndDay,'Day') || 1;
                            } else if (updatedEvents[i].eventRepeatType == "weekly") {
                                repeatType = "Week";
                                repeatTimes = Math.floor(DateFunctions.CompareDates(updatedEvents[i].eventStart,updatedEvents[i].eventRepeatEndDay,'Day') / 7) || 1;
                            } else if (updatedEvents[i].eventRepeatType == "monthly") {
                                repeatType = "Month";
                                repeatTimes = DateFunctions.CompareDates(updatedEvents[i].eventStart,updatedEvents[i].eventRepeatEndDay,'Month') || 1;
                            } else if (updatedEvents[i].eventRepeatType == "yearly") {
                                repeatType = "Year";
                                repeatTimes = DateFunctions.CompareDates(updatedEvents[i].eventStart,updatedEvents[i].eventRepeatEndDay,'Year') || 1;
                            }
                            inEVENTS["repeating"] = true;
                            inEVENTS["repeatType"] = updatedEvents[i]["eventRepeatType"];
                            inEVENTS["repeatEndDay"] = DateFunctions.FormatDate((new Date(updatedEvents[i]["eventRepeatEndDay"])).addDays(1),'UTC-');
                            
                            var inRepeatStartDate = inEVENTS["start"];
                            var inRepeatEndDate = inEVENTS["end"];
                            EVENTS.push(inEVENTS);
                            
                            for(var t = 1; t < repeatTimes; t++) {
                                var repeatInEVENTS = Object.assign({}, inEVENTS);
                                inRepeatStartDate = DateFunctions.Add(inRepeatStartDate,repeatType,1);
                                inRepeatEndDate = DateFunctions.Add(inRepeatEndDate,repeatType,1);
                                
                                repeatInEVENTS["start"] = new Date(inRepeatStartDate);
                                repeatInEVENTS["end"] = new Date(inRepeatEndDate);
                                EVENTS.push(repeatInEVENTS);
                            }
                        } else {
                            inEVENTS["repeating"] = false;
                            EVENTS.push(inEVENTS);
                        }
                        
                    }
                    
                    $("#" + ID + "_m_calendar").fullCalendar('addEventSource',{
                        events: EVENTS
                    });
                }
            },
            error: function (a, b, c) {
                if (GetData.localStorage("onScreenError") == "true") {
                    handleAlerts.Simple(a.responseText);
                } else {
                    console.log(a.responseText);
                }
            }
        });
        
//        $("#" + ID + "_m_calendar").fullCalendar('addEventSource',{
//        events: [
//            {
//                title: "All Day Event",
//                start: DateFunctions.FormatDate('01/21/2019 02:30 AM','UTC-'),
//                end: DateFunctions.FormatDate('01/22/2019 03:30 PM','UTC-'),
//                color: mApp.getColor("accent"),
//                description: "Lorem ipsum dolor incid idunt ut labore"
//            }, {
//                title: "Reporting",
//                start: t + "-14T13:30:00",
//                description: "Lorem ipsum dolor incid idunt ut labore",
//                end: t + "-14",
//                className: "m-fc-event--accent",
//                constraint: "businessHours"
//            }, {
//                title: "Company Trip",
//                start: DateFunctions.FormatDate('01/21/2019','UTC-'),
//                description: "Lorem ipsum dolor sit tempor incid",
//                end: DateFunctions.FormatDate((new Date('01/22/2019')).addDays(1),'UTC-'),
//                className: "m-fc-event--light m-fc-event--solid-primary",
//                allDay: true,
//                color: mApp.getColor("primary")
//            }, {
//                title: "Expo",
//                start: t + "-03",
//                description: "Lorem ipsum dolor sit tempor inci",
//                end: t + "-05",
//                className: "m-fc-event--primary",
//                rendering: "background",
//                color: mApp.getColor("accent")
//            }, {
//                title: "Dinner",
//                start: t + "-12",
//                description: "Lorem ipsum dolor sit amet, conse ctetur",
//                end: t + "-10",
//                rendering: "background",
//                color: mApp.getColor("info")
//            }, {
//                id: 999,
//                title: "Repeating Event",
//                start: DateFunctions.FormatDate('01/26/2019 03:30 PM','UTC-'),
//                description: "Lorem ipsum dolor sit ncididunt ut labore",
//                className: "m-fc-event--danger",
//                color: mApp.getColor("info")
//            }, {
//                id: 999,
//                title: "Repeating Event",
//                description: "Lorem ipsum dolor sit amet, labore",
//                start: DateFunctions.FormatDate('02/02/2019 03:30 PM','UTC-'),
//                className: "m-fc-event--danger",
//                color: mApp.getColor("info")
//            }, {
//                title: "Conference",
//                start: i,
//                end: o,
//                description: "Lorem ipsum dolor eius mod tempor labore",
//                className: "m-fc-event--accent",
//                rendering: "background",
//                color: mApp.getColor("metal")
//            }, {
//                title: "Meeting",
//                start: r + "T10:30:00",
//                end: r + "T12:30:00",
//                description: "Lorem ipsum dolor eiu idunt ut labore"
//            }, {
//                title: "Lunch",
//                start: r + "T12:00:00",
//                className: "m-fc-event--info",
//                description: "Lorem ipsum dolor sit amet, ut labore"
//            }, {
//                title: "Meeting",
//                start: r + "T14:30:00",
//                className: "m-fc-event--warning",
//                description: "Lorem ipsum conse ctetur adipi scing",
//                rendering: "background",
//                color: mApp.getColor("warning")
//            }, {
//                title: "Happy Hour",
//                start: r + "T17:30:00",
//                className: "m-fc-event--metal",
//                description: "Lorem ipsum dolor sit amet, conse ctetur"
//            }, {
//                title: "Dinner",
//                start: r + "T20:00:00",
//                description: "Lorem ipsum dolor sit ctetur adipi scing"
//            }, {
//                title: "Birthday Party",
//                start: o + "T07:00:00",
//                className: "m-fc-event--primary",
//                description: "Lorem ipsum dolor sit amet, scing",
//                rendering: "background",
//                color: mApp.getColor("focus")
//            }, {
//                title: "Click for Google",
//                url: "http://google.com/",
//                start: t + "-28",
//                description: "Lorem ipsum dolor sit amet, labore"
//            }]
//        });
        
//        Functions.SendAnswers(GetData.localStorage('UserId') + '’eventCalendar’1’' + Functions.AleatoryCode(15) + '’' + GetData.localStorage('Classification') + '’' + GetData.localStorage('Season') + '*eventTitle|' + 'Repeating Event' + '„eventRepeating|' + 'true' + '„eventAllDay|' + 'false' + '„eventStart|' + '01/26/2019 03:30 PM' + '„eventEnd|' + '01/26/2019 05:30 PM' + '„eventRepeatEndDay|' + '02/02/2019' + '„eventDescription|' + 'Lorem ipsum dolor incid idunt ut labore' + '„eventColor|' + 'primary',function(ret) {console.log(ret);});
    }
}

function eshCalendar() {
    if ($('#OPage_' + ID).length > 0 && REFRESHPAGE == false) {
        $('#OPage_' + ID).show();
    } else {
        if (REFRESHPAGE) {
            $('#OPage_' + ID).remove();
            REFRESHPAGE = false;
        }
        $('.m-content').append('<div id="OPage_' + ID + '" class="inRow" style="width: 100%;"></div>');
        //        GetData.SingleSqlValue("*", "OS_Question", "FormName = '" + RET[0].Name.split("|")[3] + "'", true, true, function (ret) {
        ////            debugger;
        //        });
        $('#OPage_' + ID).html(
            '<div class="row" style="height:50px;">' +
            '<div class="form-group form-md-line-input col-md-5" id="tasksfilters">' +
            '<label class="col-md-2 filterslabel inputLabel control-label ">Status Filter:</label>' +
            '<div class="col-md-10">' +
            '<div class="md-checkbox-list">' +
            '<div class="checkboxList">' +
            '<div class="md-checkbox horizontalcheckbox">' +
            '<input type="checkbox" style="background-color:lemonchiffon" data-itype="Check" id="checkbox-Current" data-saving="undefined" name="Current" data-formula=" " class="md-check form-field" onclick="filterchange("Current")">' +
            '<label for="checkbox-Current" style="text-decoration: underline;-webkit-text-decoration-color: lemonchiffon;text-decoration-color: lemonchiffon;">' +
            '<span class="inc"></span>' +
            '<span class="check"></span>' +
            '<span class="box"></span>Due this Month' +
            '</label>' +
            '</div>' +
            '<div class="md-checkbox horizontalcheckbox">' +
            '<input type="checkbox" style="background-color:#cb5a5e" data-itype="Check" id="checkbox-Overdue" data-saving="undefined" name="Overdue" data-formula=" " class="md-check form-field" onclick="filterchange("Overdue")">' +
            '<label for="checkbox-Overdue" style="text-decoration: underline;-webkit-text-decoration-color: #cb5a5e;text-decoration-color: #cb5a5e;"><span></span><span class="check"></span><span class="box"></span>Overdue</label>' +
            '</div>' +
            '<div class="md-checkbox horizontalcheckbox">' +
            '<input type="checkbox" style="background-color:#26a69a" data-itype="Check" id="checkbox-Completed" data-saving="undefined" name="Completed" data-formula=" " class="md-check form-field" onclick="filterchange("Completed")">' +
            '<label for="checkbox-Completed" style="text-decoration: underline;-webkit-text-decoration-color: #26a69a;text-decoration-color: #26a69a;">' +
            '<span></span>' +
            '<span class="check"></span>' +
            '<span class="box"></span>Completed' +
            '</label>' +
            '</div>' +
            '<div class="md-checkbox horizontalcheckbox">' +
            '<input type="checkbox" style="background-color:gainsboro" data-itype="Check" id="checkbox-NoTasks" data-saving="undefined" name="NoTasks" data-formula=" " class="md-check form-field" onclick="filterchange("NoTasks")">' +
            '<label for="checkbox-NoTasks" style="text-decoration: underline;-webkit-text-decoration-color: gainsboro;text-decoration-color: gainsboro;">' +
            '<span></span>' +
            '<span class="check"></span>' +
            '<span  class="box"></span>Next Due' +
            '</label>' +
            '</div>' +
            '<div class="md-checkbox horizontalcheckbox">' +
            '<input type="checkbox" data-itype="Check" id="checkbox-All" data-saving="undefined" name="All" data-formula=" " class="md-check form-field" onclick="filterchange("All")">' +
            '<label for="checkbox-All" style="text-decoration: underline;-webkit-text-decoration-color: black;text-decoration-color: black;">' +
            '<span></span>' +
            '<span class="check"></span>' +
            '<span class="box"></span>All' +
            '</label>' +
            '</div>' +
            '</div>' +
            '</div>' +
            '</div>' +
            '</div >' +
            '<div class="form-group form-md-line-input inactive col-md-3" id="19_form_control_Month_div">' +
            '<label class="col-md-2 inputLabel control-label" for="19_form_control_Month">Month:</label>' +
            '<div class="col-md-10">' +
            '<select class="form-control form-field select2me" id="19_form_control_Month" onchange="monthfiltertypechange();" name="Month" data-placeholder="Select..." style="width: 150px;" ;>' +
            '<option value="All">All</option>' +
            '<option value="January">January</option>' +
            '<option value="February">February</option>' +
            '<option value="March">March</option>' +
            '<option value="April">April</option>' +
            '<option value="May">May</option>' +
            '<option value="June">June</option>' +
            '<option value="July">July</option>' +
            '<option value="August">August</option>' +
            '<option value="September">September</option>' +
            '<option value="October">October</option>' +
            '<option value="November">November</option>' +
            '<option value="December">December</option>' +
            '</select>' +
            '<span class="help-block"></span>' +
            '</div>' +
            '</div>' +
            '<div class="form-group form-md-line-input inactive col-md-4" id="20_form_control_Month_div">' +
            '<label class="col-md-2 inputLabel control-label" for="20_form_control_Month">Search:</label>' +
            '<div class="col-md-10">' +
            '<input type="text" class="form-control form-field" id="20_form_control_Month" onkeyup="filterdata($(this).val());" style="width: 300px;">' +
            '<span class="help-block"></span>' +
            '</div>' +
            '</div>' +
            '</div>' +
            '<br>' +
            '<div class="row" style="height:50px;padding: 20px;">' +
            '<div id="copyalltasks" class="form-control hidden" style="width:220px;left:20px;position:absolute;" ><div style="display:inline;"><button type="button" id="inactivecommentBtn" class="btn btn-danger deleteBtn" onclick="copyAllToNewYear() ">+</button></div><div style="display:inline;padding-left: 9px;"><label>Create New Year Tasks</label></div></div>' +
            '</div>' +
            '<br>');
    }

    var PermitData;
    var downloadedtasks;
    var selectedPermit;
    var selectedtask;
    var selectedPermitName;
    var inspectorList;
    var inactiveComment = "";
    var programownertasks;
    var programinfo;
    var isRecurrent = false;

    var addingrecurrenttype = "";
    var addingmonthlytype = "";
    $('#19_form_control_Month').val(getCurrentMonth()).trigger('change');

    createtasks(0);

    $(".mainitemcurrent").show();
    $(".mainitemnotasks").show();
    $(".mainitemoverdue").show();
    $(".mainitemcompleted").show();

    $('#checkbox-Completed').removeAttr('checked');
    $('#checkbox-NoTasks').removeAttr('checked');
    $('#checkbox-All').removeAttr('checked');

    $('#checkbox-Overdue').attr('checked', 'checked');
    $('#checkbox-Current').attr('checked', 'checked');

    //Get users to be used for task responsible
    var responsibleList = GetData.SqlValue("Select id_User, Name From OS_User Where Classification like '" + GetData.localStorage('Classification') + "' and Active = 1 Order by Name");
    for (var i = 0; i < responsibleList.length; i++) {
        inspectorList += '<option value="' + responsibleList[i].id_User + '">' + responsibleList[i].Name + '</option>';
    }

    $.extend($.expr[":"], {
        "containsNC": function (elem, i, match, array) {
            return (elem.textContent || elem.innerText || "").toLowerCase().indexOf((match[3] || "").toLowerCase()) >= 0;
        }
    });

    updateVisible();

    var fromdashboard = GetData.UrlParameter('program');
    if (fromdashboard != undefined && fromdashboard != "") {
        fromdashboard = decodeURIComponent(fromdashboard);
        filterdata(fromdashboard);
    }
}
