function Machinedetail() {

    var self = {};

    self.tmp = null;
    self.selection = {};
    self.UserId = null;
    self.ActivityList = null;
    self.FaultList = null;
    self.SparePartList = null;
    self.HistoricalActivityList = null;
    self.HistoricalFaultList = null;
    self.HistoricalActivitiesPresent = false;
    self.HistoricalFaultsPresent = false;
    self.previousPageId;


    //Number of days back in time. Curently a constant, implementation of user defined value is to be implemented in the future.
    self.joblistNoOfDaysBackInTime = -200;

    //Number of days forward in time. Curently a constant, implementation of user defined value is to be implemented in the future.
    self.joblistNoOfDaysForwardInTime = 200;




    self.requestMachineInfo = function () {

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

        //var machine_search_param = $("#selectmachine_machineid_input").val();


        var requester = new AjaxRequest({
            data: { "requested_machine_number": requested_machine_number, "session_token": current_session_token },
            success: self.MachineInfoRequestComplete,
            error: self.MachineInfoRequestIncomplete,
            url: "RequestMachineInfo"
        });
        requester.ExecuteRequest();

    }

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


        if (data.d.SessionTokenValid == false) {
            //$.mobile.navigate("#dialog_tokenexpired", { role: "dialog" });

            $("#machinedetail_generic_popup_header").html(ReturnPhraseOnKey("dialogue_tokenexpired_message1"));
            $("#machinedetail_generic_popup_text").html(ReturnPhraseOnKey("dialogue_tokenexpired_message1"));

            $("#machinedetail_generic_popup").off().on("popupafterclose", function (event, ui) {
                $(":mobile-pagecontainer").pagecontainer("change", "#page_login", { role: "page", reverse: false, changeHash: false });
                e4('machinedetail row 56');
            });

            $("#machinedetail_generic_popup_button").unbind("click").click(function () {
                $("#machinedetail_generic_popup").popup("close");
            });

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

            var machineLocation = data.d.Location;
            var machineName = data.d.MachineName;
            var machineNumber = data.d.MachineNumber;
            var machineIDCode = data.d.MachineIDCode;
            var machineType = data.d.MachineType;

            var machineInfoText = '<table id="faultdetail_table">';
            machineInfoText += '<tr><td class="label">';
            machineInfoText += ReturnPhraseOnKey('machinedetail_location');
            machineInfoText += '</td><td>';
            machineInfoText += machineLocation;
            machineInfoText += '</td></tr>';
            machineInfoText += '<tr><td class="label">';
            machineInfoText += ReturnPhraseOnKey('machinedetail_machinenumber');
            machineInfoText += '</td><td>';
            machineInfoText += machineNumber;
            machineInfoText += '</td></tr>';
            machineInfoText += '<tr><td class="label">';
            machineInfoText += ReturnPhraseOnKey('machinedetail_machineidcode');
            machineInfoText += '</td><td>';
            machineInfoText += machineIDCode;
            machineInfoText += '</td></tr>';
            machineInfoText += '<tr><td class="label">';
            machineInfoText += ReturnPhraseOnKey('machinedetail_machinetype');
            machineInfoText += '</td><td>';
            machineInfoText += machineType;
            machineInfoText += '</td></tr>';
            machineInfoText += '</table>';


            $("#machinedetail_header").html(machineName);
            $("#machinedetail_details").html(machineInfoText);


            $.cookie("currently_selected_machine_name", machineName);
        }

    }

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

        $("#machinedetail_header").html('');
        $("#machinedetail_details").html('');
        DbCommunicationErrorHandler(WEBSERVICE_FAULT_JSONREQUEST);

    }

    self.RequestMachineActivityList = function () {
        var requested_machine_number = $.cookie("currently_selected_machine");


        var startOfPeriod = self.joblistNoOfDaysBackInTime;
        var endOfOfPeriod = self.joblistNoOfDaysForwardInTime;
        var requester = new AjaxRequest({
            data: { "machine_id_from_cookie": requested_machine_number, "pastDays": startOfPeriod, "futureDays": endOfOfPeriod }, // This is for the json request
            success: self.MachineActivityListRequestComplete,
            error: self.MachineActivityListRequestIncomplete,
            url: "RequestOutstandingActivitiesForMachine"
        });
        requester.ExecuteRequest();

    }

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

        console.log(data.d);

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

        if (data.d.HasContent == true) {
            c2('machine detajls row 137 - machine has activities');

            self.ActivityList = data.d.UnfinishedActivities;
            self.BuildActivitySection();

            if ($('#machinedetail_activities').is(":hidden")) {
                $('#machinedetail_activities').show();
            }
        }
        else {
            c2("machinedetail row 147: No activities present for this machine");
            $('#machinedetail_activities').hide();
            if ($('#machinedetail_activities').is(":visible")) {
                c4('machinedetail row 149 -hiding activities section');
                $('#machinedetail_activities').hide();
            }
        }
    }

    self.BuildActivitySection = function () {


        var activityListElement = '';

        jQuery.each(self.ActivityList, function () {
            //activityListElement += '<li data-theme="c" id="machinedetail_activitydetail"  class = "listdetail_default_class" data-activityid="';
            activityListElement += '<li id="machinedetail_activitydetail"  class = "listdetail_default_class" data-activityid="';
            activityListElement += this.JobID;
            activityListElement += '"><a href="#page_activitydetailwithfunction" data-transition="slide">';
            activityListElement += '<span class="collapsible_font_override">' + this.ScheduledDate;
            activityListElement += " - ";
            activityListElement += this.TaskName;
            activityListElement += '<span></a></li>';
        });


        $("#machinedetail_activitylist").html(activityListElement);

        $("#machinedetail_maincollapsible").collapsibleset("refresh");
        $("#machinedetail_activitylist").listview().listview("refresh");

    }



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

        $("#machinedetail_activitylist").html('');
        c1("machinedetail row 178: Unable to retrieve machine's activity list from database.");
        DbCommunicationErrorHandler(WEBSERVICE_FAULT_JSONREQUEST);

    }

    self.RequestMachineFaultList = function () {
        var requested_machine_number = $.cookie("currently_selected_machine");

        var startOfPeriod = self.joblistNoOfDaysBackInTime;
        var endOfOfPeriod = self.joblistNoOfDaysForwardInTime;
        var requester = new AjaxRequest({
            data: { "machine_id_from_cookie": requested_machine_number, "pastDays": startOfPeriod, "futureDays": endOfOfPeriod }, // This is for the json request
            success: self.MachineFaultListRequestComplete,
            error: self.MachineFaultListRequestIncomplete,
            url: "RequestOutstandingFaultsForMachine"
        });
        requester.ExecuteRequest();

    }


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

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

        if (data.d.HasContent == true) {
            self.FaultList = data.d.UnfinishedFaults;
            self.BuildFaultSection();
            if ($('#machinedetail_faults').is(":hidden")) {
                $('#machinedetail_faults').show();
            }

        }
        else {
            c1("machinedetail row 212: No faults present for this machine");
            $('#machinedetail_faults').hide();
            if ($('#machinedetail_faults').is(":visible")) {
                $('#machinedetail_faults').hide();
            }
        }
    }

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

        $('#machinedetail_faultlist').empty();
        c1("machinedetail row 222: Unable to retrieve machine's fault list from database.");
        DbCommunicationErrorHandler(WEBSERVICE_FAULT_JSONREQUEST);

    }

    self.BuildFaultSection = function () {

        var faultListElement = '';

        jQuery.each(self.FaultList, function () {
            //faultListElement += '<li data-theme="c" id="machinedetail_faultdetail"  class = "listdetail_default_class" data-faultid="';
            faultListElement += '<li id="machinedetail_faultdetail"  class = "listdetail_default_class" data-faultid="';
            faultListElement += this.JobID;
            faultListElement += '"><a href="#page_faultdetailwithfunction" data-transition="slide">';
            faultListElement += this.DiscoveryDate;
            faultListElement += " - ";
            faultListElement += this.FaultType;
            faultListElement += '</a></li>';

        });



        $("#machinedetail_faultlist").html(faultListElement);

        $("#machinedetail_maincollapsible").collapsibleset("refresh");

        $("#machinedetail_faultlist").listview().listview("refresh");

    }

    self.RequestSparePartListForMachine = function () {

        var requested_machine_number = $.cookie("currently_selected_machine");
        var requester = new AjaxRequest({
            data: { "machine_id_from_cookie": requested_machine_number },
            success: self.MachineSparepartListRequestComplete,
            error: self.MachineSpareparttListRequestIncomplete,
            url: "RequestSparePartsAssociatedWithMachine"
        });
        requester.ExecuteRequest();

    }

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

        $("#machinedetail_sparepartlist").empty();
        c1('Spare part list object:');
        console.log(data.d);
        if (data.d.HasContent == true) {
            self.SparePartList = data.d.TypeList;
            self.BuildSparePartSection();
            if ($('#machinedetail_spareparts').is(":hidden")) {
                $('#machinedetail_spareparts').show();
            }

        }
        else {
            c1("machinedetail row 278: No spare parts present for this machine");
            $('#machinedetail_spareparts').hide();
            if ($('#machinedetail_spareparts').is(":visible")) {
                $('#machinedetail_spareparts').hide();
            }
        }
    }

    self.MachineSpareparttListRequestIncomplete = function (data, status, xhr) {
        $("#machinedetail_sparepartlist").empty();
        c1("machinedetail row 287: Unable to retrieve machine's spare part list from database.");
        DbCommunicationErrorHandler(WEBSERVICE_FAULT_JSONREQUEST);


    }

    self.BuildSparePartSection = function () {

        var sparepartlistHTML = '';


        jQuery.each(self.SparePartList, function () {

            sparepartlistHTML += '<li role="heading" data-role="list-divider">';
            sparepartlistHTML += this.SparepartType;
            sparepartlistHTML += '</li>';

            var currentSparePartType = this;

            jQuery.each(currentSparePartType.Spareparts, function () {
                //sparepartlistHTML += '<li data-theme="c" data-sparepartid="';
                sparepartlistHTML += '<li data-sparepartid="';
                sparepartlistHTML += this.SparePartNumber;
                sparepartlistHTML += '"><a href="#" data-transition="slide" style="font-size:small">';
                sparepartlistHTML += this.SparePartNumber;
                sparepartlistHTML += '<br /> ';
                sparepartlistHTML += this.SparePartName;
                sparepartlistHTML += '</a></li>';

            });
        });

        $("#machinedetail_sparepartlist").html(sparepartlistHTML);

        $("#machinedetail_maincollapsible").collapsibleset("refresh");

        $("#machinedetail_sparepartlist").listview().listview("refresh");

    }

    self.RequestHistoricalActivityList = function () {
        var requested_machine_number = $.cookie("currently_selected_machine");

        var requester = new AjaxRequest({
            data: { "machine_id_from_cookie": requested_machine_number },
            success: self.HistoricalActivityListRequestComplete,
            error: self.HistoricalActivityListRequestIncomplete,
            url: "RequestHistoricalActivitiesForMachine"
        });
        requester.ExecuteRequest();

    }

    self.HistoricalActivityListRequestComplete = function (data, status, xhr) {
        $("#machinedetail_activities_history").empty();

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

            self.HistoricalActivityList = data.d.UnfinishedActivities;
            var historicalActivityListHTML = '';

            jQuery.each(self.HistoricalActivityList, function () {
                historicalActivityListHTML += '<li data-activityid="';
                historicalActivityListHTML += this.JobID;
                //historicalActivityListHTML += '" data-theme="c"><a href="#" data-transition="slide">';
                historicalActivityListHTML += '"><a href="#" data-transition="slide">';
                historicalActivityListHTML += this.ScheduledDate;
                historicalActivityListHTML += " - ";
                historicalActivityListHTML += this.TaskName;
                historicalActivityListHTML += '</a></li>';

            });

            $("#machinedetail_activities_history").html(historicalActivityListHTML);

            $("#machinedetail_maincollapsible").collapsibleset("refresh");

            $("#machinedetail_activities_history").listview().listview("refresh");

            $('#machinedetail_history_activitylist').show();

            self.HistoricalActivitiesPresent = true;

        }
        else {
            c1("machinedetail row 368: No historical activities present for this machine");
            self.HistoricalActivitiesPresent = false;
            $('#machinedetail_history_activitylist').hide();
        }

    }

    self.HistoricalActivityListRequestIncomplete = function (data, status, xhr) {
        $("#machinedetail_activities_history").html('');
        self.HistoricalActivitiesPresent = false;
        c1("machinedetail row 378: Unable to retrieve machine's activity history from database.");
        DbCommunicationErrorHandler(WEBSERVICE_FAULT_JSONREQUEST);

    }

    self.RequestHistoricalFaultList = function () {
        var requested_machine_number = $.cookie("currently_selected_machine");

        var requester = new AjaxRequest({
            data: { "machine_id_from_cookie": requested_machine_number },
            success: self.HistoricalFaultListRequestComplete,
            error: self.HistoricalFaultListRequestIncomplete,
            url: "RequestHistoricalFaultForMachine"
        });
        requester.ExecuteRequest();

    }

    self.HistoricalFaultListRequestComplete = function (data, status, xhr) {
        $("#machinedetail_faults_history").empty();

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

            $('#machinedetail_history_faultlist').show();
            $('#machinedetail_jobhistory').show();

            self.HistoricalFaultList = data.d.UnfinishedFaults;
            var historicalFaultListHTML = '';

            jQuery.each(self.HistoricalFaultList, function () {
                historicalFaultListHTML += '<li data-faultid="';
                historicalFaultListHTML += this.JobID;
                //historicalFaultListHTML += '" data-theme="c"><a href="#" data-transition="slide">';
                historicalFaultListHTML += '"><a href="#" data-transition="slide">';
                historicalFaultListHTML += this.DiscoveryDate;
                historicalFaultListHTML += " - ";
                historicalFaultListHTML += this.FaultType;
                historicalFaultListHTML += '</a></li>';

            });

            $("#machinedetail_faults_history").html(historicalFaultListHTML);
            $("#machinedetail_maincollapsible").collapsibleset("refresh");

            $("#machinedetail_faults_history").listview().listview("refresh");

            self.HistoricalFaultsPresent = true;


        }
        else {
            c1("machinedetail row 429: No completed faults for this machine.");
            $('#machinedetail_history_faultlist').hide();
            self.HistoricalFaultsPresent = false;
        }

        if (self.HistoricalActivitiesPresent == false && self.HistoricalFaultsPresent == false) {
            $("#machinedetail_jobhistory").hide();
        }
        else {
            $("#machinedetail_jobhistory").show();
        }


    }

    self.HistoricalFaultListRequestIncomplete = function (data, status, xhr) {
        $("#machinedetail_faults_history").html('');
        self.HistoricalFaultsPresent = false;
        c1("machinedetail row 446: Unable to retrieve machine's fault history from database.");
        DbCommunicationErrorHandler(WEBSERVICE_FAULT_JSONREQUEST);
    }



    self.attachEventToActivityList = function () {
        $('#machinedetail_activitylist').on('click', 'li', function () {
            //alert($(this).text());
            var selectedActivityID = $(this).data("activityid");
            var selectedFaultID = 0;

            if (selectedActivityID !== undefined) {
                $.cookie("currently_selected_activity", selectedActivityID);
                $.cookie("currently_selected_fault", selectedFaultID);

                var activityIdFromCookie = $.cookie("currently_selected_activity");

                $(":mobile-pagecontainer").pagecontainer("change", "#page_activitydetailwithfunction", { role: "page", reverse: false, changeHash: false });
                e4('machinedetail row 466');
            }
        });

    }

    self.attachEventToFaultList = function () {
        $('#machinedetail_faultlist').on('click', 'li', function () {
            //alert($(this).text());
            var selectedFaultID = $(this).data("faultid");
            var selectedActivityID = 0;


            if (selectedFaultID !== undefined) {
                $.cookie("currently_selected_fault", selectedFaultID);
                $.cookie("currently_selected_activity", selectedActivityID);
                $(":mobile-pagecontainer").pagecontainer("change", "#page_faultdetailwithfunction", { role: "page", reverse: false, changeHash: false });
                e4('machinedetail row 483');
            }
        });

    }

    self.attachEventToHistoricalActivityList = function () {
        $('#machinedetail_history_activitylist').on('click', 'li', function () {
            //alert($(this).text());
            var selectedActivityID = $(this).data("activityid");
            var selectedFaultID = 0;

            if (selectedActivityID !== undefined) {
                $.cookie("currently_selected_activity", selectedActivityID);
                $.cookie("currently_selected_fault", selectedFaultID);

                var activityIdFromCookie = $.cookie("currently_selected_activity");

                $.mobile.navigate("#page_activitydetailhistorical", { role: "page" });
                e4('machinedetail row 502');
            }
        });

    }

    self.attachEventToHistoricalFaultList = function () {

        $('#machinedetail_history_faultlist').on('click', 'li', function () {
            event.preventDefault();
            //alert($(this).text());
            var selectedFaultID = $(this).data("faultid");
            var selectedActivityID = 0;


            if (selectedFaultID !== undefined) {
                $.cookie("currently_selected_fault", selectedFaultID);
                $.cookie("currently_selected_activity", selectedActivityID);
                $.mobile.navigate("#page_faultdetailhistorical", { role: "page" });
                e4('machinedetail row 521');
            }
        });
    }

    self.attachEventToSparePartList = function () {

        $('#machinedetail_sparepartlist').on('click', 'li', function () {
            event.preventDefault();
            //alert($(this).text());
            var selectedSparePart = $(this).data("sparepartid");
            c7(selectedSparePart);


            if (selectedSparePart !== undefined) {
                $.cookie("sparepart_nr_for_info", selectedSparePart);
                $.mobile.navigate("#page_sparepartinfo", { role: "page" });
                e4('machinedetail row 537');
            }
        });
    }

    self.attachEventToSearchButton = function (e) {
        //$("#machinedetail_search").click(function () {
        //    $(":mobile-pagecontainer").pagecontainer("change", "#page_machineselect", { role: "page", reverse: false, changeHash: false });
        //    console.log('test XX');

        //})

        $("#machinedetail_search").click(function (e) {
            e.preventDefault();
            e.stopPropagation();

            if (CURRENT_MACHINE_SEARCH_MODE == MACHINE_SEARCH_INPUT_MANUAL) {
                $.mobile.navigate("#page_machineselect", { role: "page" });
                e4('machinedetail row 556 - navigating to manual machine search');
            }
            else if (CURRENT_MACHINE_SEARCH_MODE == MACHINE_SEARCH_INPUT_BARCODE) {
                SCAN_PAGE_TARGET = SCAN_MACHINE;
                //$.mobile.navigate("#page_barcode_cam", { role: "page" });
                $.mobile.navigate("#page_scantest", { role: "page" });                
                e4('machinedetail row 560 - navigating to barcode search with machine settings');
            }
            else {
                c1('machinedetail row 563: Unable to decide which page to navigate to next. Moving to machine list.');
                $.mobile.navigate("#page_machinelist", { role: "page" });
                e4('machinedetail row 548');
            }
        })
    }




    self.attachEventToCreateNewFaultButton = function () {
        //By default hide the 'Show all' button for fault types on next page.
        if ($('#createfault_showallfaulttypes').is(":visible")) {
            $('#createfault_showallfaulttypes').hide();
        }

        $("#machinedetail_createnewfaultbutton").click(function () {
            //$(":mobile-pagecontainer").pagecontainer("change", "#page_createfault", { role: "page", reverse: false, changeHash: true });
            $.mobile.navigate("#page_createfault", { role: "page" });
            e4('machinedetail row 565');
        })

    }

    return self;
}

var machineDetail = Machinedetail();




$(document).one("pageshow", "#page_machinedetail", function (e) {
    machineDetail.attachEventToCreateNewFaultButton();
    machineDetail.attachEventToSearchButton();
    machineDetail.attachEventToActivityList();
    machineDetail.attachEventToFaultList();
    machineDetail.attachEventToHistoricalActivityList();
    machineDetail.attachEventToHistoricalFaultList();

    machineDetail.attachEventToSparePartList();

    $("#machinedetail_backbutton").click(function (e) {
        e.preventDefault();
        e.stopPropagation();

        if (CURRENT_MACHINE_SEARCH_MODE == MACHINE_SEARCH_INPUT_MANUAL) {
            $.mobile.navigate("#page_machinelist", { role: "page" });
            c4('machinedetail row 613 - navigating to manual search for machines');
        }
        else if (CURRENT_MACHINE_SEARCH_MODE == MACHINE_SEARCH_INPUT_BARCODE) {
            //MABE 20190911 - part of testing process

            //$.mobile.navigate("#page_barcode_cam", { role: "page" });
            SCAN_PAGE_TARGET = SCAN_MACHINE;
            $.mobile.navigate("#page_scantest", { role: "page" });

            c4('machinedetail row 622 - navigating to barcode search for machines');
        }
        else {
            c1('machinedetail row 589: Unable to decide which page to navigate to next. Moving to machine list.');
            $.mobile.navigate("#page_machinelist", { role: "page" });
            c4('machinedetail row 627 - forced switch to manual machine search');
        }
    });

   

});


$(document).on("pagebeforeshow", "#page_machinedetail", function (e, data) {
    $("#machinedetail_errortext").hide();
    machineDetail.requestMachineInfo();
    machineDetail.RequestMachineActivityList();
    machineDetail.RequestMachineFaultList();
    machineDetail.RequestSparePartListForMachine();
    machineDetail.RequestHistoricalActivityList();
    machineDetail.RequestHistoricalFaultList();
    var previouspage_id = data.prevPage.attr('id');

    if (previouspage_id == 'page_machinelist') {
        $("#machinedetail_maincollapsible").children().collapsible("option", "collapsed", true);
    }


});


//MABE 20200318 - pageshow event disabled, functionality moved to beforeshow event
// to avoid 'flickering' on page updates

// $(document).on("pageshow", "#page_machinedetail", function (e, data) {
        
//    $("#machinedetail_errortext").hide();
//    machineDetail.requestMachineInfo();
//    machineDetail.RequestMachineActivityList();
//    machineDetail.RequestMachineFaultList();
//    machineDetail.RequestSparePartListForMachine();
//    machineDetail.RequestHistoricalActivityList();
//    machineDetail.RequestHistoricalFaultList();
//    var previouspage_id = data.prevPage.attr('id');

//    if (previouspage_id == 'page_machinelist') {
//        $("#machinedetail_maincollapsible").children().collapsible("option", "collapsed", true);
//    }

//        //if (previouspage_id == 'page_barcode_cam') {
//        //    console.log('coming from barcode scan');
//        //    $("#machinedetail_backbutton").unbind().click(function (event) {
//        //        e.preventDefault();
//        //        e.stopPropagation();
//        //        //$(":mobile-pagecontainer").pagecontainer("change", "#page_barcode_cam", { role: "page", reverse: false, changeHash: false });
//        //        $.mobile.navigate("#page_barcode_cam", { role: "page" });
//        //        console.log('test AA');
//        //    });

//        //    $("#machinedetail_search").unbind().click(function () {
//        //        e.preventDefault();
//        //        e.stopPropagation();
//        //        //$(":mobile-pagecontainer").pagecontainer("change", "#page_barcode_cam", { role: "page", reverse: false, changeHash: false });
//        //        $.mobile.navigate("#page_barcode_cam", { role: "page" });
//        //        console.log('test BB');
//        //    })


//        //}
//        //else {
//        //    $("#machinedetail_backbutton").unbind().click(function (event) {
//        //        e.preventDefault();
//        //        e.stopPropagation();
//        //        $.mobile.navigate("#page_machinelist", { role: "page" });
//        //        console.log('test CC');
//        //    });

//        //    $("#machinedetail_search").unbind().click(function () {
//        //        e.preventDefault();
//        //        e.stopPropagation();
//        //        //$(":mobile-pagecontainer").pagecontainer("change", "#page_machineselect", { role: "page", reverse: false, changeHash: false });
//        //        $.mobile.navigate("#page_machineselect", { role: "page" });
//        //        console.log('test DD');

//        //    })
//        //   }
//});

