function Handle_sp_consumption() {

    var self = {};


    self.tmp = null;
    self.UserId = null;
    self.previousPage = null;
    self.selection = {};
    self.incomingSparePartList = null;

    self.requestJobInfo = function () {
        var requestingUser = $.cookie("username");

        //console.log(self.previousPage);

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

        var requester = new AjaxRequest({
            data: { "userinitials": requestingUser, "job_id": currentJobId, "session_token": current_session_token },
            success: self.JobCardInfoRequestSuccess,
            error: self.JobCardInfoRequestError,
            url: "RequestJobInformation"
        });

        requester.ExecuteRequest();
    }

    self.renderJobInfo = function () {
        if (JOB_HANDLE_MODE == HANDLE_ACTIVITY) {
            if (faultDetailWithFunction !== null && defined(faultDetailWithFunction)) {
                $('#handle_sp_consumption_details').html(activityDetailWithFunction.activityInfoHTML);
                $('#handle_sp_consumption_detailcontent').html(activityDetailWithFunction.detailInfoHTML);
            }
        }
        else if (JOB_HANDLE_MODE == HANDLE_FAULT) {
            if (activityDetailWithFunction !== null && defined(activityDetailWithFunction)) {
                $('#handle_sp_consumption_details').html(faultDetailWithFunction.faultInfoHTML);
                $('#handle_sp_consumption_detailcontent').html(faultDetailWithFunction.faultDetailInfoHTML);
            }

        }
    }

    self.JobCardInfoRequestError = function (request, status, error) {
        /// <summary>This function is called by sendGetInfoReq() when the ajax-request returns an error</summary>
        c1('handle_sp_consumption row 32: Unable to retrieve sparepart info from database.');
        DbCommunicationErrorHandler(WEBSERVICE_FAULT_JSONREQUEST);
    }

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

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

            $("#handle_sp_consumption_generic_popup_header").html(ReturnPhraseOnKey("dialogue_tokenexpired_message1"));
            $("#handle_sp_consumption_generic_popup_text").html(ReturnPhraseOnKey("dialogue_tokenexpired_message1"));

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

            $("#handle_sp_consumption_generic_popup_button").unbind("click").click(function () {
                $("#handle_sp_consumption_generic_popup").popup("close");
            });

            $("#handle_sp_consumption_generic_popup").popup().popup("open");
        }
        else {
            self.incomingSparePartList = data.d.SparePartsAssignedForJob.SparepartsToBeConsumed;
            if (self.incomingSparePartList.length > 0) {
                self.populateSparePartList();
            }
            else {
                //$("#handle_sp_consumption_errormessage").text('Selected job has no associated spare parts.');
                //if ($('#handle_sp_consumption_errormessage').is(":hidden")) {
                //    $('#handle_sp_consumption_errormessage').show();
                //}

                self.populateSparePartList();

            }
        }

    }

    self.populateSparePartList = function () {
        //Reset global list of spareparts associated with current job;
        SparePartListAlreadyAssignedForJob = []; //Located in parameters.js

        console.log(self.incomingSparePartList);

        if (defined(self.incomingSparePartList) && self.incomingSparePartList != null) {
            if (self.incomingSparePartList.length > 0) {

                var sparePartListElement = '<li role="heading" class="list-header-class" data-role="list-divider">';
                sparePartListElement += ReturnPhraseOnKey('finishjobwizard_1_spareparts');
                sparePartListElement += '</li>';

                jQuery.each(self.incomingSparePartList, function () {
                    //sparePartListElement += '<li class="list-element-class" data-theme="c" data-consumptionid="'
                    sparePartListElement += '<li class="list-element-class" data-consumptionid="'
                    sparePartListElement += this.ConsumptionIdInPM5;
                    sparePartListElement += '"><a href="#" data-transition="slide">';
                    sparePartListElement += this.SparePartNumber;
                    sparePartListElement += '<span class="ui-li-count">';
                    sparePartListElement += this.SpecifiedConsumption;
                    sparePartListElement += '/';
                    sparePartListElement += this.ActualConsumption;
                    sparePartListElement += '</span></a></li>'

                    //Add sparepartnumber to global list of spare parts associated with the job
                    SparePartListAlreadyAssignedForJob.push(this.SparePartNumber);
                });

                $('#handle_sp_consumption_sparepartlist').show();
                $('#handle_sp_consumption_sparepartlist').html(sparePartListElement);
                $("#handle_sp_consumption_sparepartlist").listview().listview("refresh");
            }
            else {
                var sparePartListElement = '<li role="heading" class="list-header-class" data-role="list-divider">';
                sparePartListElement += ReturnPhraseOnKey('handle_sp_consumption_no_spareparts_associated_with_job');
                sparePartListElement += '</li>';

                $('#handle_sp_consumption_sparepartlist').show();
                $('#handle_sp_consumption_sparepartlist').html(sparePartListElement);
                $("#handle_sp_consumption_sparepartlist").listview().listview("refresh");

            }
        }
        else {
            $('#handle_sp_consumption_sparepartlist').empty();
            $('#handle_sp_consumption_sparepartlist').hide();
        }
    }





    self.AttachEventToSparePartList = function () {
        $('#handle_sp_consumption_sparepartlist').on('click', 'li', function () {
            //alert($(this).text());
            var consumptionID = $(this).data("consumptionid");
            if (consumptionID !== undefined) {
                $.cookie("currently_selected_consumptionid", consumptionID);
                $.mobile.navigate("#page_sparepartconsumption", { role: "page" });
                e4('finishjobwizard_1 row 471');
            }
        });
    }

    return self;

}

var handle_sp_consumption = Handle_sp_consumption();


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

    handle_sp_consumption.AttachEventToSparePartList();

});

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

    //var previouspage_id = data.prevPage.attr('id');

    //if (previouspage_id == 'page_machinelist') {
    //    $("#finishjobwizard_1_faultreason_divider").hide();
    //    $("#finishjobwizard_1_faultcauselistsection").hide();

    //}
    //else if (previouspage_id == 'page_faultdetailwithfunction') {
    //    $("#finishjobwizard_1_faultreason_divider").show();
    //    $("#finishjobwizard_1_faultcauselistsection").show();
    //}

    handle_sp_consumption.requestJobInfo();
    handle_sp_consumption.renderJobInfo();


});




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

    if (SessionTokenStatus == true) {

        //$("#page_finishjobwizard_1_errortext").hide();


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

        //handle_sp_consumption.incomingSparePartList = activityDetailWithFunction.SparePartList;

        //handle_sp_consumption.populateSparePartList();


        $("#handle_sp_consumption_backbutton").unbind().click(function () {

        if (JOB_HANDLE_MODE == HANDLE_ACTIVITY) {

            $.mobile.navigate("#page_activitydetailwithfunction", { role: "page" });
            e3('modifyexistingconsumption row 236');
            }
        else if (JOB_HANDLE_MODE == HANDLE_FAULT) {

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

        $("#handle_sp_consumption_addsparepart").unbind().click(function () {
            if (CURRENT_SPAREPART_SEARCH_MODE == SPAREPART_SEARCH_INPUT_MANUAL) {
                $.mobile.navigate("#page_sparepartselect", { role: "page" });
                c4('handle_sp_consumption row 223 - switching to manual spare part search');
            }
            else if (CURRENT_SPAREPART_SEARCH_MODE == SPAREPART_SEARCH_INPUT_BARCODE) {
                SCAN_PAGE_TARGET = SCAN_SPAREPART;
                //$.mobile.navigate("#page_sparepart_barcode_cam", { role: "page" });
                $.mobile.navigate("#page_scantest", { role: "page" });
                c4('handle_sp_consumption row 229 - switching to spare part scan search');
            }
            else {
                $.mobile.navigate("#page_sparepartselect", { role: "page" });
            }
        });



    }
    else {
        helper.ForcedLogout();
    }

});

$(document).on("pagehide", "#page_handle_sp_consumption", function () {
    //$("#finishjobwizard_1_hours").val("");
    //$("#finishjobwizard_1_minutes").val("");
    //$("#finishjobwizard_measured_param_input").val("");
    //$("#page_finishjobwizard_1 .default_collapsible_element").collapsible("collapse");
    ////$("#finishjobwizard_1_measuredparameter_collapsible").hide();

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

