//Test if an object is defined  :p
function defined(object) {
    if (typeof (object) == "undefined")
        return false;
    else
        return true;
}
function hasStringOrNumberContent(object) {
    return ((typeof (object) == "string") && object != "" || (typeof (object) == "number"));
}

//Test if an object is  null :p
function isnull(object) {
    if (object != null)
        return false;
    else
        return true;
}

function isInt(value) {
    if ((parseFloat(value) == parseInt(value)) && !isNaN(value)) {
        return true;
    } else {
        return false;
    }
}

var isDate = function (date) {
    var dateTest = new Date(date);
    return dateTest;
    
}

var localizeDatePickerValue = function (incomingDate) {
    if (CurrentSelectedLanguage == LANG_ENG) {
        return incomingDate;
    }
    else if (CurrentSelectedLanguage == LANG_DK) {
        var dateElements = incomingDate.split('-');
        var parsedDate = dateElements[2] + '-' + dateElements[1] + '-' + dateElements[0]
        return parsedDate;
    }
}


function parseExpectedEndDate(incomingString) {
    var dateToParse = '';
    try {
        dateToParse = localizeDatePickerValue(incomingString);        
        var parsedDate = new Date(dateToParse);
        dateToParse = parsedDate;
    }
    catch (err) {
        console.log(err.message);
    }
    
    if (dateToParse == 'Invalid Date') {
        return dateToParse;
    }
    else {
        var outgoingYear = dateToParse.getFullYear(dateToParse);
        var outgoingMonth = dateToParse.getMonth(dateToParse);
        outgoingMonth = outgoingMonth + 1;
        if (outgoingMonth < 9) { outgoingMonth = '0' + outgoingMonth };
        var outgoingDay = dateToParse.getDate(dateToParse);
        if (outgoingDay < 9) { outgoingDay = '0' + outgoingDay };
        var outgoingDate = outgoingYear + '-' + outgoingMonth + '-' + outgoingDay;
        return outgoingDate;
    }
};

function p(txt) {
    //    alert(txt)
}

function printProps(obj, objName) {
    var output = "";
    for (var prop in obj) {
        output += objName + "." + prop + " = " + obj[prop] + "\n";
    }
    alert(output);
}

function getLength(x) {
    if (defined(x))
        if (x == null)
            return 0
        else
            return x.length;
    else
        return 0;
}

function getValue(val) {
    if (defined(val) && (val != null) && (val != "")) {
        return val;
    }
    else {
        return lang.htt_unavailable;
    }
}

function getVolume(vol) {
    vol = 654321;
    if (defined(vol) && (vol != null) && (vol != "")) {
        // return '<span style="font-size: xx-large;">' + Math.ceil(vol)/VOLUME_UNIT + "</span> " + lang["hht_volume_"+VOLUME_UNIT];
        // this is if we want some rounding of the numbers
        return '<span style="font-size: xx-large;">' + Math.ceil(vol * 10 / VOLUME_UNIT) / 10 + "</span> " + lang["hht_volume_" + VOLUME_UNIT]; // rounding up using 1 decimal     
        // rounding up using 2 decimal     return '<span style="font-size: xx-large;">' + Math.ceil(vol*100/VOLUME_UNIT)/100 + "</span> " + lang["hht_volume_"+VOLUME_UNIT];
    }
    else {
        return lang.hht_volume_info_missing;
    }
}

//Get a element text
function getATextFromElement(element) {
    if (defined(element)) {
        if (element.tagName == 'a' || element.tagName == 'A') {
            return element.text;
        }
        else {
            return $(element).find('a')[0].text;
        }
    }
    else {
        return '';
    }
}

function ucfirst(text) {
    return text.substr(0, 1).toUpperCase() + text.substr(1);
}
function getDataIdFromElement(element) {
    //    alert(element);
    if (defined(element)) {
        if (element.tagName == 'a' || element.tagName == 'A') {
            //           alert("Direct:" + $(element).data( "id" ));
            return $(element).data("id");
        }
        else {
            //            alert("Through parent elements:" + $(element).find('a')[0].data( "id" ));
            if (defined($(element).find('a')[0])) {
                return $($(element).find('a')[0]).data("id");
            }
            else
                return -1; // this is when id is not found
        }
    }
    else {
        return -1;
    }
}
function getDataItemTypeFromElement(element) {
    if (defined(element)) {
        if (element.tagName == 'a' || element.tagName == 'A') {
            return $(element).data("item-type");
        }
        else {
            if (defined($(element).find('a')[0]) && defined($(element).find('a')[0].data)) {
                return $($(element).find('a')[0]).data("item-type");
            } else {
                return "unknown";
            }
        }
    }
    else {
        return 'unknown';
    }
}

function debugLogWrite(debugInfo) {
    if (defined(debugInfo)) {
        $("#debug").html(debugInfo);
    }
}
function debugLogAppend(debugInfo) {
    if (defined(debugInfo)) {
        $("#debug").append(debugInfo);
    }
}

function initScanner(self) {
    try {
        if (MyScanner != null) {
            try {
                //alert("Yes we have a Scanner II")
                intermecscannerapi.init();
                //intermecscannerapi
                // This one in turns calls the handleScennedValues
                intermecscannerapi.activeWindow = self;

                if (intermecscannerapi.canUseIntermecApi == true) {
                    audioplayer.pluginPlay = true;
                }
            }
            catch (err) {
                handleNoScanner(self);
            }
        }
        else {
            handleNoScanner(self);
        }
    }
    catch (err) {
        handleNoScanner(self);
    }
}

function handleNoScanner(self) {
    //    console.log('hooking up to keypress');
    if ($(document).keypress) {
        keyboardbuffer.activeWindow = self;
        keyboardbuffer.set('');
        $(document).unbind('keypress');
        $(document).bind('keypress', keyboardbuffer.keypressed);
    }
    if ($(document).keyup) {
        $(document).unbind("keyup");
        $(document).keyup(keyUpFunc);
    }
}

function keyUpFunc(e) {
    keyboardbuffer.keyup(e);
}

/* This compare function is implemeting 0-finten 
 * first parameter must be the scanned barcode
 * second parameter is the barcode to test against
 */
function barcodeCompare(scanBarcode, testBarcode) {
    if (scanBarcode == testBarcode)
        return true;
    if (getLength(scanBarcode) == 14 && "0" == scanBarcode.substr(0, 1) && scanBarcode.substr(1) == testBarcode)
        return true;
    return false;
}

function getObjectIndexAndId(barcode, data) {
    //    alert("INSIDE " + barcode);
    //    printProps(data, 'data');
    // test if barcode is in the product list
    var idx = -1;
    if (data.ProductInfoList != null) {
        for (var i = 0; i < getLength(data.ProductInfoList) ; i++) {
            if (barcodeCompare(barcode, data.ProductInfoList[i].ProductBarcode)) {
                idx = i;
                break
            }

        }
    }
    if (idx > -1) {
        return {
            "product": true,
            "index": idx,
            "id": data.ProductInfoList[idx].StockId
        }
    }

    // Test if barcode is container
    idx = -1;
    if (data.ContainerInfoList != null) {
        for (var i = 0; i < getLength(data.ContainerInfoList) ; i++) {
            if (barcodeCompare(barcode, data.ContainerInfoList[i].ContainerBarCode)) {
                idx = i;
                break;
            }
        }
    }
    if (idx > -1) {
        return {
            "container": true,
            "index": idx,
            "id": data.ContainerInfoList[idx].ContainerId
        }
    }

    // Test if barcode is container on a container
    idx = -1;
    if (data.ContainersOnContainer != null) {
        for (var i = 0; i < getLength(data.ContainersOnContainer) ; i++) {
            if (barcodeCompare(barcode, data.ContainersOnContainer[i].ContainerBarCode)) {
                idx = i;
                break;
            }
        }
    }
    if (idx > -1) {
        return {
            "container": true,
            "index": idx,
            "id": data.ContainersOnContainer[idx].ContainerId
        }
    }

    // Test if barcode is in a PickLinesList (Used in the Pick Single ...)
    idx = -1;
    if (data.PickLinesList != null) {
        for (var i = 0; i < getLength(data.PickLinesList) ; i++) {
            if (barcodeCompare(barcode, data.PickLinesList[i].LocationStockInformation.ContainerBarCode)) {
                idx = i;
                break;
            }
        }
    }
    if (idx > -1) {
        return {
            "container": true,
            "index": idx,
            "id": data.PickLinesList[idx].ContainerId
        }
    }

    // if we get down here, then neither product nor container was found in the object.
    // There is a little TODO that might be good to implement, and that is the abbillity
    // to look inside containers
    return false;
}

function setScrollTop(elm) {
    //TODO  mayby we should only scroll, if element is not visible
    var pos = $(elm).offset().top - 30; // make sure elm is a jQuery element before we get the offset().top
    if (pos < 0)
        pos = 0;

    $('html,body').animate({
        scrollTop: $(elm).offset().top
    },
    100);
}

function lookupBarcode(barcodeText) {
    barcodedescriptorlist.setDescriptor(barcodeText);
    var bCode = barcodeText;
    var fieldIds = [];
    var barcodes = [];
    var fieldIdArray = [];
    var debug = "";
    if (getLength(barcodedescriptorlist.valueDescriptors) > 0) {
        for (var i = 0; i < getLength(barcodedescriptorlist.valueDescriptors) ; i++) {
            debug += " [" + barcodedescriptorlist.valueDescriptors[i].getbarcodeFieldId() + "," + barcodedescriptorlist.valueDescriptors[i].getDataValue() + "]";
            var fieldId = barcodedescriptorlist.valueDescriptors[i].getbarcodeFieldId();
            if (fieldId == FIELD_ID_LOCATION || fieldId == FIELD_ID_PRODUCT || fieldId == FIELD_ID_STOCK_CONTAINER ||
                fieldId == FIELD_ID_STOCK_CONTAINER_TYPE || fieldId == FIELD_ID_QTY || fieldId == FIELD_ID_BATCH ||
                fieldId == FIELD_ID_EXP_DATA || fieldId == FIELD_ID_PRODUCTION_DATE || fieldId == FIELD_ID_SERIAL_NUMBER) {
                var bCode = barcodedescriptorlist.valueDescriptors[i].getDataValue();
                barcodes[fieldId] = bCode;
                fieldIds[fieldId] = true;
                fieldIdArray.push(fieldId);
            }
        }
    }
    console.log("lookupBarcode(" + barcodeText + ")" + debug);
    return { "barcodes": barcodes, "fieldIds": fieldIds, "fieldIdArray": fieldIdArray };
}

/* Check if the containerBarcode is on the location */
function barcodeOnLocation(containerBarcode, locationData) {
    var result = false;
    var x = -1;
    var y = -1;
    if (defined(locationData) && locationData.ContainerInfoList != null) {
        $.each(locationData.ContainerInfoList, function (i, container) {
            //            alert("Compare: " + containerBarcode + " == " + container.ContainerBarCode + " ==>>> " +  (containerBarcode == container.ContainerBarCode));

            // barcodeCompare is implementing 0-finten
            if (barcodeCompare(containerBarcode, container.ContainerBarCode)) {
                //            if(containerBarcode == container.ContainerBarCode){
                result = true;
                x = i;
            } // else try 0-finten

                // Check subcontainers
            else if (container.ContainersOnContainer != null) {
                $.each(container.ContainersOnContainer, function (j, cont) {
                    //                    alert("Sub Compare: " + containerBarcode + " == " + cont.ContainerBarCode + " ==>>> " +  (containerBarcode == cont.ContainerBarCode));
                    console.log("Sub Compare: " + getLength(containerBarcode) + " # " + containerBarcode.substr(0, 1) + " # " + containerBarcode.substr(1) + " # " + container.ContainerBarCode + "----> " + (containerBarcode == cont.ContainerBarCode) + " && " + (containerBarcode.substr(1) == cont.ContainerBarCode));
                    // barcodeCompare is implementing 0-finten
                    if (barcodeCompare(containerBarcode, cont.ContainerBarCode)) {
                        result = true;
                        y = j;
                        x = i;
                    }
                });
            }
        });
    }
    return { "result": result, "con": x, "sub": y };
}

function IsExpired(barcodeDate) {
    var currentDate = new Date();
    var dd = currentDate.getDate();
    var mm = currentDate.getMonth() + 1;
    var yy = currentDate.getFullYear() - 2000; //Subtract 2 k as we dont expect this solution to be running in 85 years from now.
    var ystr = '';
    if (yy < 10) {
        ystr += '0' + yy;
    }
    else {
        ystr += yy;
    }
    if (mm < 10) {
        ystr += '0' + mm;
    }
    else {
        ystr += mm;
    }
    if (dd < 10) {
        ystr += '0' + mm;
    }
    else {
        ystr += mm;
    }
    var cur = parseInt(ystr);
    var bcD = parseInt(barcodeDate);
    if (bcD < cur) {
        return true;
    }
    else {
        return false;
    }
}

// Todo: remove this function when ws returns the navigation
//function refreshNavigation(navigation) {
//    var htmlNavigation = getNavigation(navigation);
//    $("#navigation").html(htmlNavigation);
//    $('#navigation').find('div[data-role=collapsible]').collapsible();
//    $('#navigation').find('div[data-role=collapsible]').collapsibleset();
//    $('#navigation').find('a[data-role=button]').button();
//}

//function appendNavigation(navigation) {
//    var htmlNavigation = getNavigationUser(navigation);
//    $("#navigation").append(htmlNavigation);  //Todo, change .append() to .html()
//    $('#navigation').find('div[data-role=collapsible]').collapsible();
//    $('#navigation').find('div[data-role=collapsible]').collapsibleset();
//    $('#navigation').find('a[data-role=button]').button();
//}

function DbCommunicationErrorHandler(messagevariant) {
    var template = "<div data-role='popup' class='default_popup_class' id='errormanager_popup' style='max-width:600px'>"
    + "<div data-role='header' id='errormanager_popup_header' class='pm5_popup_header'></div>"
    + "<div data-role='content' data-theme='d' class='ui-corner-bottom ui-content'>"
    + "<span class='generic_popup_text' id='errormanager_popup_text'></span>"
    + "<a href='#' id='errormanager_popup_button' data-role='button' data-theme='b'>OK</a>"
    + "</div></div>";

    var message_header = '';
    var message_text = '';

    if (messagevariant == WEBSERVICE_FAULT_JSONREQUEST) {
        message_header = ReturnPhraseOnKey('errormanager_popup_header');
        message_text = ReturnPhraseOnKey('errormanager_popup_message_a');
        message_text += '<br>';
        message_text += ReturnPhraseOnKey('errormanager_popup_message_b');
    }
    else if (messagevariant == WEBSERVICE_FAULT_LOGIN) {
        message_header = ReturnPhraseOnKey('errormanager_popup_header');
        message_text = ReturnPhraseOnKey('errormanager_popup_message_a');
        message_text += '<br>';
        message_text += ReturnPhraseOnKey('errormanager_popup_message_c');
    }

    $.mobile.activePage.append(template).trigger('create');
    $('#errormanager_popup_header').html(message_header);
    $('#errormanager_popup_text').html(message_text);

    $("#errormanager_popup_button").unbind("click").click(function () {
        $("#errormanager_popup").popup("close");
    });

    $("#errormanager_popup").off().on("popupafterclose", function (event, ui) {
        if (messagevariant == WEBSERVICE_FAULT_JSONREQUEST) {
            $(":mobile-pagecontainer").pagecontainer("change", "#page_login", { role: "page", reverse: false, changeHash: false });
            mainMenu.LogoutCurrentUser();
        }

        $("#errormanager_popup").remove();
    });




    $('#errormanager_popup').popup().popup("open");

}

function c1(displayInConsole) {
    if (DEBUG_STATE == DEBUG_ACTIVE) {
        var toConsole = '%c ' + displayInConsole;
        console.log(toConsole, 'background: green; color: white');
    }
}

function c2(displayInConsole) {
    if (DEBUG_STATE == DEBUG_ACTIVE) {
        var toConsole = '%c ' + displayInConsole;
        console.log(toConsole, 'background: orange; color: black');
    }
}

function c3(displayInConsole) {
    if (DEBUG_STATE == DEBUG_ACTIVE) {
        var toConsole = '%c ' + displayInConsole;
        console.log(toConsole, 'background: red; color: lightgrey');
    }
}

function c4(displayInConsole) {
    if (DEBUG_STATE == DEBUG_ACTIVE) {
        var toConsole = '%c ' + displayInConsole;
        console.log(toConsole, 'background: lightblue; color: saddlebrown');
    }
}

function c5(displayInConsole) {
    if (DEBUG_STATE == DEBUG_ACTIVE) {
        var toConsole = '%c ' + displayInConsole;
        console.log(toConsole, 'background: olivedrab; color: lightgrey');
    }
}

function c6(displayInConsole) {
    if (DEBUG_STATE == DEBUG_ACTIVE) {
        var toConsole = '%c ' + displayInConsole;
        console.log(toConsole, 'background: purple; color: yellow');
    }
}

function c7(displayInConsole) {
    if (DEBUG_STATE == DEBUG_ACTIVE) {
        var toConsole = '%c ' + displayInConsole;
        console.log(toConsole, 'background: darkblue; color: lightgoldenrodyellow');
    }
}

function c8(displayInConsole) {
    if (DEBUG_STATE == DEBUG_ACTIVE) {
        var toConsole = '%c ' + displayInConsole;
        console.log(toConsole, 'background: aqua; color: black');
    }
}

function c9(displayInConsole) {
    if (DEBUG_STATE == DEBUG_ACTIVE) {
        var toConsole = '%c ' + displayInConsole;
        console.log(toConsole, 'background: orchid; color: yellow; font-size: 25px');
    }
}

function e1(displayInConsole) {
    if (E_TRACE == E_TRACE_ACTIVE) {
        var toConsole = '%c ' + displayInConsole;
        console.log(toConsole, 'background: chartreuse; color: darkslategrey; font-size: 15px');
    }
}

function e2(displayInConsole) {
    if (E_TRACE == E_TRACE_ACTIVE) {
        var toConsole = '%c ' + displayInConsole;
        console.log(toConsole, 'background: mediumslateblue; color: white; font-size: 15px');
    }
}

function e3(displayInConsole) {
    if (E_TRACE == E_TRACE_ACTIVE) {
        var toConsole = '%c ' + displayInConsole;
        console.log(toConsole, 'background: gold ; color: indigo; font-size: 15px');
    }
}

function e4(displayInConsole) {
    if (E_TRACE == E_TRACE_ACTIVE) {
        var toConsole = '%c ' + displayInConsole;
        console.log(toConsole, 'background: lightskyblue; color: black; font-size: 15px');
    }
}

function e5(displayInConsole) {
    if (E_TRACE == E_TRACE_ACTIVE) {
        var toConsole = '%c ' + displayInConsole;
        console.log(toConsole, 'background: green; color: gold; font-size: 15px');
    }
}

function c_objects(objectToOutput) {
    if (DEBUG_STATE == DEBUG_ACTIVE) {
        console.log(objectToOutput);
    }
}

function needTranslation() {
    for (var key in dk) {
        translationFlag = 'NT';
        var value = dk[key];
        if(value.includes(translationFlag)){
            console.log(value);
        }        
    }
}

function unspecifiedFromPM5(incomingString) {
    if (typeof incomingString !== 'undefined') {
        return incomingString.length > 0 ? incomingString : ReturnPhraseOnKey('global_unspecified');
    }
    else {
        return 'incoming is undefined';
    }
}

function hasGetUserMedia() {
    //return false;
    return !!(navigator.mediaDevices && navigator.mediaDevices.getUserMedia);
}

function hideBarcodeScannerAccessComponents() {
    c3('hiding barcode switches');
    //$("#machineselect_footer").css("display", "none");
    $("#selectmachine_camera").css("display", "none");
    $("#sparepartselectinstore_camera").css("display", "none");
    $("#jobselectonid_camera").css("display", "none");
    $("#selectmachine_camera").css("display", "none");
    //$("#selectsparepart_footer").css("display", "none");
    $("#selectsparepart_changetobarcode").css("display", "none");
    $("#consumption_on_job_search_button_grid").css("display", "none");
    $("#consumption_on_job_just_search").css("display", "block");
    $("#consumption_on_job__work_menu").css("display", "none");
    $("#consumption_on_job_sparepart_search_2").css("display", "block");

    c3('reseting barcode read control flags to manual searct trigger');
    CURRENT_MACHINE_SEARCH_MODE = MACHINE_SEARCH_INPUT_MANUAL;
    CURRENT_SPAREPART_SEARCH_MODE = SPAREPART_SEARCH_INPUT_MANUAL;
    CURRENT_JOBID_SEARCH_MODE = JOBID_SEARCH_INPUT_MANUAL;
    CONSUMPTION_SP_SEARCH_MODE = SPAREPART_SEARCH_INPUT_MANUAL;
}

function barcodeReaderFlags() {
    c1('Selected Application Section: ' + currently_selected_application_section);
    c1('Current Machine Search Mode: ' + CURRENT_MACHINE_SEARCH_MODE);
    c1('Current Sparepart Search Mode: ' + CURRENT_SPAREPART_SEARCH_MODE);
    c1('Current Job Id Search Mode: ' + CURRENT_JOBID_SEARCH_MODE);
    c1('Current Consumption Spare Part Search Mode: ' + CONSUMPTION_SP_SEARCH_MODE);
    c1('Scan page target: ' + SCAN_PAGE_TARGET);

}


function ShowScanButtons() {
    $('#scantest_buttons').show();
}

function HideScanButtons() {
    $('#scantest_buttons').hide();
}

function printCurrentPageName() {
    var pageName = $.mobile.activePage.attr('id');
    console.log(pageName);
}

//$(function () {
//    $(".date-input-css").datepicker().focus(function() {
//        $(this).prop("autocomplete", "off")
//    });
//})

//$(function () {
//    $("#createfault_expected_end_date2").datepicker().focus(function () {
//        $(this).prop("autocomplete", "off")
//    });
//});

$(function () {

    $("#datepicker_test2").datepicker().focus(function () {
        $(this).prop("autocomplete", "off")
    });

});


//$("#test_datepicker").click(function () {

//    if (!$(this).is(":checked")) { // enable autocomplete

//        $("#autocomplete").autocomplete({
//            disabled: false
//        });

//    }
//    else { // disable autocomplete
//        $("#autocomplete").autocomplete({
//            disabled: true
//        });

//    }
//});

function swapButton(button) {
    //var b = $('#testpage_icon_button');
    var b = button;
    var current_icon = b.data('icon');
    c5(current_icon);

    if (current_icon == "edit") {
        b.buttonMarkup({ icon: "check" });
        b.data("icon", "check");
        current_icon = b.data('icon');
        c3(current_icon);
    }
    else if (current_icon == "check") {
        b.buttonMarkup({ icon: "edit" });
        b.data("icon", "edit");
        current_icon = b.data('icon');
        c4(current_icon);

    }

    //b.buttonMarkup({ icon: "check" });
    //b.button('refresh');
}


