window.OrderModulDefault={
    actionFunction: function () {},
}
class DataModelOrder extends DataModel{

    /*
     * Constructor
     */
    constructor (data,options) {
        super(data,options)
        if(typeof this.productSelected ==="undefined"){
            this.productSelected={};
        }
        if(typeof this.productComment ==="undefined"){
            this.productComment={};
        }
        console.log(this.constructor.name+' constructor called');
    };
};
window.DataModelOrder=DataModelOrder;

window.Stepper=function () {

    /*
     * Variables accessible
     * in the class
     */
    let Opts = {
        complete: ['supplier'],
        available: ['supplier', 'parameter', 'productSelect', 'invoice', 'send'],
        enable: ['supplier', 'invoice'],
        load: [],
        excludeLoaded:['invoice','send'],
        loaded: [],
        active: false,
        URL: {
            create: '',
        },
        UrlData:false,
        onAfterLoad:function () {},
        onAfterActivate:function () {},
        autoCallback:{
            'invoice':{
                onAfterActivate:function () {},
            },
            'send':{
                onAfterActivate:function () {},
            },
        },
        nowLoaded:false,

    };

    let root=this;
    /*
     * Constructor
     */
    this.construct = function (options) {
        $.extend(Opts, options);
    };

    this.getOpts=function(){
        return Opts;
    }
    this.setOpts=function(options){
        $.extend(Opts, options);
    }



    this.init=function (options){
        $.extend(Opts, options);

        debug(Opts);
        $('.step').each(function(){
            let stepName=$(this).data('stepname');
            if(Opts.complete.includes(stepName)){
                root.setCompleted(stepName);
            }
            if(Opts.enable.includes(stepName)){
                root.setEnabled(stepName);
            }
            if(Opts.load.includes(stepName)){
                root.loadStepContent(stepName);
            }

            if(Opts.active===stepName){
                root.setActive(stepName);
            }
        });
        root.bindClickAction();
    }

    this.bindClickAction=function (){
        let stepClickButtons=$('.stepClick');
        stepClickButtons.off('click');
        stepClickButtons.on('click',root.stepClick);

    }

    this.setCompleted=function (stepName){
        console.log(stepName+' completed');
        $('.step[data-stepName="'+stepName+'"]').addClass('completed');
    }

    this.unsetCompleted=function (stepName){
        console.log(stepName+' Uncompleted');
        $('.step[data-stepName="'+stepName+'"]').removeClass('completed');
        Opts.complete=arrayRemove(Opts.complete,stepName);
    }

    this.unsetEnabled=function (stepName){
        console.log(stepName+' Un enabled');
        $('.click'+stepName).contents().unwrap();
        Opts.enable=arrayRemove(Opts.enable,stepName);
    }
    this.setEnabled=function (stepName){
        console.log(stepName+' enabled');
        let stepItem=$('.step[data-stepName="'+stepName+'"]');
        stepItem.html('<a class="stepClick click'+stepName+'" data-stepName="'+stepName+'" href="#">'+stepItem.html()+'</a>');
        root.bindClickAction();
        //$('.stepClick').click(root.stepClick);

    }

    this.addEnabled=function(stepName){
        if(!Opts.enable.includes(stepName)){
            Opts.enable.push(stepName);
        }
        root.setEnabled(stepName);
    }

    this.addCompleted=function(stepName){
        if(!Opts.complete.includes(stepName)){
            Opts.complete.push(stepName);
        }
        root.setCompleted(stepName);
        root.bindClickAction();
    }


    this.loadStepContent=function (stepName){
        let data={'type':stepName};
        $.extend(data, Opts.UrlData);

        $.ajax({
            async: true,
            type: "GET",
            url: Opts.URL.create,
            data: data,
            cache: false,
            success: function(result)
            {
                let container=$('.SC'+stepName.capitalize());
                if($.inArray(stepName,Opts.excludeLoaded)==-1){
                    Opts.loaded.push(stepName);
                }else{
                    console.log('excluded View');
                }
                container.html(result);
                if(Opts.nowLoaded){
                    Opts.nowLoaded(stepName);
                }
                Opts.onAfterLoad();
            }
        });
    }

    this.clearLoaded=function () {
        Opts.loaded=['supplier'];
        $('.stepContainer').each(function(){
/*
            console.log(this.classList);
            console.log(this.classList.contains('SCSupplier'));
            console.log($(this).attr('class'));
*/
            if(!this.classList.contains('SCSupplier')){
                $(this).html('');
            }
        });
    }

    this.setActiveFinish=function(stepName){
        let container=$('.SC'+stepName.capitalize());
        if(stepName==='productSelect'){
            $('.containerStepper').addClass('activeSideBar');
        }else{
            $('.containerStepper').removeClass('activeSideBar');
        }
        debug('setActiveFinish show:'+stepName);
        container.show();
        Opts.nowLoaded=false;
        root.active=stepName;
        Opts.onAfterActivate();
        if(typeof Opts.autoCallback[stepName]!=='undefined' ){
            Opts.autoCallback[stepName].onAfterActivate();
        }
    }
    this.setActive=function(stepName){
        $('.stepContainer').hide();
        if(!Opts.loaded.includes(stepName)){
            root.loadStepContent(stepName);
            Opts.nowLoaded=this.setActiveFinish;
        }else{
            this.setActiveFinish(stepName);
        }
    }

    this.stepClick=function(event){
        event.preventDefault();
        let stepName=$(event.currentTarget).data('stepname');
        console.log('setActive:'+stepName);
        root.setActive(stepName);
    }
}

window.OrderModule = function () {

    /*
     * Variables accessible
     * in the class
     */
    let Opts = {
        testMode: false,
        needStepper:true,
        CSSSelectorForm:'.orderParameterForm',
        defaultDeliveryDate:'',
        dataSyncPauseTime:500,
        token:null,
        URL: {
            root:null,
            getDataTableContentProductList:null,
            checkReadyToSend:null,
            index:null,
            show:null,
            edit:null,
            create: null,
            store: null,
            update:null,
            destroy:null,
            toggleFavorites:null,
        },
    };

    const PublicVar = {};
    let PublicVar2 = {'asd': '21'};
    let ApiToken = null;
    let Order=null;
    let root = this;
    let viewInicialized=[];

    this.setOpts = function (options) {
        $.extend(Opts, options);
    }

    this.getOpts = function () {
        return Opts;
    }
    this.clickOrderEdit=function (data){
        debug('clickEdit');
        debug(data);
        let ajaxUrl=Opts.URL.edit.replace('%id%',data.id);
        APP.loadMainContent(ajaxUrl);
/*        let ajaxData={};
        ajaxData._token=Opts.token;
        $.extend(ajaxData,Order);
        let ajaxUrl=Opts.URL.edit.replace('%id%',data.id);
        $.ajax({
            url: ajaxUrl,
            method:'GET',
            data:ajaxData,
            success:function (response) {
                if(response.success){
                    let orderData=response.data;
                    orderData.supplierId=orderData.supplier_id;
                    delete(orderData.supplier_id);
                    root.initOrder(orderData);
                    root.initStepper();
                    //root.afterOrderSetSupplierOk(data.data);
                }
            }
        });*/


    }
    this.afterOrderDeleted=function (data){
        if(data.success==true){
            debug('Order delete success');
            APP.loadMainContent(Opts.URL.index);
        }else{
            Toast.create("Error deleted !",'', TOAST_STATUS.DANGER,5000);
        }
    }
    this.clickOrderDeleteConfirmed=function (event){
        debug('clickOrderDeleteConfirmed');
        debug(event);
        debug(event.data);
        $('#dialogModal').modal('hide');
        let ajaxData={};
        ajaxData._token=Opts.token;
        let ajaxUrl=Opts.URL.destroy.replace('%id%',event.data.id);
        $.ajax({
            url:ajaxUrl,
            data:ajaxData,
            method:"DELETE",
            success:root.afterOrderDeleted,
            //error:ajaxErrorHandler
        });

    }
    this.initViewOrderSelect=function (){
        debug('called initViewOrderSelect ');
        $('.ordersSelectTable button').off('click');
        $('.ordersSelectTable button').on('click',function (){
            let action=$(this).data('action');
            let orderId=$($(this).closest('tr')[0]).data('orderid');
            debug(action);
            debug(orderId);

            if(action=='delete'){
                $('#dialogModal').on('show.bs.modal', function (event) {
                    // If necessary, you could initiate an AJAX request here (and then do the updating in a callback).
                    // Update the modal's content. We'll use jQuery here, but you could use a data binding library or other methods instead.
                    var modal = $(this);
                    modal.find('.modal-title').text('Megerősítés ');
                    modal.find('.modal-body').text('Biztosan törli a megrendelést?');
                    modal.find('.buttonYes').off('click');
                    modal.find('.buttonYes').on('click',{id:orderId},root.clickOrderDeleteConfirmed);
                });
                $('#dialogModal').modal('show');
            }else{
                root.clickOrderEdit({id:orderId});
            }
        });
        $('.buttonNew').off('click');
        $('.buttonNew').on('click',function (){
            APP.loadMainContent(Opts.URL.index,'force=true');
        });

    }
    this.initStepper=function (){
        debug(Order.getData());
        viewInicialized=[];
        $('.statusNamePlace').text('Nincs elküldve');
        $('.statusNamePlace').addClass('statusBlink');
        root.setDeliveryDate('-');
        root.setSupplier('-');

        let unEnabled=['parameter', 'productSelect', 'invoice', 'send'];
        $.each(unEnabled,function (index,value) {
            root.Stepper.unsetEnabled(value);
            root.Stepper.unsetCompleted(value);
        });

        debug(root.Stepper.getOpts()['available']);
        debug(Order.getData()['orderStatus']);

        let stepActive='supplier';
        let stepComplete=['supplier'];
        let stepEnable=[];
        let stepOnAfterActivate=function (){};

        let avalaibleSteps=root.Stepper.getOpts()['available'];
        let stepUrlData=false;
        let stepAutoCallback=[];
        for (let stepName of avalaibleSteps) {
            stepOnAfterActivate=this['initView'+stepName.capitalize()];
            let item={};
            item['onAfterActivate']=stepOnAfterActivate;
            stepAutoCallback[stepName]=item;
        }
        debug(stepAutoCallback);
        debug(Order.getData()['id']);
        if(Order.getData()['id']>0){
            debug('hajra');
            debug(Order.getData());
            if(Order.getData()['deliveryDate']){
                root.setDeliveryDate(Order.getData()['deliveryDate']);
                /*
                @todo: weekly-t beallitani
                 */
            }
            if(Order.getData()['supplierName']){
                root.setSupplier(Order.getData()['supplierName']);
            }
            stepUrlData={'supplierId':Order.supplierId,id:Order.id};
            for (let stepName of avalaibleSteps) {
                console.log(stepName);
                stepComplete.push(stepName);
                stepEnable.push(stepName);
                if(Order.getData()['orderStatus']==stepName){
                    stepActive=stepName;
                    /*
                    debug('initView'+stepName.capitalize());
                    if(stepName!=='invoice' && stepName!=='send'){
                        stepOnAfterActivate=this['initView'+stepName.capitalize()];
                    }else{
                        stepOnAfterActivate=function (){};
                    }
                    */
                    break;
                }
            }

/*
            //refactored for loop
            var BreakException = {};
            try {
                avalaibleSteps.forEach(function(stepName) {
                    console.log(stepName);
                    stepComplete.push(stepName);
                    stepEnable.push(stepName);
                    if(Order.getData()['orderStatus']==stepName){
                        stepActive=stepName;
                        throw BreakException;
                    }

                });
            } catch (e) {
                if (e !== BreakException) throw e;
            }*/

        }

        root.Stepper.init({
            complete:stepComplete,
            enable:stepEnable,
            loaded:[],
            active: stepActive,
            URL: {
                create: Opts.URL.create,
            },
            UrlData:stepUrlData,
            onAfterActivate:stepOnAfterActivate,
            autoCallback: stepAutoCallback,
            /*{
                invoice: {
                    onAfterActivate:root.initViewInvoice
                },
                send: {
                    onAfterActivate:root.initViewSend
                },

            }*/
        });
    }

    this.initOrder=function (data){
        Order=new DataModelOrder(data);
    }

    this.init = function (options) {
        debug('OrderModul init called');
        $.extend(Opts, window.OrderModulDefault, options);
        Order=new DataModelOrder();
        if(Opts.needStepper){
            if (typeof this.Stepper == 'undefined') {
                this.Stepper=new Stepper();
            }
        }
        if(Opts.testMode){
            return root.testMode();
        }
    }

    this.setSupplier=function (supplierName,supplierId){
       if(supplierName){
           $('.supplierNamePlace').text(supplierName);
       }
       if(supplierId){
           Order.setData({supplierId:supplierId});
           root.Stepper.setOpts({'UrlData':{'supplierId':supplierId}});
       }
    }
    this.setDeliveryDate=function (dateText,dateTextTo){
        let dateTextHuman=dateText.replaceAll('-','.')+'.';
        if(dateTextHuman.length<5){
            $('.deliveryDatePlace').text(dateText);
            return;
        }
        if(dateTextTo){
            dateTextHuman+=' - '+dateTextTo.replaceAll('-','.')+'.';
        }

        $(Opts.CSSSelectorForm+' .selectedDateText').text(dateTextHuman);
        $('.deliveryDatePlace').text(dateTextHuman);
        $(Opts.CSSSelectorForm+' input[name="deliveryDate"]').val(dateText);
    }



    this.getData=function (){
        return Order;
    }


    this.setSupplierCompleted=function () {
        console.log('bingo');
        root.initViewParameter()
    }

    this.afterOrderSetSupplierOk=function (data) {
        Toast.create("Supplier selected !",data.supplier.name , TOAST_STATUS.INFO,5000);
        root.setSupplier(data.supplier.name,data.supplier.id);
        Order.setData({id:data.id});
        root.Stepper.setOpts({'UrlData':{'supplierId':Order.supplierId,id:Order.id}});
        //root.Stepper.setOpts({onAfterLoad:root.setSupplierCompleted})
        root.Stepper.setEnabled('parameter');
        root.Stepper.addCompleted('parameter');
        root.Stepper.setCompleted('parameter');
        root.Stepper.setActive('parameter');
    }


    this.initViewSupplier=function (){
        debug('call initViewSupplier');
        root.Stepper.setOpts({onAfterLoad:function (){}});
        $('.supplierItem').off('click');
        $('.supplierItem').on('click',function(event){
            console.log(Order.getData());

            event.preventDefault();
            let supplierId=$(event.currentTarget).data('id');
            let supplierName=$(event.currentTarget).find('h5.card-title').text();
            if(typeof Order.supplierId=='undefined'){
                //new order

                let ajaxData={};
                ajaxData._token=Opts.token;
                ajaxData.supplierId=supplierId;
                ajaxData.storeType='supplierSelect';
                $.extend(ajaxData,Order);
                $.ajax({
                    url: Opts.URL.store,
                    method:'POST',
                    data:ajaxData,
                    success:function (data) {
                        if(data.success){
                            root.afterOrderSetSupplierOk(data.data);
                        }
                    }
                });
                //Order.setData({supplierId:supplierId});
            }else{
                //ide kellene egy jo kis kerdes
                if(Order.supplierId!=supplierId){
                    Toast.create("Supplier change to!", supplierName, TOAST_STATUS.WARNING,5000);
                    root.Stepper.clearLoaded();
                    Order=new DataModelOrder();
                    //Order.setData({supplierId:supplierId});
                }
            }

            return;
            console.log('-----------');
            console.log(root.Stepper.getOpts());
            console.log('-----------');

            //$('.supplierNamePlace').text(supplierName);
            root.setSupplier(supplierName,supplierId);
            console.log(supplierName)
            //@todo:ide kell egy mentes!
            //@todo:mentes eredemenyekeppen lehet valtani
            event.preventDefault();
            root.Stepper.setOpts({onAfterLoad:root.setSupplierCompleted})
            root.Stepper.setEnabled('parameter');
            root.Stepper.addCompleted('parameter');
            root.Stepper.setCompleted('parameter');
            root.Stepper.setActive('parameter');


        });
    }

    this.checkContactNameField=function () {
        let CSSSelectorForm='.orderParameterForm';
        let node=$(CSSSelectorForm+' input[name=contactName]');
        if(node.val().length<2){
            node.removeClass('is-valid');
            node.addClass('is-invalid');
            return false;
        }else{
            node.addClass('is-valid');
            node.removeClass('is-invalid');
            return true;
        }
    }



    this.sendOrderDataToServer=function (updateType,callback,errorCallback) {
        let ajaxData= {};
        let ajaxUrl=Opts.URL.store;
        let ajaxMethod="POST";
        if(Order.id){
            ajaxUrl=Opts.URL.update.replace('%id%',Order.id);
            //ajaxMethod="PUT";
            //ajaxData=new FormData($(CSSSelectorForm)[0]);
            ajaxData._method='PUT';
        }
        ajaxData._token=Opts.token;
        ajaxData.updateType=updateType;
        $.extend(ajaxData,Order);
        debug(Order);
        debug(ajaxData);
        debug('ajaxUrl:'+ajaxUrl);
        ajaxData=jsonToFormData(ajaxData);
        $.ajax({
            url:ajaxUrl,
            data:ajaxData,
            type:ajaxMethod,
            contentType:false,
            processData: false,
            success:function (data) {
                debug('ajax returned data');
                debug(data);
                if(data.success){
                    //root.afterOrderSetSupplierOk(data.data);
                    callback(data);
                }
            },
            error: function (xhr, ajaxOptions, thrownError) {
                ajaxErrorHandler(xhr, ajaxOptions, thrownError);
                if(typeof errorCallback!='undefined'){
                    errorCallback(xhr.responseJSON);
                }
            },

        });

    }
    this.afterOrderSetParameterOk=function (data) {
        debug('called afterOrderSetParameterOk');
        root.Stepper.setOpts({'UrlData':{'supplierId':Order.supplierId,'id':Order.id}});
        //root.Stepper.setOpts({onAfterLoad:root.setParameterCompleted})
        root.Stepper.setEnabled('productSelect');
        root.Stepper.addCompleted('productSelect');
        root.Stepper.setCompleted('productSelect');
        root.Stepper.setActive('productSelect');
    }
    this.selectCurrentWeek = function() {
        console.error('selectCurrentWeek');
        console.error($('.ui-datepicker').find('.ui-datepicker-current-day a'));
        $('.ui-datepicker').find('.ui-datepicker-current-selected-weekday a').addClass('ui-state-active')
    }
    this.weekHover = function() {
        console.error('hover Active');
        $('.ui-datepicker-calendar tr').off('mousemove');
        $('.ui-datepicker-calendar tr').off('mouseleave');

        $('.ui-datepicker-calendar tr').on('mousemove', function() { $(this).find('td a').addClass('ui-state-hover'); });
        $('.ui-datepicker-calendar tr').on('mouseleave', function() { $(this).find('td a').removeClass('ui-state-hover'); });

    }
    this.weekHoverSlow = function() {
        console.error('weekHoverSlow');
        if($('.ui-datepicker-calendar tr').length<1){
            setTimeout(root.weekHoverSlow, 1);
            return;
        }
        root.weekHover();
    }
    this.initDatePicker=function (type) {
        console.error('asdasdadad');
        console.log('tipus' + type);
        let CSSSelectorForm = '.orderParameterForm';
        let startDate=new Date('1900-01-01');
        let endDate=new Date('1900-01-02');

        $(CSSSelectorForm + ' .datePicker').datepicker("destroy");

        if (type == 'weekly') {
            $(CSSSelectorForm + ' .datePicker').datepicker({
                showOtherMonths: true,
                selectOtherMonths: true,
                showWeek: true,
                dateFormat: 'yy-mm-dd',
                firstDay: 1,
                minDate: new Date(),
                afterShow: function (dateText, inst) {
                  root.weekHover();
                  root.selectCurrentWeek();
                },
                onSelect: function (dateText, inst) {
                    let date = $(this).datepicker('getDate');
                    startDate = new getMonday(date);
                    endDate = new Date(date.getFullYear(), date.getMonth(), date.getDate() - date.getDay() + 7);
                    root.setDeliveryDate($.datepicker.formatDate( 'yy-mm-dd',startDate),$.datepicker.formatDate( 'yy-mm-dd',endDate))
                },
                beforeShow: function () {
                    console.group('beforeShow')
                    console.log(startDate);
                    console.log(endDate);
                    //root.weekHoverSlow();
                    console.groupEnd();
                },
                beforeShowDay: function(date) {
                    console.group('beforeShowDay');
                    console.log(date.toLocaleDateString('hu-Hu'));
                    let cssClass = '';
                    if(date >= startDate && date <= endDate){
                        console.error(date.toLocaleDateString('hu-Hu'));
                        cssClass = 'ui-datepicker-current-selected-weekday';
                        //cssClass = 'ui-state-active';
                    }
                    console.log(cssClass);
                    console.groupEnd();

                    return [true, cssClass];
                },
                onChangeMonthYear: function(year, month, inst) {
                    //root.selectCurrentWeek();
                }
            });

        } else {
            $(CSSSelectorForm + ' .datePicker').datepicker({
                dateFormat: 'yy-mm-dd',
                minDate: new Date(),
                onSelect: function (dateText) {
                    $(CSSSelectorForm + ' .selectedDateText').text(dateText);
                    $('.deliveryDatePlace').text(dateText.replaceAll('-', '.') + '.');
                    $(CSSSelectorForm + ' input[name="deliveryDate"]').val(dateText);

                },
            });

        }
    }
    this.callChangeOrderType=function(){
        console.log(this);
        console.log(this.value);
        root.initDatePicker(this.value);
        //enum('daily', 'weekly')
        /*let CSSSelectorForm='.orderParameterForm';
        let node=$(CSSSelectorForm+' input[name=contactName]');
        if(node.val().length<2){
            node.removeClass('is-valid');
            node.addClass('is-invalid');
            return false;
        }else{
            node.addClass('is-valid');
            node.removeClass('is-invalid');
            return true;
        }
        */
    }

    this.initViewParameter=function () {
        debug('call initViewParameter');
        root.Stepper.setOpts({onAfterLoad:function (){}});
        let CSSSelectorForm='.orderParameterForm';
        $(CSSSelectorForm+' .datePickerClick').click(function(){
            $(CSSSelectorForm+' .datePicker').datepicker('show');
        });

        $(CSSSelectorForm+' .orderParameterDeliveryAddress').select2({}).show();
        $(CSSSelectorForm+' input[name=contactName]').off('blur');
        $(CSSSelectorForm+' input[name=contactName]').off('keyup');
        $(CSSSelectorForm+' input[name=contactName]').on('blur',root.checkContactNameField);
        $(CSSSelectorForm+' input[name=contactName]').on('keyup',root.checkContactNameField);

        $(CSSSelectorForm+' input[name=orderType]').off('change');
        $(CSSSelectorForm+' input[name=orderType]').on('change',root.callChangeOrderType);


        $(CSSSelectorForm+' .orderParameterNextButton').off('click');
        if(Order.getData()['id']>0){
            if(Order.getData()['orderType']=='weekly'){
                root.initDatePicker(Order.getData()['orderType']);
                $(CSSSelectorForm+" input[name=orderType][value=" + Order.getData()['orderType'] + "]").prop('checked', true);

                const endDate = new Date(Order.getData()['deliveryDate']);
                endDate.setDate(endDate.getDate() + 6);
                root.setDeliveryDate(Order.getData()['deliveryDate'],$.datepicker.formatDate( 'yy-mm-dd',endDate));
                root.initDatePicker('weekly');
            }else{
                if(Order.getData()['deliveryDate']){
                    root.setDeliveryDate(Order.getData()['deliveryDate']);
                }
                root.initDatePicker('daily');
            }



            if(Order.getData()['contactName']){
                $(CSSSelectorForm+' input[name=contactName]').val(Order.getData()['contactName']);
            }
            if(Order.getData()['note']){
                $(CSSSelectorForm+' textarea[name=note]').val(Order.getData()['note']);
            }
            if(Order.getData()['deliveryAddressId']){
                console.log($(CSSSelectorForm+' select[name=deliveryAddressId]'));
                $(CSSSelectorForm+' select[name=deliveryAddressId]').val(Order.getData()['deliveryAddressId']);
            }
            if(Order.getData()['customNotificationEmail']){
                console.log($(CSSSelectorForm+' select[name=customNotificationEmail]'));
                $(CSSSelectorForm+' select[name=customNotificationEmail]').val(Order.getData()['customNotificationEmail']);
            }
        }else{
            root.initDatePicker('daily');
        }

        $(CSSSelectorForm+' .orderParameterDeliveryAddress').select2({}).show();
        $(CSSSelectorForm+' .orderParameterCustomNotificationEmail').select2({}).show();

        $(CSSSelectorForm).submit(function(event){

            event.preventDefault();
            if ($(CSSSelectorForm)[0].checkValidity() === false) {
                debug('validaton false');
                event.stopPropagation();
                return;
            } else {
               debug('validaton ok');
                //do your ajax submition here
            }
            $('.deliveryDatePlace').text($(CSSSelectorForm+' input[name=deliveryDate]').val().replaceAll('-','.')+'.');

            Order.setData({
                contactName:$(CSSSelectorForm+' input[name=contactName]').val(),
                note:$(CSSSelectorForm+' textarea[name=note]').val(),
                orderType:$(CSSSelectorForm+' input:checked[name=orderType]').val(),
                deliveryDate:$(CSSSelectorForm+' input[name=deliveryDate]').val(),
                deliveryAddressId:$(CSSSelectorForm+' select[name=deliveryAddressId]').val(),
                deliveryAddress:$(CSSSelectorForm+' select[name=deliveryAddress]').val(),
                customNotificationEmail:$(CSSSelectorForm+' select[name=customNotificationEmail]').val(),
            });
            console.group('parameter form submit')
            console.error($(CSSSelectorForm+' input:checked[name=orderType]').val());
            console.error($(CSSSelectorForm+' input[name=deliveryDate]').val());
            debug(Order.getData());
            console.groupEnd();
            root.sendOrderDataToServer('parameter',root.afterOrderSetParameterOk);
        });

    }
    this.blank=function (){};
    this.setParameterCompleted=function () {
        console.log('setParameterCompleted called');
        root.Stepper.setOpts({onAfterLoad:function (){}});
        //root.initViewProductSelect()
    }

    this.bindRowFavoritesAction = function () {
        $('.buttonItemFavorites').off('click');
        $('.buttonItemFavorites').on('click', function () {
            let productId = $(this).data('id');
            console.log(productId);

            let ajaxUrl=Opts.URL.toggleFavorites.replace('%id%',productId);
            let ajaxData={};
            ajaxData._token=Opts.token;
            let button=this;
            console.log(ajaxUrl);
            $.ajax({
                url: ajaxUrl,
                method:'POST',
                data:ajaxData,
                success:function (response) {
                    if(response.success){
                        if(response.status){
                            console.log('true');
                            $(button).addClass('btn-warning');
                            $(button).removeClass('btn-light');
                        }else{
                            $(button).removeClass('btn-warning');
                            $(button).addClass('btn-light');
                            console.log('false');
                        }
                    }
                }
            });
            /*
                                $(this).toggleClass('btn-warning');
                                $(this).toggleClass('btn-light');
            */
        });
    }

    this.bindRowDescriptionAction=function (){
        $('textarea.orderItemComment').on('change',function (){
            let comment=$(this).val();
            let productId=$(this).data('id');
            let productComment=Order.getData('productComment');
            if(productComment!==null){
                if(typeof productComment[productId]=='undefined' && comment.length===0){
                    return;
                }
                if(productComment[productId]===comment){
                    return;
                }
            }
            productComment[productId]=comment;
            if(comment.length===0){
                delete Order.productComment[productId];
            }
            Order.productComment=productComment;
            queueAjax.push(Date.now());
            root.syncOrderDataToServer();
        });
    }

    this.productSelectDatatablesRowFormatter=function (d) {
        // `d` is the original data object for the row
        /**
        @todo: felszedni es updatelni az adott termek memojat az orderban
         */
        console.group('productSelectDatatablesRowFormatter');
        console.log(d);
        let templateData=d;
        templateData.comment='';
//        debug(Order);
        if(Order.productComment && Order.productComment!==null){
            debug(typeof Order.productComment[d.id]);
            if(typeof Order.productComment[d.id]!='undefined' && Order.productComment[d.id].length>0){
                templateData.comment=Order.productComment[d.id];
            }
        }
        /** @typedef {boolean} d.favorites */
        if(d.favorites===true){
            templateData.btnFavoritesClass='btn-warning';
        }else{
            templateData.btnFavoritesClass='btn-light';
        }
        let template=$('template[data-name="orderProductSelectDetails"]').html()
        templateData.weekly=false;
        if(Order.getData().orderType==='weekly'){
            templateData.weekly=true;
/*

            templateData.weeklyDay=[
                {"index":1,"name":"Hétfő"},
            {"index":2,"name":"Kedd"},
            {"index":3,"name":"Szerda"},
            {"index":4,"name":"Csütörtök"},
            {"index":5,"name":"Péntek"},
            {"index":6,"name":"Szombat"},
            {"index":7,"name":"Vasárnap"},
            ];

            templateData.weeklyDay=[
                {"index":2,"name":"Hétfő" },
                {"name":"Kedd"},
                {"name":"Szerda"},
                {"name":"Csütörtök"},
                {"name":"Péntek"},
                {"name":"Szombat"},
                {"name":"Vasárnap"}
            ];
*/
        }
        let productSelected=Order.getData('productSelected');
        if(typeof productSelected[d.id]!='undefined'){
            templateData.itemQuantity=productSelected[d.id];
        }
        console.log(['templateData',templateData]);
        let oldTags=Mustache.tags;
        Mustache.tags = ["~!", "!~"];
        if(templateData['specification']=='false' || templateData['specification']==false){
            templateData.specificationClass='d-none';
        }
        templateData.pictureImg='';
        if(templateData['picture']=='false' || templateData['picture']==false){
            templateData.pictureClass='d-none';
        }else{
            templateData.pictureImg='<img src= "'+templateData['picture']+'" class="productPicture" ></img>';
        }
        console.log('templateData',templateData);
        //templateData['aa_specification']=false;
        let render=Mustache.render(template,templateData);
        Mustache.tags =oldTags;
        console.groupEnd();
        return render;
/*
solution before template
        return '<table cellpadding="5" cellspacing="0" border="0" style="padding-left:50px;">'+
            '<tr>'+
            '<td>Info:</td>'+
            '<td>'+d.note+'</td>'+
            '</tr>'+
            '<tr>'+
            '<td>hooreyca :</td>'+
            '<td><span style="padding-right: 2em;">'+d.hooreycaId+'</span>' +

            '<button type="button"\n' +
            '        data-id="'+d.id+'"\n' +
            '        class="buttonItemFavorites btn '+btnFavoritesClass+'">\n' +
            '    <i class="bi bi-star-fill pr-2" aria-hidden="true"></i>\n' +
            '    Kedvenc\n' +
            '</button>' +
            '</td>'+
            '</tr>'+
            /!*
                        '<tr>'+
                        '<td>Extension number:</td>'+
                        '<td>'+d.extn+'</td>'+
                        '</tr>'+
            *!/
            '<tr>'+
            '<td>Info:</td>'+
            '<td>'+d.note+'</td>'+
            '</tr>'+
            '<tr>'+
            '<td>Megjegyzés:</td>'+
            '<td><textarea class="orderItemComment" data-id="'+d.id+'">'+comment+'</textarea></td>'+
            '</tr>'+
            /!*
            *!/
            '</table>';
*/
    }

    this.setDatatableHeaderText=function(text){
        $('.tableHeaderText').text(text);
    }

    this.getTreePathName=function (node){
        let res='';
        let items=$(node).parents('li').toArray();
        items.shift();
        items.reverse();
        for (const item in items) {
            console.log($(items[item]).children('a.categoryItem'));
            if($(items[item]).children('a.categoryItem').length>0){
                res+=$(items[item]).children('a.categoryItem').text()+'/'
            }
        }
        res+=$(node).text();
        console.log(res);
        return res;
    }

    let selectedProductGroup=null;
    let dataTableSearchStr=null;
    let dataTableSearchKrel=false;

    this.searchProductByString=function (filterStr){
        root.setDatatableHeaderText('Termékek szűrve:'+filterStr);
        dataTableSearchStr=filterStr;
        $('.dataTableOrderProductSelect').DataTable().ajax.reload();
    }

    this.clickSearchProduct=function (){
        debug(this);
        let filterStr=$('.sidebar-search input[name=searchValue]').val()
        debug(filterStr);
        root.searchProductByString(filterStr);
    }

    this.clickFavoritesProduct = function () {
        debug('clickFavoritesProduct');
        root.setDatatableHeaderText('Termékek szűrve: kedvencek');
        dataTableSearchStr='**favorites**';
        $('.dataTableOrderProductSelect').DataTable().ajax.reload();
    }
    this.clickOftenProduct = function () {
        debug('clickOftenProduct');
        root.setDatatableHeaderText('Termékek szűrve: gyakran vásárolt');
        dataTableSearchStr='**often**';
        $('.dataTableOrderProductSelect').DataTable().ajax.reload();
    }

    this.clickSpecialOffer = function () {
        debug('clickSpecialOffer');
        root.setDatatableHeaderText('Termékek szűrve: Akciós termékek');
        dataTableSearchStr='**specialOffer**';
        $('.dataTableOrderProductSelect').DataTable().ajax.reload();
    }




    this.clickLastProduct = function () {
        debug('clickLastProduct');
        root.setDatatableHeaderText('Termékek szűrve: utoljára vásárolt');
        dataTableSearchStr='**last**';
        $('.dataTableOrderProductSelect').DataTable().ajax.reload();

    }

    this.clickWeeklyProduct = function () {
        debug('clickWeeklyProduct');
        root.setDatatableHeaderText('Termékek szűrve: Heti termékek');
        dataTableSearchStr='**weekly**';
        $('.dataTableOrderProductSelect').DataTable().ajax.reload();

    }

    this.clickKrelProduct = function () {
        debug('clickKrelProduct');
        //root.setDatatableHeaderText('Termékek szűrve: Heti termékek');
        //dataTableSearchStr='**weekly**';
        //$('.dataTableOrderProductSelect').DataTable().ajax.reload();
        $(this).parent().toggleClass('krelActive');
        dataTableSearchKrel=!dataTableSearchKrel;
        $('.dataTableOrderProductSelect').DataTable().ajax.reload();
    }

    this.productSelectDataTableColumnDefs=function (){
        return [
            {"width": "10px", "targets": 0 },
            { "className": "dt-left", "targets": 1 },
//                { "width": "120px", "targets": 1 },
            { "width": "28px", "targets": 2 },
            { "width": "41px", "targets": 3 },
            { "width": "76px", "targets": 4 },
            { "width": "55px", "targets": 5 },
            { "width": "70px", "targets": 6 },
            { "width": "54px", "targets": 7 },
            { "width": "57px", "targets": 8 },
            { "width": "42px", "targets": 9 },
            { "width": "100px", "targets": 10},
            {"className": "dt-center", "targets": "_all"},
        ];
    }
    this.productSelectDataTableColumn=function (){
        let columnData=[
            {
                "className":      'details-control',
                "orderable":      false,
                "data":           null,
                "defaultContent": ''
            },
            { "data": "name" },
            { "data": "krel" },
            { "data": "packing"},
            { "data": "unitValue" },
            { "data": "productUnit"},
            { "data": "sellerUnit" },
            { "data": "unitMultiplier"},
            { "data": "amountUnit" },
            { "data": "price" },

        ];

        let actionColumn={                "className":      'details-control2',
            "orderable":      false,
            "data":           null,
            "width": "80px",
            "defaultContent":''
        };
        if(Order.getData('orderType')=='daily'){
            actionColumn.defaultContent='<input type="number" value="0" min="0" max="9999" step="1" data-decimals="1"  class="form-control-sm inputNumberSpinner" style="width: 1em;" "/>'
                /*
                                    "defaultContent":'<div class="input-group input-group-sm ">' +
                                        '<button style="min-width: 1.5rem" class="btn-sm btn-decrement btn-outline-secondary btn-minus" type="button">' +
                                        '<strong>−</strong></button>' +
                                        '<input type="text" inputmode="decimal" style="text-align: center" class="form-control " placeholder="">' +
                                        '<button style="min-width: 1.5rem" class="btn-sm btn-increment btn-outline-secondary btn-plus" type="button">' +
                                        '<strong>+</strong></button>' +
                                        '</div>'
                */

            ;
        }
        columnData.push(actionColumn);
        return columnData;
    }
    this.getDatatables=function (orderType){
        console.error(orderType);
        var table = $('.dataTableOrderProductSelect').DataTable( {
            language: {
                url: '//cdn.datatables.net/plug-ins/1.10.24/i18n/Hungarian.json'
            },

            //"ajax": "{{asset('exapmle2.json')}}",
            "ajax": {
                url:Opts.URL.getDataTableContentProductList,
                data:function (data) {
                    data.searchStr=dataTableSearchStr;
                    data.krel=dataTableSearchKrel;
                    data.groupId=selectedProductGroup;
                    data.supplierId=Order.supplierId;
                    data.deliveryDate=Order.deliveryDate;
                }
            },
            buttons: {
                buttons: []
            },
            "columnDefs": root.productSelectDataTableColumnDefs(),
            "columns": root.productSelectDataTableColumn(),
            "order": [[1, 'asc']],
        } );
        return table;
    }

    this.productSelectDataTableDrawDT=function (e) {
        //debug( 'Table draw complete: '+new Date().getTime() );

        //$('td:contains("*")').html('<i class="bi bi-check-circle-fill"></i>');
        $("td").filter(function(){
            return $(this).text() === '*';
        }).html('<i class="bi bi-check-circle-fill"></i>');
        if(Order.getData().orderType=='daily'){
            $("input[type='number'].inputNumberSpinner").inputSpinner({
                template:
                    '<div class="input-group ${groupClass}">' +
                    '<button style="min-width: ${buttonsWidth}" class="btn btn-sm btn-decrement ${buttonsClass}" type="button">${decrementButton}</button>' +
                    //'<input type="text" inputmode="decimal" style="text-align: ${textAlign}" class="productQuantity form-control"/>' +
                    '<input type="text" step="0.1" data-decimals="2" style="text-align: ${textAlign}" class="productQuantity form-control"/>' +
                    '<button style="min-width: ${buttonsWidth}" class="btn btn-sm btn-increment ${buttonsClass}" type="button">${incrementButton}</button>' +
                    '</div>',
                buttonsWidth: "0.5rem",
                groupClass: "", // css class of the resulting input-group
                buttonsClass: "btn-outline-secondary",
            });
        }
        root.bindWeakUserHelper();
        /*
        ----------------------------------------------------------
        change order quantity
         */
        $(".dataTableOrderProductSelect .details-control2 input[type=text]").off('change');
        $(".dataTableOrderProductSelect .details-control2 input[type=text]").on('change',function (e){
            let quantity=$(this).val();
            quantity=quantity.replace(',','.');
            quantity=parseFloat(quantity);
            let rowData=$('.dataTableOrderProductSelect').DataTable().row($(this).closest('tr')).data();
            root.orderItemsChange(rowData,quantity)
        });

        $(".dataTableOrderProductSelect .details-control2 input[type=text]").each(function (){
            //debug('ez a function2')
            let quantity=$(this).val();
            let rowData=$('.dataTableOrderProductSelect').DataTable().row($(this).closest('tr')).data();

            if(Order.productSelected[rowData.id]){
                debug(rowData);
                debug($($(this).closest('tr').find('input[type=number]')[0]));
                debug(Order.productSelected[rowData.id]);
                let quantityCurrent=Order.productSelected[rowData.id];
                if(typeof quantityCurrent!='string'){
                    quantityCurrent+='';
                }
                $($(this).closest('tr').find('input[type=number]')[0]).val(quantityCurrent.replace(',','.'));
            }
        });


        $(".dataTableOrderProductSelect .details-control2 button").off('click');
        $(".dataTableOrderProductSelect .details-control2 button").on('click',function () {
            // debug('.details-control2 button click ')
            // debug(this);
            $(this).parent().find('input[type=text]').trigger('change');
        });

    }

    this.initViewProductSelect=function () {
        let functionName='initViewProductSelect';
        console.log(functionName+' called');
        if(viewInicialized.includes(functionName)){
            return;
        }
        //debug(Object.getOwnPropertyNames(root));
        root.setDatatableHeaderText('');
        root.Stepper.setOpts({onAfterActivate:function (){}});
        //@note: be kell kapcsolni az elonezetet
        root.Stepper.addCompleted('invoice');
        root.Stepper.addEnabled('invoice');
        let CSSSelectorForm='.orderParameterForm';
        //console.log(Opts.URL.getDataTableContentProductList);change
        debug((CSSSelectorForm+' .fa-search'));

        $('.sidebar-search .fa-search').off('click');
        $('.sidebar-search .fa-search').on('click',root.clickSearchProduct);

        $('a.sidebar.favorites').off('click');
        $('a.sidebar.favorites').on('click',root.clickFavoritesProduct);

        $('a.sidebar.often').off('click');
        $('a.sidebar.often').on('click',root.clickOftenProduct);

        $('a.sidebar.last').off('click');
        $('a.sidebar.last').on('click',root.clickLastProduct);

        $('a.sidebar.weekly').off('click');
        $('a.sidebar.weekly').on('click',root.clickWeeklyProduct);

        $('a.sidebar.krel').off('click');
        $('a.sidebar.krel').on('click',root.clickKrelProduct);

        $('a.sidebar.specialOffer').off('click');
        $('a.sidebar.specialOffer').on('click',root.clickSpecialOffer);


        $('.sidebar-search input[name=searchValue]').off('keypress');
        $('.sidebar-search input[name=searchValue]').on('keypress',function (event) {
            if ( event.which == 13 ) {
                event.preventDefault();
            }
            if($(this).val().length>=2){
                root.searchProductByString($(this).val()+event.key);
            }
        });



        $('.sidebar-wrapper .sidebar-menu .sidebar-dropdown .sidebar-submenu li a.categoryItem.clickable').off('click');
        $('.sidebar-wrapper .sidebar-menu .sidebar-dropdown .sidebar-submenu li a.categoryItem.clickable').on('click',
            function () {
                let groupId=$(this).data('id');
                selectedProductGroup=groupId;
                dataTableSearchStr=null;
                console.log(groupId);
                console.log(root.getTreePathName(this));
                root.setDatatableHeaderText(root.getTreePathName(this));
/*
                let ajaxData={
                    'groupId':groupId,
                    'supplier_id':Order.supplierId,
                };
                //$('.dataTableOrderProductSelect').DataTable().ajax.data(ajaxData).load();

*/
/*
                let ajaxUrl=Opts.URL.getDataTableContentProductList+'?groupId='+groupId+'&supplier_id='+Order.supplierId;
                $('.dataTableOrderProductSelect').DataTable().ajax.url(ajaxUrl).load();
*/
                $('.dataTableOrderProductSelect').DataTable().ajax.reload();
            });


        let table = root.getDatatables(Order.getData('orderType'));

        $('.dataTableOrderProductSelect').on( 'init.dt', function () {
            console.log( 'Table initialisation complete: '+new Date().getTime() );
        } ).dataTable();



        $('.dataTableOrderProductSelect').on( 'draw.dt',root.productSelectDataTableDrawDT).dataTable();

        //$('.dataTableOrderProductSelect').on( 'draw.dt',  ).dataTable();

        $('.dataTableOrderProductSelect').on( 'xhr.dt', function () {
            debug( 'Table xhr complete: '+new Date().getTime() );
        } ).dataTable();

        //$("input[type='number'].inputNumberSpinner").inputSpinner();

/*
----------------------------------------------------------
 Add event listener for opening and closing details
 */

        $('.dataTableOrderProductSelect tbody').on('click', 'td.details-control', function () {
            let tr = $(this).closest('tr');
            let row = table.row( tr );

            if ( row.child.isShown() ) {
                // This row is already open - close it
                row.child.hide();
                tr.removeClass('shown');
            }
            else {
                // Open this row
                row.child( root.productSelectDatatablesRowFormatter(row.data()) ).show();
                tr.addClass('shown');
                root.bindProductDetailsAction();
            }
        } );
        viewInicialized.push(functionName);
    }

    this.bindProductDetailsAction=function (){
        root.bindRowDescriptionAction();
        root.bindRowFavoritesAction();
        if(Order.getData()['orderType']=='weekly'){
            root.bindOrderItemWeekQuantity();
        }
   }

    this.bindWeakUserHelper=function (){
        $( "input.inputNumberSpinner" ).off( "focus");
        $( "input.inputNumberSpinner" ).on( "focus", function() {
            let quantity=$(this).val();
            quantity=quantity.replace(',','.');
            quantity=parseFloat(quantity);
            if(quantity===0){
                $(this).val('')
            }
        });
        $( "input[type=text].inputNumberSpinner" ).off( "keypress");
        $( "input[type=text].inputNumberSpinner" ).on( "keypress", function(event) {
            if ( event.which == 13 ) {
//                console.error('enter pressed');
                let actualItem=this;
                let items=$( "input[type=text].inputNumberSpinner" );
                items.each(function (item){
//                    console.log(this);
                    if(this==actualItem){
//                        console.error(item);
                        if(item+1<=items.length){
//                            console.error(items[item+1]);
                            $(items[item+1]).focus();
                        }
                        return false;
                    }
                });
            }
        });
    }

    this.bindOrderItemWeekQuantity=function (){
        $("input.productSelectDayQuantity").off('change');
        $("input.productSelectDayQuantity").on('change',function () {
            console.log(this.name);
            console.log(this.value);
            console.log($(this).data('dayindex'));

            let rowData=null;
            let rowNode=$($(this).closest('table.orderProductSelectRowDetailsTable').closest('tr')).prev();
            rowData=$('.dataTableOrderProductSelect').DataTable().row(rowNode).data();
            console.log(rowData);
            let quantity=$(this).val();
            quantity=quantity.replace(',','.');
            quantity=parseFloat(quantity);
            console.log(rowData.id);
            root.orderItemsChange(rowData,quantity,$(this).data('dayindex'));
//            root.orderItemsChange
            //orderItemsChange
            //quantity[1683][1]
        });

    }

    this.afterSyncOrderDataToServer=function (data) {
        //root.toggleEnableSend();
        //console.log('most vegzett. ennyit kiszed'+batchNum);
        for (let i = 0; i <queueAjax.length; i++) {
            console.log('shiftel')
            queueAjax.shift();
        }
        //console.log('remaining left '+queueAjax.length);
        setTimeout(function(){
            syncDoing=false;
            root.syncOrderDataToServer();
        }, Opts.dataSyncPauseTime);
    }
    let queueAjax=[];
    let syncDoing=false;

    this.syncOrderDataToServer=function () {
        //debug(queueAjax);
        if(syncDoing){
            //debug('sync in progress....');
            return false;
        }
        if(queueAjax.length<1){
            return ;
        }
        syncDoing=true;

        root.sendOrderDataToServer('productSelect',root.afterSyncOrderDataToServer);
        return ;
    }

    this.orderItemsChange=function(ItemData,quantity,dayIndex){

/*
        debug('-----------------');
        debug(ItemData);
        debug(quantity);
        debug(Order.getData('productSelected'));
        debug('-----------------');

*/
        if(isNaN(quantity)){
            quantity=0;
        }
        let productSelected=Order.getData('productSelected');
        console.group('orderItemsChange');
        console.log(['productSelected',productSelected]);
        console.log(['ItemData',ItemData]);
        console.log(['ItemData.id',ItemData.id]);
        console.log(['quantity',quantity]);
        console.log(['dayIndex',dayIndex]);
        console.log(productSelected[ItemData.id]);

        let productSelectedItem=productSelected[ItemData.id];
        /*
        ha 0 ertek jon es nem is volt akkor hamar kiugratjuk
         */
        if(quantity==0){
            console.error('quantity==0');
            if(typeof productSelectedItem=='undefined'){
            console.error('itt lep1');
            console.groupEnd();
                return;
            }
            if(dayIndex){
                console.log('van dayIndex')
                if(typeof productSelected[ItemData.id][dayIndex]=='undefined'){
                    console.log(['productSelectedItem',productSelectedItem]);
                    console.error('itt lep2');
                    console.groupEnd();
                    return;
                }
            }
        }
        /*
        ha azonos az ertek kiugrunk
         */
        if(dayIndex){
            if(typeof productSelected[ItemData.id]!='undefined'
                && typeof productSelected[ItemData.id][dayIndex]!='undefined'){
                if(productSelected[ItemData.id][dayIndex]==quantity){
                    console.error('azonos napi');
                    console.groupEnd();
                    return;
                }
            }
        }else{
            if(productSelected[ItemData.id]==quantity){
                console.error('azonos');
                console.groupEnd();
                return;
            }
        }

        if(quantity==0){
            if(dayIndex){
                delete Order.productSelected[ItemData.id][dayIndex];
                delete productSelected[ItemData.id][dayIndex];
            }else{
                delete Order.productSelected[ItemData.id];
                delete productSelected[ItemData.id];
            }
        }else{
            /*
            ha van ertek erteket adunk!
             */
            if(dayIndex){
                if(typeof productSelected[ItemData.id]=='undefined'){
                    productSelected[ItemData.id]=[];
                }
                console.log('set quantity productSelected[ItemData.id][dayIndex]',quantity);
                productSelected[ItemData.id][dayIndex]=quantity;
            }else{
                productSelected[ItemData.id]=quantity;
                console.log('set quantity productSelected[ItemData.id]',quantity);
            }
        }
        console.log(['productSelected',productSelected]);
        Order.productSelected=productSelected;

        console.groupEnd();
        queueAjax.push(Date.now());
        root.syncOrderDataToServer();

        return;


        if(productSelected[ItemData.id]==quantity){
            debug('itt lep12');
            console.groupEnd();
            return;
        }
        productSelected[ItemData.id]=quantity;
        if(quantity==0){
            delete Order.productSelected[ItemData.id];
        }
        Order.productSelected=productSelected;
        console.groupEnd();
        return;

        queueAjax.push(Date.now());
        root.syncOrderDataToServer();

        /*
        debug(Order.getData('productSelected'));
        debug('*******************');
*/
    }
    this.initViewInvoice=function () {
        root.Stepper.setOpts({onAfterLoad:function (){}});

        if(Object.keys(Order.productSelected).length>0){
            root.Stepper.addCompleted('send');
            root.Stepper.addEnabled('send');
        }
        let styleStr='<link rel="stylesheet" href="'+Opts.URL.root+'/css/invoice.css">';
        $('table.invoice button.printButton').off('click');
        $('table.invoice button.printButton').on('click',function () {
            window.print();
            return;

            let newWin= window.open("");
            newWin.document.write(styleStr);
            let print=$('table.invoice').clone();
            print.find('button.printButton').remove();
//            newWin.document.write($('table.invoice').prop('outerHTML'));
            newWin.document.write(print.prop('outerHTML'));
            newWin.print();
           newWin.close();
        });
    }

    this.resetOrder=function () {
        root.init();
        root.setDeliveryDate('-');
        root.setSupplier('-');

    }

    this.afterOrderSendOk=function (data) {
        Toast.create("Sent!",'Order Sent' , TOAST_STATUS.INFO,5000);
        $('.buttonOrderSend').off('click');
        $('.buttonOrderSend').prop('disabled',true);
        $('.statusNamePlace').removeClass('statusBlink');
        $('.statusNamePlace').text('elküldve');
        $('.buttonOrderSending').toggleClass('d-none');
        $('.buttonOrderSendOk').toggleClass('d-none');
        $('div.invoiceContainer').html(data.retHTML);
        //root.resetOrder();
    }
    this.afterOrderSendError=function (data) {
        $('.buttonOrderSend').toggleClass('d-none');
        $('.buttonOrderSending').toggleClass('d-none');
        $.each(APP.OrderModule.Stepper.getOpts().available,function (index,value) {
            APP.OrderModule.Stepper.setEnabled(value);
            APP.OrderModule.Stepper.setCompleted(value);
        });
    }

    this.initViewSend=function () {
        console.log('initViewSend called 2');
        root.Stepper.setOpts({onAfterLoad:function (){}});
        $('.buttonOrderSend').off('click');
        $('.buttonOrderSend').on('click',function () {
            console.log('Send buton clicked');
            //@todo: datasynchere and callback
            $('.buttonOrderSend').toggleClass('d-none');
            $('.buttonOrderSending').toggleClass('d-none');
            /**
             * PM158
             */
            $.each(APP.OrderModule.Stepper.getOpts().available,function (index,value) {
                root.Stepper.unsetEnabled(value);
                root.Stepper.unsetCompleted(value);
            });
            /**

             */
            root.sendOrderDataToServer('send',root.afterOrderSendOk,root.afterOrderSendError);

/*            let ajaxData={};
            ajaxData._token=Opts.token;
            ajaxData.send=true;
            $.extend(ajaxData,Order);
            $.ajax({
               url: Opts.URL.store,
                method:'POST',
                data:ajaxData,
                success:function (data) {
                    if(data.success){
                        root.afterOrderSendOk(data);
                    }
                }
            });*/
        });

    }

    this.testModeSend=function () {

    }


    this.testMode=function () {
        console.log('testMode called ')
        Order.setData({
            id:234,
            supplierId:7,
            productSelected:{
                116 : 3,
                293 : 2,
            },
            contactName:'Contact Name',
            note:'Note',
            type:'daily',
            deliveryDate:Opts.defaultDeliveryDate,
            deliveryAddress:12,
        });
        console.log(Order.getData());

        console.log('*******************');
        //root.Stepper.setOpts({'UrlData':{'supplierId':supplierId}});
        root.Stepper.setOpts({'UrlData':{'supplierId':Order.supplierId,id:Order.id}});
        this.Stepper.init({
            URL: {
                create: Opts.URL.create,
            },
/*
csupasz az elejerol
            complete:['supplier'],
            enable: ['supplier'],
            active: 'supplier',
            onAfterActivate:this.initViewSupplier,

product select
            complete:['supplier','parameter','productSelect'],
            enable: ['supplier','parameter','productSelect'],
            active: 'productSelect',
            onAfterActivate:this.initViewProductSelect,

fullos
            complete:['supplier','parameter','productSelect','invoice'],
            enable: ['supplier','parameter','productSelect','invoice','send'],
            active: 'productSelect',
            onAfterActivate:this.initViewProductSelect,

send
            complete:['supplier','parameter','productSelect','invoice','send'],
            enable: ['supplier','parameter','productSelect','invoice','send'],
            active: 'send',
            onAfterActivate:this.initViewProductSelect,

*/
            complete:['supplier','parameter','productSelect'],
            enable: ['supplier','parameter','productSelect'],
            active: 'productSelect',
            onAfterActivate:this.initViewProductSelect,


            autoCallback: {
                invoice: {
                    onAfterActivate:root.initViewInvoice
                },
                send: {
                    onAfterActivate:root.initViewSend
                },

            }

        });
        console.log('*******************');

    }
    this.toggleEnableSend=function () {
        console.log('toggleEnableSend called');
        let ajaxUrl=Opts.URL.checkReadyToSend.replace('%id%',Order.id);
        $.ajax({
            url:ajaxUrl,
            success:function (data) {
                if(data.success){
                    if(data.readyToSend){
                        root.Stepper.addCompleted('send');
/*
                        root.Stepper.addCompleted('invoice');
                        root.Stepper.addEnabled('invoice');
*/
                        root.Stepper.addEnabled('send');
                    }else{
                        root.Stepper.unsetCompleted('send');
/*
                        root.Stepper.unsetCompleted('invoice');
                        root.Stepper.unsetEnabled('invoice');
*/
                        root.Stepper.unsetEnabled('send');
                    }
                }
                console.log(data);
            }
        });
    }

}
