function Handle_manhours() {

    var self = {};


    self.tmp = null;
    self.UserId = null;
    self.previousPage = null;
    self.selection = {};
    self.activityID = 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.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_manhours_generic_popup_header").html(ReturnPhraseOnKey("dialogue_tokenexpired_message1"));
            $("#handle_manhours_generic_popup_text").html(ReturnPhraseOnKey("dialogue_tokenexpired_message1"));

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

            $("#handle_manhours_generic_popup_button").unbind("click").click(function () {
                $("#handle_manhours_generic_popup").popup("close");
            });

            $("#handle_manhours_generic_popup").popup().popup("open");
        }
        else {
            self.activityID = data.d;
            c6(self.activityID);
        }

    }

    self.RequestManHoursData = function () {
        if (JOB_HANDLE_MODE == HANDLE_ACTIVITY) {
            self.RequestActivityManHoursData();
        }
        else if (JOB_HANDLE_MODE == HANDLE_FAULT) {
            self.RequestFaultManHoursData();
        }
    }


    self.RequestActivityManHoursData = function () {
        var requester = new AjaxRequest({
            data: { "activity_id": activityDetailWithFunction.selectedActivityID },
            success: self.ManHoursDataRequestSuccess,
            error: self.ManHoursDataRequestError,
            url: "RequestSelectedActivityManHoursUse"
        });

        requester.ExecuteRequest();
    }

    self.RequestFaultManHoursData = function () {

        c1(faultDetailWithFunction.selectedFaultID);
        var requester = new AjaxRequest({
            data: { "fault_id": faultDetailWithFunction.selectedFaultID },
            success: self.ManHoursDataRequestSuccess,
            error: self.ManHoursDataRequestError,
            url: "RequestSelectedFaultManHoursUse"
        });

        requester.ExecuteRequest();
    }

    self.ManHoursDataRequestSuccess = function (data, status, xhr) {
        c3('asking for manhours data');
        self.RenderManhoursInfoTable(data.d.ManhoursList);
    }

    self.ManHoursDataRequestError = function (request, status, error) {
        c5('asking for manhours data failed!!!');
    }

    self.ValidateAndRequestManhourRegistration = function () {
        var hoursQty = $("#handle_manhours_hours").val();
        var minutesQty = $("#handle_manhours_minutes").val();
        c1('hour validation l110 ' + hoursQty);
        c1('minutes validation l111 ' + minutesQty);

        if (hoursQty == '') {
            hoursQty = 0;
        }
        if (minutesQty == '') {
            minutesQty = 0;
        }

        if (self.verifyTimeInput(hoursQty, minutesQty) == false) {
            //$("#finishjobwizard_1_errormessage").text(ReturnPhraseOnKey('finishjobwizard_1_errormessage_invalidtimeinput'));

            c2('hour/minutes validation failed. trying to write error message!');
            self.setErrorMsg(ReturnPhraseOnKey('finishjobwizard_1_errormessage_invalidtimeinput'));
        }
        else {
            self.clearErrorMsg();
            if(JOB_HANDLE_MODE == HANDLE_ACTIVITY){
                self.requestManhoursUseOnActivity(hoursQty, minutesQty);
            }
            else if (JOB_HANDLE_MODE == HANDLE_FAULT) {
                self.requestManhoursUseOnFault(hoursQty, minutesQty);
            }
        }
    }

    self.requestManhoursUseOnActivity = function (hoursToRegister, minutesToRegister) {

        var requestingUser = $.cookie("user_id");
        var currentActivityID = activityDetailWithFunction.selectedActivityID;
        var current_session_token = $.cookie("session_token");

        c5(currentActivityID);
        c5(hoursToRegister);
        c5(minutesToRegister);
        c5(requestingUser);
        c5(current_session_token);

        var requester = new AjaxRequest({
            data: { "activityid": currentActivityID, "hours": hoursToRegister, "minutes": minutesToRegister, "userid" : requestingUser,"session_token": current_session_token },
            success: self.ManhoursRegistrationSuccess,
            error: self.ManhoursRegistrationError,
            url: "RegisterManhoursOnActivity"
        });

        requester.ExecuteRequest();
    }

    self.requestManhoursUseOnFault = function (hoursToRegister, minutesToRegister) {

        var requestingUser = $.cookie("user_id");
        var currentFaultID = faultDetailWithFunction.selectedFaultID;
        var current_session_token = $.cookie("session_token");

        c5(currentFaultID);
        c5(hoursToRegister);
        c5(minutesToRegister);
        c5(requestingUser);
        c5(current_session_token);

        var requester = new AjaxRequest({
            data: { "activityid": currentFaultID, "hours": hoursToRegister, "minutes": minutesToRegister, "userid": requestingUser, "session_token": current_session_token },
            success: self.ManhoursRegistrationSuccess,
            error: self.ManhoursRegistrationError,
            url: "RegisterManhoursOnFault"
        });

        requester.ExecuteRequest();
    }

    self.ManhoursRegistrationSuccess = function (data, status, xhr) {
        c7('Register success');

        $("#handle_manhours_hours").val('');
        $("#handle_manhours_minutes").val('');
        
        self.RequestManHoursData();

    }
    
    self.ManhoursRegistrationError = function (request, status, error) {
        console.log('something went wrong');
    }

    self.RenderManhoursInfoTable = function (incomingData) {
        var manhoursInfoTable = '';

        if (defined(incomingData) && (incomingData.length == 0)) {
            manhoursInfoTable = '<p><b>' + ReturnPhraseOnKey('handle_manhours_info_header1') + '</b></p>';
        }
        else {
            console.log(incomingData);
            manhoursInfoTable = '<p><b>' + ReturnPhraseOnKey('handle_manhours_info_header2') + '</b></p>';
            manhoursInfoTable += '<table class="job_info_table"><tr><td class="label">';
            manhoursInfoTable += ReturnPhraseOnKey('handle_manhours_initials');
            manhoursInfoTable += '</td><td class="label">';
            manhoursInfoTable += ReturnPhraseOnKey('handle_manhours_estimated');
            manhoursInfoTable += '</td><td class="label">';
            manhoursInfoTable += ReturnPhraseOnKey('handle_manhours_actual');
            manhoursInfoTable += '</td></tr>';
            jQuery.each(incomingData, function () {
                manhoursInfoTable += '<tr><td>'
                manhoursInfoTable += this.ManhoursInitials;
                manhoursInfoTable += '</td><td>';
                manhoursInfoTable += this.ManhoursEstimatedTime;
                manhoursInfoTable += '</td><td>';
                manhoursInfoTable += this.ManhoursRegisteredTime;
                manhoursInfoTable += '</td></tr>';
            });




            manhoursInfoTable += '</table>';
        }

        $('#handle_manhours_manhours_list').html(manhoursInfoTable);
    }

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

        }
    }



    self.verifyTimeInput = function (hours, minutes) {

        var rx = new RegExp(/^\d+$/);
        var inputCheckValid = false;
        inputCheckValid = (((rx.test(hours) && (hours > -1) && (hours < 24))) && ((rx.test(minutes) && (minutes > -1) && minutes < 60)));
        return inputCheckValid;

    }

    self.setErrorMsg = function (msg) {

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

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

    return self;

}

var handle_manhours = Handle_manhours();


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

    //handle_manhours.AttachEventToSparePartList();

});

$(document).on("pagebeforeshow", "#page_handle_manhours", 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_manhours.requestJobInfo();
    handle_manhours.renderJobInfo();
    handle_manhours.RequestManHoursData();


});




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

    if (SessionTokenStatus == true) {

        //****************************************
        //20200401 - moved to pagebeforeshow event
        //handle_manhours.requestJobInfo();
        //handle_manhours.renderJobInfo();
        //handle_manhours.RequestManHoursData();
        //****************************************

        $("#handle_manhours_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_manhours_add_manhours").unbind().click(function () {
            handle_manhours.ValidateAndRequestManhourRegistration();
        });




    }
    else {
        helper.ForcedLogout();
    }

});

$(document).on("pagehide", "#page_handle_manhours", function () {
    $("#handle_manhours_manhours_list").html("");
    $("#handle_manhours_details").html("");
    $("#handle_manhours_detailcontent").html("");
    $("#handle_manhours_hours").val("");
    $("#handle_manhours_minutes").val("");
    //$("#finishjobwizard_measured_param_input").val("");
    //$("#page_finishjobwizard_1 .default_collapsible_element").collapsible("collapse");
    ////$("#finishjobwizard_1_measuredparameter_collapsible").hide();

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

