var changeProductTimeout;

$(document).on('click', '.change-product i', function () {
    var button = $(this);
    computeSpinnerMove(button);

    changeProductTimeout = setTimeout(function () {
        changeItem(button);
    }, 600);
});

$(document).ready( function() {
   $(document).find("[data-form-new] :input[name*=id_product_text]").focus();
});

function computeSpinnerMove($button) {
    clearTimeout(changeProductTimeout);

    var oldValue = $button.closest('.form-control-spinner').find("input.orderInput").val(),
        newVal;

    if ($button.hasClass("plus_unit")) {
        newVal = parseFloat(oldValue) + 1;
    } else {
        // Don't allow decrementing below zero
        if (oldValue > 1) {
            newVal = parseFloat(oldValue) - 1;
        } else {
            newVal = 0;
        }
    }
    $button.closest('.form-control-spinner').find("input.orderInput").val(newVal);
}

// Change input on Item
$(document).on('keyup', 'input.orderInput', function (event) {
    var input = $(this);
    if (event.keyCode == 188 || //comma
        event.keyCode == 109) //minus
    {
        event.preventDefault();
    }
    if (event.keyCode == 13) //minus
    {
        clearTimeout(changeProductTimeout);

        changeItem(input);
        return;
    }
    lazyChangePieces(input);
});

$(document).on('click', '.orderInput', function () {
    clearTimeout(changeProductTimeout);
    $(this).select();
});

function lazyChangePieces(input) {
    clearTimeout(changeProductTimeout);

    changeProductTimeout = setTimeout(function () {
        changeItem(input);
    }, 700);

    return false
}


function changeItem(tthis) {
    var index = tthis.closest(".list_item").find("#delete-item").attr("name"),
        pieces = tthis.closest(".list_item").find('.product_pieces').val(),
        id_order = getOrderID(),
        product = tthis.closest(".list_item").find("#delete-item").data('id_product'),
        discount = tthis.closest(".list_item").find(".product_discount").val();

    if (product != '') {
        $('#items').load('launch.php?s=pos.pos.php #items_content', {
            acn: 'ChangeItem',
            item_id: index,
            pieces: pieces,
            id_order: id_order,
            product_discount: discount,
            user_id: getUserID()
        }, function (response, status) {
            responseFromStatus(status, response);
        });
    }
    else {
        sendRequest({
            acn: 'ChangeItem',
            item_id: index,
            pieces: pieces,
            product_discount: discount
        });
    }

    return false;
}

function checkInputDataType(type, event) {
    if (!event)
        return;

    if (type == 'int') {
        if ((event.which < 48 || event.which > 57) && event.which != 13 && event.which != 8 && event.which != 9) {
            event.preventDefault();
        }
    }
}

function responseFromStatus(status, response) {
    if (status == "success") {
        printRecapitulation(response);
    }
    if (status == "error") {
        timeExceeded()
    }
}
// Click on cupon add
$(document).on('click', '.add-coupon', function () {
    var coupon_number = $(document).find('.coupon-number').val();
    $('#items').load('launch.php?s=pos.pos.php #items_content', {
        acn: 'addCoupon',
        coupon_number: coupon_number,
        user_id: getUserID()
    }, function (response, status) {
        responseFromStatus(status, response);
        if (status == "success") {
            printAdditionalInputs(response);
        }
    });
});

// Click on cuppon remove
$(document).on('click', '.remove-coupon', function () {
    var coupon_number = -1;
    $('#items').load('launch.php?s=pos.pos.php #items_content', {
        acn: 'addCoupon',
        coupon_number: coupon_number,
        user_id: getUserID()
    }, function (response, status) {
        responseFromStatus(status, response);
        if (status == "success") {
            printAdditionalInputs(response);
        }
    });
    return false;
});


// Add coupon to list
function addCoupon(item) {
    //if (tr.length == 0) {
    $(document).find(".empty-row-coupon:first").clone().appendTo(".coupons").removeAttr('style').removeClass('empty-row-coupon');
    var row = $(document).find('.coupons .row:last');
    //}
    row.find(".coupon-name").text(item.descr);
    row.find(".coupon-value").text(item.discount_number + ' ' + item.unit);
    row.find(".coupon-id").val(item.id);
}

//
$(document).on('click', '[data-form-new] .id_product', function (event) {
    if ($(this).val() == '')
        prepareForNextProduct();
});

$(document).on('keydown', '[data-form-new] .id_product', function (event) {
    if (event.keyCode == 13) //minus
    {
        $(document).find('[data-form-new] :input[name*=piece_price]').focus();
    }
});


// Click on add item button
$(document).on('click', '.addItem', function () {
    clickAddItem();
});

$(document).on('keydown', '[data-form-new] :input[name*=piece_price]', function (event) {
    if (event.keyCode == 13) //minus
    {
        clickAddItem();
    }
});

function clickAddItem() {
    $form = $(document).find("[data-form-new]");
    var id_product = $form.find(".id_product").val();
    var id_variation = $form.find(":input[name*=id_variation]").val();
    var data;

    if (id_variation == -1) {
        showMessage("Není zvolena varianta!", 'danger');
        return;
    }

    scrollDown = true;
    if (id_product != '')
       //     productRow = $("#delete-item").find('[data-id_product=' + id_product + ']');
       //
       // if (productRow !== undefined) {
       //    if (id_variation) {
       //       variationRow = $("#delete-item").find('[data-id_variation=' + id_variation + ']');
       //
       //       if (variationRow !== undefined) {
       //          changeItem(variationRow)
       //       }
       //    } else {
       //       changeItem(productRow)
       //    }
       // } else {
        addProduct(id_product, id_variation, "");
    else {
        var title = $(document).find("[data-form-new] :input[name*=id_product_text]").val(),
            price = $(document).find("[data-form-new] :input[name*=piece_price]").val(),
            vat = $(document).find("[data-form-new] :input[name*=vat]").val();

        if (title == '') {
            showMessage("Chybí název produktu!", 'danger');
            return false;
        }

        if (price == '') {
            showMessage("Chybí cena produktu!", 'danger');
            return false;
        }

        addNonProduct(title, price, vat);
    }

    prepareForNextProduct();
}

function prepareForNextProduct() {
    $(document).find("[data-form-new] :input[name*=id_product]").val('');
    $(document).find("[data-form-new] :input[name*=piece_price]").val('').removeAttr('disabled');
    $(document).find("#vat_selecter").prop('disabled', false).val(1).trigger("chosen:updated");
    $(document).find("[data-form-new] :input[name*=id_product_text]").focus();
    $(document).find(".chosen-single").val('').trigger("liszt:updated");
}


// Delete item
$(document).on('click', '#delete-item', function () {
    var id_order = getOrderID();
    //$(this).prop("name");
    $('#items').load('launch.php?s=pos.pos.php #items_content', {
        acn: 'deleteItem',
        item_id: $(this).prop("name"),
        id_order: id_order,
        user_id: getUserID()
    }, function (response, status) {
        responseFromStatus(status, response);
    });
    return false;
});

function getUserID() {
    return $(document).find(".user_id").val();
}

// Button Pay
$(document).on('click', '#pay', function () {
    let error = null;
    $('#items').load('launch.php?s=pos.pos.php #items_content', {
        acn : 'checkCart',
        id_order: getOrderID(),
    }, function (response, status, request) {
        error = request.getResponseHeader('pos-error');

        if (error) {
            showErrorHeaderMessage(error);
            return;
        }

        if ($('.list_item').length > 0) {
            $("#dialog_paying").dialog("open");
        } else {
            showMessage("Neni pridan zadny produkt!", 'danger');
        }
    });

});

function showErrorHeaderMessage(requestError){
    showMessage(decodeURI(requestError).replace(/\+/g, ' '), "danger");
}

var scrollDown = false;
function printRecapitulation(response) {
    var scrollTop = $('#items').scrollTop();

    $(document).find("#price_without_vat").text($(response).find("#price_without_vat").text());
    $(document).find("#price_with_vat").text($(response).find("#price_with_vat").text());
    $(document).find("#price_to_pay").text($(response).find("#price_to_pay").text());
    $(document).find("#input_to_pay").val($(response).find("#input_to_pay").val());
    $(document).find(".panel-group.recapitulation .global_discount").val($(response).find(".panel-group.recapitulation .global_discount").val());

    $(document).find(".coupons").html($(response).find(".coupons").html());
    showResulFromResponse(response);
    printAdditionalInputs(response);

    if (scrollDown) {
        $('#items').scrollTop($('#items').height());
        scrollDown = false;
    } else {
        $('#items').scrollTop(scrollTop);
    }
}

function setOrderIDFromResponse(response) {
    setOrderID($(response).find(".id_order").val());
}

function printAdditionalInputs(response) {
    var resp_add = $(response).find('#additional-inputs');
    var form_add = $(document).find('#additional-inputs');

    // printAdditionalInput(form_add, resp_add, '.order_number');
    //printAdditionalInput(form_add, resp_add, '.user');
    replaceUser(response);
    replaceOrder(response);
    printAdditionalInput(form_add, resp_add, '.coupon-number');
    printAdditionalInput($(document), $(response), '.global_discount');

    form_add.find('.id_order').val(resp_add.find('.id_order').val());
    form_add.find('.user_id').val(resp_add.find('.user_id').val());

    form_add.find('.user-group').html(resp_add.find('.user-group').html());
    form_add.find('.coupon-number-group').html(resp_add.find('.coupon-number-group').html());

    resp_add.find('[data-reload]').each(function() {
      $(document).find('[data-reload="'+$(this).data('reload')+'"]').html($(this).html());
   });
}


function replaceUser(response){
    var resp_user = $(response).find('.user');

    $(document).find('.user').replaceWith(resp_user);

    bindUser();
}

function replaceOrder(response){
    var resp_order = $(response).find('.order');

    $(document).find('.order').replaceWith(resp_order);

    bindOrder();
}

function printAdditionalInput(form_add, resp_add, fieldname) {
    form_add.find(fieldname).val(resp_add.find(fieldname).val());
    if (resp_add.find(fieldname).attr('disabled') == "disabled") {
        form_add.find(fieldname).attr('disabled', 'disabled');
    } else {
        form_add.find(fieldname).removeAttr('disabled');
    }
}

function createOrder(){
    $('#items').load('launch.php?s=pos.pos.php #items_content', {
        acn: 'createOrder',
        user_id: getUserID()
    }, function (response, status) {
        responseFromStatus(status, response);
        if (status == "success") {
            setOrderIDFromResponse(response);
        }
    });
}

function showPayingLoad(show){
    if (show){
        $(document).find('#paying_buttons').fadeOut(300);
        $(document).find('#paying_loader').fadeIn(300);
    }else{
        $(document).find('#paying_buttons').fadeIn(300);
        $(document).find('#paying_loader').fadeOut(300);
    }
}

function pay(method) {
    $('#items').load('launch.php?s=pos.pos.php #items_content', {
        acn : 'pay',
        id_order: getOrderID(),
        method: method
    }, function (response, status, request) {
        let error = request.getResponseHeader('pos-error');

        if (error) {
            showErrorHeaderMessage(error);
            return;
        }

        disablePayButtons();
        showPayingLoad(true);

        if (status == "success") {
            responseFromStatus(status, response);
            PrintInvoice();
        }
        if (status == "error") {
            timeExceeded();
            enablePayButtons();
            showPayingLoad(false);
        }
    });
}

$(document).on('click', '#dialog_paying .pay_cancel', function () {
    $("#dialog_paying ").dialog('close');
});

// $(document).on('click', '#dialog_paying.pay_storno', function () {
//     var storno = confirm("Stornovat objednavku? (tento krok nelze vratit)");
//
//     if (storno) {
//         $.get('launch.php?s=pos.pos.php&acn=Storno&id_order' + getOrderID(), function (data, status) {
//             if (status == "success") {
//                 clearPage();
//             }
//         });
//     }
//     return false;
// });


$(document).on('click', '#print_invoice', function () {
    PrintInvoice();
});

$(document).on('click', '.print-product', function () {
    $("#print_iframe")[0].contentWindow.location.href = $(this).attr('href');
    $("#dialog_print_iframe").dialog('open');
    return false;
});

$(document).on('click', '.finish_order, #order_cancel', function () {
    newCustomer();
});

$(document).on('click', '#dialog_paying input[name*=getting_money]', function (event){
    $(this).select();
});

// Recalculate back money
$(document).on('keyup change', '#dialog_paying input[name*=getting_money]', function (event) {
    if (event.keyCode == 13) //minus
    {
        pay(1);
        return;
    }

    var to_pay = $('input[name*=to_pay]').val();
    to_pay = to_pay.replace(/ +/g, "");
    to_pay = to_pay.replace(/,/g, ".");
    var payed = $(this).val();
    payed = payed.replace(/ +/g, "");
    payed = payed.replace(/,/g, ".");
    var give_back = Number(payed - to_pay);
    if (isNaN(give_back))
        return;
    $('input[name*=give_back]').val(give_back);


//            if (give_back >= 0 ){
//                $('.pay_cash').removeAttr('disabled');
//            }else{
//                $('.pay_cash').attr('disabled', 'disabled');
//            }
});

function newCustomer() {
    $.get('launch.php?s=pos.pos.php&acn=ClearOrder', function (data, status) {
        if (status == "success") {
            $(document).find("[data-form-new] :input[name*=id_product]").val("");

            location.reload(true);
        }
    });
}


$(document).on('click', '.remove-user', function () {
    $('#items').load('launch.php?s=pos.pos.php #items_content', {
        acn: 'userLoad',
        user_id: '-1',
        id_order: getOrderID()
    }, function (response, status) {
        responseFromStatus(status, response);
        if (status == "success") {
            setOrderIDFromResponse(response);
            printAdditionalInputs(response);
        }
    });
    return false;
});

$(document).on('click', '.remove-order', function () {
    $('#items').load('launch.php?s=pos.pos.php #items_content', {
        acn: 'orderLoad'
    }, function (response, status) {
        responseFromStatus(status, response);
        if (status == "success") {
            setOrderIDFromResponse(response);
            printAdditionalInputs(response);
        }
    });
    return false;
});

function addProduct(id_product, id_variation, ean) {
   scrollDown = true;
    if ($("#dialog_paying").dialog('isOpen')) {
        showMessage('Během placení nelze přidávat další produkty!', 'danger');
        return;
    }

    sendRequest({
        acn: 'addProduct',
        id_product: id_product,
        id_variation: id_variation,
        ean: ean
    });
}

function addNonProduct(title_value, price_value, vat) {
    var data = {
        acn: 'addNonProduct',
        id: 'null',
        vat: vat,
        title: title_value,
        price: price_value
    };
    sendRequest(data);
}

function sendRequest(data) {
    var default_data = {
        id_order: getOrderID(),
        user_id: getUserID()
    };

    var send_data = $.extend(default_data, data);

    $('#items').load('launch.php?s=pos.pos.php #items_content', send_data,
        function (response, status) {
            responseFromStatus(status, response);
        });
}

function selectProduct() {
    $(document).find("[data-form-new] :input[name*=piece_price]").attr('disabled', 'disabled');
    $(document).find("#vat_selecter").prop('disabled', true).trigger("chosen:updated");
}

function showOkMessage(msg) {
    showMessage(msg, 'success');
}

function showResulFromResponse(response) {
    showMessage($(response).find('[data-result=msg]').val(), $(response).find('[data-result=type]').val());
}

function timeExceeded() {
    showMessage("Časový limit odpověďi vypršel, zkuste to prosím za okamžik znovu", "danger");
}

var infobox;
function showMessage(str, type) {
    clearTimeout(infobox);

    var infoRow =
        "<div class=\"row static\">" +
        " <div class=\"alert autoclose alert-" + type + " alert-dismissable fade in\">" +
        " <button type=\"button\" class=\"close\" data-dismiss=\"alert\">" +
        "<span aria-hidden=\"true\">&times;</span><span class=\"sr-only\">Close</span></button>" +
        "<span class=\"glyphicon glyphicon-" + ((type == "success") ? "ok" : "remove") + "\"></span>" +
        "<strong>" + str + "</strong>" +
        "</div>" +
        "</div>";

    $("#info_box").html(infoRow);

    infobox = setTimeout(function () {
        $(".alert.autoclose").alert("close")
    }, 5000);
}

$(".alert.autoclose").mouseover(function (e) {
    $(this).hide()
});

function clearPage() {
    $(document).find(".finish_order").removeAttr('disabled');
}

function clearTable() {
    $(document).find("#items:child").remove();
    $(document).find(".coupons").empty();
}

function recalcOrder(data) {
    $(document).find(".panel-group.recapitulation .price_without_vat").text(data.totalPriceNoVat + " Kč");
    $(document).find(".panel-group.recapitulation .price_with_vat").text(data.totalPriceWithVat + " Kč");
    $(document).find(".panel-group .to_pay h1").text(data.totalPricePay + " Kč");
    $(document).find("#dialog_paying :input[name*=to_pay]").val(data.totalPricePay);
}

function disablePayButtons() {
    $(document).find('#dialog_paying .pay_cash').prop('disabled', 'disabled');
    $(document).find('#dialog_paying .pay_card').prop('disabled', 'disabled');
    $(document).find('#dialog_paying .pay_invoice').prop('disabled', 'disabled');
    // $(document).find('#dialog .pay_storno').prop('disabled', 'disabled');
}

function enablePayButtons() {
    $(document).find('#dialog_paying .pay_cash').removeAttr('disabled');
    $(document).find('#dialog_paying .pay_card').removeAttr('disabled');
    $(document).find('#dialog_paying .pay_invoice').removeAttr('disabled');
    // $(document).find('#dialog .pay_storno').removeAttr('disabled');

}

function setOrderID(id) {
    $(document).find(".id_order").val(id);

    if (id) {
       $('#save_order').prop('disabled', 'disabled').prop('title', 'Existujici objednavku lze pouze editovat').val('Režim editace objednávky');
    } else {
       $('#save_order').prop('disabled', '').prop('title', '').val('Uložit jako objednávku');
    }
}

function getOrderID() {
    return $(document).find(".id_order").val();
}

/*****
 AUTOCOMPLETES DEFS
 *****/

// products searching
$form = $(document).find("[data-form-new]");
new $.wpjAutoCompleteVariation({
    inputProduct: $form.find(":input[name*=id_product]"),
    inputVariation: $form.find(":input[name*=id_variation]"),
    inputFields: {
        'vat': $form.find(":input[name*=vat]"),
        'price_with_vat': $form.find(":input[name*=piece_price]")
    },
    callbacks: {
        //'selectVariation': selectVariation,
        'selectProduct': selectProduct
    },
    productOptions: {
        source: 'launch.php?s=autocomplete.php&limit=50&visible=0'
    }
});


// Autocomplete for cupon load
var $discount = new $.wpjAutoComplete({
    input: "#coupon-number",
    type: 'discount'
});

$discount.inputHidden.bind("autocompleteselect", function (event, ui) {
    var coupon_number = ui.item.value;
    $('#items').load('launch.php?s=pos.pos.php #items_content', {
        acn: 'addCoupon',
        coupon_number: coupon_number,
        user_id: getUserID()
    }, function (response, status) {
        responseFromStatus(status, response);
        if (status == "success") {
            printAdditionalInputs(response);
        }
    });
});


// Autocomplete for order load
var $order;
bindOrder();
function bindOrder(){
    $order = new $.wpjAutoComplete({
        input: "#order",
        type: 'order_id',
        params: 'only_active=1'
    });

    $order.inputHidden.bind("autocompleteselect", function (event, ui) {
        var id_order = ui.item.value;
        setOrderID(id_order);
        $('#items').load('launch.php?s=pos.pos.php #items_content', {
            acn: 'orderLoad',
            id_order: id_order
        }, function (response, status) {
            scrollDown = true;
            responseFromStatus(status, response);
            if (status == "success") {
                setOrderIDFromResponse(response);
                printAdditionalInputs(response);
            }
        });
    });
}

// Autocomplete for user load
var $user;
bindUser();

function bindUser(){
    $user = new $.wpjAutoComplete({
        input: "#user",
        type: 'user'
    });

    $user.inputHidden.bind("autocompleteselect", function (event, ui) {
        var user_id = ui.item.value;
        $('#items').load('launch.php?s=pos.pos.php #items_content', {
            acn: 'userLoad',
            user_id: user_id,
            id_order: getOrderID()
        }, function (response, status) {
            responseFromStatus(status, response);
            scrollDown = true;
            if (status == "success") {
                setOrderIDFromResponse(response);
                printAdditionalInputs(response);
            }
        });
    });
}


/*****
 JQUERY UI DIALOGS DEFS
 *****/

// Paying dialog
$("#dialog_paying").dialog(
    {
        dialogClass: "no-close",
        autoOpen: false,
        width: 600,
        height: 630,
        resizable: false,
        modal: true,
        draggable: false
    }
);

// Insert money dialog
$("#dialog_insert_money").dialog(
    {
        dialogClass: "no-close",
        autoOpen: false,
        width: 500,
        height: 330,
        title: "Vklad do kasy",
        resizable: false,
        modal: true,
        draggable: false
    }
);

// Choose money dialog
$("#dialog_choose_money").dialog(
    {
        dialogClass: "no-close",
        autoOpen: false,
        width: 500,
        height: 330,
        title: "Výběr z kasy",
        resizable: false,
        modal: true,
        draggable: false
    }
);

// List of transaction in POS
$("#dialog_list_money").dialog(
    {
        autoOpen: false,
        width: 1100,
        height: 600,
        title: "Seznam pohybů peněz v kase",
        resizable: false,
        modal: true,
        draggable: false
    }
);

//
$("#dialog_print_iframe").dialog(
    {
        // dialogClass: "no-close",
        autoOpen: false,
        width: 850,
        height: 640,
        title: "Tisk faktury",
        resizable: false,
        modal: true,
        draggable: false
    }
);

/*****
 JQUERY UI DIALOGS HANDLING
*****/

// Button insert money for open dialog
$(document).on('click', '.list-money', function () {
    $("#list_money")[0].contentWindow.location.reload(true);
    $("#dialog_list_money").dialog("open");
});

// Button insert money for open dialog
$(document).on('click', '.insert-money', function () {
    $("#dialog_insert_money").dialog("open");
});

// Button choose money for open dialog
$(document).on('click', '.choose-money', function () {
    $("#dialog_choose_money").dialog("open");
});

// Button cancel for insert money dialog
$(document).on('click', '#dialog_insert_money .insert_cancel', function () {
    $("#dialog_insert_money").dialog("close");
    return false;
});

// Button cancel for choose money dialog
$(document).on('click', '#dialog_choose_money .choose_cancel', function () {
    $("#dialog_choose_money").dialog("close");
    return false;
});

// Button Pay by Cash
$(document).on('click', '#dialog_paying .pay_cash', function () {
    pay(1);
});

// Button Pay by Card
$(document).on('click', '#dialog_paying .pay_card', function () {
    pay(2);
});

//Button Pay by Invoice
$(document).on('click', '#dialog_paying .pay_invoice', function () {
    pay(3);
});

//Button Save as order
$(document).on('click', '#save_order', function () {
    createOrder();
});

// Button for accept insert money
$(document).on('click', '#dialog_insert_money .insert_accept', function () {
    var value = $(document).find("#inserted_money").val();
    var descr = $(document).find("#inserted_money_descr").val();

    processMoney(value, descr, 'inserted', '#dialog_insert_money');
});

// Button for accept choose money
$(document).on('click', '#dialog_choose_money .choose_accept', function () {
    var value = $(document).find("#choosed_money").val();
    var descr = $(document).find("#choosed_money_descr").val();

    processMoney(-value, descr, 'choosed', '#dialog_choose_money');
});

function processMoney(value, descr, type, dialog_name){
    if (value == '')
        return;

    $.ajax({
        type: 'POST',
        url: 'launch.php?s=pos.pos.php',
        data: {
            acn : 'moveMoney',
            value: value,
            descr: descr
        },
        success: function (msg) {
            $(dialog_name).dialog("close");
            $(document).find("#" + type + "_money").val('');
            $(document).find("#" + type + "_money_descr").val('');
            showResulFromResponse(msg);
        },
        error: function () {
            timeExceeded()
        }
    });
}

/*****
 SESSION EXTEND
*****/

sendExtendSession();

function sendExtendSession() {
    setTimeout(function () {
        $.ajax({
            type: 'POST',
            url: 'launch.php?s=pos.pos.php&acn=extendSession',
            success: function (msg) {
            }
        });
        sendExtendSession();
    }, 1000 * 60 * 5);
}

/*****
 WEBCHANNELS
 *****/

window.onload = function () {
    let triedsReconnect = false;

    function connectSocket(url){
        let socket = new WebSocket(url);

        socket.onclose = function () {
            if (!triedsReconnect) {
                socket = null;
                triedsReconnect = true;
                connectSocket("ws://localhost:12345");
                return;
            }
            console.error("web channel closed");
        };
        socket.onerror = function (error) {
            if (!triedsReconnect) {
                socket = null;
                triedsReconnect = true;
                connectSocket("ws://localhost:12345");
                return;
            }
            console.error("web channel error: " + error);
        };
        socket.onopen = function () {
            new QWebChannel(socket, function (channel) {
                // make dialog object accessible globally
                window.codereader = channel.objects.codereader || channel.objects.kupshopCheckout;
            });
        }
    }

    connectSocket("ws://localhost:13458");
};
