function Createnewfault() {

    var self = {};
    self.tmp = null;
    self.selection = {};
    self.UserId = null;
    self.completeFaultTypeList = null;
    self.faultPriorityCodeList = null;
    self.faultStarted = false;
    self.expectedEndDate = '';

    self.requestFaultTypeList = function () {
        var currentMachine = $.cookie("currently_selected_machine");
        var requester = new AjaxRequest({
            data: { "machineid": currentMachine }, // This is for the json request
            success: self.requestFaultTypeListSuccess,
            error: self.requestFaultTypeListFailure,
            url: "RequestFaultTypeListWithGrouping"
        });
        requester.ExecuteRequest();

    }

    self.requestFaultTypeListSuccess = function (data, status, xhr) {
        self.completeFaultTypeList = data.d.AvailableFaultTypes;
        self.UpdateFaultList(data.d.ReducedListPresent, data.d.AvailableFaultTypes);
    }



    self.requestFaultTypeListFailure = function (request, status, error) {
        /// <summary>This function is called by sendGetInfoReq() when the ajax-request returns an error</summary>


        c1('createnewfault row 34: Unable to retrieve fault type list from database.');
        DbCommunicationErrorHandler(WEBSERVICE_FAULT_JSONREQUEST);
    }

    self.requestPriorityCodeList = function () {
        var requester = new AjaxRequest({
            data: {}, // This is for the json request
            success: self.requestPriorityCodeListSuccess,
            error: self.requestPriorityCodeListFailure,
            url: "RequestFaultPriorityCodes"
        });
        requester.ExecuteRequest();

    }

    self.requestPriorityCodeListSuccess = function (data, status, xhr) {
        self.faultPriorityCodeList = data.d.AvailablePriorityCodeList;
        self.UpdatePriorityCodeList();
    }



    self.requestPriorityCodeListFailure = function (request, status, error) {
        /// <summary>This function is called by sendGetInfoReq() when the ajax-request returns an error</summary>


        c1('createnewfault row 60: Unable to retrieve priority code list from database.');
        DbCommunicationErrorHandler(WEBSERVICE_FAULT_JSONREQUEST);
    }

    self.commitNewFault = function () {
        var currentmachinenumber = $.cookie("currently_selected_machine");
        var selectedfaulttypeid = $("#createfault_faulttype").val();
        var current_userid = $.cookie("user_id");
        var provideddescription = $("#createfault_newfaultnote").val();
        var tobesolvedby_id = $("#createfault_tobesignedby").val();
        var priority_id = $("#createfault_prioritycodes").val();
        var current_session_token = $.cookie("session_token");
        var expected_solution_date = '';

        var cleanupRequested = "null";

        if (($("#createfault_cleanupflag_on").prop("checked") == true) &&
            $("#createfault_cleanupflag_off").prop("checked") == false) {
            c3("createnewfault row 79 - cleanup selected");
            cleanupRequested = "true";
        }

        if (($("#createfault_cleanupflag_on").prop("checked") == false) &&
            $("#createfault_cleanupflag_off").prop("checked") == true) {
            c3("createnewfault row 85 - cleanup declined");
            cleanupRequested = "false";
        }

        console.log(cleanupRequested);


        //function parseExpectedEndDate(incomingString) {
        //    var dateToParse = new Date(localizeDatePickerValue(incomingString));
        //    console.log(dateToParse);
        //    if (dateToParse == 'Invalid date') {                
        //        return dateToParse;
        //    }
        //    else {
        //        var outgoingYear = dateToParse.getFullYear(dateToParse);
        //        var outgoingMonth = dateToParse.getMonth(dateToParse);
        //        outgoingMonth = outgoingMonth + 1;
        //        if (outgoingMonth < 9) { outgoingMonth = '0' + outgoingMonth };
        //        var outgoingDay = dateToParse.getDate(dateToParse);
        //        if (outgoingDay < 9) { outgoingDay = '0' + outgoingDay };
        //        var outgoingDate = outgoingYear + '-' + outgoingMonth + '-' + outgoingDay;
        //        console.log(outgoingDate);
        //        return outgoingDate;
        //    }
        //};


        if (($("#createfault_report_as_started").is(":checked"))) {
            //expected_solution_date = $("#createfault_expected_end_date2").val();

            var jsDate = $('#datepicker_test2').datepicker('getDate');
            if (jsDate !== null) { // if any date selected in datepicker
                jsDate instanceof Date; // -> true
                var selectedDay = (jsDate.getDate()).toString();
                if (selectedDay.length == 1) {
                    selectedDay = '0' + selectedDay;
                }

                var selectedMonth = (jsDate.getMonth() + 1).toString();
                if (selectedMonth.length == 1) {
                    selectedMonth = '0' + selectedMonth;
                }

                var dbDate = jsDate.getFullYear().toString() + '-' + selectedMonth + '-' + selectedDay;
                c8(dbDate);
                expected_solution_date = dbDate;
                c5(expected_solution_date);
            }
        };

        if (expected_solution_date.length == 0 && ($("#createfault_report_as_started").is(":checked"))) {
            self.setErrorMsg(ReturnPhraseOnKey('createfault_errormessage_expected_end_date_not_specified'));
        }       
        else {            

            //expected_solution_date = parseExpectedEndDate(expected_solution_date);

            c7(expected_solution_date);

            if (expected_solution_date !== 'Invalid Date') {


                var requester = new AjaxRequest({
                    data: {
                        "machinenumber": currentmachinenumber, "faulttypeid": selectedfaulttypeid,
                        "reportedby": current_userid, "faultdescription": provideddescription, "tobesolvedby": tobesolvedby_id,
                        "expectedenddate": expected_solution_date, "priorityid": priority_id, "cleanup_flag" : cleanupRequested, "session_token": current_session_token
                    }, // This is for the json request
                    success: self.commitNewFaultSuccess,
                    error: self.commitNewFaultFailure,
                    url: "RegisterNewFault"
                });
                requester.ExecuteRequest();
            }
            else {
                self.setErrorMsg(ReturnPhraseOnKey('createfault_errormessage_expected_end_date_invalid_input'));
                $("#datepicker_test2").val('').focus();
            }
        }
    }


    self.commitNewFaultSuccess = function (data, status, xhr) {

        $("#datepicker_test2").val('');

        console.log(data.d);

        if (data.d.SessionTokenValid == false) {
            //$(":mobile-pagecontainer").pagecontainer("change", "#dialog_tokenexpired", { role: "dialog", reverse: false, changeHash: false });

            $("#faultcreated_generic_popup_header").html(ReturnPhraseOnKey("dialogue_tokenexpired_message1"));
            $("#faultcreated_generic_popup_text").html(ReturnPhraseOnKey("dialogue_tokenexpired_message1"));

            $("#faultcreated_generic_popup").off().on("popupafterclose", function (event, ui) {
                $(":mobile-pagecontainer").pagecontainer("change", "#page_login", { role: "page", reverse: false, changeHash: false });
                e3('createnewfault row 114');
            });

            $("#faultcreated_generic_popup_button").unbind("click").click(function () {
                $("#faultcreated_generic_popup").popup("close");
            });

            $("#faultcreated_generic_popup").popup().popup("open");
        }
        else {
            console.log(data.d);
            var newFaultJobId = data.d.ValueToPass;
            var newFaultFaultId = data.d.Value2ToPass;
            var workOnFault = 0;
            $.cookie("newfault_job_id", newFaultJobId);
            //$(":mobile-pagecontainer").pagecontainer("change", "#dialog_faultadded", { role: "dialog", reverse: false, changeHash: false });

            var newfaultid = $.cookie("newfault_job_id");
            var message = ReturnPhraseOnKey("dialogue_faultadded_part1");
            message += newfaultid;
            message += ReturnPhraseOnKey("dialogue_faultadded_part2");

            $("#faultcreated_postcreation_popup_header").html(message);
            $("#faultcreated_postcreation_popup_text").html(message);

            $("#faultcreated_postcreation_popup").off().on("popupafterclose", function (event, ui) {

                if (workOnFault == 0) {
                    c2('moving to machines');
                    $(":mobile-pagecontainer").pagecontainer("change", "#page_machinedetail", { role: "page", reverse: false, changeHash: false });
                    e3('createnewfault row 139');
                }
                else {
                    c2('will move directly to fault');
                    $.cookie("currently_selected_fault", newFaultFaultId);
                    $.cookie("currently_selected_activity", 0);
                    //$(":mobile-pagecontainer").pagecontainer("change", "#page_directfault_test", { role: "page", reverse: false, changeHash: false });


                    $.mobile.navigate("#page_faultdetailwithfunction", { role: "page" });
                    e3('createnewfault row 193');

                }
            });

            $("#faultcreated_back_to_machine_button").unbind().click(function (event) {
                workOnFault = 0;
                $("#faultcreated_postcreation_popup").popup("close");
            });

            $("#faultcreated_work_with_fault_button").unbind().click(function (event) {
                workOnFault = 1;
                $("#faultcreated_postcreation_popup").popup("close");
            });

            $("#faultcreated_postcreation_popup").popup().popup("open");
        }

    }

    self.commitNewFaultFailure = function (data, status, xhr) {
        /// <summary>This function is called by sendGetInfoReq() when the ajax-request returns an error</summary>

        c1('createnewfault row 152: Unable to commit new fault, database access failure.');
        DbCommunicationErrorHandler();
    }


    self.UpdatePriorityCodeList = function () {
        $("#createfault_prioritycodes option").remove();

        var priorityListElements = '<option value=0>' + ReturnPhraseOnKey("createfault_priority_code_not_selected") + '</option>';



        jQuery.each(self.faultPriorityCodeList, function () {
            priorityListElements += '<option value="'
            priorityListElements += this.PriorityCodeId;
            priorityListElements += '">';
            priorityListElements += this.PriorityCodeName;
            priorityListElements += '</option>';
        });

        $("#createfault_prioritycodes").html(priorityListElements);
        $("#createfault_prioritycodes").selectmenu().selectmenu("refresh");
        $("#createfault_prioritycodes").val(0);
        $("#createfault_prioritycodes").selectmenu("refresh");
    };

    self.UpdateFaultList = function (reduceList, faultListFromRequest) {
        $("#createfault_faulttype option").remove();

        faultTypeListElements = '';

        if (reduceList == false) {

            if ($('#createfault_showallfaulttypes').is(":visible")) {
                $('#createfault_showallfaulttypes').hide();
            }


            jQuery.each(faultListFromRequest, function () {
                faultTypeListElements += '<option value="'
                faultTypeListElements += this.FaultTypeId;
                faultTypeListElements += '">';
                faultTypeListElements += this.FaultTypeName;
                faultTypeListElements += '</option>';
            });
        }
        else {
            jQuery.each(faultListFromRequest, function () {
                if (this.IncludedInReducedList == true) {
                    faultTypeListElements += '<option value="'
                    faultTypeListElements += this.FaultTypeId;
                    faultTypeListElements += '">';
                    faultTypeListElements += this.FaultTypeName;
                    faultTypeListElements += '</option>';
                }
            });

            if ($('#createfault_showallfaulttypes').is(":hidden")) {
                $('#createfault_showallfaulttypes').show();
            }
        }

        $("#createfault_faulttype").html(faultTypeListElements);
        $("#createfault_faulttype").selectmenu().selectmenu("refresh");
        //$("#createfault_faulttype").val(1);
        //$("#createfault_faulttype").selectmenu("refresh");


    }


    self.requestSignatoryList = function () {

        var requester = new AjaxRequest({
            data: {}, // This is for the json request
            success: self.requestSignatoryListSuccess,
            error: self.requestSignatoryListFailure,
            url: "RequestPossibleFaultSignatories"
        });
        requester.ExecuteRequest();

    }

    self.requestSignatoryListSuccess = function (data, status, xhr) {

        self.UpdateSignatoryList(data.d.FaultSignatories);
    }



    self.requestSignatoryTypeListFailure = function (request, status, error) {
        /// <summary>This function is called by sendGetInfoReq() when the ajax-request returns an error</summary>
        c1('createnewfault row 223: Unable to retrieve list of fault signatories from database.');
        DbCommunicationErrorHandler(WEBSERVICE_FAULT_JSONREQUEST);
    }

    self.UpdateSignatoryList = function (signatoryListFromRequest) {
        $("#createfault_tobesignedby option").remove();

        var current_initials = $.cookie('username');

        signatoryListElements = '';

        jQuery.each(signatoryListFromRequest, function () {

            //MABE 20200324 - adding autoselection of logged in user in this combobox

            //signatoryListElements += '<option value="'
            //signatoryListElements += this.Initials;
            //signatoryListElements += '">';

            if (current_initials.toLowerCase() == this.Initials.toLowerCase()) {
                c3('createnewfault row 341 - ' +  current_initials + ' - ' + this.Initials);
                signatoryListElements += '<option value="'
                signatoryListElements += this.Initials;
                signatoryListElements += '" selected = "selected">';
            }
            else {
                signatoryListElements += '<option value="'
                signatoryListElements += this.Initials;
                signatoryListElements += '">';
            }

            signatoryListElements += this.FirstName;
            signatoryListElements += ' ';
            signatoryListElements += this.LastName;
            signatoryListElements += '</option>';
        });

        $("#createfault_tobesignedby").html(signatoryListElements);
        $("#createfault_tobesignedby").selectmenu().selectmenu("refresh");
        //$("#createfault_tobesignedby").val(1);
        //$("#createfault_tobesignedby").selectmenu("refresh");


    }

    self.UpdateMachineInformation = function () {
        var selectedMachineName = $.cookie("currently_selected_machine_name");
        var selectedMachineNumber = $.cookie("currently_selected_machine");

        var machinedetails = '';
        machinedetails += '<p><b>';
        machinedetails += ReturnPhraseOnKey('createfault_machinename');
        machinedetails += '</b>';
        machinedetails += selectedMachineName;
        machinedetails += '</p><p><b>';
        machinedetails += ReturnPhraseOnKey('createfault_machinenumber');
        machinedetails += '</b>';
        machinedetails += selectedMachineNumber;
        machinedetails += '</p>';

        $("#createfault_details").html(machinedetails);
    }

    self.setErrorMsg = function (msg) {

        $('#createfault_errortext').html(msg);
        $('#createfault_errortext').show();
    }

    self.clearErrorMsg = function (msg) {
        $('#createfault_errortext').html('');
        $('#createfault_errortext').hide();
    }



    return self;
}

var createNewFault = Createnewfault();




$(document).one("pageshow", "#page_createfault", function (e) {

    $("#createnewfault_cancel").click(function () {

        $(":mobile-pagecontainer").pagecontainer("change", "#page_machinedetail", { role: "page", reverse: false, changeHash: true });
        e3('createnewfault row 296');
    })

    $("#createnewfault_commit").click(function () {
        createNewFault.commitNewFault();
        e3('createnewfault row 301');
    })

    $("#createfault_showallfaulttypes").click(function () {
        $("#createfault_showallfaulttypes").hide();

        //Calling for refresh of fault reason list. 
        //The 'false' overrides initial reduced list flag from request response to database.
        //The complete list, saved when initially received, is reused as source for list.
        createNewFault.UpdateFaultList(false, createNewFault.completeFaultTypeList);
        e3('createnewfault row 311');
    });


    $("#createfault_report_as_started").bind( "change", function(event, ui) {
        event.preventDefault();
        event.stopPropagation();
        if ($("#createfault_report_as_started").is(":checked")) {
            if($("#createfault_expected_end_date_picker").is(":hidden")){
                $("#createfault_expected_end_date_picker").show();
                createNewFault.faultStarted = true;
            }
        }
        else {
            $("#createfault_expected_end_date_picker").hide();
            createNewFault.faultStarted = false;
        }
        e3('createnewfault row 328');

    });

})

$(document).on( "pagebeforeshow", "#page_createfault", function(e) { 
    $("#createfault_expected_end_date_picker").hide();
    $("#createfault_report_as_started").removeAttr('checked').checkboxradio('refresh');

    $("#createfault_cleanupflag_on").removeAttr('checked').checkboxradio('refresh');
    $("#createfault_cleanupflag_off").removeAttr('checked').checkboxradio('refresh');

    if (CLEANUP_ACTIVE == false) {
        c2("createnewfault row 456 - cleanup section hidden");
        $("#createfault_cleanup_section").hide();
    }
    else {
        c2("createnewfault row 456 - cleanup section visible");
        $("#createfault_cleanup_section").show();
    }

    if (SessionTokenStatus == true) {

        $("#createfault_errortext").hide();
        $("#createfault_newfaultnote").val("");

        createNewFault.requestFaultTypeList();
        createNewFault.requestPriorityCodeList();
        createNewFault.requestSignatoryList();
        createNewFault.UpdateMachineInformation();
    }

})


$(document).on("pageshow", "#page_createfault", function (e) {
    if (SessionTokenStatus == true) {
        
        //********************************************
        //20200401 - moved to pagebeforeshow event
        //$("#createfault_errortext").hide();
        //$("#createfault_newfaultnote").val("");
        //createNewFault.requestFaultTypeList();
        //createNewFault.requestPriorityCodeList();
        //createNewFault.requestSignatoryList();
        //createNewFault.UpdateMachineInformation();
        //********************************************


        //if ($('#createfault_showallfaulttypes').is(":visible")) {
        //    $('#createfault_showallfaulttypes').hide();
        //}

        $("#createnewfault_backbutton").unbind().click(function () {
            $(":mobile-pagecontainer").pagecontainer("change", "#page_machinedetail", { role: "page", reverse: false, changeHash: false });
            e3('createnewfault row 352');
        });

    }
    else {
        helper.ForcedLogout();
    }
});

$(document).on("pagehide", "#page_createfault", function (e) {

    c4('page_createfault row 464 - pagehide triggered');

    //collapse fault started section
    $("#createfault_expected_end_date_picker").hide();

    //reset fault started flag
    createNewFault.faultStarted = false;

    //uncheck fault started checkbox
    $("#createfault_report_as_started").removeAttr('checked').checkboxradio('refresh');

    //reset cleanup flag status in prep for next job
    $("#createfault_cleanupflag_on").removeAttr('checked').checkboxradio('refresh');
    $("#createfault_cleanupflag_off").removeAttr('checked').checkboxradio('refresh');

    //cleanup fault started date field
    $("#datepicker_test2").val('');

});

