function Registermachinestop() {

    var self = {};
    self.stopTypeList = null;
    

    self.displayFaultInfo = function () {
        //var infoHTML = ReturnPhraseOnKey("stop_period_job_id") + ": " + faultDetailWithFunction.selectedJobID + '<br>';
        //infoHTML += ReturnPhraseOnKey("stop_period_fault_type") + ": " + faultDetailWithFunction.faultType + '<br>';
        //infoHTML += ReturnPhraseOnKey("stop_period_machine_name") + ": " + faultDetailWithFunction.machineName + '<br>';
        //infoHTML += ReturnPhraseOnKey("stop_period_machine_number") + ": " + faultDetailWithFunction.machineNumber + '<br>';
        //infoHTML += ReturnPhraseOnKey("stop_period_machine_stop_group") + ": " + faultDetailWithFunction.machineStopGroup;
        //infoHTML += '<p>';

        infoHTML = '<table class="job_info_table"><tr><td class="label">';
        infoHTML += ReturnPhraseOnKey('stop_period_job_id');
        infoHTML += '</td><td>';
        infoHTML += faultDetailWithFunction.selectedJobID;
        infoHTML += '</td></tr><tr><td class="label">';
        infoHTML += ReturnPhraseOnKey('stop_period_fault_type');
        infoHTML += '</td><td>';
        infoHTML += faultDetailWithFunction.faultType;
        infoHTML += '</td></tr><tr><td class="label">';
        infoHTML += ReturnPhraseOnKey('stop_period_machine_name');
        infoHTML += '</td><td>';
        infoHTML += faultDetailWithFunction.machineName;
        infoHTML += '</td></tr><tr><td class="label">';
        infoHTML += ReturnPhraseOnKey('stop_period_machine_number');
        infoHTML += '</td><td>';
        infoHTML += faultDetailWithFunction.machineNumber;
        infoHTML += '</td></tr><tr><td class="label">';
        infoHTML += ReturnPhraseOnKey('stop_period_machine_stop_group');
        infoHTML += '</td><td>';
        infoHTML += faultDetailWithFunction.machineStopGroup;
        infoHTML += '</td></tr>';
        infoHTML += '</table>'

        $('#stop_period_selected_fault_info').html(infoHTML);

    }

    self.requestStopTypeList = function () {
        var requester = new AjaxRequest({
            data: {}, // This is for the json request
            success: self.requestStopTypeListSuccess,
            error: self.requestStopTypeListFailure,
            url: "RequestStopTypes"
        });
        requester.ExecuteRequest();

    }

    self.requestStopTypeListSuccess = function (data, status, xhr) {
        console.log(data.d);
        self.stopTypeList = data.d.AvailableStopTypes;
        self.updateStopTypeList();
    }

    self.requestStopTypeListFailure = function (request, status, error) {
        c1('registermachinestop line 33: Unable to retrieve stop type list from database.');
        DbCommunicationErrorHandler(WEBSERVICE_FAULT_JSONREQUEST);
    }

    self.updateStopTypeList = function () {

        $("#stop_period_stop_type_list option").remove();

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



        jQuery.each(self.stopTypeList, function () {
            stopTypeListElements += '<option value="'
            stopTypeListElements += this.StopTypeID;
            stopTypeListElements += '">';
            stopTypeListElements += this.StopTypeDescription;
            stopTypeListElements += '</option>';
        });

        $("#stop_period_stop_type_list").html(stopTypeListElements);
        $("#stop_period_stop_type_list").selectmenu().selectmenu("refresh");
        $("#stop_period_stop_type_list").val(0);
        $("#stop_period_stop_type_list").selectmenu("refresh");
    };

    self.handleNewMachineStop = function () {

        self.clearErrorMsg();

        c3("row 63 - Starting machine stop registry");
        c3("row 64 - Input value validation starts");

        var faultID = faultDetailWithFunction.selectedFaultID;
        var startDate = $("#stop_period_start_date").val();
        var startTime = $("#stop_period_start_time").val();
        var endDate = $("#stop_period_end_date").val();
        var endTime = $("#stop_period_end_time").val();
        var stopType = $("#stop_period_stop_type_list").val();

        var machineOnly = $("#stop_period_selected_machine_only").is(":checked");
        !!machineOnly;


        var current_session_token = $.cookie("session_token");

        //c4(faultID + ',' + startDate + ',' + startTime + ',' + endDate + ',' + endTime + ',' + stopType + ',' + machineOnly + ',' + stopGroupID);
      
        if (self.inputValueValidation(startDate, startTime, endDate, endTime) === false) {

            c5('Validation failed');
            return;
        }

        var outgoingStartDate = parseExpectedEndDate(startDate);
        var outgoingEndDate = parseExpectedEndDate(endDate);



        if (moment(startTime, 'HH:mm', true).isValid() == false) {
            c4('Start time not defined');
            startTime = '00:00';
            c4('Start time set to ' + startTime);
        }

        if (moment(endTime, 'HH:mm', true).isValid() == false) {
            c4('End time not defined');
            endTime = '00:00';
            c4('End time set to ' + endTime);
        }

        c6("Fault ID: " + faultID);
        c6("Start Date: " + outgoingStartDate);
        c6("Start Time: " + startTime);
        c6("End Date: " + outgoingEndDate);
        c6("End Time: " + endTime);
        c6("Machine Only Flag: " + machineOnly);
        c6("Session Token: " + current_session_token);

        //c6(faultID + ',' + outgoingStartDate + ',' + startTime + ',' + outgoingEndDate + ',' + endTime + ',' + machineOnly + ',' + stopGroupID + ',' + current_session_token);


        
        var requester = new AjaxRequest({
            data: {
                "incomingfaultid": faultID, "incomingstartdate": outgoingStartDate, "incomingstarttime": startTime, "incomingenddate": outgoingEndDate,
                "incomingendtime": endTime, "incomingmachineonlyflag": machineOnly,"incomingstoptypeid": stopType, "session_token": current_session_token
            }, 
            success: self.commitStopPeriodSuccess,
            error: self.commitStopPeriodFailure,
            url: "RegisterNewStopPeriod"
        });
        requester.ExecuteRequest();


    };

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

        console.log(data.d);

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

            $("#stop_period_generic_popup_header").html(ReturnPhraseOnKey("dialogue_tokenexpired_message1"));
            $("#stop_period_generic_popup_text").html(ReturnPhraseOnKey("dialogue_tokenexpired_message1"));

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

            $("#stop_period_generic_popup_button").unbind("click").click(function () {
                $("#stop_period_generic_popup").popup("close");
            });

            $("#stop_period_generic_popup").popup().popup("open");
        }
        else if (data.d.SessionTokenValid == true && data.d.TrueOrFalse == false) {
            $("#stop_period_generic_popup_header").html(ReturnPhraseOnKey("stop_period_failure_header"));
            $("#stop_period_generic_popup_text").html(ReturnPhraseOnKey("stop_period_failure_message"));

            $("#stop_period_generic_popup").off().on("popupafterclose", function (event, ui) {
                e3('closing failure to register stop period popup row 155');
            });

            $("#stop_period_generic_popup_button").unbind("click").click(function () {
                $("#stop_period_generic_popup").popup("close");
            });

            $("#stop_period_generic_popup").popup().popup("open");
        }
        else {

            var newStopID = data.d.ValueToPass;
            self.afterStopCreation();
        }
    }

    self.commitStopPeriodFailure = function (data, status, xhr) {
        console.log(data.d);
        console.log(status);
        console.log(xhr);
        c1('registermachinestop row 195: Unable to create new machine stop, database access failure.');
        DbCommunicationErrorHandler();
    }

    self.afterStopCreation = function () {
        $("#stop_period_generic_popup_header").html(ReturnPhraseOnKey("stop_period_creation_message_header"));
        $("#stop_period_generic_popup_text").html(self.afterStopCreationMessage());

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

            $.mobile.navigate("#page_faultdetailwithfunction", { role: "page" });
        });

        $("#stop_period_generic_popup_button").unbind().click(function () {
            $("#stop_period_generic_popup").popup("close");
        });

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

    self.afterStopCreationMessage = function () {
        var messageToShow = '<strong>' + ReturnPhraseOnKey("stop_period_job_id") + ":</strong> " + faultDetailWithFunction.selectedJobID + '<br>';
        messageToShow += '<strong>' + ReturnPhraseOnKey("stop_period_fault_type") + ":</strong> " + faultDetailWithFunction.faultType + '<br>';
        messageToShow += '<strong>' + ReturnPhraseOnKey("stop_period_machine_name") + ":</strong> " + faultDetailWithFunction.machineName + '<br>';
        messageToShow += '<strong>' + ReturnPhraseOnKey("stop_period_machine_number") + ":</strong> " + faultDetailWithFunction.machineNumber + '<br>';
        messageToShow += '<strong>' + ReturnPhraseOnKey("stop_period_machine_stop_group") + ":</strong> " + faultDetailWithFunction.machineStopGroup + '<br>';
        messageToShow += '<strong>' + ReturnPhraseOnKey("stop_period_type") + ":</strong> " + $("#stop_period_stop_type_list option:selected").text() + '<br>';
        messageToShow += '<strong>' + ReturnPhraseOnKey("stop_period_start") + ":</strong> " + $("#stop_period_start_date").val() + " " + $("#stop_period_start_time").val() + '<br>';
        messageToShow += '<strong>' + ReturnPhraseOnKey("stop_period_stop") + ":</strong> " + $("#stop_period_end_date").val() + " " + $("#stop_period_end_time").val();

        return messageToShow;

    }

    self.inputValueValidation = function (startDate, startTime, endDate, endTime){

        var validationSuccess = true;
        !!validationSuccess;

        var errorMessage = '';
        
        //First, test on empty input for start/end date

        if (startDate.length == 0) {
            errorMessage += ReturnPhraseOnKey('stop_period_start_date_input_not_selected');
            validationSuccess = false;
        }

        if (endDate.length == 0) {
            if (errorMessage.length > 0) {
                errorMessage += '<br/>';
            }
            errorMessage += ReturnPhraseOnKey('stop_period_end_date_input_not_selected');
            validationSuccess = false;
        }


        //Second, if there is input for start/end date, validate correct date format for input values
        if (validationSuccess === true) {

            startDateTest = parseExpectedEndDate(startDate);
            endDateTest = parseExpectedEndDate(endDate);

            if (startDateTest == 'Invalid Date' || endDateTest == 'Invalid Date') {
                errorMessage = ReturnPhraseOnKey('stop_period_date_format_incorrect');
                validationSuccess = false;
            }
            else if (startDateTest > endDateTest) {
                errorMessage = ReturnPhraseOnKey('stop_period_start_date_later_than_end_date')
                validationSuccess = false;
            }
        }

        self.setErrorMsg(errorMessage);

        return validationSuccess;



    };

    self.clearFields = function () {

        $("#stop_period_stop_type_list option[value=0]").attr('selected', 'selected');

        $('#startTime option[value=0]').prop('selected', true);

        $("#stop_period_start_date").val('');
        $("#stop_period_start_time").val('');
        $("#stop_period_end_date").val('');
        $("#stop_period_end_time").val('');
    }

    self.setErrorMsg = function (msg) {

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

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


    return self;

}

var registerMachineStop = Registermachinestop();

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

    $("#stop_period_back_button").click(function () {
        e.preventDefault();
        e.stopPropagation();
        $(":mobile-pagecontainer").pagecontainer("change", "#page_faultdetailwithfunction", { role: "page", reverse: false, changeHash: true });
    })

    $("#stop_period_cancel").click(function () {
        e.preventDefault();
        e.stopPropagation();
        $(":mobile-pagecontainer").pagecontainer("change", "#page_faultdetailwithfunction", { role: "page", reverse: false, changeHash: true });
    })

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

        e.preventDefault();
        e.stopPropagation();
        c2("Commit stop period to db");
        registerMachineStop.handleNewMachineStop();
    })

});

$(document).on("pagebeforeshow", "#page_stop_period", function (e) {

    if (SessionTokenStatus == true) {

        $("#stop_period_errormessage").hide();
        registerMachineStop.requestStopTypeList();
        registerMachineStop.displayFaultInfo();

    }
});


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

    registerMachineStop.clearErrorMsg();
    registerMachineStop.clearFields();
});