/// <reference path="locationselection.js" />
function Faultdetailwithfunction() {

    var self = {};

    self.tmp = null;
    self.selection = {};
    self.UserId = null;
    self.selectedJobID = null;
    self.FaultDescription = '';
    self.FaultSolution = '';
    self.FaultDescriptionEditFlag = false;
    self.FaultSolutionEditFlag = false;
    self.SparePartList = null;
    self.faultInfoHTML = '';
    self.faultDetailInfoHTML = '';
    self.selectedJobID = '';
    self.selectedFaultID = '';
    self.FaultDescriptionRaw = '';
    self.FaultSolutionRaw = '';

    self.requestFaultInfo = function () {
        var fault_search_param = $.cookie("currently_selected_fault");
        var current_session_token = $.cookie("session_token");

        var requester = new AjaxRequest({
            data: { "fault_id": fault_search_param, "session_token": current_session_token }, // This is for the json request
            success: self.FaultInfoReceptionSuccess,
            error: self.FaultInfoReceptionFailure,
            url: "RequestSelectedFaultInfo"
        });
        requester.ExecuteRequest();
    }

    self.requestFaultStopList = function () {
        var fault_search_param = $.cookie("currently_selected_fault");
        c2('From requestFaultStopList');
        c2('Fault ID: ' + fault_search_param);
        var requester = new AjaxRequest({
            data: { "fault_id": fault_search_param}, // This is for the json request
            success: self.FaultStopInfoReceptionSuccess,
            error: self.FaultStopInfoFailure,
            url: "RequestStopPeriodsForFault"
        });
        requester.ExecuteRequest();
    }

    self.checkForAssociatedSpareParts = function () {
        var fault_search_param = $.cookie("currently_selected_fault");
        var requester = new AjaxRequest({
            data: { "fault_id": fault_search_param },
            success: self.checkForAssociatedSparePartsSuccess,
            error: self.checkForAssociatedSparePartsFailure,
            url: "RequestSelectedFaultSparePartList"
        });
        requester.ExecuteRequest();
    }


    self.checkForAssociatedSparePartsSuccess = function (data, status, xhr) {
        c1('Success fetching associated spare parts');

        self.SparePartList = data.d.SparepartsToBeConsumed;

        $.cookie("currently_selected_jobid", self.selectedJobID);

        if (defined(self.SparePartList) && self.SparePartList.length > 0) {
            $.mobile.navigate("#page_handle_sp_consumption", { role: "page" });
        }
        else {
            $.mobile.navigate("#page_handle_sp_consumption", { role: "page" });
            // $.mobile.navigate("#page_handle_sp_consumption", { role: "page" });
        }


    }

    self.checkForAssociatedSparePartsFailure = function (data, status, xhr) {
        c1('Failed to fetch associated spare parts list!');
        DbCommunicationErrorHandler(WEBSERVICE_FAULT_JSONREQUEST);
    }


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

        $('#faultpagewithfunction_details').empty();

        console.log(data.d);

        if (data.d.HasContent == true && data.d.SessionTokenValid == true) {

            self.FaultDescription = data.d.FaultDescription;
            self.FaultSolution = data.d.FaultSolution;
            self.selectedJobID = data.d.JobID;
            self.selectedFaultID = data.d.FaultID;

            self.FaultDescriptionRaw = data.d.FaultDescriptionRaw;
            self.FaultSolutionRaw = data.d.FaultSolutionRaw;
            self.machineStopGroup = data.d.MachineStopGroup;
            self.machineStopGroupID = data.d.MachineStopGroupID;




            var faultID = data.d.FaultID;
            var jobID = data.d.JobID;
            var discoveredBy = data.d.DiscoveredBy;
            var discoveredOn = data.d.DiscoveredOn;
            var faultCause = data.d.FaultCause;
            if (faultCause == 'Unspecified') {
                faultCause = ReturnPhraseOnKey('global_unspecified');
            }
            self.faultType = data.d.FaultType;
            self.machineName = data.d.MachineName;
            self.machineNumber = data.d.MachineNumber;
            var resolvedOn = data.d.ResolvedOn;
            if ((resolvedOn == 'Unspecified') || (resolvedOn == '')) {
                resolvedOn = ReturnPhraseOnKey('global_unspecified');
            }
            var signingPerson = data.d.SigningPerson;
            if (signingPerson == 'Unspecified') {
                signingPerson = ReturnPhraseOnKey('global_unspecified');
            }
            var expectedEndDate = data.d.ExpectedEndDate;
            var selectedPriorityCode = data.d.SelectedPriorityCode;
            var faultLocation = data.d.LocationFullPath;
            var cleanupStatus = data.d.CleanupFlag;


            self.selectedJobID = data.d.JobID;

 

            self.faultInfoHTML = '<p><strong>';
            self.faultInfoHTML += ReturnPhraseOnKey('faultdetailwithfunction_jobid');
            self.faultInfoHTML += ' </strong>';
            self.faultInfoHTML += jobID;
            self.faultInfoHTML += ' ';
            if (data.d.FaultStarted == true) {
                self.faultInfoHTML += '<img src="images/led.gif" height="20" width="20" style="position:relative; bottom:-4px; padding-right: 3px">';
            }
            self.faultInfoHTML += '</p><p><b>';
            self.faultInfoHTML += ReturnPhraseOnKey('faultdetailwithfunction_machinename');
            self.faultInfoHTML += '</b>';
            self.faultInfoHTML += self.machineName;
            self.faultInfoHTML += '</p>';

            self.faultDetailInfoHTML = '<table class="job_info_table"><tr><td class="label">';
            self.faultDetailInfoHTML += ReturnPhraseOnKey('faultdetailwithfunction_machinenumber');
            self.faultDetailInfoHTML += '</td><td>';
            self.faultDetailInfoHTML += self.machineNumber;
            self.faultDetailInfoHTML += '</td></tr><tr><td class="label">';
            self.faultDetailInfoHTML += ReturnPhraseOnKey('faultdetailwithfunction_location_path');
            self.faultDetailInfoHTML += '</td><td>';
            self.faultDetailInfoHTML += faultLocation;
            self.faultDetailInfoHTML += '</td></tr><tr><td class="label">';
            self.faultDetailInfoHTML += ReturnPhraseOnKey('faultdetailwithfunction_discoveredon');
            self.faultDetailInfoHTML += '</td><td>';
            self.faultDetailInfoHTML += discoveredOn;
            self.faultDetailInfoHTML += '</td></tr><tr><td class="label">';
            self.faultDetailInfoHTML += ReturnPhraseOnKey('faultdetailwithfunction_discoveredby');
            self.faultDetailInfoHTML += '</td><td>';
            self.faultDetailInfoHTML += discoveredBy;
            self.faultDetailInfoHTML += '</td></tr><tr><td class="label">';
            self.faultDetailInfoHTML += ReturnPhraseOnKey('activitydetailwithfunction_selectedprioritycode');
            self.faultDetailInfoHTML += '</td><td>';
            if (selectedPriorityCode.length == '') {
                self.faultDetailInfoHTML += ReturnPhraseOnKey('global_unspecified');
            }
            else {
                self.faultDetailInfoHTML += selectedPriorityCode;
            }
            self.faultDetailInfoHTML += '</td></tr><tr><td class="label">';
            self.faultDetailInfoHTML += ReturnPhraseOnKey('faultdetailwithfunction_faulttype');
            self.faultDetailInfoHTML += '</td><td>';
            self.faultDetailInfoHTML += self.faultType;
            self.faultDetailInfoHTML += '</td></tr><tr><td class="label">';
            self.faultDetailInfoHTML += ReturnPhraseOnKey('faultdetailwithfunction_faultcause');
            self.faultDetailInfoHTML += '</td><td>';
            self.faultDetailInfoHTML += faultCause;
            self.faultDetailInfoHTML += '</td></tr>';
            self.faultDetailInfoHTML += (expectedEndDate.length > 0) ? '<tr><td class="label">' + ReturnPhraseOnKey('faultdetailwithfunction_expectedenddate') + '</td><td>' + expectedEndDate + '</td></tr>' : "";
            self.faultDetailInfoHTML += '<tr><td class="label">';
            self.faultDetailInfoHTML += ReturnPhraseOnKey('faultdetailwithfunction_signingperson');
            self.faultDetailInfoHTML += '</td><td>';
            self.faultDetailInfoHTML += signingPerson;
            self.faultDetailInfoHTML += '</td></tr>';
            if (CLEANUP_ACTIVE == true) {
                
                self.faultDetailInfoHTML += '<tr><td class="label">' + ReturnPhraseOnKey('activitydetailwithfunction_cleanup_status') + '</td><td>';
                if (cleanupStatus == true){
                    self.faultDetailInfoHTML += ReturnPhraseOnKey('global_yes');
                }
                else if (cleanupStatus == false) {
                    self.faultDetailInfoHTML += ReturnPhraseOnKey('global_no');
                }
                else {
                    self.faultDetailInfoHTML += ReturnPhraseOnKey('global_unspecified');
                }
                self.faultDetailInfoHTML += '</td></tr>';
            }
            self.faultDetailInfoHTML += '</table>'


            $('#faultpagewithfunction_details').html(self.faultInfoHTML);
            $('#faultpagewithfunction_detailcontent').html(self.faultDetailInfoHTML);

            var seeMoreLabel = ReturnPhraseOnKey('activitydetailwithfunction_expandtext');
            var seeLessLabel = ReturnPhraseOnKey('activitydetailwithfunction_collapsetext');

            if (self.FaultDescription.length > 0) {
                $('#faultpagewithfunction_faultdescription').html(self.FaultDescription);
                $('#faultpagewithfunction_faultdescription').jTruncate(
                    {
                        length: 50,
                        minTrail: 50,
                        moreText: seeMoreLabel,
                        lessText: seeLessLabel
                    });

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

            }
            else {
                $('#faultpagewithfunction_faultdescription').html('');

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

            if (self.FaultSolution.length > 0) {
                $('#faultpagewithfunction_faultsolution').html(self.FaultSolution);
                $('#faultpagewithfunction_faultsolution').jTruncate(
                    {
                        length: 50,
                        minTrail: 50,
                        moreText: seeMoreLabel,
                        lessText: seeLessLabel
                    });

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

            }
            else {
                $('#faultpagewithfunction_faultsolution').html('');

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

            if (data.d.FaultStarted == true) {
                $('#faultdetailwithfunction_finishonly').show();
                $('#faultdetailwithfunction_startfinish_menu').hide();
            }
            else {
                $('#faultdetailwithfunction_startfinish_menu').show();
                $('#faultdetailwithfunction_finishonly').hide();
            }

        }
        else if (data.d.SessionTokenValid == false) {
            //$.mobile.navigate("#dialog_tokenexpired", { role: "dialog" });
            $("#faultdetailwithfunction_generic_popup_header").html(ReturnPhraseOnKey("dialogue_tokenexpired_message1"));
            $("#faultdetailwithfunction_generic_popup_text").html(ReturnPhraseOnKey("dialogue_tokenexpired_message1"));

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

            $("#faultdetailwithfunction_generic_popup_button").unbind("click").click(function () {
                $("#faultdetailwithfunction_generic_popup").popup("close");
            });

            $("#faultdetailwithfunction_generic_popup").popup().popup("open");
        }
        else if (data.d.HasContent == false) {
            c1("faultdetailwithfunction row 198: No unfinished faults for this machine.");
        }
    }

    self.FaultInfoReceptionFailure = function (data, status, xhr) {
        $('#faultpagewithfunction_details').empty();
        c1('faultdetailwithfunction row 204: Unable to retrieve fault information from database.');
        DbCommunicationErrorHandler(WEBSERVICE_FAULT_JSONREQUEST);

    }

    self.FaultStopInfoReceptionSuccess = function (data, status, xhr) {
        c1('faultdetailwithfunction row 396: received stop list');
        console.log(data.d);
        var stoplist = data.d.StopListForFault;
        if (stoplist.length > 0) {

            c4('stop list present');
            $('#faultpagewithfunction_stoplist').html(self.BuildFaultStopSection(data.d));

            //$("#faultpagewithfunction_stoplist").collapsibleset("refresh");

            //$("#faultpagewithfunction_stoplist").listview().listview("refresh");


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


        }
        else {
            c4('no machine stops registered');
        }
    }

    self.FaultStopInfoReceptionFailure = function (data, status, xhr) {
        c1('faultdetailwithfunction row 300: Unable to retrieve stop period from database.');
        DbCommunicationErrorHandler(WEBSERVICE_FAULT_JSONREQUEST);
    }

    self.BuildFaultStopSection = function (incomingData) {
        c2('++++++');
        c2(incomingData);
        //stoplistHTML += '<tr><td class="label">' + 'Start' + '</td><td class="label">' + 'End' + '</td><td class="label">' + 'Stop Type' + '</td><td class="label">' + 'Machine Only' + '</td></tr>'
        stoplistHTML = '';

        jQuery.each(incomingData.StopListForFault, function () {
            var startdate = localizeDatePickerValue(this.StartDate);
            var starttime = this.StartTime;
            var enddate = localizeDatePickerValue(this.EndDate);
            var endtime = this.EndTime;
            var machineOnly = this.MachineOnly;
            var stopType = this.StopType;
            stoplistHTML += '<table id="stop_detail_table" class="job_info_table">';
            stoplistHTML += '<tr><td class="label">';
            stoplistHTML += ReturnPhraseOnKey('stop_period_start');
            stoplistHTML += '</td><td>';
            stoplistHTML += startdate;
            stoplistHTML += ' ';
            stoplistHTML += starttime
            stoplistHTML += '</td></tr>';
            stoplistHTML += '<tr><td class="label">';
            stoplistHTML += ReturnPhraseOnKey('stop_period_stop');
            stoplistHTML += '</td><td>';
            stoplistHTML += enddate;
            stoplistHTML += ' ';
            stoplistHTML += endtime
            stoplistHTML += '</td></tr>';
            stoplistHTML += '<tr><td class="label">';
            stoplistHTML += ReturnPhraseOnKey('stop_period_selected_machine_only');
            stoplistHTML += '</td><td>';
            if (machineOnly == true) {
                stoplistHTML += ReturnPhraseOnKey('global_yes');
            }
            else {
                stoplistHTML += ReturnPhraseOnKey('global_no');
            }
            stoplistHTML += '</td></tr>';
            stoplistHTML += '<tr><td class="label">';
            stoplistHTML += 'Stop type';
            stoplistHTML += '</td><td>';
            if (stopType == 'Unspecified') {
                stoplistHTML += ReturnPhraseOnKey('global_unspecified');
            }
            else {
                stoplistHTML += ReturnPhraseOnKey('stop_period_type');
            }
            stoplistHTML += '</td></tr></table><br>';
        
        });


        console.log(stoplistHTML);
        return stoplistHTML;
    }

    self.SaveFaultDescriptionEditNote = function () {

        var faultDescriptionContent = $('#faultpagewithfunction_faultdescription_editbox').val();

        var requester = new AjaxRequest({
            data: { "faultdescription": faultDescriptionContent, "jobid": self.selectedJobID }, // This is for the json request
            success: self.SaveFaultDescriptionEditSuccess,
            error: self.SaveFaultDescriptionEditFailure,
            url: "SaveFaultDescription"
        });
        requester.ExecuteRequest();

    }

    self.SaveFaultDescriptionEditSuccess = function (data, status, xhr) {
        c_objects(data.d);
    }

    self.SaveFaultDescriptionEditFailure = function (data, status, xhr) {
        c1('faultdetailwithfunction row 228: Failed to save activity edit in database!');
        DbCommunicationErrorHandler(WEBSERVICE_FAULT_JSONREQUEST);
    }

    self.SaveFaultSolutionEditNote = function () {

        var faultSolutionContent = $('#faultpagewithfunction_faultsolution_editbox').val();

        var requester = new AjaxRequest({
            data: { "faultsolution": faultSolutionContent, "jobid": self.selectedJobID }, // This is for the json request
            success: self.SaveFaultSolutionEditSuccess,
            error: self.SaveFaultSolutionEditFailure,
            url: "SaveFaultSolution"
        });
        requester.ExecuteRequest();

    }

    self.SaveFaultSolutionEditSuccess = function (data, status, xhr) {
        c_objects(data.d);
    }

    self.SaveFaultSolutionEditFailure = function (data, status, xhr) {
        c1('faultdetailwithfunction row 251: Failed to save activity edit in database!');
        DbCommunicationErrorHandler(WEBSERVICE_FAULT_JSONREQUEST);
    }

    self.FaultDescriptionEditable = function () {
        //var editbox = '<div data-role="fieldcontain" data-controltype="textarea">';
        //editbox += '<textarea id="faultpagewithfunction_faultdescription_editbox" placeholder="">';
        //editbox += '</textarea></div>';

        var editbox = '<textarea id="faultpagewithfunction_faultdescription_editbox" placeholder="">';
        editbox += '</textarea></div>';

        self.FaultDescriptionEditFlag = true;
        if ($('#faultpagewithfunction_faultdescription').is(":hidden")) {
            $('#faultpagewithfunction_faultdescription').show();
        }

        $('#faultpagewithfunction_faultdescription').replaceWith(editbox);

        $('#faultpagewithfunction_faultdescription_editbox').val(self.FaultDescriptionRaw);
        $('#faultpagewithfunction_faultdescription_editbox').textinput().textinput("refresh");

        $('#faultpagewithfunction_editdescriptionbuttonlabel').html(ReturnPhraseOnKey('faultpagewithfunction_savefaultdescription'));
    }

    self.FaultDescriptionReadOnly = function () {
        var plainbox = '<div class="default_jobnotecontent_class jobnote-presentation-only" id="faultpagewithfunction_faultdescription"></div></div>';
        self.FaultDescriptionEditFlag = false;
        var editedText = $('#faultpagewithfunction_faultdescription_editbox').val();

        var seeMoreLabel = ReturnPhraseOnKey('faultdetailwithfunction_expandtext');
        var seeLessLabel = ReturnPhraseOnKey('faultdetailwithfunction_collapsetext');

        $('#faultpagewithfunction_faultdescription_editbox').replaceWith(plainbox);

        if (editedText.length > 0) {
            self.FaultDescription = editedText;
            self.FaultDescriptionRaw = editedText;

            self.FaultDescription = self.FaultDescription.replace(new RegExp('\r?\n', 'g'), '<br />');


            $('#faultpagewithfunction_faultdescription').html(self.FaultDescription);
            $('#faultpagewithfunction_faultdescription').jTruncate(
                    {
                        length: 50,
                        minTrail: 50,
                        moreText: seeMoreLabel,
                        lessText: seeLessLabel
                    });
        }
        else {
            $('#faultpagewithfunction_faultdescription').html('');
            self.FaultDescription = '';

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

        $('#faultpagewithfunction_editdescriptionbuttonlabel').html(ReturnPhraseOnKey('faultpagewithfunction_editfaultdescription'));

    }


    self.FaultSolutionEditable = function () {
        //var editbox = '<div data-role="fieldcontain" data-controltype="textarea">';
        //editbox += '<textarea id="faultpagewithfunction_faultsolution_editbox" placeholder="">';
        //editbox += '</textarea></div>';

        var editbox = '<textarea id="faultpagewithfunction_faultsolution_editbox" placeholder="">';
        editbox += '</textarea></div>';

        self.FaultSolutionEditFlag = true;
        if ($('#faultpagewithfunction_faultsolution').is(":hidden")) {
            $('#faultpagewithfunction_faultsolution').show();
        }

        $('#faultpagewithfunction_faultsolution').replaceWith(editbox);

        $('#faultpagewithfunction_faultsolution_editbox').val(self.FaultSolutionRaw);
        $('#faultpagewithfunction_faultsolution_editbox').textinput().textinput("refresh");

        $('#faultpagewithfunction_editfaultsolutionbuttonlabel').html(ReturnPhraseOnKey('faultpagewithfunction_savefaultsolution'));
    }

    self.FaultSolutionReadOnly = function () {
        var plainbox = '<div class="default_jobnotecontent_class jobnote-presentation-only" id="faultpagewithfunction_faultsolution"></div></div>';
        self.FaultSolutionEditFlag = false;
        var editedText = $('#faultpagewithfunction_faultsolution_editbox').val();

        var seeMoreLabel = ReturnPhraseOnKey('faultdetailwithfunction_expandtext');
        var seeLessLabel = ReturnPhraseOnKey('faultdetailwithfunction_collapsetext');

        $('#faultpagewithfunction_faultsolution_editbox').replaceWith(plainbox);

        if (editedText.length > 0) {

            self.FaultSolution = editedText;
            self.FaultSolutionRaw = editedText;

            self.FaultSolution = self.FaultSolution.replace(new RegExp('\r?\n', 'g'), '<br />');


            $('#faultpagewithfunction_faultsolution').html(self.FaultSolution);
            $('#faultpagewithfunction_faultsolution').jTruncate(
                    {
                        length: 50,
                        minTrail: 50,
                        moreText: seeMoreLabel,
                        lessText: seeLessLabel
                    });
        }
        else {
            $('#faultpagewithfunction_faultsolution').html('');
            self.FaultSolution = '';

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

        $('#faultpagewithfunction_editfaultsolutionbuttonlabel').html(ReturnPhraseOnKey('faultpagewithfunction_editfaultsolution'));

    }

    self.MarkFaultAsStarted = function (selectedExpectedEndDate) {
        var current_session_token = $.cookie("session_token");
        var requester = new AjaxRequest({
            data: { "jobid": self.selectedJobID, "selected_end_date": selectedExpectedEndDate, "session_token": current_session_token }, // This is for the json request
            success: self.MarkFaultAsStartedSuccess,
            error: self.MarkFaultAsStartedFailure,
            url: "RegisterFaultAsStarted"
        });
        requester.ExecuteRequest();

    };

    self.MarkFaultAsStartedSuccess = function (data, status, xhr) {
        $('#faultdetailwithfunction_startfinish_menu').hide();
        $('#faultdetailwithfunction_finish_fault_select_expected_enddate').hide();
        $('#faultdetailwithfunction_expected_end_date').val("");

        //$('#faultdetailwithfunction_finish_fault_finishonly').show();
        $('#faultdetailwithfunction_finishonly').show();
        $('#faultdetailwithfunction_work_menu').show();
        self.requestFaultInfo();

    }

    self.MarkFaultAsStartedFailure = function (data, status, xhr) {
        c1('faultdetailwithfunction row 382: Failed to mark fault as started!');
        DbCommunicationErrorHandler(WEBSERVICE_FAULT_JSONREQUEST);
    }

    self.RequestExpectedFinishDate = function () {
        $('#faultdetailwithfunction_startfinish_menu').hide();
        $('#faultdetailwithfunction_work_menu').hide();
        $('#faultdetailwithfunction_finish_fault_select_expected_enddate').show();
    };

    self.HandleExpectedFinishedDate = function () {
        var selectedExpectedFinishDate = "";
        selectedExpectedFinishDate = $("#faultdetailwithfunction_expected_end_date").val();
        if (selectedExpectedFinishDate.length == 0) {
            self.setErrorMsg(ReturnPhraseOnKey("faultdetailwithfunction_errormessage_expected_end_date_needs_selection"));
        }
        else {
            self.clearErrorMsg();
            selectedExpectedFinishDate = parseExpectedEndDate(selectedExpectedFinishDate);
            c3(selectedExpectedFinishDate);
            if (selectedExpectedFinishDate !== 'Invalid Date' || selectedExpectedFinishDate !== 'NaN-NaN-NaN') {
                self.MarkFaultAsStarted(selectedExpectedFinishDate);

            }
            else {
                self.setErrorMsg(ReturnPhraseOnKey('faultdetailwithfunction_errormessage_expected_end_date_invalid_input'));
                $("#faultdetailwithfunction_expected_end_date").val('').focus();
            }
        }
    };

    self.AbortExpectedEndDateSpecification = function () {
        //if ($('#faultdetailwithfunction_finish_fault_finishonly').is(":visible")) {
        //    $('#faultdetailwithfunction_finish_fault_finishonly').hide();
        //}

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

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

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

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

        $("#faultdetailwithfunction_expected_end_date").val("");
        self.clearErrorMsg();


    }

    self.setErrorMsg = function (msg) {

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

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



    return self;
}

var faultDetailWithFunction = Faultdetailwithfunction();

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

    //$('#faultpagewithfunction_editfaultdescriptionbutton').click(function () {
    //    if (faultDetailWithFunction.FaultDescriptionEditFlag == false) {

    //        faultDetailWithFunction.FaultDescriptionEditable(); 

    //    }
    //    else if (faultDetailWithFunction.FaultDescriptionEditFlag == true) {
    //        faultDetailWithFunction.SaveFaultDescriptionEditNote();
    //        faultDetailWithFunction.FaultDescriptionReadOnly();
    //    }

    //});

    $('#faultdetailwithfunction_descriptionnote_toggle_button').click(function () {
        if (faultDetailWithFunction.FaultDescriptionEditFlag == false) {
            c1('faultdetailwithfunction row 544 - switching description to editable');
            faultDetailWithFunction.FaultDescriptionEditable();

        }
        else if (faultDetailWithFunction.FaultDescriptionEditFlag == true) {
            c2('faultdetailwithfunction row 544 - switching description to read only');
            faultDetailWithFunction.SaveFaultDescriptionEditNote();
            faultDetailWithFunction.FaultDescriptionReadOnly();
        }

        swapButton($('#faultdetailwithfunction_descriptionnote_toggle_button'));

    });

    //$('#faultpagewithfunction_editfaultsolutionbutton').click(function () {
    //    if (faultDetailWithFunction.FaultSolutionEditFlag == false) {

    //        faultDetailWithFunction.FaultSolutionEditable();

    //    }
    //    else {
    //        faultDetailWithFunction.SaveFaultSolutionEditNote();
    //        faultDetailWithFunction.FaultSolutionReadOnly();
    //    }

    //});

    $('#faultdetailwithfunction_solutionnote_toggle_button').click(function () {
        if (faultDetailWithFunction.FaultSolutionEditFlag == false) {

            faultDetailWithFunction.FaultSolutionEditable();

        }
        else {
            faultDetailWithFunction.SaveFaultSolutionEditNote();
            faultDetailWithFunction.FaultSolutionReadOnly();
        }

        swapButton($('#faultdetailwithfunction_solutionnote_toggle_button'));

    });

});

$(document).on("pagebeforeshow", "#page_faultdetailwithfunction", function () {
    //$('#faultdetailwithfunction_finish_fault_finishonly').hide;
    $('#faultdetailwithfunction_finishonly').hide;
    $('#faultdetailwithfunction_startfinish_menu').hide();
    $('#faultdetailwithfunction_finish_fault_select_expected_enddate').hide();
    $('#faultdetailwithfunction_work_menu').show();
    $('#faultpagewithfunction_registered_stops').hide();

    if (SessionTokenStatus == true) {
        faultDetailWithFunction.requestFaultInfo();
        faultDetailWithFunction.requestFaultStopList();
    }


});


$(document).on("pageshow", "#page_faultdetailwithfunction", function (e) {

    if (SessionTokenStatus == true) {

        $("#faultdetailwithfunction_errortext").hide();


        //*****************************************************************************************************
        //20200401 - moved to pagebeforeshow event, additional check on visibility of bottom menus added below
        //faultDetailWithFunction.requestFaultInfo();
        //*****************************************************************************************************

        if (currently_selected_application_section == MACHINES_SECTION) {
            $("#faultdetailwithfunction_back_button").unbind().click(function () {
                $(":mobile-pagecontainer").pagecontainer("change", "#page_machinedetail", { role: "page", reverse: false, changeHash: false });
                e3('faultdetailwithfunction row 492');
            });
        }
        else if (currently_selected_application_section == USER_SECTION) {
            $("#faultdetailwithfunction_back_button").unbind().click(function () {
                $(":mobile-pagecontainer").pagecontainer("change", "#page_mainpersonallist", { role: "page", reverse: false, changeHash: false });
                e3('faultdetailwithfunction row 498');
            });
        }

        //$('#faultdetailwithfunction_finishfault').unbind().click(function () {

        //    $.cookie("currently_selected_jobid", faultDetailWithFunction.selectedJobID);
        //    var checkCookie = $.cookie("currently_selected_jobid");
        //    finishjobwizard_faultreasonlist_visible = SHOW_COMPONENT;
        //    $.mobile.navigate("#page_finishjobwizard_1", { role: "page" });
        //    JOB_HANDLE_MODE = FINISH_JOB;
        //    e3('faultdetailwithfunction row 508');
        //});

        $('#faultdetailwithfunction_startfinish_menu_finishfault').unbind().click(function () {

            $.cookie("currently_selected_jobid", faultDetailWithFunction.selectedJobID);
            var checkCookie = $.cookie("currently_selected_jobid");
            finishjobwizard_faultreasonlist_visible = SHOW_COMPONENT;
            $.mobile.navigate("#page_finishjobwizard_1", { role: "page" });
            JOB_HANDLE_MODE = FINISH_JOB;
            e3('faultdetailwithfunction row 519');


        });

        $('#faultdetailwithfunction_finishonly_menu_finishfault').unbind().click(function () {

            $.cookie("currently_selected_jobid", faultDetailWithFunction.selectedJobID);
            var checkCookie = $.cookie("currently_selected_jobid");
            finishjobwizard_faultreasonlist_visible = SHOW_COMPONENT;
            $.mobile.navigate("#page_finishjobwizard_1", { role: "page" });
            JOB_HANDLE_MODE = FINISH_JOB;
            e3('faultdetailwithfunction row 519');


        });

        $('#faultdetailwithfunction_startfinish_menu_startfault').unbind().click(function (e) {

            e.preventDefault();
            e.stopPropagation();
            //faultDetailWithFunction.MarkFaultAsStarted();
            faultDetailWithFunction.RequestExpectedFinishDate();
        });

        $("#faultdetailwithfunction_submit_finish_date").unbind().click(function (e) {
            e.preventDefault();
            e.stopPropagation();
            faultDetailWithFunction.HandleExpectedFinishedDate();
        });

        $("#faultdetailwithfunction_submit_abort_date").unbind().click(function (e) {
            e.preventDefault();
            e.stopPropagation();
            faultDetailWithFunction.AbortExpectedEndDateSpecification();

        });


        $("#faultdetailwithfunction_startfinish_menu_handlespareparts").unbind().click(function () {
            e.preventDefault();
            e.stopPropagation();
            JOB_HANDLE_MODE = HANDLE_FAULT;
            c2('testing navigation to spare part handling page');
            faultDetailWithFunction.checkForAssociatedSpareParts();
        });

        $("#faultdetailwithfunction_startfinish_menu_handlemanhours").unbind().click(function () {
            e.preventDefault();
            e.stopPropagation();
            JOB_HANDLE_MODE = HANDLE_FAULT;
            c3('calling navigation to handle manhours' + faultDetailWithFunction.selectedJobID);
            $.cookie("currently_selected_jobid", faultDetailWithFunction.selectedJobID);
            c2('testing navigation to manhours handling page from a fault detail page');
            $.mobile.navigate("#page_handle_manhours", { role: "page" });
        });

        $("#faultdetailwithfunction_startfinish_menu_register_stop").unbind().click(function () {
            e.preventDefault();
            e.stopPropagation();
            JOB_HANDLE_MODE = HANDLE_FAULT;
            $.cookie("currently_selected_jobid", faultDetailWithFunction.selectedJobID);
            c2('navigating to register machine stop page');
            $.mobile.navigate("#page_stop_period", { role: "page" });
        });

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

$(document).on("pagehide", "#page_faultdetailwithfunction", function () {
    //if ($('#faultdetailwithfunction_finish_fault_finishonly').is(":visible")) {
    //    $('#faultdetailwithfunction_finish_fault_finishonly').hide();
    //}

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

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

