
var scannerRunning = false;
var detectedSparePartBarcode = null;
var detectedJobIDBarcode = null;


// Machine section

var checkForMachineBarcodePresence = function (incoming_barcode) {

    c3('running check for machine function');

    var machine_search_param = incoming_barcode;
    var current_session_token = $.cookie("session_token");
    var user_id = $.cookie("user_id");

    c5(machine_search_param);
    c5(current_session_token);
    c5(user_id);
    barcodeScanClearErrorMsg();

    var requester = new AjaxRequest({
        data: {
            "machine_search_param": machine_search_param,
            "user_id": user_id,
            "session_token": current_session_token
        },
        success: machineBarcodePresenceComplete,
        error: function (data, status, xhr) {
            c1("scantest2 row 27: Unable to reach web service. Can't verify presence of machine search result.");
            DbCommunicationErrorHandler(WEBSERVICE_FAULT_JSONREQUEST);
        },
        url: "CheckForMachinePresenceOnBarcode"
    });
    requester.ExecuteRequest();

};


var machineBarcodePresenceComplete = function (data, status, xhr) {

    var checkValidation = data.d.SessionTokenValid;
    var machinesPresent = data.d.TrueOrFalse;
    var machineCount = data.d.ValueToPass;
    c1('scantest2 row 42 - Machines found: ' + machineCount);

    if (checkValidation == false) {

        barcodeScanSetErrorMsg(ReturnPhraseOnKey("scan_barcode_error_user_validation_failed"));
    }
    else if (machinesPresent == false) {
        barcodeScanSetErrorMsg(ReturnPhraseOnKey("scan_barcode_error_machine_not_found"));
    }
    else if (machineCount > MAXIMUM_NUMBER_RECORDS_IN_SEARCH) {

        barcodeScanSetErrorMsg(ReturnPhraseOnKey("scan_barcode_error_more_than_one_machine_found"));
    }

    else if (machinesPresent == true) {
        c6('machine barcode found')
        if (data.d.StringToPass !== undefined) {
            $.cookie("currently_selected_machine", data.d.StringToPass);
        }
        c6('moving on to machine page');
        $.mobile.navigate("#page_machinedetail", { role: "page" });
    }

};

//Sparepart section

var checkForSparePartBarcodePresence = function (incomingBarcode) {
    var sparepart_search_param = incomingBarcode;
    detectedSparePartBarcode = incomingBarcode;
    var current_session_token = $.cookie("session_token");
    var user_id = $.cookie("user_id");



    var requester = new AjaxRequest({
        data: { "sparepart_search_param": sparepart_search_param, "user_id": user_id, "session_token": current_session_token }, // This is for the json request
        success: sparepartBarcodePresenceComplete,
        error: function (data, status, xhr) {
            c1("scantest2 row79 row 450: Unable to reach web service. Can't verify presence of spare part search result.");
            DbCommunicationErrorHandler(WEBSERVICE_FAULT_JSONREQUEST);
        },
        url: "CheckForSparepartPresenceOnBarcode"
    });
    requester.ExecuteRequest();
}


var sparepartBarcodePresenceComplete = function (data, status, xhr) {

    var checkValidation = data.d.SessionTokenValid;
    var sparepartsPresent = data.d.TrueOrFalse;
    var stockCount = data.d.ValueToPass;
    
    if (checkValidation == false) {

        barcodeScanSetErrorMsg(ReturnPhraseOnKey("scan_barcode_error_user_validation_failed"));
    }
    else if (sparepartsPresent == false) {
        barcodeScanSetErrorMsg(ReturnPhraseOnKey("scan_barcode_error_sparepart_not_found"));
    }    
    else if (sparepartsPresent == true) {
        if (data.d.StringToPass !== undefined) {
            $.cookie("currently_selected_sparepartid", data.d.StringToPass);
        }

        $.cookie("sparepartsearchparam", detectedSparePartBarcode);
        $.cookie("spareparttypesearchparam", 0);

        initScanner(undefined);

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

}

var checkForSparePartBarcodePresence_WithStore = function (incomingBarcode) {
    c2('scantest2 row 123: in checkForSparePartBarcodePresence_WithStore')
    var sparepart_search_param = incomingBarcode;
    var current_store_id = CURRENT_SELECTED_STORE;
    var spareparttype_search_param = '0';
    var current_session_token = $.cookie("session_token");
    var user_id = $.cookie("user_id");

    detectedSparePartBarcode = incomingBarcode;

    var requester = new AjaxRequest({
        data: {
            "sparepart_search_param": sparepart_search_param,
            "spareparttype_search_param": spareparttype_search_param,
            "store_id": current_store_id,
            "session_token": current_session_token
        }, // This is for the json request // This is for the json request
        success: sparepartBarcodePresenceInSelectedStoreComplete,
        error: function (data, status, xhr) {
            c1("scantest2 row79 row 450: Unable to reach web service. Can't verify presence of spare part search result.");
            DbCommunicationErrorHandler(WEBSERVICE_FAULT_JSONREQUEST);
        },
        url: "CheckForSparepartPresenceAtSpecificStore"
    });
    requester.ExecuteRequest();
}

var sparepartBarcodePresenceInSelectedStoreComplete = function (data, status, xhr) {
    var checkValidation = data.d.SessionTokenValid;
    var stockCount = data.d.ValueToPass;

    if (checkValidation == false) {
        barcodeScanSetErrorMsg(ReturnPhraseOnKey("scan_barcode_error_user_validation_failed"));
    }
    else {
        var stockCount = data.d.ValueToPass;
        var sparePartId = data.d.StringToPass;

        if (stockCount == 0) {
            barcodeScanSetErrorMsg(ReturnPhraseOnKey("scan_barcode_error_sparepart_not_found_at_selected_store"));
        }
        else {

            $.cookie("sparepartsearchparam", detectedSparePartBarcode);
            $.cookie("spareparttypesearchparam", 0);

            initScanner(undefined);

            $(":mobile-pagecontainer").pagecontainer("change", "#page_sparepartlistonstore", { role: "page", reverse: false, changeHash: false });
            c5('scantest2 row 171 - navigating to spare part list with store limitation');
            
        }
    }
}

//Job ID scan section

var LookupScannedJobId = function (incomingScan) {
    var detectedJobIDBarcode = parseInt(incomingScan);
    if (detectedJobIDBarcode > MAX_ALLOWED_JOB_ID) {
        //alert('Scanned value is too big for ID');
        barcodeScanSetErrorMsg(ReturnPhraseOnKey("scan_barcode_error_scanned_job_id_is_not_valid"));
        return;
    }
    else {



        var current_session_token = $.cookie("session_token");
        var detected_jobid = detectedJobIDBarcode;
        var requester = new AjaxRequest({
            data: { "jobid": detected_jobid, "userid": $.cookie("user_id"), "session_token": current_session_token }, // This is for the json request
            success: function (data, status, xhr) {
                if (currently_selected_application_section == USER_SECTION) {
                    navigateToSelectedJob(data);
                }
                else {
                    checkForScannedJobIdBarcode(data);
                }
            },
            error: function (data, status, xhr) {
                $("#jobselectonid_jobid_input").val("");
                c1("Unable to reach web service. Can't verify presence of job search result.");
                DbCommunicationErrorHandler(WEBSERVICE_FAULT_JSONREQUEST);
            },
            url: "CheckForJobExistenceOnJobId"
        });
        requester.ExecuteRequest();
    }
}

var navigateToSelectedJob = function (incomingData) {
    if (incomingData.d.TrueOrFalse == false) {
        barcodeScanSetErrorMsg(ReturnPhraseOnKey('jobselectonid_errormessage_no_job_with_such_id')); 
    }
    else {
        if (incomingData.d.StringToPass == "Finished") {
            var errorMessageToShow = ReturnPhraseOnKey('jobselectonid_errormessage_job_with_id_finished_1') + detectedJobIDBarcode +
            ReturnPhraseOnKey('jobselectonid_errormessage_job_with_id_finished_2')
            barcodeScanSetErrorMsg(errorMessageToShow);
        }
        else if (incomingData.d.StringToPass == "NoAccess") {
            var errorMessageToShow = ReturnPhraseOnKey('jobselectonid_errormessage_job_with_id_noaccess_1') + detectedJobIDBarcode +
            ReturnPhraseOnKey('jobselectonid_errormessage_job_with_id_noaccess_2')
            barcodeScanSetErrorMsg(errorMessageToShow);
        }
        else {
            if (incomingData.d.StringToPass == 'Activity') {

                var selectedActivityID = incomingData.d.ValueToPass;
                var selectedFaultID = 0;

                if (selectedActivityID !== undefined) {
                    $.cookie("currently_selected_activity", selectedActivityID);
                    $.cookie("currently_selected_fault", selectedFaultID);
                    $.cookie("currently_selected_machine", -1);
                    $("#jobselectonid_jobid_input").val("");
                    $(":mobile-pagecontainer").pagecontainer("change", "#page_activitydetailwithfunction", { role: "page", reverse: false, changeHash: false });
                    //e1('jobsearchonid row 80');
                    //self.clearErrorMsg();
                }
            }
            else if (incomingData.d.StringToPass == 'Fault') {

                var selectedFaultID = incomingData.d.ValueToPass;
                var selectedActivityID = 0;


                if (selectedFaultID !== undefined) {
                    $.cookie("currently_selected_fault", selectedFaultID);
                    $.cookie("currently_selected_activity", selectedActivityID);
                    $.cookie("currently_selected_machine", -1);
                    $("#jobselectonid_jobid_input").val("");
                    $(":mobile-pagecontainer").pagecontainer("change", "#page_faultdetailwithfunction", { role: "page", reverse: false, changeHash: false });
                    //e1('jobsearchonid row 96');
                    //self.clearErrorMsg();
                }
            }
        }
    }
}



var checkForScannedJobIdBarcode = function (data) {
    if (data.d.TrueOrFalse == false) {

        c2('scantest2 row 202 - job id not found');
        barcodeScanSetErrorMsg(ReturnPhraseOnKey("jobselectonid_errormessage_no_job_with_such_id"));
    }

    else {
        c1('scantest2 row 218 - job with detected barcode is found in database, moving on to sp consumption page');
        $.cookie("currently_selected_jobid", detectedJobIDBarcode);
        $.mobile.navigate("#page_consumption_on_job", { role: "page" });
    }
}

var _scan = function(result) {
    if (scannerRunning === true) {
            scannerRunning = false;
            this.setState({
                open: false,
            });
            Quagga.offDetected();
            Quagga.offProcessed();
            document.getElementById('interactive').innerHTML = '';
            Quagga.stop();
    } 
    else {
        scannerRunning = true;
        this.setState({
                open: true,
            });
            setTimeout(this._componentDidMount, 100);
        }
    };

var _componentDidMount = function () {

    Quagga.init(
        {
            inputStream: {
                type: "LiveStream",
                constraints: {
                    width: { min: 640 },
                    height: { min: 480 },                
                    facingMode: "environment",
                    aspectRatio: { min: 1, max: 2 }
                }
            },
            locator: {
                patchSize: "medium",
                halfSample: true
            },
            numOfWorkers: 2,
            frequency: 5,
            decoder: {
                readers: [{
                    format: "code_128_reader",
                    config: {}
                }]
            },
            locate: true
        },
    function (err) {
        if (err) {
            return managed_log(err);
        }
        Quagga.start();
    }
    )
};


var shutdownQuagga = function () {
    //this.setState({
    //    open: false,
    //    isScanning: false,
    //});


    //Ask SANA how to make off-functions to work (or really, how to access App() after initial start)
    //Quagga.offDetected();
    //Quagga.offProcessed();


    document.getElementById('interactive').innerHTML = '';
    Quagga.stop();
    QuaggaIsRunning = false;
}

var startQuagga = function () {

    Quagga.init(
        {
            inputStream: {
                type: "LiveStream",
                constraints: {
                    width: { min: 640 },
                    height: { min: 480 },
                    facingMode: "environment",
                    aspectRatio: { min: 1, max: 2 }
                }
            },
            locator: {
                patchSize: "medium",
                halfSample: true
            },
            numOfWorkers: 1,
            frequency: 1,
            decoder: {
                readers: [{
                    format: "code_128_reader",
                    config: {}
                }]
            },
            locate: true
        },
    function (err) {
        if (err) {
            return managed_log(err);
        }
        Quagga.start();
        QuaggaIsRunning = true;
    }
    )
};





var machineBarcodePresenceIncomplete = function (data, status, xhr) {
    c1("scantest2 row 234: Unable to reach web service. Can't verify presence of machine search result.");
    DbCommunicationErrorHandler(WEBSERVICE_FAULT_JSONREQUEST);
}

var localizeScanPage = function () {

    //if (SCAN_PAGE_TARGET == SCAN_JOB_ID) {
    //    c8('scantest row 303 - scan job id');
    //    $('#scantest_info1').html(ReturnPhraseOnKey("scan_barcode2_scan_job_barcode"));
    //}
    //else if (SCAN_PAGE_TARGET == SCAN_MACHINE) {
    //    c8('scantest row 307 - scan machines');
    //    $('#scantest_header').html("scan_barcode_machine_selection");        
    //    $('#scantest_info1').html(ReturnPhraseOnKey("scan_barcode2_scan_machine_barcode"));
    //}
    //else if (SCAN_PAGE_TARGET == SCAN_SPAREPART &&
    //    (currently_selected_application_section == MACHINES_SECTION || currently_selected_application_section == USER_SECTION)) {
    //    c8('scantest row 311 - scan spareparts at all stocks');
    //    $('#scantest_info1').html(ReturnPhraseOnKey("scan_barcode2_scan_sparepart_barcode"));
    //}
    //else if (SCAN_PAGE_TARGET == SCAN_SPAREPART && currently_selected_application_section == SPAREPARTS_SECTION) {
    //    c8('scantest row 315 - scan spareparts at single, preselected stock');
    //    $('#scantest_info1').html(ReturnPhraseOnKey("scan_barcode2_scan_sparepart_barcode"));
    //}
    //else if (SCAN_PAGE_TARGET == SCAN_SPAREPART_FOR_JOB) {
    //    c8('scantest row 319- scan spareparts for direct job consumption');
    //    $('#scantest_info1').html(ReturnPhraseOnKey("scan_barcode2_scan_sparepart_barcode") + 'for job***********');
    //}
    //else {
    //    c8('Scan mode unknown. Switching to machine scan.');
    //    SCAN_PAGE_TARGET = SCAN_MACHINE;
    //    $('#scantest_info1').html("Dazed and confused. Switching to machine mode");
    //}


    if (SCAN_PAGE_TARGET == SCAN_MACHINE) {
        c8('scantest row 307 - scan machines');
        $('#scantest_header').html(ReturnPhraseOnKey("scan_barcode_machine_selection"));
        $('#scantest_info1').html(ReturnPhraseOnKey("scan_barcode2_scan_machine_barcode"));
    }
    else if (SCAN_PAGE_TARGET == SCAN_SPAREPART) {
        if (currently_selected_application_section == MACHINES_SECTION || currently_selected_application_section == USER_SECTION) {
                c8('scantest row 311 - scan spareparts at all stocks');
                $('#scantest_header').html(ReturnPhraseOnKey("scan_barcode_sparepart_selection_for_job_consumption"));
                $('#scantest_info1').html(ReturnPhraseOnKey("scan_barcode2_scan_sparepart_barcode"));

        }
        else if (currently_selected_application_section == SPAREPARTS_SECTION) {
            c8('scantest row 315 - scan spareparts at single, preselected stock');
            $('#scantest_header').html(ReturnPhraseOnKey("scan_barcode_sparepart_selection_for_stock_management"));
            $('#scantest_info1').html(ReturnPhraseOnKey("scan_barcode2_scan_sparepart_barcode"));
        }
    }
    else if (SCAN_PAGE_TARGET == SCAN_SPAREPART_FOR_JOB) {
        c8('scantest row 319- scan spareparts for direct job consumption');
        $('#scantest_header').html(ReturnPhraseOnKey("scan_barcode_sparepart_selection_for_direct_consumption"));
        $('#scantest_info1').html(ReturnPhraseOnKey("scan_barcode2_scan_sparepart_barcode"));    
    }
    else if (SCAN_PAGE_TARGET == SCAN_JOB_ID) {

        if (currently_selected_application_section == SPAREPARTS_SECTION) {
            c8('scantest row 319- scan job id - selection for direct spare part consumption');
            $('#scantest_header').html(ReturnPhraseOnKey("scan_barcode_job_selection_for_direct_consumption"));
            $('#scantest_info1').html(ReturnPhraseOnKey("scan_barcode_scan_job_id_barcode"));
        }
        else if (currently_selected_application_section == USER_SECTION) {
            c8('scantest row 319- scan job id - job selection on job id');
            $('#scantest_header').html(ReturnPhraseOnKey("scan_barcode_job_selection_search_on_job_id"));
            $('#scantest_info1').html(ReturnPhraseOnKey("scan_barcode_scan_job_id_barcode"));

        }
    }
}

var handleManualSwitch = function (previousPageName) {

    if (previousPageName == 'page_consumption_on_job'
            || (currently_selected_application_section == SPAREPARTS_SECTION && SELECTED_SPAREPART_JOB_TYPE == CONSUMPTION_ON_JOB)) {
        $('#barcode_search_switch_to_manual').unbind().click(function (event) {
            
            if (SCAN_PAGE_TARGET == SCAN_JOB_ID) {
                CONSUMPTION_SP_SEARCH_MODE = SPAREPART_SEARCH_INPUT_MANUAL;
                c3('scantest2 row 469 - previous page name: ' + previousPageName);
                c3('scantest2 row 470 - switching to page_consumption_on_job');
                //Reseting any old scanned job id numbers
                $.cookie("currently_selected_jobid", '');
                $.mobile.navigate("#page_jobsearch_onid", { role: "page" });                
            }
            else if (SCAN_PAGE_TARGET == SCAN_SPAREPART_FOR_JOB) {
                CURRENT_JOBID_SEARCH_MODE == JOBID_SEARCH_INPUT_MANUAL;
                c3('scantest2 row 477 - previous page name: ' + previousPageName);
                c3('scantest2 row 478 - switching to page_consumption_on_job');
                $.mobile.navigate("#page_consumption_on_job", { role: "page" });
            }
        });
    }
    else if (previousPageName == 'page_sparepartselectinstore' 
                || (currently_selected_application_section == SPAREPARTS_SECTION && 
                        (SELECTED_SPAREPART_JOB_TYPE == STOCK_ADJUSTMENT || SELECTED_SPAREPART_JOB_TYPE == STOCK_REPLENISHMENT))) {
        $('#barcode_search_switch_to_manual').unbind().click(function (event) {
            c3('scantest2 row 487 - previous page name: ' + previousPageName);
            c3('scantest2 row 488- switching to manual sparepart selection with store page');
            CONSUMPTION_SP_SEARCH_MODE = SPAREPART_SEARCH_INPUT_MANUAL;
            $.mobile.navigate("#page_sparepartselectinstore", { role: "page" });
        });
    }
    else if (previousPageName == 'page_jobsearch_onid'
                || (currently_selected_application_section == SPAREPARTS_SECTION && SELECTED_SPAREPART_JOB_TYPE == CONSUMPTION_ON_JOB)
                || (currently_selected_application_section == USER_SECTION && SCAN_PAGE_TARGET == SCAN_JOB_ID)) {
        $('#barcode_search_switch_to_manual').unbind().click(function (event) {
            c3('scantest2 row 497 - previous page name: ' + previousPageName);
            c3('scantest2 row 498 - switching to manual job search');
            CURRENT_JOBID_SEARCH_MODE = JOBID_SEARCH_INPUT_MANUAL;
            $.mobile.navigate("#page_jobsearch_onid", { role: "page" });
        });
    }
    else if ((currently_selected_application_section == MACHINES_SECTION || currently_selected_application_section == USER_SECTION) 
                && SCAN_PAGE_TARGET == SCAN_MACHINE) {
        $('#barcode_search_switch_to_manual').unbind().click(function (event) {
            c3('scantest2 row 506 - previous page name: ' + previousPageName);
            c3('scantest2 row 507 - switching to manual machine selection');
            CURRENT_MACHINE_SEARCH_MODE = MACHINE_SEARCH_INPUT_MANUAL;
            $.mobile.navigate("#page_machineselect", { role: "page" });
        });
    }
    else if ((currently_selected_application_section == MACHINES_SECTION || currently_selected_application_section == USER_SECTION)
                && SCAN_PAGE_TARGET == SCAN_SPAREPART) {
        $('#barcode_search_switch_to_manual').unbind().click(function (event) {
            c3('scantest2 row 515 - previous page name: ' + previousPageName);
            c3('scantest2 row 516 - switching to manual sparepart selection');
            CURRENT_SPAREPART_SEARCH_MODE = SPAREPART_SEARCH_INPUT_MANUAL;
            $.mobile.navigate("#page_sparepartselect", { role: "page" });
        });
    }
    else {
        c9('scantest row 522 - scan mode undefined - reseting all to manual and returning to main menu');
        $('#barcode_search_switch_to_manual').unbind().click(function (event) {

            CURRENT_MACHINE_SEARCH_MODE = MACHINE_SEARCH_INPUT_MANUAL;
            CURRENT_SPAREPART_SEARCH_MODE = SPAREPART_SEARCH_INPUT_MANUAL;
            CURRENT_JOBID_SEARCH_MODE = JOBID_SEARCH_INPUT_MANUAL;
            $.mobile.navigate("#page_mainmenu", { role: "page" });
        });
    }
}

barcodeScanSetErrorMsg = function (msg) {
    $('#scantest_errortext').html(msg);
    $('#scantest_errortext').show();
    setTimeout(barcodeScanClearErrorMsg, 3000);
}

barcodeScanClearErrorMsg = function () {
    $('#scantest_errortext').html('');
    //$('#scantest_errortext').hide();
}


$(document).on("pagebeforeshow", "#page_scantest", function (e, data) {
    localizeScanPage();
    handleManualSwitch(data.prevPage.attr("id"));

    if (QuaggaIsRunning == false) {
        startQuagga();
        c4('scantest2 row 485 - Starting quagga on pagebeforeshow event');
    }
});

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

    if (QuaggaIsRunning == true) {
        shutdownQuagga();
        c4('scantest2 row 493 - Stopping quagga on page hide event');
    }
    barcodeScanClearErrorMsg();
});



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

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

    if (previouspage_id == 'page_machinelist') {
        //$("#machinedetail_maincollapsible").children().collapsible("option", "collapsed", true);
        c2('coming from machine search');
    }
    else if (previouspage_id == 'page_sparepartselect') {
        c2('coming from spare part search');
    }
    else if (previouspage_id == 'page_sparepartselect') {
        c2('coming from spare part search');
    }

    $("#barcode_start").unbind().click(function (event) {
        startQuagga();
        //App.init();
        e1('calling quagga on');
    });

    $("#barcode_stop").unbind().click(function (event) {
        shutdownQuagga();
        e1('calling quagga off');
    });

});