
function addTask(taskprogramid, tasknumber, recurrenttask) {

    selectedPermit = taskprogramid;
    var indexofelement = 0;

    for (var i = 0; i < programinfo.length; i++) {
        if (programinfo[i]["id_Catalog"] == taskprogramid) {
            indexofelement = i;
            break;
        }
    }

    if (tasknumber != -1) {
        if (recurrenttask == false) {
            selectedPermitName = programinfo[indexofelement]["Name"] + " - " + programownertasks[tasknumber]["Name"];

            handleAlerts.CustomDialog({
                destroy: true,

                message: "<div class='container'><div> <button type='button' class='buttonpadding' id='addnewtask' style='background-color: transparent;border: none;'><div style='display: inline-block;vertical-align: middle;'></div>" + "</button></div><div class='form-control md-checkbox-list' style='width:100px;top: 0;right: 50px;position: absolute;'><div style='display:inline;'><button type='button' id='inactivecommentBtn' class='btn btn-danger circleBtn ' onclick='deleteTask(" + programownertasks[tasknumber]["id_Permit"] + ")'>X</button></div><div style='display:inline;padding-left: 9px;'><label>" + Functions.LanguageSelect("Borrar", "Delete") + "</label></div></div><div class='form-control md-checkbox-list' style='width:130px;top: 0;right:160px;position: absolute;'><div style='display:inline;'><button type='button' id='recurrentCurrentBtn' class='btn btn-warning circleBtn' onclick='addTask(" + taskprogramid + "," + tasknumber + ",true)'>+</button></div><div style='display:inline;padding-left: 9px;'><label>" + Functions.LanguageSelect("Recurrente", "Recurrent") + "</label></div></div><div class='col-lg-9'>" + "<form class='form-horizontal' action='' id='tasksform'><div class='col-lg-6'><div class='form-group'> <label class='control-label col-sm-4' for='boxtaskname'>" + Functions.LanguageSelect("Tareas:", "Task:") + ":</label>" + "<div class='col-sm-8'> <input type='text' readonly class='form-control accessLevel_Admin' id='boxtaskname' placeholder='" + Functions.LanguageSelect("Entre el nombre de la tarea", "Enter task name") + "'></div></div><div class='form-group'>" + " <label class='control-label col-sm-4' for='boxresponsible'>" + Functions.LanguageSelect("Responsable:", "Responsible:") + "</label><div class='col-sm-8'> <select disabled='true' class='form-control accessLevel_Admin' id='boxresponsible'>" + inspectorList + "</select>" + "</div></div><div class='form-group'> <label class='control-label col-sm-4' for='boxstartdate'>" + Functions.LanguageSelect("Fecha de Comienzo:", "Start Date:") + "</label><div class='col-sm-8'>" + " <input type='date' readonly class='form-control accessLevel_Admin' id='boxstartdate' placeholder='" + Functions.LanguageSelect("Entre la fecha de comienzo", "Enter Start Date") + "'></div></div><div class='form-group'>" + " <label class='control-label col-sm-4' for='boxenddate'>" + Functions.LanguageSelect("Fecha de Terminación:", "End Date:") + "</label><div class='col-sm-8'> <input type='date' readonly class='form-control accessLevel_Admin' id='boxenddate' placeholder='" + Functions.LanguageSelect("Entre la fecha de terminación", "Enter End Date") + "'>" + "</div></div><div class='form-group'> <label class='control-label col-sm-4' for='boxduration'>" + Functions.LanguageSelect("Duración:", "Duration:") + "</label><div class='col-sm-8'>" + " <input type='text' readonly class='form-control accessLevel_Admin' id='boxduration' placeholder='" + Functions.LanguageSelect("Entre la duración de la tarea", "Enter Task Duration") + "'></div></div><div class='form-group'> <label class='control-label col-sm-4' for='boxdescription'>" + Functions.LanguageSelect("Descripción:", "Description:") + "</label><div class='col-sm-8'>" + "<textarea readonly rows='7' class='form-control accessLevel_Admin' id='boxdescription' notes='" + Functions.LanguageSelect("entre la descripción de la tarea", "Enter Task Description") + "'></textarea></div></div></div>" + "<div class='col-lg-6'><div class='form-group'> <label class='control-label col-sm-4' for='boxstatus'>" + Functions.LanguageSelect("Estatus:", "Status:") + "</label><div class='col-sm-8'>" + " <select class='form-control' id='boxstatus'><option id='statusnotstarted' value='statusnotstarted'>" + Functions.LanguageSelect("No Empezado", "Not Started") + "</option><option id='statusinprogress' value='statusinprogress'>" + Functions.LanguageSelect("En Progreso", "In Progress") + "</option>" + "<option id='statuscompleted' value='statuscompleted'>" + Functions.LanguageSelect("Completado", "Completed") + "</option>" + "<option id='statusna' value='statusna'>" + Functions.LanguageSelect("No Aplica", "Does Not Apply") + "</option> </select></div></div><div class='form-group'> <label class='control-label col-sm-4' for='boxpercent'>" + Functions.LanguageSelect("Porciento:", "Percent:") + "</label>" + "<div class='col-sm-8'> <select class='form-control' id='boxpercent'><option id='p0' value='0'>0%</option><option id='p25' value='25'>25%</option><option id='p50' value='50'>50%</option>" + "<option id='p75' value='75'>75%</option><option id='p100' value='100'>100%</option> </select></div></div><div class='form-group'>" + " <label class='control-label col-sm-4' for='boxcompleteddate'>" + Functions.LanguageSelect("Fecha de Completado:", "Completed Date:") + "</label><div class='col-sm-8'>" + " <input type='date' class='form-control' id='boxcompleteddate' placeholder='" + Functions.LanguageSelect("Fecha de Completado", "Completed Date") + "'></div></div><div class='form-group'>" + " <label class='control-label col-sm-4' for='boxentrydate'>" + Functions.LanguageSelect("Fecha de Entrado:", "Entry Date:") + "</label><div class='col-sm-8'>" + " <input type='date' class='form-control' id='boxentrydate' placeholder='" + Functions.LanguageSelect("Fecha de Entrado", "Entry Date") + "' readonly></div></div><div class='form-group'>" + " <label class='control-label col-sm-4' for='boxnotes'>" + Functions.LanguageSelect("Notas:", "Notes:") + "</label><div class='col-sm-8'><textarea rows='7' class='form-control' id='boxnotes' notes='" + Functions.LanguageSelect("Entre las notas", "Enter Notes") + "'></textarea></div>" + "</div></div></form></div></div>",
                title: selectedPermitName,
                buttons: {
                    danger: {
                        label: "Close",
                        className: "btn-info pull-right",
                        callback: function () {
                            createtasks(0);
                            filterchange();

                            var searchvalue = $("#20_form_control_Month").val();

                            if (searchvalue != "") {
                                filterdata(searchvalue);
                            }

                            //else{
                            //    updateVisible();
                            //}

                            scrolltoprogram(selectedPermit);
                        }
                    }
                },
                closeButton: false,
                size: "large",
                init: function () {
                    $("[name='taskduedate']").datepicker({
                        //rtl: Metronic.isRTL(),
                        //orientation: "right",
                        autoclose: true,
                        forceParse: false,
                        todayHighlight: true,
                        assumeNearbyYear: true,
                        todayBtn: true,
                        clearBtn: true
                    });
                }
            });

            bootboxlistselection(tasknumber);
        } else {
            selectedPermitName = programinfo[indexofelement]["Name"] + " - " + programownertasks[tasknumber]["Name"] + " - Recurrent";

            isRecurrent = true;

            var d = new Date();
            var c = d.getFullYear();
            var e = c + 10;
            var yearoptions = "";

            for (var yi = c; yi < e; yi++) {
                yearoptions = yearoptions + "<option value='Test'>" + yi + "</option>";
                //alert(yearoptions);
            }

            handleAlerts.CustomDialog({
                destroy: true,
                message: "<div class='container'><div class='col-lg-9'>" + "<form class='form-horizontal' action='' id='tasksform'><div class='col-lg-6'><div class='form-group'> <label class='control-label col-sm-4' for='boxaddtaskname'>" + Functions.LanguageSelect("Tareas:", "Task:") + ":</label>" + "<div class='col-sm-8'> <input type='text' readonly class='form-control accessLevel_Admin' id='boxaddtaskname' placeholder='" + Functions.LanguageSelect("Entre el nombre de la tarea", "Enter task name") + "'></div></div><div class='form-group'>" + " <label class='control-label col-sm-4' for='boxaddresponsible'>" + Functions.LanguageSelect("Responsable:", "Responsible:") + "</label><div class='col-sm-8'> <select disabled='true' class='form-control accessLevel_Admin' id='boxaddresponsible'>" + inspectorList + "</select>" + "</div></div><div class='form-group'> <label class='control-label col-sm-4' for='boxaddstartdate'>" + Functions.LanguageSelect("Fecha de Comienzo:", "Start Date:") + "</label><div class='col-sm-8'>" + " <input type='date' readonly class='form-control accessLevel_Admin' id='boxaddstartdate' placeholder='" + Functions.LanguageSelect("Entre la fecha de comienzo", "Enter Start Date") + "'></div></div><div class='form-group'>" + " <label class='control-label col-sm-4' for='boxaddenddate'>" + Functions.LanguageSelect("Fecha de Terminación:", "End Date:") + "</label><div class='col-sm-8'> <input type='date' readonly class='form-control accessLevel_Admin' id='boxaddenddate' placeholder='" + Functions.LanguageSelect("Entre la fecha de terminación", "Enter End Date") + "'>" + "</div></div><div class='form-group'> <label class='control-label col-sm-4' for='boxaddduration'>" + Functions.LanguageSelect("Duración:", "Duration:") + "</label><div class='col-sm-8'>" + " <input type='text' readonly class='form-control accessLevel_Admin' id='boxaddduration' placeholder='" + Functions.LanguageSelect("Entre la duración de la tarea", "Enter Task Duration") + "'></div></div><div class='form-group'> <label class='control-label col-sm-4' for='boxadddescription'>" + Functions.LanguageSelect("Descripción:", "Description:") + "</label><div class='col-sm-8'>" + "<textarea readonly rows='7' class='form-control accessLevel_Admin' id='boxadddescription' notes='" + Functions.LanguageSelect("entre la descripción de la tarea", "Enter Task Description") + "'></textarea></div></div>" + "<div id='recurrentfields' class='hidden'><div><tr><td> <span class='' title='Recurrence Type: Weekly'><input id='weekly' type='radio' name='recurrencetype' value='1' onclick='RecurPatternType_ShowRecurType(this.id);'><label for='weekly'>Weekly</label></span></td></tr><tr><td> <span class='' title='Recurrence Type: Monthly'><input id='monthly' type='radio' name='recurrencetype' value='2' onclick='RecurPatternType_ShowRecurType(this.id);'><label for='monthly'>Monthly</label></span></td></tr></div><div id='monthlyfields' class='hidden'><tr><td> <span class='' title='Whole Month'><input id='wholemonth' type='radio' name='recurrentmonthtype' value='1' onclick='monthtypevalues(this.id);' style='margin-left:38px;' ><label for='wholemonth'>Whole Month</label></span></td></tr><tr><td> <span class='' title='Specific'><input id='specificmonth' style='margin-left:38px;' type='radio' name='recurrentmonthtype' value='2' onclick='monthtypevalues(this.id);'><label for='specificmonth'>Specific:</label></span></td></tr><span id='RecurMonthDay'> From <input name='FirstDay' type='text' value='1' maxlength='255' id='FirstDay' title='First day in the month that this task starts' class='ms-input' size='2'>to<input name='LastDay' type='text' maxlength='255' id='LastDay' title='The last day in the month for to complete this task' class='ms-input' size='2' value='15'></span></div></div></div></form></div></div>",
                title: selectedPermitName,
                buttons: {
                    danger: {
                        label: "Add",
                        className: "btn-info pull-right",
                        callback: function () {
                            addnewtasktoprogram();
                            createtasks(0);
                            filterchange();

                            var searchvalue = $("#20_form_control_Month").val();

                            if (searchvalue != "") {
                                filterdata(searchvalue);
                            }

                            scrolltoprogram(selectedPermit);
                        }
                    },
                    cancel: {
                        label: "Cancel",
                        className: 'btn-danger',
                        callback: function () {
                            //Example.show('Custom cancel clicked');
                        }
                    }
                },
                closeButton: false,
                size: "medium",
                init: function () {
                    $("[name='taskduedate']").datepicker({
                        //rtl: Metronic.isRTL(),
                        //orientation: "right",
                        autoclose: true,
                        forceParse: false,
                        todayHighlight: true,
                        assumeNearbyYear: true,
                        todayBtn: true,
                        clearBtn: true
                    });

                    var addtaskname = programownertasks[tasknumber]["Name"];
                    var addduration = programownertasks[tasknumber]["Duration"];
                    var adddescription = programownertasks[tasknumber]["Description"];
                    var addresponsible = programownertasks[tasknumber]["Responsible"];

                    $('#boxaddtaskname').val(addtaskname);
                    $('#boxaddduration').val(addduration);
                    $('#boxadddescription').val(adddescription);
                    $('#boxaddresponsible').val(addresponsible);

                    showrecurrentfields();
                }
            });

            if (GetData.localStorage('SubClassification').includes("ESH")) {
                ////////////////////Add Task Fields
                $('#boxaddtaskname').removeAttr("readonly");
                $('#boxaddstartdate').removeAttr("readonly");
                $('#boxaddenddate').removeAttr("readonly");
                $('#boxaddduration').removeAttr("readonly");
                $('#boxadddescription').removeAttr("readonly");
                $('#boxaddresponsible').removeAttr("disabled");

            }
        }
    } else {

        selectedPermitName = programinfo[indexofelement]["Name"] + " - New Tasks";

        isRecurrent = false;

        //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        var year = GetData.localStorage('Season');

        handleAlerts.CustomDialog({
            destroy: true,
            message: "<div class='container'><div class='col-lg-9'>" + "<form class='form-horizontal' action='' id='tasksform'><div class='col-lg-6'><div class='form-group'> <label class='control-label col-sm-4' for='boxaddtaskname'>" + Functions.LanguageSelect("Tareas:", "Task:") + ":</label>" + "<div class='col-sm-8'> <input type='text' readonly class='form-control accessLevel_Admin' id='boxaddtaskname' placeholder='" + Functions.LanguageSelect("Entre el nombre de la tarea", "Enter task name") + "'></div></div><div class='form-group'>" + " <label class='control-label col-sm-4' for='boxaddresponsible'>" + Functions.LanguageSelect("Responsable:", "Responsible:") + "</label><div class='col-sm-8'> <select disabled='true' class='form-control accessLevel_Admin' id='boxaddresponsible'>" + inspectorList + "</select>" + "</div></div><div class='form-group'> <label class='control-label col-sm-4' for='boxaddstartdate'>" + Functions.LanguageSelect("Fecha de Comienzo:", "Start Date:") + "</label><div class='col-sm-8'>" + " <input type='date' readonly class='form-control accessLevel_Admin' id='boxaddstartdate' placeholder='" + Functions.LanguageSelect("Entre la fecha de comienzo", "Enter Start Date") + "'></div></div><div class='form-group'>" + " <label class='control-label col-sm-4' for='boxaddenddate'>" + Functions.LanguageSelect("Fecha de Terminación:", "End Date:") + "</label><div class='col-sm-8'> <input type='date' readonly class='form-control accessLevel_Admin' id='boxaddenddate' placeholder='" + Functions.LanguageSelect("Entre la fecha de terminación", "Enter End Date") + "'>" + "</div></div><div class='form-group'> <label class='control-label col-sm-4' for='boxaddduration'>" + Functions.LanguageSelect("Duración:", "Duration:") + "</label><div class='col-sm-8'>" + " <input type='text' readonly class='form-control accessLevel_Admin' id='boxaddduration' placeholder='" + Functions.LanguageSelect("Entre la duración de la tarea", "Enter Task Duration") + "'></div></div><div class='form-group'> <label class='control-label col-sm-4' for='boxadddescription'>" + Functions.LanguageSelect("Descripción:", "Description:") + "</label><div class='col-sm-8'>" + "<textarea readonly rows='7' class='form-control accessLevel_Admin' id='boxadddescription' notes='" + Functions.LanguageSelect("entre la descripción de la tarea", "Enter Task Description") + "'></textarea></div></div>" + "<div class='form-group md-checkbox-list'><div class='checkboxList'>" + "<div class='md-checkbox'> <input type='checkbox' data-itype='Check' id='checkbox-State' data-saving='undefined' name='Recurrente' data-formula=' ' class='md-check form-field' onclick='showrecurrentfields()'> <label for='checkbox-State'><span class='inc'></span><span class='check'></span><span class='box'></span>" + Functions.LanguageSelect("Recurrente", "Recurrent") + "</label></div></div></div><div id='recurrentfields' class='hidden'><div><tr><td> <span class='' title='Recurrence Type: Weekly'><input id='weekly' type='radio' name='recurrencetype' value='1' onclick='RecurPatternType_ShowRecurType(this.id);'><label for='weekly'>Weekly</label></span></td></tr><tr><td> <span class='' title='Recurrence Type: Monthly'><input id='monthly' type='radio' name='recurrencetype' value='2' onclick='RecurPatternType_ShowRecurType(this.id);'><label for='monthly'>Monthly</label></span></td></tr></div><div id='monthlyfields' class='hidden'><tr><td> <span class='' title='Whole Month'><input id='wholemonth' type='radio' name='recurrentmonthtype' value='1' onclick='monthtypevalues(this.id);' style='margin-left:38px;' ><label for='wholemonth'>Whole Month</label></span></td></tr><tr><td> <span class='' title='Specific'><input id='specificmonth' style='margin-left:38px;' type='radio' name='recurrentmonthtype' value='2' onclick='monthtypevalues(this.id);'><label for='specificmonth'>Specific:</label></span></td></tr><span id='RecurMonthDay'> From <input name='FirstDay' type='text' value='1' maxlength='255' id='FirstDay' title='First day in the month that this task starts' class='ms-input' size='2'>to<input name='LastDay' type='text' maxlength='255' id='LastDay' title='The last day in the month for to complete this task' class='ms-input' size='2' value='15'></span></div></div></div></form></div></div>",
            title: selectedPermitName,
            buttons: {
                danger: {
                    label: "Add",
                    className: "btn-info pull-right",
                    callback: function () {
                        addnewtasktoprogram();
                        createtasks(0);
                        filterchange();

                        var searchvalue = $("#20_form_control_Month").val();

                        if (searchvalue != "") {
                            filterdata(searchvalue);
                        }

                        scrolltoprogram(selectedPermit);
                    }
                },
                cancel: {
                    label: "Cancel",
                    className: 'btn-danger',
                    callback: function () {
                        //Example.show('Custom cancel clicked');
                    }
                }
            },
            closeButton: false,
            size: "medium",
            init: function () {
                $("[name='taskduedate']").datepicker({
                    //rtl: Metronic.isRTL(),
                    //orientation: "right",
                    autoclose: true,
                    forceParse: false,
                    todayHighlight: true,
                    assumeNearbyYear: true,
                    todayBtn: true,
                    clearBtn: true
                });
            }
        });


        if (GetData.localStorage('SubClassification').includes("ESH")) {
            ////////////////////Add Task Fields
            $('#boxaddtaskname').removeAttr("readonly");
            $('#boxaddstartdate').removeAttr("readonly");
            $('#boxaddenddate').removeAttr("readonly");
            $('#boxaddduration').removeAttr("readonly");
            $('#boxadddescription').removeAttr("readonly");
            $('#boxaddresponsible').removeAttr("disabled");

        }
    }
    ///////////////////////////////////////////////////////////////

    $('#boxtaskname').change(function () {

        if ($('#boxtaskname').val() != "") {
            programownertasks[selectedtask]["Name"] = $('#boxtaskname').val();
            savechanges(programownertasks[selectedtask]["id_Permit"], "Name", $('#boxtaskname').val());
        }
    });

    $('#boxresponsible').change(function () {
        programownertasks[selectedtask]["Responsible"] = $('#boxresponsible').val();
        savechanges(programownertasks[selectedtask]["id_Permit"], "Responsible", $('#boxresponsible').val());
    });

    $('#boxdescription').change(function () {
        programownertasks[selectedtask]["Description"] = $('#boxdescription').val();
        savechanges(programownertasks[selectedtask]["id_Permit"], "Description", $('#boxdescription').val());
    });

    $('#boxstatus').change(function () {
        programownertasks[selectedtask]["Status"] = $('#boxstatus').val();
        savechanges(programownertasks[selectedtask]["id_Permit"], "Status", $('#boxstatus').val());

        if ($('#boxstatus').val() == "statuscompleted" || $('#boxstatus').val() == "statusna") {
            $('#p100').attr('selected', 'selected');
            programownertasks[selectedtask]["Percent"] = $('#boxpercent').val();
            savechanges(programownertasks[selectedtask]["id_Permit"], "Percent", $('#boxpercent').val());

            var today = new Date();
            $('#boxentrydate').val(formatdatetoyyyymmdd(today));
            programownertasks[selectedtask]["EntryDate"] = $('#boxentrydate').val();
            savechanges(programownertasks[selectedtask]["id_Permit"], "EntryDate", $('#boxentrydate').val());
        } else if ($('#boxstatus').val() == "statusinprogress" && $('#boxpercent').val() == '100') {

            $('#p75').attr('selected', 'selected');
            programownertasks[selectedtask]["Percent"] = $('#boxpercent').val();
            savechanges(programownertasks[selectedtask]["id_Permit"], "Percent", $('#boxpercent').val());

            $('#boxentrydate').val(null);
            programownertasks[selectedtask]["EntryDate"] = $('#boxentrydate').val();
            savechanges(programownertasks[selectedtask]["id_Permit"], "EntryDate", $('#boxentrydate').val());
        } else if ($('#boxstatus').val() == "statusnotstarted") {

            $('#p0').attr('selected', 'selected');
            programownertasks[selectedtask]["Percent"] = $('#boxpercent').val();
            savechanges(programownertasks[selectedtask]["id_Permit"], "Percent", $('#boxpercent').val());

            $('#boxentrydate').val(null);
            programownertasks[selectedtask]["EntryDate"] = $('#boxentrydate').val();
            savechanges(programownertasks[selectedtask]["id_Permit"], "EntryDate", $('#boxentrydate').val());
        }
    });

    $('#boxpercent').change(function () {
        programownertasks[selectedtask]["Percent"] = $('#boxpercent').val();
        savechanges(programownertasks[selectedtask]["id_Permit"], "Percent", $('#boxpercent').val());

        if ($('#boxpercent').val() != '100' && $('#boxstatus').val() == "statuscompleted" && $('#boxpercent').val() != '0') {

            $('#statusinprogress').attr('selected', 'selected');
            programownertasks[selectedtask]["Status"] = $('#boxstatus').val();
            savechanges(programownertasks[selectedtask]["id_Permit"], "Status", $('#boxstatus').val());

            $('#boxentrydate').val(null);
            programownertasks[selectedtask]["EntryDate"] = $('#boxentrydate').val();
            savechanges(programownertasks[selectedtask]["id_Permit"], "EntryDate", $('#boxentrydate').val());

        } else if ($('#boxpercent').val() == '100') {
            $('#statuscompleted').attr('selected', 'selected');
            programownertasks[selectedtask]["Status"] = $('#boxstatus').val();
            savechanges(programownertasks[selectedtask]["id_Permit"], "Status", $('#boxstatus').val());

            var today = new Date();
            $('#boxentrydate').val(formatdatetoyyyymmdd(today));
            programownertasks[selectedtask]["EntryDate"] = $('#boxentrydate').val();
            savechanges(programownertasks[selectedtask]["id_Permit"], "EntryDate", $('#boxentrydate').val());
        } else if ($('#boxpercent').val() == '0') {
            $('#statusnotstarted').attr('selected', 'selected');
            programownertasks[selectedtask]["Status"] = $('#boxstatus').val();
            savechanges(programownertasks[selectedtask]["id_Permit"], "Status", $('#boxstatus').val());

            var today = new Date();
            $('#boxentrydate').val(null);
            programownertasks[selectedtask]["EntryDate"] = $('#boxentrydate').val();
            savechanges(programownertasks[selectedtask]["id_Permit"], "EntryDate", $('#boxentrydate').val());
        }
    });


    $('#boxnotes').change(function () {
        programownertasks[selectedtask]["Notes"] = $('#boxnotes').val();
        savechanges(programownertasks[selectedtask]["id_Permit"], "Notes", $('#boxnotes').val());
    });

    $("#boxstartdate").change(function () {

        if ($('#boxstartdate').val() != "" && $('#boxstartdate').val() != "NaN") {
            programownertasks[selectedtask]["StartDate"] = $('#boxstartdate').val();
            $('#boxduration').val(getdaysbetweendates($('#boxstartdate').val(), $('#boxenddate').val()));
            programownertasks[selectedtask]["Duration"] = $('#boxduration').val();

            savechanges(programownertasks[selectedtask]["id_Permit"], "StartDate", $('#boxstartdate').val());
            savechanges(programownertasks[selectedtask]["id_Permit"], "Duration", $('#boxduration').val());
        }
    });


    $("#boxenddate").change(function () {
        if ($('#boxenddate').val() != "" && $('#boxenddate').val() != "NaN") {
            programownertasks[selectedtask]["EndDate"] = $('#boxenddate').val();
            $('#boxduration').val(getdaysbetweendates($('#boxstartdate').val(), $('#boxenddate').val()));
            programownertasks[selectedtask]["Duration"] = $('#boxduration').val();

            savechanges(programownertasks[selectedtask]["id_Permit"], "EndDate", $('#boxenddate').val());
            savechanges(programownertasks[selectedtask]["id_Permit"], "Duration", $('#boxduration').val());
        }
    });

    $("#boxcompleteddate").change(function () {
        programownertasks[selectedtask]["CompletedDate"] = $('#boxcompleteddate').val();
        savechanges(programownertasks[selectedtask]["id_Permit"], "CompletedDate", $('#boxcompleteddate').val());
    });

    $("#boxduration").change(function () {
        programownertasks[selectedtask]["Duration"] = $('#boxduration').val();

        if ($('#boxstartdate').val() != "" && $('#boxenddate').val() == "") {
            var calculateddate = datefromduration($('#boxstartdate').val(), "add", $('#boxduration').val());
            $('#boxenddate').val(formatdatetoyyyymmdd(calculateddate));
            programownertasks[selectedtask]["EndDate"] = $('#boxenddate').val();
        } else if ($('#boxenddate').val() != "") {
            var calculateddate = datefromduration($('#boxenddate').val(), "subtract", $('#boxduration').val());
            $('#boxstartdate').val(formatdatetoyyyymmdd(calculateddate));
            programownertasks[selectedtask]["StartDate"] = $('#boxstartdate').val();
        }
        savechanges(programownertasks[selectedtask]["id_Permit"], "Duration", $('#boxduration').val());
        savechanges(programownertasks[selectedtask]["id_Permit"], "StartDate", $('#boxstartdate').val());
        savechanges(programownertasks[selectedtask]["id_Permit"], "EndDate", $('#boxenddate').val());
    });
}

function RecurPatternType_ShowRecurType(id) {
    switch (id) {
        case "weekly":
            $("#monthlyfields").addClass("hidden");
            addingrecurrenttype = "weekly";
            addingmonthlytype = "";
            break;
        case "monthly":
            $("#monthlyfields").removeClass("hidden");
            addingrecurrenttype = "monthly";
            addingmonthlytype = "wholemonth";
            break;
        default:
            $("#monthlyfields").removeClass("hidden");
            addingrecurrenttype = "monthly";
            addingmonthlytype = "wholemonth";
    }
}

function monthtypevalues(valuetype) {
    addingmonthlytype = valuetype;
}

function scrolltoprogram(selectedprogramid) {
    $('html, body').animate({
        scrollTop: $('#' + selectedprogramid).offset().top - 160
    });
}
/////////////////////////////////////////////////////////////////////////////add new tasks

function deleteTask(tasktodelete) {
    var istaskrecurrent = GetData.SqlValue("select * from OS_Permits where Permit_ID in (select Permit_ID from OS_Permits where id_Permit = '" + tasktodelete + "') and Name = (select Name from OS_Permits where id_Permit = '" + tasktodelete + "')");

    if (istaskrecurrent.length > 1) {
        handleAlerts.CustomDialog({
            destroy: true,
            message: "<p>" + Functions.LanguageSelect("Esta tarea es recurrente, selecciones si quiere borrar esta tarea solamente o todas la serie", "The task is recurrent, select if you want to delete this single task or the whole serie") + "</p>",

            title: "Delete Task",

            buttons: {
                danger: {
                    label: "Delete Ocurrence",
                    className: "btn-danger pull-right",
                    callback: function () {

                        //var searchvalue = $("#20_form_control_Month").val();
                        //alert("Delete Ocurrence:" + tasktodelete);

                        deletingTaskFromDB(tasktodelete, istaskrecurrent[0]["Status"], istaskrecurrent[0]["Notes"], istaskrecurrent[0]["Percent"]);
                        bootbox.hideAll();
                    }
                },
                deleteSeries: {
                    label: "Delete Series",
                    className: 'btn-danger pull-right',
                    callback: function () {
                        //Example.show('Custom cancel clicked');

                        for (var i = 0; i < istaskrecurrent.length; i++) {

                            //alert("Delete Series:" + istaskrecurrent[i]["id_Permit"]);
                            deletingTaskFromDB(istaskrecurrent[i]["id_Permit"], istaskrecurrent[i]["Status"], istaskrecurrent[i]["Notes"], istaskrecurrent[i]["Percent"]);
                        }

                        //alert("Delete Ocurrence:" + tasktodelete);
                        bootbox.hideAll();
                    }
                },
                cancel: {
                    label: "Cancel",
                    className: 'btn-info',
                    callback: function () {
                        //Example.show('Custom cancel clicked');
                        //
                    }
                }

            },
            closeButton: false,
            size: "medium",
            init: function () {
                //                    $("[name='taskduedate']").datepicker({
                //                        //rtl: Metronic.isRTL(),
                //                        //orientation: "right",
                //                        autoclose: true,
                //                        forceParse: false,
                //                        todayHighlight: true,
                //                        assumeNearbyYear: true,
                //                        todayBtn: true,
                //                        clearBtn: true
                //                    });
            }
        });
    } else {
        alert("Just Delete Selected");

        deletingTaskFromDB(tasktodelete, istaskrecurrent[0]["Status"], istaskrecurrent[0]["Notes"], istaskrecurrent[0]["Percent"]);
        bootbox.hideAll();
    }
}

function deletingTaskFromDB(taskid, taskstatus, tasknotes, taskpercent) {
    // if($('#boxstatus').val()== "statusnotstarted" && $('#boxnotes').val()=="" && $('#boxpercent').val()=="0"){
    if (taskstatus == "statusnotstarted" && tasknotes == "" && taskpercent == "0") {

        //alert("delete");
        var deletemessage = Functions.LanguageSelect("La tarea fue borrada exitosamente", "The task was deleted successfuly");
        Functions.SendSP('sp_OS_Permits_Delete', taskid, function () {
            handleAlerts.Simple(deletemessage);
        });

        bootbox.hideAll();

        createtasks(0);
        filterchange();

        var searchvalue = $("#20_form_control_Month").val();

        if (searchvalue != "") {
            filterdata(searchvalue);
        }

        scrolltoprogram(selectedPermit);
    } else {
        var deletealert = Functions.LanguageSelect("Can\'t delete task because there's information in the notes, the percent is not 0% or the status is not set to not started", "No se puede borrar esta tarea porque hay información en las notas, el porciento no es 0% o el estatus no esta en No Empezado");
        alert(deletealert);
    }
}

function addyeartodate(taskdate) {
    var originaldate = new Date(taskdate);
    var copydate = new Date(originaldate);
    copydate.setDate(originaldate.getDate() + 365);

    copydate = formatdatetoyyyymmdd(copydate)

    return copydate
}

function copyAllToNewYear() {

    bootbox.confirm(Functions.LanguageSelect("Desea copiar todas las tareas del año pasado en este nuevo a año?", "Do you want to copy all the tasks from last year?"), function (result) {

        if (result == true) {
            var yeartocopy = GetData.localStorage('Season') - 1;

            var copyprogramownertasks = GetData.SqlValue("SELECT *,CASE WHEN [percent] <> 100 and enddate < DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE()),0)) and StartDate <> '' and enddate <> '' THEN 'Overdue' WHEN [percent] <> 100 and startdate < DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE())(PLUS)1,0)) THEN 'Current' WHEN [percent] = 100 THEN 'Completed' ELSE 'NoTask' END as SFC FROM OS_Permits where Permit_ID in (SELECT id_Catalog FROM OS_Catalog WHERE Category = 18) and StartDate BETWEEN '" + yeartocopy + "-01-01' AND '" + yeartocopy + "-12-31' ORDER BY Permit_ID,enddate");

            var copyprogramid;
            var copypermitname;
            var copyresponsible;
            var copydescription;
            var copystartdate;
            var copyenddate;
            var copyduration;
            var copynotes;

            for (var i = 0; i < copyprogramownertasks.length; i++) {
                copyprogramid = copyprogramownertasks[i]["Permit_ID"];
                copypermitname = copyprogramownertasks[i]["Name"];
                copyresponsible = copyprogramownertasks[i]["Responsible"];
                copydescription = copyprogramownertasks[i]["Description"];

                copystartdate = copyprogramownertasks[i]["StartDate"];
                copystartdate = addyeartodate(copystartdate);

                copyenddate = copyprogramownertasks[i]["EndDate"];
                copyenddate = addyeartodate(copyenddate);

                copyduration = copyprogramownertasks[i]["Duration"];

                copynotes = copyprogramownertasks[i]["Notes"];

                console.log("Permit_ID" + copyprogramid + "Name" + copypermitname + "Responsible" + copyresponsible + "Description" + copydescription + "StartDate" + copystartdate + "EndDate" + copyenddate + "Duration" + copyduration)

                //Push new value to array

                programownertasks.push({
                    "id_Permit": 0,
                    "Permit_ID": copyprogramid,
                    "Name": "New Task",
                    "StartDate": "",
                    "EndDate": "",
                    "Duration": 0,
                    "Dependency": -1,
                    "Description": "",
                    "Status": "statusnotstarted",
                    "Percent": 0,
                    "Notes": "",
                    "Responsible": -1,
                    "URLs": ""
                });

                selectedtask = programownertasks.length - 1;

                console.log("programownertasks[selectedtask][id_Permit]:" + programownertasks[selectedtask]["id_Permit"]);
                //console.log("Permit_ID:" + copyprogramid);

                selectedPermit = copyprogramid;

                //save taskname
                programownertasks[selectedtask]["Name"] = copypermitname;
                savechanges(programownertasks[selectedtask]["id_Permit"], "Name", copypermitname);

                //save responsible
                programownertasks[selectedtask]["Responsible"] = copyresponsible;
                savechanges(programownertasks[selectedtask]["id_Permit"], "Responsible", copyresponsible);

                //save description
                programownertasks[selectedtask]["Description"] = copydescription;
                savechanges(programownertasks[selectedtask]["id_Permit"], "Description", copydescription);

                programownertasks[selectedtask]["StartDate"] = copystartdate;
                savechanges(programownertasks[selectedtask]["id_Permit"], "StartDate", copystartdate);

                //save enddate
                programownertasks[selectedtask]["EndDate"] = copyenddate;
                savechanges(programownertasks[selectedtask]["id_Permit"], "EndDate", copyenddate);

                //save duration
                programownertasks[selectedtask]["Duration"] = getdaysbetweendates(copystartdate, copyenddate);
                savechanges(programownertasks[selectedtask]["id_Permit"], "Duration", getdaysbetweendates(copystartdate, copyenddate));

                //save notes
                programownertasks[selectedtask]["Notes"] = copynotes;
                savechanges(programownertasks[selectedtask]["id_Permit"], "Notes", copynotes);

            }
        }
    });
}

function addnewtasktoprogramSaveFields(startingdate, endingdate) {
    startingdate = formatdatetoyyyymmdd(startingdate);
    endingdate = formatdatetoyyyymmdd(endingdate);

    //Push new value to array
    programownertasks.push({
        "id_Permit": 0,
        "Permit_ID": selectedPermit,
        "Name": "New Task",
        "StartDate": "",
        "EndDate": "",
        "Duration": 0,
        "Dependency": -1,
        "Description": "",
        "Status": "statusnotstarted",
        "Percent": 0,
        "Notes": "",
        "Responsible": -1,
        "URLs": ""
    });

    selectedtask = programownertasks.length - 1;

    //save taskname
    programownertasks[selectedtask]["Name"] = $('#boxaddtaskname').val();
    savechanges(programownertasks[selectedtask]["id_Permit"], "Name", $('#boxaddtaskname').val());

    //save responsible
    programownertasks[selectedtask]["Responsible"] = $('#boxaddresponsible').val();
    savechanges(programownertasks[selectedtask]["id_Permit"], "Responsible", $('#boxaddresponsible').val());

    //save description
    programownertasks[selectedtask]["Description"] = $('#boxadddescription').val();
    savechanges(programownertasks[selectedtask]["id_Permit"], "Description", $('#boxadddescription').val());

    programownertasks[selectedtask]["StartDate"] = startingdate;
    savechanges(programownertasks[selectedtask]["id_Permit"], "StartDate", startingdate);

    //save enddate
    programownertasks[selectedtask]["EndDate"] = endingdate;
    savechanges(programownertasks[selectedtask]["id_Permit"], "EndDate", endingdate);

    //save duration
    $('#boxaddduration').val(getdaysbetweendates(startingdate, endingdate));
    programownertasks[selectedtask]["Duration"] = $('#boxaddduration').val();
    savechanges(programownertasks[selectedtask]["id_Permit"], "Duration", $('#boxaddduration').val());

}

function addnewtasktoprogram() {

    if (($('#boxaddstartdate').val() != "" && $('#boxaddstartdate').val() != "NaN") && ($('#boxaddenddate').val() != "" && $('#boxaddenddate').val() != "NaN") && $('#boxaddtaskname').val() != "") {
        //alert("Save");

        var fromDate = new Date(localizeDateStr($('#boxaddstartdate').val()));
        var toDate = new Date(localizeDateStr($('#boxaddenddate').val()));

        var savingstartdate;
        var savingenddate;

        var calculatedDate = 0;
        var fixdayschange = 0;
        var wholemonthnumber = 0;
        var lastwholemonthrecurrent = diff_months(fromDate, toDate);
        var calculatedrecurrentmonth = 0;
        var nextmonthstart;
        var mmnumber;
        var mm;
        var yyyy;
        var mm2;
        var yyyy2;

        var ddstart = $('#FirstDay').val();
        if (ddstart < 10) {
            ddstart = '0' + ddstart;
        }

        var ddend = $('#LastDay').val();
        if (ddend < 10) {
            ddend = '0' + ddend;
        }

        var specificstartday = '-' + ddstart;
        var specificendday = '-' + ddend;

        savingstartdate = new Date(localizeDateStr($('#boxaddstartdate').val()));

        if (isRecurrent == true) {
            switch (addingrecurrenttype) {
                case "weekly":
                    do {
                        calculatedDate = new Date(savingstartdate);
                        calculatedDate.setDate(calculatedDate.getDate() + 6);
                        savingenddate = new Date(calculatedDate);

                        if (savingenddate > toDate) {
                            savingenddate = toDate;
                        }

                        addnewtasktoprogramSaveFields(savingstartdate, savingenddate);

                        calculatedDate = new Date(savingenddate);
                        calculatedDate.setDate(calculatedDate.getDate() + 1);
                        savingstartdate = new Date(calculatedDate);
                    } while (savingstartdate <= toDate);
                    break;
                case "monthly":
                    switch (addingmonthlytype) {
                        case "wholemonth":
                            do {
                                mm = savingstartdate.getMonth() + 1; //January is 0!
                                yyyy = savingstartdate.getFullYear();
                                if (mm < 10) {
                                    mm = '0' + mm
                                }
                                savingstartdate = yyyy + '-' + mm + '-01';
                                savingstartdate = new Date(localizeDateStr(savingstartdate));
                                savingenddate = savingstartdate;

                                mm2 = savingenddate.getMonth() + 2;
                                if (mm2 > 12) {
                                    mm2 = 1;
                                    yyyy2 = savingenddate.getFullYear() + 1;
                                } else {
                                    yyyy2 = savingenddate.getFullYear();
                                }

                                if (mm2 < 10) {
                                    mm2 = '0' + mm2
                                }
                                nextmonthstart = yyyy2 + '-' + mm2 + '-01';
                                savingenddate = new Date(localizeDateStr(nextmonthstart));
                                savingenddate.setDate(savingenddate.getDate() - 1);

                                addnewtasktoprogramSaveFields(savingstartdate, savingenddate);

                                savingstartdate = new Date(localizeDateStr(nextmonthstart));

                                wholemonthnumber = wholemonthnumber + 1;
                            } while (wholemonthnumber < lastwholemonthrecurrent);
                            break;
                        case "specificmonth":
                            do {
                                mmnumber = savingstartdate.getMonth() + 1; //January is 0!
                                yyyy = savingstartdate.getFullYear();
                                if (mmnumber < 10) {
                                    mm = '0' + mmnumber;
                                } else {
                                    mm = mmnumber;
                                }

                                savingstartdate = yyyy + '-' + mm + specificstartday;
                                savingstartdate = new Date(localizeDateStr(savingstartdate));

                                if (mmnumber < 10) {
                                    mm = '0' + mmnumber;
                                } else {
                                    mm = mmnumber;
                                }

                                savingenddate = yyyy + '-' + mm + specificendday;
                                savingenddate = new Date(localizeDateStr(savingenddate));

                                addnewtasktoprogramSaveFields(savingstartdate, savingenddate);

                                mmnumber = mmnumber + 1;

                                if (mmnumber > 12) {
                                    mmnumber = 1;
                                    yyyy = savingstartdate.getFullYear() + 1;
                                } else {
                                    yyyy = savingstartdate.getFullYear();
                                }

                                if (mmnumber < 10) {
                                    mm = '0' + mmnumber;
                                } else {
                                    mm = mmnumber;
                                }

                                nextmonthstart = yyyy + '-' + mm + '-01';
                                savingstartdate = new Date(localizeDateStr(nextmonthstart));

                                wholemonthnumber = wholemonthnumber + 1;

                            } while (wholemonthnumber < lastwholemonthrecurrent);

                            break;
                    }
                    break;
            }
        } else {
            addnewtasktoprogramSaveFields(fromDate, toDate);
        }

    }

}

function showrecurrentfields() {
    if ($('#recurrentfields').hasClass('hidden')) {
        $('#recurrentfields').removeClass('hidden');
        $("#monthlyfields").removeClass("hidden");

        $("#monthly").prop("checked", true);
        $("#wholemonth").prop("checked", true);
        isRecurrent = true;

        addingrecurrenttype = "monthly";
        addingmonthlytype = "wholemonth";
    } else {
        $('#recurrentfields').addClass('hidden');
        $("#monthlyfields").addClass("hidden");
        isRecurrent = false;

        addingrecurrenttype = "";
        addingmonthlytype = "";
    }

}

///////////////////////////////////////////////////////////////////////////dates function
function diff_months(dt2, dt1) {
    var diff = (dt2.getTime() - dt1.getTime()) / 1000;
    diff /= (60 * 60 * 24 * 7 * 4);
    return Math.abs(Math.round(diff));
}

function localizeDateStr(date_to_convert_str) {
    var date_to_convert = new Date(date_to_convert_str);
    var local_date = new Date();
    date_to_convert.setHours(date_to_convert.getHours() + (local_date.getTimezoneOffset() / 60));
    return date_to_convert;
}

function datefromduration(calcDate, operandtype, dayschange) {

    var fixdayschange;
    var calculatedDate = new Date(calcDate);

    switch (operandtype) {
        case "add":
            fixdayschange = parseInt(dayschange);
            calculatedDate.setDate(calculatedDate.getDate() + fixdayschange);
            break;
        case "subtract":
            fixdayschange = parseInt(dayschange) - 2;
            calculatedDate.setDate(calculatedDate.getDate() - fixdayschange);
            break;
        default:
            fixdayschange = parseInt(dayschange);
            calculatedDate.setDate(calculatedDate.getDate() + fixdayschange);
            break;
    }

    var nd = new Date(calculatedDate);

    return nd;
}

function formatdatetoyyyymmdd(datetoformat) {
    formatteddate = new Date(localizeDateStr(datetoformat));
    var dd = formatteddate.getDate();
    var mm = formatteddate.getMonth() + 1; //January is 0!
    var yyyy = formatteddate.getFullYear();
    if (dd < 10) {
        dd = '0' + dd
    }
    if (mm < 10) {
        mm = '0' + mm
    }
    formatteddate = yyyy + '-' + mm + '-' + dd;

    return formatteddate;
}

function getdaysbetweendates(start, end) {
    fromDate = new Date(start);
    toDate = new Date(end);
    diff = new Date(toDate - fromDate);
    daysleft = Math.ceil(diff / 1000 / 60 / 60 / 24);
    return daysleft + 1;
}
/////////////////////////////////////////////////////////////////////////dates
function savechanges(id, question, answer) {

    console.log("selectedPermit:" + selectedPermit);

    var permId = id;
    if (permId == 0) {
        $.ajax({
            type: "POST",
            data: "StringJSON=#sp_OS_Permits_Insert|" + selectedPermit + "^New Task^^^0^-1^^statusnotstarted^0^^-1^",
            dataType: "xml",
            async: false,
            url: DUrl + "WebServiceOsiris.asmx/Get_Tables2",
            success: function (retData) {

                var data = $(retData).find('string').first().text();
                if (data != '[]') {
                    permId = JSON.parse(data)[0]["Identity"];
                    programownertasks[selectedtask]["id_Permit"] = permId;
                }
            },
            error: function (a, b, c) {
                if (GetData.localStorage("onScreenError") == "true") {
                    handleAlerts.Simple(a.responseText);
                } else {
                    console.log(a.responseText);
                }
            }
        });
    }

    $.ajax({
        type: "POST",
        data: "StringJSON=#sp_OS_Permits_Update|" + permId + "^" + question + "^" + answer + "^" + GetData.localStorage("EmpName"),
        dataType: "xml",
        async: false,
        url: DUrl + "WebServiceOsiris.asmx/Get_Tables2",
        success: function (retData) {},
        error: function (a, b, c) {
            if (GetData.localStorage("onScreenError") == "true") {
                handleAlerts.Simple(a.responseText);
            } else {
                console.log(a.responseText);
            }
        }
    });
}

function bootboxlistselection(i) {

    var taskname;
    var startdate;
    var enddate;
    var entrydate;
    var completeddate;
    var duration;
    var dependency;
    var description;
    var status;
    var percent;
    var notes;
    var responsible;
    var documenturl;

    taskname = programownertasks[i]["Name"];
    duration = programownertasks[i]["Duration"];
    description = programownertasks[i]["Description"];
    status = programownertasks[i]["Status"];
    percent = programownertasks[i]["Percent"];
    notes = programownertasks[i]["Notes"];
    responsible = programownertasks[i]["Responsible"];
    documenturl = programownertasks[i]["URLs"];

    status = programownertasks[i]["Status"];

    $('#' + status).attr('selected', 'selected');
    $('#p' + percent).attr('selected', 'selected');

    startdate = formatdatetoyyyymmdd(programownertasks[i]["StartDate"]);
    enddate = formatdatetoyyyymmdd(programownertasks[i]["EndDate"]);

    entrydate = null;
    if (programownertasks[i]["EntryDate"]) {
        entrydate = formatdatetoyyyymmdd(programownertasks[i]["EntryDate"]);
    }

    completeddate = null;
    if (programownertasks[i]["CompletedDate"]) {
        completeddate = formatdatetoyyyymmdd(programownertasks[i]["CompletedDate"]);
    }

    $('#boxtaskname').val(taskname);
    $('#boxstartdate').val(startdate);
    $('#boxenddate').val(enddate);
    $('#boxcompleteddate').val(completeddate);
    $('#boxentrydate').val(entrydate);
    $('#boxduration').val(duration);
    $('#boxdescription').val(description);
    $('#boxnotes').val(notes);
    $('#boxresponsible').val(responsible);


    if (GetData.localStorage('SubClassification').includes("ESH")) {
        $('#boxtaskname').removeAttr("readonly");
        $('#boxstartdate').removeAttr("readonly");
        $('#boxenddate').removeAttr("readonly");
        $('#boxduration').removeAttr("readonly");
        $('#boxdescription').removeAttr("readonly");
        $('#boxnotes').removeAttr("readonly");

        $('#boxresponsible').removeAttr("disabled");
        $('#boxstatus').removeAttr("disabled");
        $('#boxpercent').removeAttr("disabled");
        $('#boxcompleteddate').removeAttr("disabled");

        $("#btnaddnewtasks").show();
        //$("#copyalltasks").show();

        ////////////////////Add Task Fields
        $('#boxaddtaskname').removeAttr("readonly");
        $('#boxaddstartdate').removeAttr("readonly");
        $('#boxaddenddate').removeAttr("readonly");
        $('#boxaddduration').removeAttr("readonly");
        $('#boxadddescription').removeAttr("readonly");
        $('#boxaddresponsible').removeAttr("disabled");

    } else if (GetData.localStorage('EmpName') == $("#boxresponsible option:selected").text()) {
        $('#boxstatus').removeAttr("disabled");
        $('#boxpercent').removeAttr("disabled");
        $('#boxcompleteddate').removeAttr("disabled"); //////////////
        $('#boxnotes').removeAttr("readonly");

        $("#btnaddnewtasks").hide();
        $("#copyalltasks").hide();

    }

    selectedtask = i;
}

function filterchange(filterstate) {
    switch (filterstate) {
        case "Current":

            if (!$("#checkbox-Current").is(':checked')) {
                $('#checkbox-All').removeAttr('checked');
            }
            break;

        case "Overdue":

            if (!$("#checkbox-Overdue").is(':checked')) {
                $('#checkbox-All').removeAttr('checked');
            }
            break;

        case "Completed":

            if (!$("#checkbox-Completed").is(':checked')) {
                $('#checkbox-All').removeAttr('checked');
            }
            break;

        case "NoTasks":

            if (!$("#checkbox-NoTasks").is(':checked')) {
                $('#checkbox-All').removeAttr('checked');
            }
            break;

        case "All":

            if ($("#checkbox-All").is(':checked')) {

                //check all checkbox
                $('#checkbox-Current').attr('checked', 'checked');
                $('#checkbox-Overdue').attr('checked', 'checked');
                $('#checkbox-Completed').attr('checked', 'checked');
                $('#checkbox-NoTasks').attr('checked', 'checked');
            } else {

                //remove all check
                $('#checkbox-Completed').removeAttr('checked');
                $('#checkbox-NoTasks').removeAttr('checked');
            }
            break;

        default:
            break;
    }
    updateVisible();
}

function localizeDateStr(date_to_convert_str) {
    var date_to_convert = new Date(date_to_convert_str);
    var local_date = new Date();
    date_to_convert.setHours(date_to_convert.getHours() + (local_date.getTimezoneOffset() / 60));
    return date_to_convert;
}

function formatdatetoyyyymmdd(datetoformat) {
    formatteddate = new Date(localizeDateStr(datetoformat));
    var dd = formatteddate.getDate();
    var mm = formatteddate.getMonth() + 1; //January is 0!
    var yyyy = formatteddate.getFullYear();
    if (dd < 10) {
        dd = '0' + dd
    }
    if (mm < 10) {
        mm = '0' + mm
    }
    formatteddate = yyyy + '-' + mm + '-' + dd;

    return formatteddate;
}

function updateVisible() {

    $(".mainitemcurrent").hide();
    $(".mainitemnotasks").hide();
    $(".mainitemoverdue").hide();
    $(".mainitemcompleted").hide();
    $(".permitstatusactive").hide();
    $(".permitstatusinactive").hide();
    $(".monthtitle").hide();

    $(".overduetitle").addClass("hidden");

    var monthfilter = "";

    var currentMonth = "." + getCurrentMonth();
    var monthTitle = "";

    if ($("#19_form_control_Month").val() != "All") {
        monthfilter = "." + $("#19_form_control_Month").val();
        monthTitle = "Due this Month - " + getCurrentMonth();
    } else {
        monthTitle = getCurrentMonth();
    }

    $(".monthtitle" + currentMonth + " h3").html(monthTitle);

    if ($("#checkbox-Current").is(':checked')) {
        $(".mainitemcurrent.permitstatusactive.searchresult" + monthfilter).show();
        $($(".mainitemcurrent.permitstatusactive.searchresult" + monthfilter)).parent().show();
    }

    if ($("#checkbox-Overdue").is(':checked')) {
        var currentMonth = "." + getCurrentMonth();

        if (monthfilter == currentMonth) {
            $(".mainitemoverdue.permitstatusactive.searchresult").show();
            $($(".mainitemoverdue.permitstatusactive.searchresult")).parent().show();
        } else {
            $(".mainitemoverdue.permitstatusactive.searchresult" + monthfilter).show();
            $($(".mainitemoverdue.permitstatusactive.searchresult" + monthfilter)).parent().show();
        }
    }

    if ($("#checkbox-Completed").is(':checked')) {
        $(".mainitemcompleted.permitstatusactive.searchresult" + monthfilter).show();
        $($(".mainitemcompleted.permitstatusactive.searchresult" + monthfilter)).parent().show();
    }

    if ($("#checkbox-NoTasks").is(':checked')) {
        $(".mainitemnotasks.permitstatusactive.searchresult" + monthfilter).show();
        $($(".mainitemnotasks.permitstatusactive.searchresult" + monthfilter)).parent().show();
    }

    if ($("#checkbox-All").is(':checked')) {

        $(".mainitemnotasks.permitstatusactive.searchresult" + monthfilter).show();
        $($(".mainitemnotasks.permitstatusactive.searchresult" + monthfilter)).parent().show();
        $(".mainitemcurrent.permitstatusactive.searchresult" + monthfilter).show();
        $($(".mainitemcurrent.permitstatusactive.searchresult" + monthfilter)).parent().show();

        var currentMonth = "." + getCurrentMonth();

        if (monthfilter == currentMonth) {
            $(".mainitemoverdue.permitstatusactive.searchresult").show();
            $($(".mainitemoverdue.permitstatusactive.searchresult")).parent().show();
        } else {
            $(".mainitemoverdue.permitstatusactive.searchresult" + monthfilter).show();
            $($(".mainitemoverdue.permitstatusactive.searchresult" + monthfilter)).parent().show();
        }

        $(".mainitemoverdue.permitstatusactive.searchresult" + monthfilter).show();
        $($(".mainitemoverdue.permitstatusactive.searchresult" + monthfilter)).parent().show();

        $(".mainitemoverdue.permitstatusactive.searchresult" + monthfilter).show();
        $($(".mainitemoverdue.permitstatusactive.searchresult" + monthfilter)).parent().show();

        $(".mainitemcompleted.permitstatusactive.searchresult" + monthfilter).show();
        $($(".mainitemcompleted.permitstatusactive.searchresult" + monthfilter)).parent().show();
    }

    if (GetData.localStorage('SubClassification').includes("ESH")) {
        $(".btnaddnewtasks").show();

        var todayDate = new Date();

        var currentyear = (new Date()).getFullYear();
        var mindate = new Date(currentyear + "-01-01");
        var maxdate = new Date(currentyear + "-01-31");

        todayDate = localizeDateStr(formatdatetoyyyymmdd(todayDate));
        mindate = localizeDateStr(mindate);
        maxdate = localizeDateStr(maxdate);

        if (todayDate >= mindate && todayDate <= maxdate) {
            $("#copyalltasks").removeClass('hidden');
        }
    } else {
        $(".btnaddnewtasks").hide();
        $("#copyalltasks").addClass('hidden');
    }
}

function getCurrentMonth() {
    const monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];

    var todayDate = new Date();
    var currentmonthnumber = todayDate.getMonth();
    return monthNames[currentmonthnumber];
}

function monthfiltertypechange() {
    createtasks(1);

    var searchvalue = $("#20_form_control_Month").val();

    if (searchvalue != "") {
        filterdata(searchvalue);
    } else {
        updateVisible();
    }
}

function filterdata(keypressed) {
    $("div h4#tasknameid.titlewrap").parent().parent().parent().removeClass("searchresult"); //task
    $("div.programsdata h3").parent().hide(); //program
    $(".monthtitle").hide(); //if month filter == All

    if ($("#19_form_control_Month").val() == "All") {
        //show parent of inside on all
        $($("div h4#tasknameid.titlewrap:containsNC('" + keypressed + "')").parent().parent().parent().parent()).parent().parent().show(); //Program

        //show inside
        $("div h4#tasknameid.titlewrap:containsNC('" + keypressed + "')").parent().parent().parent().addClass("searchresult"); //inside

        //show month
        $("div h4#tasknameid.titlewrap:containsNC('" + keypressed + "')").parent().parent().parent().parent().show() //all

        //show parent and all children
        $("div.programsdata h3:containsNC('" + keypressed + "')").parent().show(); //same for both filters

        //show childrens on all
        $($("div.programsdata h3:containsNC('" + keypressed + "')")).next().next().children('.monthtitle').children().addClass("searchresult");

    } else {
        //show parent of inside
        $($("div h4#tasknameid.titlewrap:containsNC('" + keypressed + "')").parent().parent().parent()).parent().parent().show();

        //show inside
        $("div h4#tasknameid.titlewrap:containsNC('" + keypressed + "')").parent().parent().parent().addClass("searchresult"); //inside

        //show parent and all children
        $("div.programsdata h3:containsNC('" + keypressed + "')").parent().show(); //same for both filters

        //show children on month
        $($("div.programsdata h3:containsNC('" + keypressed + "')")).next().next().children().addClass("searchresult"); //internal month filter
    }

    //run status filter
    updateVisible();
}

function createtasks(calltype) {

    //alert(GetData.localStorage('Season'));

    $(".programsdata").remove();

    var fromDate = new Date();
    var toDate;
    var diff;
    var taskstatus = "";
    var textcolor = "";
    var tasks = "";
    var taskstyle = "";
    var daysleft;
    var daysleftlabel;
    var taskpercent;
    var permitstatusactive;
    var permitname;
    var expirationdate;
    var programname = "";
    var programid = "";

    var taskstartingdate;

    var programarea = 0;
    var tasksthismonth;

    var currentyeardata = GetData.localStorage('Season');

    if (calltype == 0 || typeof programinfo == 'undefined') //call to get values from db, other calls are just to rearrange and will use the values previously saved
    {
        programinfo = GetData.SqlValue("SELECT * FROM OS_Catalog WHERE Category = 18 ORDER BY Name");

        //programownertasks = GetData.SqlValue("SELECT *,CASE WHEN [percent] <> 100 and enddate < DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE()),0)) and StartDate <> '' and enddate <> '' THEN 'Overdue' WHEN [percent] <> 100 and startdate < DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE())(PLUS)1,0)) THEN 'Current' WHEN [percent] = 100 THEN 'Completed' ELSE 'NoTask' END as SFC FROM OS_Permits where Permit_ID in (SELECT id_Catalog FROM OS_Catalog WHERE Category = 18) and StartDate BETWEEN '" + currentyeardata + "-01-01' AND '" + currentyeardata + "-12-31' ORDER BY Permit_ID,enddate");

        programownertasks = GetData.SqlValue("SELECT *,CASE WHEN [percent] <> 100 and enddate < GETDATE() and StartDate <> '' and enddate <> '' THEN 'Overdue' WHEN [percent] <> 100 and startdate < DATEADD(s,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE())(PLUS)1,0)) THEN 'Current' WHEN [percent] = 100 THEN 'Completed' ELSE 'NoTask' END as SFC FROM OS_Permits where Permit_ID in (SELECT id_Catalog FROM OS_Catalog WHERE Category = 18) and StartDate BETWEEN '" + currentyeardata + "-01-01' AND '" + currentyeardata + "-12-31' ORDER BY Permit_ID,startdate");
    }

    for (var i = 0; i < programinfo.length; i++) {
        programname = programinfo[i]["Name"];
        programid = programinfo[i]["id_Catalog"];
        $('#OPage_' + ID).append("<div class='programsdata'><h3 id='title" + programid + "' onclick='hideshowprojecttasks(" + programid + ")' style='cursor: pointer;'>" + programname + "</h3><div class='btnaddnewtasks'><h3  style=color: red; font-weight: bold;cursor:pointer; onclick='addTask(" + programid + ",-1)'>+</h3></div><div class='row' id='" + programid + "'></div></div>");
    }

    const monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
    var currentmonth;
    var tempmonth = "";
    var tempprogramid = "";
    var permitgroup = "";
    var modifyby = "";

    var monthfilter = "";
    var multiplemonth = "";
    var startingmonth = -1;
    var endingmonth = -1;


    if ($("#19_form_control_Month").val() != "All") {
        monthfilter = $("#19_form_control_Month").val();
    }

    for (var i = 0; i < programownertasks.length; i++) {
        switch (programownertasks[i]["SFC"]) {
            case "Completed":
                taskstatus = "mainitemcompleted";
                taskstyle = "itemcompleted";
                break;
            case "Current":
                taskstatus = "mainitemcurrent";
                taskstyle = "itemcurrent";
                break;
            case "Overdue":
                taskstatus = "mainitemoverdue";
                taskstyle = "itemoverdue";
                break;
            case "NoTask":
                taskstatus = "mainitemnotasks";
                taskstyle = "itemnotasks";
                break;
            default:
                taskstatus = "mainitemnotasks";
                taskstyle = "itemnotasks";
        }

        permitname = programownertasks[i]["Name"];
        programid = programownertasks[i]["Permit_ID"];
        modifyby = programownertasks[i]["Modify_By"];
        multiplemonth = "";
        startingmonth = -1;
        endingmonth = -1;

        if (tempprogramid != programid) {
            tempmonth = "";
            tempprogramid = programid;
        }

        expirationdate = programownertasks[i]["EndDate"];

        taskstartingdate = programownertasks[i]["StartDate"];

        if (taskstartingdate != "N/A") {
            toDate = new Date(localizeDateStr(taskstartingdate));
            currentmonth = monthNames[toDate.getMonth()];

            startingmonth = toDate.getMonth();
        }

        daysleftlabel = "Days Left:";

        if (expirationdate != "N/A") {
            toDate = new Date(localizeDateStr(expirationdate));
            diff = new Date(toDate - fromDate);
            daysleft = Math.ceil(diff / 1000 / 60 / 60 / 24);

            endingmonth = toDate.getMonth();

            //currentmonth = monthNames[toDate.getMonth()];
            expirationdate = DateFunctions.FormatDate(toDate, "MMMM dd, yyyy")
        } else {
            expirationdate = "Don't Expire";
            daysleft = "N/A";
        }

        if (daysleft < 0) {
            daysleftlabel = "Days Overdue:";
        }

        taskpercent = programownertasks[i]["Percent"];
        permitstatusactive = "permitstatusactive";

        if (tempmonth != currentmonth) {
            $("#" + programid).append("<div class='row col-lg-12 monthtitle " + currentmonth + "'><h3 style='margin-left:30px;margin-bottom:-10px'>" + currentmonth + "</h3></div>");
            tempmonth = currentmonth;
        }

        for (var m = startingmonth; m <= endingmonth; m++) {
            if (m > -1) {
                multiplemonth = multiplemonth + " " + monthNames[m];
            } else {
                multiplemonth = currentmonth;
            }

        }

        // for(var i=0;i<programownertasks.length;i++)

        //////////////////////////////////////////////


        //                    if(permitname =="Test Multiple Months") 
        //                    {

        tasks = "<div class='col-sm-6 col-md-2 col-lg-2 searchresult " + taskstatus + " " + permitstatusactive + " " + multiplemonth + "' style='cursor:pointer;padding-top:20px;' onclick='addTask(" + programid + "," + i + ",false)'><div class='" + taskstyle + "'><div ><p></p><h4 id='tasknameid' class='titlewrap' style='padding-right:30px'>" + permitname + "</h4><p></p><p>Due Date: " + expirationdate + "</p><p></p><p>" + daysleftlabel + " " + daysleft + "</p></div><div><div class='row' style='padding-right:15px;'><div class='col-sm-3'><p>Status:</p></div><div class='col-sm-9' style='padding:0; background-color: lightcyan;'><div class='progress-bar' role='progressbar' aria-valuenow='" + taskpercent + "' aria-valuemin='0' aria-valuemax='100' style='width:" + taskpercent + "%'>" + taskpercent + "%</div></div></div></div></div>" + "<div style='width: 100%;display: block; position: absolute; bottom: 15px; right: 25px;'><span style='position: absolute; font-size: 9px; width: 100%;text-align: right; '>" + (modifyby == null ? "" : "Modified by: " + modifyby) + "</span></div>" + "</div>";
        //                    }
        //                    else{
        //                        tasks = "<div class='col-sm-6 col-md-2 col-lg-2 searchresult " + taskstatus + " " + permitstatusactive + " " + currentmonth + "' style='cursor:pointer;padding-top:20px;' onclick='addTask(" + programid + "," + i + ",false)'><div class='" + taskstyle + "'><div ><p></p><h4 id='tasknameid' class='titlewrap' style='padding-right:30px'>" + permitname + "</h4><p></p><p>Due Date: " + expirationdate + "</p><p></p><p>" + daysleftlabel + " " + daysleft + "</p></div><div><div class='row' style='padding-right:15px;'><div class='col-sm-3'><p>Status:</p></div><div class='col-sm-9' style='padding:0; background-color: lightcyan;'><div class='progress-bar' role='progressbar' aria-valuenow='" + taskpercent + "' aria-valuemin='0' aria-valuemax='100' style='width:" + taskpercent + "%'>" + taskpercent + "%</div></div></div></div></div>" + "<div style='width: 100%;display: block; position: absolute; bottom: 15px; right: 25px;'><span style='position: absolute; font-size: 9px; width: 100%;text-align: right; '>" + (modifyby == null ? "" : "Modified by: " + modifyby) + "</span></div>" + "</div>";
        //                    }


        if ($("#19_form_control_Month").val() != "All") {
            $("#" + programid).append(tasks);
        } else {
            $("#" + programid + " div.row.col-lg-12.monthtitle." + currentmonth).append(tasks);
        }

        $("h3#title" + programid).addClass('hidingelements');
    }
}

function hideshowprojecttasks(id) {

    $("#" + id).fadeToggle("fast", "linear");

    if ($("h3#title" + id).hasClass('hidingelements')) {
        $("h3#title" + id).removeClass('hidingelements');
        $("h3#title" + id).addClass('showelements');
    } else if ($("h3#title" + id).hasClass('showelements')) {
        $("h3#title" + id).removeClass('showelements');
        $("h3#title" + id).addClass('hidingelements');
    }
}