var invoice_ref = function(id,order,status,amount,items,invoice,date,client_id,destination_id){
    var self = this;

    self.id = ko.observable(id);
    self.order = ko.observable(order);
    self.status = ko.observable(status);
    self.amount = ko.observable(amount);
    self.items = ko.observable(items);
    self.invoice = ko.observable(invoice);
    self.date = ko.observable(date);
    self.client = ko.observable(client_id ? $.grep(viewModel.clients(),function(s){ return s.id == client_id;})[0] : null);
    self.destination = ko.observable(destination_id ? $.grep(viewModel.t_sales(),function(s){ return s.id == destination_id;})[0] : null);

    self.remove = function(){
        var parent = viewModel.chosenwo();
        if(viewModel.selected_stock() != null)
            parent = viewModel.selected_stock();
        if(self.id() != null)
            parent.deleted_invoices.push(self);
        parent.invoices.remove(self);

    };
    self.step_up = function(){
        var tinvoice = self;
        if(viewModel.selected_stock() != null){
            var index = viewModel.selected_stock().invoices.indexOf(self);
            viewModel.selected_stock().invoices.remove(self);
            viewModel.selected_stock().invoices.splice(index - 1,0,tinvoice);
        }
        else{
            var index = viewModel.chosenwo().invoices.indexOf(self);
            viewModel.chosenwo().invoices.remove(self);
            viewModel.chosenwo().invoices.splice(index - 1,0,ttask);
        }
    };
    self.step_down = function(){
        var tinvoice = self;
        if(viewModel.selected_stock() != null){
            var index = viewModel.selected_stock().invoices.indexOf(self);
            viewModel.selected_stock().invoices.remove(self);
            viewModel.selected_stock().invoices.splice(index + 1,0,tinvoice);
        }
        else{
            var index = viewModel.chosenwo().invoices.indexOf(self);
            viewModel.chosenwo().invoices.remove(self);
            viewModel.chosenwo().invoices.splice(index + 1,0,ttask);
        }
    };
}
var stock = function(own_id,woas_id,asdb_id,stock,serial,number,hours_miles,model,cap,year,cond,brand,tgc,engine,loc,
                     acond,actual_workorder,equipment_id,status,client_id,due_date,delivery_date,from,t_sale_id,
                     t_work_id){
    var self = this;
    self.own_id = ko.observable(own_id);
    self.woas_id = ko.observable(woas_id);
    self.asdb_id = ko.observable(asdb_id);self.stock = ko.observable(stock);
    self.serial = ko.observable(serial);self.number = ko.observable(number);self.hours_miles = ko.observable(hours_miles);
    self.model = ko.observable(model);self.cap = ko.observable(cap);self.year = ko.observable(year);self.cond = ko.observable(cond);
    self.brand = ko.observable(brand);self.tgc = ko.observable(tgc);self.engine = ko.observable(engine);
    self.loc = ko.observable(loc);
    self.from = ko.observable(from);
    self.invoices = ko.observableArray(new Array());
    self.deleted_invoices = ko.observableArray(new Array());
    self.acond = ko.observable(acond);self.actual_workorder = ko.observable(actual_workorder);
    self.equipment = ko.observable(equipment_id ? $.grep(viewModel.equipments(),function(s){ return s.id == equipment_id;})[0] : null);
    self.t_sale = ko.observable(t_sale_id ? $.grep(viewModel.t_sales(),function(s){ return s.id == t_sale_id;})[0] : null);
    self.t_work = ko.observable(t_work_id ? $.grep(viewModel.t_works(),function(s){ return s.id == t_work_id;})[0] : null);
    self.client = ko.observable(client_id ? $.grep(viewModel.clients(),function(s){ return s.id == client_id;})[0] : null);
    self.status = ko.observable(status != null? status : viewModel.chosenwo().status());
    self.due_date = ko.observable(due_date);
    self.delivery_date = ko.observable(delivery_date);
    self.picture = ko.computed(function(){return self.asdb_id()!=null ? "http://www.aeroservicios.com/system/images/"+self.asdb_id()+"_0.jpg" : null;});
    self.model_2_show = ko.computed(function(){var cad="";if(self.model()!=null)cad=extrim($.trim(self.model().length<=10 ? self.model() : self.model().substr(0,10)));return cad;});
    self.brand_2_show = ko.computed(function(){var cad="";if(self.brand()!=null)cad=extrim($.trim(self.brand().length <= 10 ? self.brand() : self.brand().substr(0,10)));return cad;});
    self.status_2_show = ko.computed(function(){
        return self.invoices().length > 0 ? self.invoices().last().status() : "";
    });
    self.show_me = function(){viewModel.chosenwo().showStock(self);};
    self.edit_me = function(){viewModel.chosenwo().editStock(self);};
    self.delete_me = function(){viewModel.chosenwo().deleteStock(self);};
    self.save_me = function(){if(self.own_id() != null){$.ajax({type: 'post',async: true,dataType: 'json',url: get_save_stock_url(),
        data: {own_id: self.own_id(),stock: self.stock(),serial: self.serial(),hours_miles: self.hours_miles(),model: self.model(),
            cap: self.cap(),year: self.year(),cond: self.cond(),brand: self.brand(),tgc: self.tgc(),engine: self.engine(),
            loc: self.loc(),acond: self.acond(),actual_workorder: self.actual_workorder(),equipment_id: self.equipment().id,
            status: self.status(),client_id: self.client().id,delivery_date: self.delivery_date()},
        success:function(response){/*self.fill_stock(response.result,response.message);*/},error:function(){alert("Error saving stock. Please contact your administrator.");}
    });}};
    self.manage_invoices = function(){
        viewModel.selected_stock(self);
        $('#stock-invoices-manager').modal("show");
        self.apply_invoices_features();
        $('#stock-invoices-manager').on('hidden.bs.modal',function(e){viewModel.selected_stock(null);});
    };
    self.add_invoice = function(){
        self.invoices.push(new invoice_ref(null,null,(self.client() ? self.client().internal ? "S" : "PF" : "PF"),null,1,
            null,null,(self.client() ? self.client().id : null),(self.t_sale() ? self.t_sale().id : null)));
        self.apply_new_invoice_features();
    };
    self.invoices4save = function(){
        var order = 1;
        var list = $.map(self.invoices(),function(inv) {
            return {id: inv.id(),
                order: order++,
                status: inv.status(),
                amount: inv.amount(),
                items: inv.items(),
                invoice: inv.invoice(),
                date: inv.date(),
                client_id: inv.client() ? inv.client().id : null,
                destination_id: inv.destination() ? inv.destination().id : null
            };
        });

        return list;
    };
    self.invoices4delete = function(){
        var list = $.map(self.deleted_invoices(),function(inv) {
            if(inv.id())
                return {id: inv.id()};
        });

        return list;
    };
    self.number.subscribe(function(new_value){if(new_value != null){var number = viewModel.chosenwo().check_stock_no_duplicity(new_value,this);
        if(number == null)alert(viewModel.chosenwo().wo_number() + "-" + new_value + " already exists! Please check your stock list." )
        self.number(number);}});
    self.client.subscribe(function(new_value){
        if(new_value != null){
            $.each( self.invoices(),function( i,val ) {
                if(val.client() == null)
                    val.client(self.client());
            });
        }
    });
    self.status.subscribe(function(new_value){
        if(new_value != null){
            if((new_value == "Rented" || new_value == "Sold")){
                if(self.delivery_date() == null){
                    var date = new Date();
                    date = (date.getMonth() > 8 ? (date.getMonth() + 1): "0" + (date.getMonth() + 1)) + "/"
                        + (date.getDate() > 9 ? date.getDate() : "0" + date.getDate()) + "/"
                        + date.getFullYear();

                    self.delivery_date(date);
                }
            }
            else
                self.delivery_date(null);
            viewModel.chosenwo().update_status();
        }});
    self.delivery_date.subscribe(function(new_value){
        if(new_value != null && new_value != ""){
            var subject = viewModel.chosenwo().wo_number() + "-" + self.stock() + " (Delivery date changes)";
            var message = "Work Order: " + viewModel.chosenwo().wo_number() + "%0d%0a";
            message += "Stock: " + self.stock() + "%0d%0a";
            message += "Status: " + self.status() + "%0d%0a";
            message += "Cliente: " + self.client().name + "%0d%0a";
            message += "Delivery date: " + self.delivery_date() + "%0d%0a";
            message += "Sale type: " + self.t_sale().name + "%0d%0a";
            message += "Condition: " + self.t_work().name + "%0d%0a";
            message = message.replace(" ","%20");
            var mail = "mailto:?subject=" + subject + "&body=" + message;
            open_mail(mail);
        }});

    self.show_stickers = function(){
        go_print_stock_stickers(self.woas_id());
        /*viewModel.sticker({created: viewModel.chosenwo().created(),
            supervisor: viewModel.chosenwo().supervisor().name,
            workorder: viewModel.chosenwo().wo_number() + "-" + self.number(),
            stock: self.stock(),
            make: self.brand(),
            client: self.client().name,
            worktype: self.t_work().name,
            saletype: self.t_sale().name,
            delivery_date: self.delivery_date()});
        $('#sticker-panel').modal('show');*/
    };
    self.apply_invoices_features = function(){
        if(check_device() == 2){
            $('.stock-invoice-datepicker').datetimepicker({
                language:  'en',
                format: 'mm/dd/yy',
                weekStart: 0,
                daysOfWeekDisabled: [0],
                autoclose: true,
                startView: 2,
                minView: 2,
                todayHighlight: true,
                forceParse: true,
                todayBtn:  true
            });
        }
        else{
            $('.stock-invoice-datepicker').each(function(html_element){
                var value = new Date(html_elementval());
                html_element.type="date";
                value = value.getFullYear() + '-'
                    + (value.getMonth() < 9 ? '0' + (value.getMonth() + 1) : (value.getMonth() + 1)) + "-"
                    + (value.getDate() < 10 ? '0' + value.getDate() : value.getDate());
                html_element.val(value);});
        }
    };
    self.apply_new_invoice_features = function(){
        var index = self.invoices().length - 1;
        var html_element = $('#stock-invoice-datepicker-' + self.stock() + "-" + index);
        if(check_device() == 2){
            html_element.datetimepicker({
                language:  'en',
                format: 'mm/dd/yy',
                weekStart: 0,
                daysOfWeekDisabled: [0],
                autoclose: true,
                startView: 2,
                minView: 2,
                todayHighlight: true,
                forceParse: true,
                todayBtn:  true
            });
        }
        else{

            var value = new Date(html_element.val());
            html_element.type="date";
            value = value.getFullYear() + '-'
                + (value.getMonth() < 9 ? '0' + (value.getMonth() + 1) : (value.getMonth() + 1)) + "-"
                + (value.getDate() < 10 ? '0' + value.getDate() : value.getDate());
            html_element.val(value);
        }
    };
};
var task = function(own_id,order,area,description,unit_id,supervisor_id,status,start_date,etime,death_line,obs,ended,rtime,
                    created_at,created_by_id){
    var self = this;

    self.is_new = ko.observable(false);
    self.own_id = ko.observable(own_id);
    self.order = ko.observable(order);
    self.area = ko.observable(area);
    self.description = ko.observable(description);
    self.status = ko.observable(status);
    self.start_date = ko.observable(start_date);
    self.etime = ko.observable(null);
    self.death_line = ko.observable(death_line);
    self.obs = ko.observable(obs);
    self.ended = ko.observable(ended);
    self.rtime = ko.observable(rtime);
    self.created_at = ko.observable(created_at);

    self.supervisor = ko.observable(supervisor_id ?
        $.grep(viewModel.supervisors(),
            function(s){ return s.id == supervisor_id;})[0] : null);
    self.unit = ko.observable(unit_id ?
        $.grep(viewModel.units(),
            function(s){ return s.id == unit_id;})[0] : null);
    self.created_by = ko.observable(created_by_id ?
        $.grep(viewModel.supervisors(),
            function(s){ return s.id == created_by_id;})[0] : null);

    self.edit_task = function(){
        viewModel.chosenwo().task_4_update(self);
        $("#modal-task").modal("show");
        loadPageFeatures();
    };
    self.create = function(){
        self.is_new(false);
        viewModel.chosenwo().tasks.push(self);
        viewModel.chosenwo().task_4_update(null);
        $("#modal-task").modal("hide");
    };
    self.delete_js = function(){
        $("#modal-task").modal("hide");
        viewModel.chosenwo().task_4_update(null);
        if(self.own_id() != null)
            viewModel.chosenwo().deleted_tasks.push(self);
        viewModel.chosenwo().tasks.remove(self);
    };
    self.update = function(){
        $("#modal-task").modal("hide");
        viewModel.chosenwo().task_4_update().is_new(false);
        viewModel.chosenwo().task_4_update(null);
    };
    self.step_up = function(){
        var ttask = self;
        var index = viewModel.chosenwo().tasks.indexOf(self);
        viewModel.chosenwo().tasks.remove(self);
        viewModel.chosenwo().tasks.splice(index - 1,0,ttask);
    };
    self.step_down = function(){
        var ttask = self;
        var index = viewModel.chosenwo().tasks.indexOf(self);
        viewModel.chosenwo().tasks.remove(self);
        viewModel.chosenwo().tasks.splice(index + 1,0,ttask);
    };
}
var workorder = function(id,picture,wo_number,origin,equipment_id,stocks_qty,created,started,price,deliverydt,
                         due_date,supervisor_id,client_id,t_sale_id,t_work_id,status,obs,cost,x_price){
    var self = this;

    self.stock4search = ko.observable("");

    self.id = ko.observable(id);
    self.picture = ko.observable(picture);
    self.wo_number = ko.observable(wo_number);
    self.origin = ko.observable(origin);
    self.stocks_qty = ko.observable(stocks_qty);
    self.created = ko.observable(created);
    self.started = ko.observable(started);
    self.price = ko.observable(price);
    self.x_price = ko.observable(x_price);
    self.cost = ko.observable(cost);
    self.obs_plus = ko.observable(null);
    self.equipment = ko.observable(equipment_id ?
        $.grep(viewModel.equipments(),
            function(s){ return s.id == equipment_id;})[0] : null);
    self.supervisor = ko.observable(supervisor_id ?
        $.grep(viewModel.supervisors(),
            function(s){ return s.id == supervisor_id;})[0] : null);
    self.client = ko.observable(client_id ?
        $.grep(viewModel.clients(),
            function(s){ return s.id == client_id;})[0] : null);
    self.t_sale = ko.observable(t_sale_id ?
        $.grep(viewModel.t_sales(),
            function(s){ return s.id == t_sale_id;})[0] : null);
    self.t_work = ko.observable(t_work_id ?
        $.grep(viewModel.t_works(),
            function(s){ return s.id == t_work_id;})[0] : null);
    self.status = ko.observable(status != null ? status : "Current");
    self.due_date = ko.observable(due_date);
    self.deliverydt = ko.observable(deliverydt);
    self.obs = ko.observableArray(new Array());
    self.deleted_obs = ko.observableArray(new Array());
    self.stocks = ko.observableArray(new Array());
    self.deleted_stocks = ko.observableArray(new Array());
    self.tasks = ko.observableArray(new Array());
    self.deleted_tasks = ko.observableArray(new Array());
    self.invoices = ko.observableArray(new Array());
    self.deleted_invoices = ko.observableArray(new Array());
    self.new_stock = ko.observable(null);
    self.found_stock = ko.observable(null);
    self.found_stock_real_status = ko.observable(null);
    self.task_4_update = ko.observable(null);
    self.showing_stock = ko.observable(null);
    self.editing_stock = ko.observable(null);
    self.creator_id = ko.observable(null);
    self.creator_name = ko.observable(null);
    /*self.formatedPrice = ko.computed(function() {
     if(self.price()){
     return '$' + self.price().toFixed(2);
     }
     var result = 0;
     return '$' + result.toFixed(2);
     });*/
    self.formatedCost = ko.computed(function() {
        if(self.cost()){
            return '$' + parseFloat(self.cost()).format(2,3,',','.');
        }
        var result = 0;
        return '$' + result.format(2,3,',','.');
    });

    self.origin.subscribe(function(new_value){
        if(new_value != null && extrim(new_value) != ''){
            $.each( self.stocks(),function( i,val ) {
                if(val.from() == null || val.from() == '')
                    val.from(new_value);
            });
        }
    });
    self.t_sale.subscribe(function(new_value){
        if(new_value != null){
            $.each( self.stocks(),function( i,val ) {
                if(val.t_sale() == null)
                    val.t_sale(new_value);
            });
            $.each( self.invoices(),function( i,inv ) {
                if(inv.destination() == null)
                    inv.destination(self.t_sale);
            });
        }
    });
    self.t_work.subscribe(function(new_value){
        if(new_value != null){
            $.each( self.stocks(),function( i,val ) {
                if(val.t_work() == null)
                    val.t_work(new_value);
            });
        }
    });
    self.client.subscribe(function(new_cl){
        if(new_cl != null){
            $.each( self.stocks(),function( i,val ) {
                if(val.client() == null)
                    val.client(new_cl);
            });
            $.each( self.invoices(),function( i,inv ) {
                if(inv.client() == null)
                    inv.client(self.client());
            });
        }
    });
    self.due_date.subscribe(function(new_value){
        if(new_value != null){
            $.each( self.stocks(),function( i,val ) {
                if(val.due_date() == null)
                    val.due_date(new_value);
            });
        }
    });
    self.status.subscribe(function(new_status){
        if(new_status != null)
            $.each( self.stocks(),function( i,val ) {
                if(val.status() == null)
                    val.status(new_status);
            });
    });
    self.deliverydt.subscribe(function(new_value){
        if(new_value != null && new_value != "" && self.stocks().length == 0){
            var subject = self.wo_number() + " (Delivery date changes)";
            var message = "Work Order: " + self.wo_number() + "%0d%0a";
            message += "Status: " + self.status() + "%0d%0a";
            message += "Cliente: " + self.client().name + "%0d%0a";
            message += "Delivery date: " + self.deliverydt() + "%0d%0a";
            message += "Sale type: " + self.t_sale().name + "%0d%0a";
            message += "Condition: " + self.t_work().name + "%0d%0a";
            message = message.replace(" ","%20");
            var mail = "mailto:?subject=" + subject + "&body=" + message;
            open_mail(mail);
        }});
    self.wo_number.subscribe(function(new_value){
        new_value = new_value.replace(/\D/g,'');
        if(new_value != null && new_value.length == 4){
            if(viewModel.current_wo_number_to_creation() != null)
                if(parseInt(new_value) > parseInt(viewModel.current_wo_number_to_creation())
                    && parseInt(new_value) != 9999){
                    alert("The current number for Work Order creation is "
                        + viewModel.current_wo_number_to_creation()
                        + ". Please contact your administrator.");
                    new_value = viewModel.current_wo_number_to_creation();
                    self.wo_number(viewModel.current_wo_number_to_creation());
                }
                else
                    self.checkWOExist(new_value);
        }
    });
    self.equipment.subscribe(function(new_eqt){
        if(new_eqt != null)
            $.each( self.stocks(),function( i,val ) {
                val.equipment(new_eqt);
            });
    });
    self.price.subscribe(function(new_price){
        if(new_price != null)
            $.each( self.invoices(),function( i,val ) {
                if(val.amount() == null || val.amount() == '' || val.amount() == '0')
                    val.amount(new_price);
            });
    });

    self.update_status = function(){
        var status_from_stock = null;
        if(self.stocks().length > 0){
            for(var i = 0; i < self.stocks().length; i++) {
                var tstatus = self.stocks()[i].status();
                if(tstatus != null){
                    if(tstatus == "Current"){
                        self.status(tstatus);
                        return;
                    }
                    else{
                        if(tstatus == "Hold")
                            status_from_stock = "Hold";
                        else if(status_from_stock != "Hold"){
                            if(status_from_stock != null && status_from_stock != "Out"
                                && status != status_from_stock)
                                status_from_stock = "Out";
                            else
                                status_from_stock = status;

                        }
                    }
                }
                else
                    return;
            };
            self.status(status_from_stock);
        }
        return;
    };

    self.checkWOExist = function(new_value){
        $.ajax({
            type: 'post',
            async: false,
            dataType: 'json',
            url: get_workorder_check_existence_url(),
            data: {wo_number: new_value},
            success: function(response) {
                if(response.exist){
                    alert("The entered Work Order number already exist.");
                    viewModel.get_wo_data_id(response.wo_id);
                }
            },
            error:function() {
                alert("Checking WO number error");
            }
        });
    };
    self.check_stock_no_duplicity = function(new_value,st){
        if($.grep(self.stocks(),
            function(s){ return s.number() == new_value &&
                self.stocks().indexOf(s) != self.stocks().indexOf(st); }).length > 1){
            return null;
        }
        return new_value;
    };
    self.invoices4save = function(){
        var order = 1;
        var list = $.map(self.invoices(),function(inv) {
            return {id: inv.id(),
                order: order++,
                status: inv.status(),
                amount: inv.amount(),
                items: inv.items(),
                invoice: inv.invoice(),
                date: inv.date(),
                client_id: inv.client() ? inv.client().id : null,
                destination_id: inv.destination() ? inv.destination().id : null
            };
        });

        return list;
    };
    self.invoices4delete = function(){
        var list = $.map(self.deleted_invoices(),function(inv) {
            if(inv.id())
                return {id: inv.id()};
        });

        return list;
    };
    self.stocks4save = function(){
        var list = $.map(self.stocks(),function(st) {
            return {own_id: st.own_id(),
                asdb_id: st.asdb_id(),
                stock: st.stock(),
                serial: st.serial(),
                number: st.number(),
                hours_miles: st.hours_miles(),
                model: st.model(),
                cap: st.cap(),
                year: st.year(),
                cond: st.cond(),
                brand: st.brand(),
                tgc: st.tgc(),
                engine: st.engine(),
                loc: st.loc(),
                acond: st.acond(),
                actual_workorder: st.actual_workorder(),
                from: st.from(),
                equipment: st.equipment() ? st.equipment().id : null,
                t_sale: st.t_sale() ? st.t_sale().id : null,
                t_work: st.t_work() ? st.t_work().id : null,
                status: st.status() ? st.status() : null,
                client: st.client() ? st.client().id : null,
                due_date: st.due_date(),
                delivery_date: st.delivery_date(),
                invoices4save: st.invoices4save(),
                invoices4delete: st.invoices4delete()
            };
        });

        return list;
    };
    self.stocks4delete = function(){
        var list = $.map(self.deleted_stocks(),function(st) {
            if(st.own_id())
                return {own_id: st.own_id()};
        });

        return list;
    };
    self.tasks4save = function(){
        var order = 1;
        var list = $.map(self.tasks(),function(st) {
            return {own_id: st.own_id(),
                order: order++,
                area: st.area(),
                description: st.description(),
                unit_id: st.unit() ? st.unit().id : null,
                supervisor_id: st.supervisor() ? st.supervisor().id : null,
                status: st.status(),
                start_date: st.start_date(),
                eTime: st.etime(),
                death_line: st.death_line(),
                obs: st.obs(),
                rTime: st.rtime(),
                ended: st.ended()
            };
        });

        return list;
    };
    self.tasks4delete = function(){
        var list = $.map(self.deleted_tasks(),function(st) {
            if(st.own_id())
                return {own_id: st.own_id()};
        });

        return list;
    };
    self.obs4save = function(){
        var list = $.map(self.obs(),function(st) {
            if(st.id == null)
                return {obs: st.obs};
        });

        return list;
    };
    self.obs4delete = function(){
        var list = $.map(self.deleted_obs(),function(st) {
            if(st.id)
                return {id: st.id};
        });

        return list;
    };
    self.save4PDF = function(){
        alert("TODO");
    };
    self.save4XLS = function(){
        alert("TODO");
    };
    self.edit = function(){
        alert("TODO");
    };
    self.search_stock = function(){
        if(self.stock4search().replaceAll(" ","").length > 1){
            self.blanck_new_found_stocks();
            $.ajax({
                type: 'post',
                async: true,
                dataType: 'json',
                url: get_search_4_stock_url(),
                data: {stock: self.stock4search()},
                success: function(response) {
                    self.found_stock_real_status(response.message);
                    self.fill_stock(response.result,response.message);
                },
                error:function() {
                    alert("Looking for stock error ");
                }
            });
        }
    };
    self.fill_stock = function(fstock,message){
        switch(message){
            case 4:{
                self.found_stock(new stock(fstock.own_id,fstock.woas_id,fstock.asdb_id,fstock.stock,fstock.serial,
                    fstock.number,fstock.hours_miles,fstock.model,fstock.cap,fstock.year,fstock.cond,fstock.brand,
                    fstock.tgc,fstock.engine,fstock.loc,fstock.acond,fstock.wo,fstock.equipment_id,fstock.status,
                    fstock.client_id,self.deliverydt(),null,fstock.from,fstock.t_sale_id,fstock.t_work_id));
                if(!(self.equipment() ? self.equipment().multiple_wos : false))
                    show_simple_message("ban-circle danger-color","Action blocked!!!",
                        "This stock is being used by another WO/OT, please contact your supervisor.",
                        "Usted intenta agregar un stock ligado a otra OT, por favor contacte a su supervisor.",
                        "search-add-stock");
                else
                    show_simple_message("warning-sign warning-color","Warning, check your action!!!",
                        "This stock is being used by another WO/OT, be careful please.",
                        "Usted intenta agregar un stock ligado a otra OT, por favor proceda con cuidado.",
                        "search-add-stock");
                break;
            }
            case 0:{
                self.found_stock(new stock(fstock.own_id,fstock.woas_id,fstock.asdb_id,fstock.stock,fstock.serial,
                    fstock.number,fstock.hours_miles,fstock.model,fstock.cap,fstock.year,fstock.cond,fstock.brand,
                    fstock.tgc,fstock.engine,fstock.loc,fstock.acond,fstock.wo,fstock.equipment_id,fstock.status,
                    fstock.client_id,self.deliverydt(),null,fstock.from,fstock.t_sale_id,fstock.t_work_id));
                break;
            }
            case 1:{
                $('#alternative-message').modal('toggle');
                break;
            }
            case 2:{
                show_simple_message("ban-circle danger-color","Error, stock duplicity!!!",
                    "Stock number " + stockNo + " is duplicated, please contact your administrator.",
                    "El stock "+ stockNo +" aparece duplicado, por favor contacte a su administrador.",
                    "search-add-stock");
                break;
            }
            default :{
                show_simple_message("warning-sign warning-color","Warning, stock sold!!!",
                    "This stock is sold, be careful please.",
                    "Usted intenta agregar un stock vendido, por favor proceda con cuidado.",
                    "search-add-stock");
                self.found_stock(new stock(fstock.own_id,fstock.woas_id,fstock.asdb_id,fstock.stock,fstock.serial,
                    fstock.number,fstock.hours_miles,fstock.model,fstock.cap,fstock.year,fstock.cond,fstock.brand,
                    fstock.tgc,fstock.engine,fstock.loc,fstock.acond,fstock.wo,fstock.equipment_id,fstock.status,
                    fstock.client_id,self.deliverydt(),null,fstock.from,fstock.t_sale_id,fstock.t_work_id));
                break;
            }
        }
    };
    self.create_stock = function(){
        self.new_stock(new stock(null,null,null,self.stock4search(),null,null,null,null,null,null,null,null,
            null,null,null,null,null,null,self.status(),null,self.deliverydt(),null,null,
            (self.t_sale() ? self.t_sale().id : null),(self.t_work() ? self.t_work().id : null)))
        $('#search-add-stock').modal('show');
    };
    self.show_stock_search_modal = function(){
        self.blanck_new_found_stocks();
        $( "#show-workorder-modal" ).modal('hide');
        $('#search-add-stock').modal('show');
    };
    self.blanck_new_found_stocks = function(){
        self.new_stock(null);
        self.found_stock(null);
    };
    self.add_obs = function(){
        if(self.obs_plus() != null){
            self.obs.push({id: null,obs: self.obs_plus(),
                remove: function(){
                viewModel.chosenwo().deleted_obs.push(this);
                viewModel.chosenwo().obs.remove(this);}
            });
            self.obs_plus(null);
        }
    };
    self.addStock = function(){
        var stock2add = null;
        if(self.found_stock() != null){
            stock2add = new stock(
                self.found_stock().own_id(),
                self.found_stock().woas_id(),
                self.found_stock().asdb_id(),
                self.found_stock().stock(),
                self.found_stock().serial(),
                self.found_stock().number() != null ? self.found_stock().number() : self.stocks().length + 1,
                self.found_stock().hours_miles(),
                self.found_stock().model(),
                self.found_stock().cap(),
                self.found_stock().year(),
                self.found_stock().cond(),
                self.found_stock().brand(),
                self.found_stock().tgc(),
                self.found_stock().engine(),
                self.found_stock().loc(),
                self.found_stock().acond(),
                self.found_stock().actual_workorder(),
                self.equipment() != null ? self.equipment().id : null,
                self.found_stock().status(),
                self.found_stock().client() ? self.found_stock().client().id
                    : self.client() != null ? self.client().id : null,
                self.deliverydt(),
                null,
                (self.origin() ? self.origin() : null),
                (self.t_sale() ? self.t_sale().id : null),
                (self.t_work() ? self.t_work().id : null));
        }
        else if(self.new_stock() != null){
            stock2add = new stock(null,null,null,self.new_stock().stock(),self.new_stock().serial(),
                self.stocks().length + 1,self.new_stock().hours_miles(),self.new_stock().model(),
                self.new_stock().cap(),self.new_stock().year(),self.new_stock().cond(),self.new_stock().brand(),
                self.new_stock().tgc(),self.new_stock().engine(),self.new_stock().loc(),self.new_stock().acond(),
                self.wo_number(),self.equipment() != null ? self.equipment().id : null,
                self.new_stock().status(),
                self.new_stock().client() ? self.new_stock().client().id
                    : self.client() != null ? self.client().id : null,
                self.deliverydt(),null,(self.origin() ? self.origin() : null),
                (self.t_sale() ? self.t_sale().id : null),(self.t_work() ? self.t_work().id : null));
        }
        if(stock2add != null){
            var list = $.grep(self.stocks(),function(s){ return s.stock() == stock2add.stock(); });
            if(list.length == 0){
                if(self.stocks().length == 0 && stock2add.asdb_id())
                    self.picture('http://www.aeroservicios.com/system/images/'+ stock2add.asdb_id() +'_0.jpg');
                self.stocks.push(stock2add);
                self.apply_new_stok_features();
                var dlst = $.grep(self.deleted_stocks(),function(s){ return s.stock() == stock2add.stock(); });
                if(dlst.length == 1)
                    self.deleted_stocks.remove(dlst[0]);
                self.stocks_qty(self.stocks().length > self.stocks_qty() ? self.stocks().length : self.stocks_qty());
            }
        }
    };
    self.add_task = function(){
        self.task_4_update(new task(null,null,null,null,null,null,"Current",null,null,null,null,null,null,null,
            null));
        self.task_4_update().is_new(true);
        $("#modal-task").modal("show");
        loadPageFeatures();
    };
    self.add_invoice = function(){
        self.invoices.push(new invoice_ref(null,null,(self.client() ? self.client().internal ? "S" : "PF" : "PF"),null,1,
            null,null,(self.client() ? self.client().id : null),(self.t_sale() ? self.t_sale().id : null)));
        self.apply_new_invoice_features();
    };
    self.showStock = function(st){
        self.showing_stock(st);
        $('#showing-stock').modal('toggle');
    };
    self.editStock = function(st){
        self.editing_stock(st);
        $('#editing-stock').modal('toggle');
    };
    self.deleteStock = function(st){
        if(st.own_id() != null)
            self.deleted_stocks.push(st);
        self.stocks.remove(st);
    };
    self.validate_myself = function(){
        var message = "";
        var valid = true;
        if(self.wo_number() == null){
            valid = false;
        }
        else if(self.wo_number().replaceAll(" ","",true).length < 4 ){
            valid = false;
            message = "Please review the WO/OT number";
        }
        if(self.t_sale() == null){
            valid = false;
            message = "Please select a destination";
        }
        if(self.t_work() == null){
            valid = false;
            message = "Please select a work type";
        }
        if(!valid)
            alert(message);
        return valid;
    };
    self.create_myself = function(){
        if(self.validate_myself()){
            $.ajax({
                type: 'post',
                async: true,
                dataType: 'json',
                url: get_workorder_create_url(),
                data: {wo_number: self.wo_number(),
                    origin: self.origin(),
                    supervisor: self.supervisor() != null ? self.supervisor().id : null,
                    equipment: self.equipment() ? self.equipment().id : null,
                    due_date: self.due_date() ? self.due_date() : null,
                    deliverydt: self.deliverydt() ? self.deliverydt() : null,
                    t_sale: self.t_sale().id,
                    t_work: self.t_work().id,
                    client: self.client() ? self.client().id : null,
                    status: self.status(),
                    price: self.price(),
                    x_price: self.x_price(),
                    stocks_qty: self.stocks_qty(),
                    obs: self.obs_plus(),
                    obs4save: JSON.stringify(self.obs4save()),
                    stocks4save: JSON.stringify(self.stocks4save()),
                    invoices4save: JSON.stringify(self.invoices4save()),
                    tasks4save: JSON.stringify(self.tasks4save())},
                success: function(response) {
                    $('#show-workorder-modal').modal('hide');
                    $("#saved-message").modal('show');
                    setTimeout(function() {
                        $("#saved-message").modal('hide');
                        go_home_list();
                    },1200);
                },
                error:function() {
                    alert("Looking for stock error ");
                }
            });
        }
    };
    self.update_myself = function(){
        if(self.validate_myself()){
            $.ajax({
                type: 'post',
                async: true,
                dataType: 'json',
                url: get_workorder_update_url(),
                data: {own_id: self.id(),
                    wo_number: self.wo_number(),
                    origin: self.origin(),
                    supervisor: self.supervisor() != null ? self.supervisor().id : null,
                    equipment: self.equipment() ? self.equipment().id : null,
                    due_date: self.due_date() ? self.due_date() : null,
                    deliverydt: self.deliverydt() ? self.deliverydt() : null,
                    t_sale: self.t_sale().id,
                    t_work: self.t_work().id,
                    client: self.client() ? self.client().id : null,
                    status: self.status(),
                    price: self.price(),
                    x_price: self.x_price(),
                    obs: self.obs_plus(),
                    obs4save: JSON.stringify(self.obs4save()),
                    obs4delete: JSON.stringify(self.obs4delete()),
                    stocks_qty: self.stocks_qty(),
                    stocks4save: JSON.stringify(self.stocks4save()),
                    stocks4delete: JSON.stringify(self.stocks4delete()),
                    invoices4save: JSON.stringify(self.invoices4save()),
                    invoices4delete: JSON.stringify(self.invoices4delete()),
                    tasks4save: JSON.stringify(self.tasks4save()),
                    tasks4delete: JSON.stringify(self.tasks4delete())},
                success: function(response) {
                    $('#show-workorder-modal').modal('hide');
                    $("#saved-message").modal('show');
                    setTimeout(function() {
                        $("#saved-message").modal('hide');
                    },1200);
                },
                error:function() {
                    alert("Looking for stock error ");
                }
            });
        }
    };
    self.update_myself_back = function(){
        if(self.validate_myself()){
            $.ajax({
                type: 'post',
                async: true,
                dataType: 'json',
                url: get_workorder_update_url(),
                data: {own_id: self.id(),
                    wo_number: self.wo_number(),
                    origin: self.origin(),
                    supervisor: self.supervisor() != null ? self.supervisor().id : null,
                    equipment: self.equipment() ? self.equipment().id : null,
                    due_date: self.due_date() ? self.due_date() : null,
                    deliverydt: self.deliverydt() ? self.deliverydt() : null,
                    t_sale: self.t_sale().id,
                    t_work: self.t_work().id,
                    client: self.client() ? self.client().id : null,
                    status: self.status(),
                    price: self.price(),
                    x_price: self.x_price(),
                    stocks_qty: self.stocks_qty(),
                    obs: self.obs_plus(),
                    obs4save: JSON.stringify(self.obs4save()),
                    obs4delete: JSON.stringify(self.obs4delete()),
                    stocks4save: JSON.stringify(self.stocks4save()),
                    stocks4delete: JSON.stringify(self.stocks4delete()),
                    invoices4save: JSON.stringify(self.invoices4save()),
                    invoices4delete: JSON.stringify(self.invoices4delete()),
                    tasks4save: JSON.stringify(self.tasks4save()),
                    tasks4delete: JSON.stringify(self.tasks4delete())},
                success: function(response) {
                    $('#show-workorder-modal').modal('hide');
                    $("#saved-message").modal('show');
                    setTimeout(function() {
                        $("#saved-message").modal('hide');
                        //go_home_list();
                    },1200);
                },
                error:function() {
                    alert("Looking for stock error ");
                }
            });
        }
    };
    self.get_my_obs = function(){
        if(self.id() != null){
            $.ajax({
                type: 'post',
                async: true,
                dataType: 'json',
                url: get_workorder_obs_url(),
                data: {id: self.id()},
                success: function(response) {
                    var tobs=[];
                    $.each( response.data,function( i,val ) {
                        tobs.push({id: val.id,obs: val.obs,
                            remove: function(){
                                viewModel.chosenwo().deleted_obs.push(this);
                                viewModel.chosenwo().obs.remove(this);
                            }});
                    });
                    self.obs(tobs);
                },
                error:function() {
                    alert("Error");
                }
            });
        }
    };
    self.get_my_tasks = function(){
        if(self.id() != null){
            $.ajax({
                type: 'post',
                async: true,
                dataType: 'json',
                url: get_workorder_tasks_url(),
                data: {id: self.id()},
                success: function(response) {
                    var ttasks=[];
                    $.each( response.data,function( i,val ) {
                        ttasks.push(new task(val.own_id,val.order,val.area,val.description,val.unit_id,val.supervisor_id,val.status,
                            val.start_date,val.etime,val.death_line,val.obs,val.ended,val.rtime,val.created_at,val.created_by_id));
                    });
                    self.tasks(ttasks);
                },
                error:function() {
                    alert("Error");
                }
            });
        }
    };
    self.get_my_stocks = function(){
        if(self.id() != null){
            $.ajax({
                type: 'post',
                async: true,
                cache:false,
                dataType: 'json',
                url: get_workorder_stocks_url(),
                data: {id: self.id()},
                success: function(response) {
                    var tstocks=[];
                    $.each( response.data,function( i,val ) {
                        var tinvoices = [];
                        var st = new stock(val.own_id,val.woas_id,val.asdb_id,val.stock,val.serial,val.number,
                            val.hours_miles,val.model,val.cap,val.year,val.cond,val.brand,val.tgc,val.engine,
                            val.loc,val.acond,val.actual_workorder,val.equipment_id,val.status,val.client_id,
                            val.due_date,val.delivery_date,val.from,val.t_sale_id,val.t_work_id);
                        $.each( val.invoices,function( i,inv ) {
                            tinvoices.push(new invoice_ref(inv.id,inv.order,inv.status,inv.amount,inv.items,inv.invoice,
                                inv.date,inv.client_id,inv.destination_id));
                        });
                        st.invoices(tinvoices);
                        tstocks.push(st);
                    });
                    self.stocks(tstocks);
                    self.apply_stoks_features();
                },
                error:function() {
                    alert("Error");
                }
            });
        }
    };
    self.get_my_invoices = function(){
        if(self.id() != null){
            $.ajax({
                type: 'post',
                async: true,
                cache:false,
                dataType: 'json',
                url: get_workorder_invoices_url(),
                data: {id: self.id()},
                success: function(response) {
                    var tinvoices=[];
                    $.each( response.data,function( i,val ) {
                        tinvoices.push(new invoice_ref(val.id,val.order,val.status,val.amount,val.items,val.invoice,val.date,
                            val.client_id,val.destination_id));
                    });
                    self.invoices(tinvoices);
                    self.apply_invoices_features();
                },
                error:function() {
                    alert("Error");
                }
            });
        }
    };
    self.set_my_data = function(data){
        $('#wo-number').blur();

        self.id(data.id);
        self.wo_number(data.wo_number);
        self.origin(data.origin);
        self.status(data.status ? data.status : "Current");
        self.stocks_qty(data.stocks_qty);
        self.price(data.price);
        self.x_price(data.x_price);
        self.picture(data.picture);
        self.created(data.created);
        self.started(data.started);
        self.due_date(data.due_date);
        self.deliverydt(data.delivery_date);
        self.cost(data.cost);
        self.obs_plus(null);
        self.obs.removeAll();
        self.deleted_obs.removeAll();
        self.tasks.removeAll();
        self.deleted_tasks.removeAll();
        self.stocks.removeAll();
        self.deleted_stocks.removeAll();

        if(data.created_by != null){
            self.creator_id(data.created_by.id);
            self.creator_name(data.created_by.name);
        }

        self.equipment($.grep(viewModel.equipments(),
            function(s){ return s.id == data.equipment_id;}).length == 1 ?
            $.grep(viewModel.equipments(),function(s){
                return s.id == data.equipment_id;})[0] : null);
        self.t_sale($.grep(viewModel.t_sales(),
            function(s){ return s.id == data.ts_id;}).length == 1 ?
            $.grep(viewModel.t_sales(),function(s){
                return s.id == data.ts_id;})[0] : null);
        self.t_work($.grep(viewModel.t_works(),
            function(s){ return s.id == data.tw_id;}).length == 1 ?
            $.grep(viewModel.t_works(),function(s){
                return s.id == data.tw_id;})[0] : null);
        self.supervisor($.grep(viewModel.supervisors(),
            function(s){ return s.id == data.sup_id;}).length == 1 ?
            $.grep(viewModel.supervisors(),function(s){
                return s.id == data.sup_id;})[0] : null);
        self.client($.grep(viewModel.clients(),
            function(s){ return s.id == data.client_id;}).length == 1 ?
            $.grep(viewModel.clients(),function(s){
                return s.id == data.client_id;})[0] : null);

        if(data.obs > 0)
            self.get_my_obs();
        if(data.tasks > 0)
            self.get_my_tasks();
        if(data.stocks > 0)
            self.get_my_stocks();
        if(data.invoices > 0)
            self.get_my_invoices();
    };

    self.apply_invoices_features = function(){
        if(check_device() == 2){
            $('.wo-invoice-datepicker').datetimepicker({
                language:  'en',
                format: 'mm/dd/yy',
                weekStart: 0,
                daysOfWeekDisabled: [0],
                autoclose: true,
                startView: 2,
                minView: 2,
                todayHighlight: true,
                forceParse: true,
                todayBtn:  true
            });
        }
        else{
            $('.wo-invoice-datepicker').each(function(html_element){
                var value = new Date(html_element.val());
                html_element.type="date";
                value = value.getFullYear() + '-'
                    + (value.getMonth() < 9 ? '0' + (value.getMonth() + 1) : (value.getMonth() + 1)) + "-"
                    + (value.getDate() < 10 ? '0' + value.getDate() : value.getDate());
                html_element.val(value);});
        }
    };
    self.apply_new_invoice_features = function(){
        var index = self.invoices().length - 1;
        var html_element = $('#wo-invoice-datepicker-' + index);
        if(check_device() == 2){
            html_element.datetimepicker({
                language:  'en',
                format: 'mm/dd/yy',
                weekStart: 0,
                daysOfWeekDisabled: [0],
                autoclose: true,
                startView: 2,
                minView: 2,
                todayHighlight: true,
                forceParse: true,
                todayBtn:  true
            });
        }
        else{

            var value = new Date(html_element.val());
            html_element.type="date";
            value = value.getFullYear() + '-'
                + (value.getMonth() < 9 ? '0' + (value.getMonth() + 1) : (value.getMonth() + 1)) + "-"
                + (value.getDate() < 10 ? '0' + value.getDate() : value.getDate());
            html_element.val(value);
        }
    };
    self.apply_stoks_features = function(){
        if(check_device() == 2){
            var min_date = new Date();
            min_date = new Date(min_date.setMonth(min_date.getMonth() - 3));
            $('.stock-delivery-date').datetimepicker({
                language:  'en',
                format: 'mm/dd/yy',
                weekStart: 0,
                startDate: min_date,
                endDate: new Date(),
                daysOfWeekDisabled: [0],
                autoclose: true,
                startView: 2,
                minView: 2,
                todayHighlight: true,
                forceParse: true,
                todayBtn:  true
            });
            $('.stock-due-date').datetimepicker({
                language:  'en',
                format: 'mm/dd/yy',
                weekStart: 0,
                daysOfWeekDisabled: [0],
                autoclose: true,
                startView: 2,
                minView: 2,
                todayHighlight: true,
                forceParse: true,
                todayBtn:  true
            });
        }
        else{
            $('.stock-datepicker').each(function(html_element){
                var value = new Date(html_element.val());
                html_element.type="date";
                value = value.getFullYear() + '-'
                    + (value.getMonth() < 9 ? '0' + (value.getMonth() + 1) : (value.getMonth() + 1)) + "-"
                    + (value.getDate() < 10 ? '0' + value.getDate() : value.getDate());
                html_element.val(value);});
        }
    };
    self.apply_new_stok_features = function(){
        var index = self.stocks().length - 1;
        if(check_device() == 2){
            var min_date = new Date();
            min_date = new Date(min_date.setMonth(min_date.getMonth() - 3));
            $('#stock-delivery-date-' + index).datetimepicker({
                language:  'en',
                format: 'mm/dd/yy',
                weekStart: 0,
                startDate: min_date,
                endDate: new Date(),
                daysOfWeekDisabled: [0],
                autoclose: true,
                startView: 2,
                minView: 2,
                todayHighlight: true,
                forceParse: true,
                todayBtn:  true
            });
            $('#stock-due-date-' + index).datetimepicker({
                language:  'en',
                format: 'mm/dd/yy',
                weekStart: 0,
                daysOfWeekDisabled: [0],
                autoclose: true,
                startView: 2,
                minView: 2,
                todayHighlight: true,
                forceParse: true,
                todayBtn:  true
            });
        }
        else{
            $('#stock-delivery-date-' + index +',#stock-due-date-' + index).each(function(html_element){
                var value = new Date(html_element.val());
                html_element.type="date";
                value = value.getFullYear() + '-'
                    + (value.getMonth() < 9 ? '0' + (value.getMonth() + 1) : (value.getMonth() + 1)) + "-"
                    + (value.getDate() < 10 ? '0' + value.getDate() : value.getDate());
                html_element.val(value);});
        }
    };
};
var viewModel = {
    equipments: ko.observableArray(new Array()),
    supervisors: ko.observableArray(new Array()),
    units: ko.observableArray(new Array()),
    departments: ko.observableArray(new Array()),
    clients: ko.observableArray(new Array()),
    t_sales: ko.observableArray(new Array()),
    t_works: ko.observableArray(new Array()),
    wo_status: ko.observableArray(new Array()),
    stocks_status: ko.observableArray(new Array()),
    task_status: ko.observableArray(new Array()),
    invoice_status: ["F","PF","S"],

    current_wo_number_to_creation: ko.observable(null),
    chosenwo: ko.observable(null),
    selected_stock: ko.observable(null),
    /*sticker: ko.observable(null),*/

    work_orders: ko.observableArray(new Array()),
    get_wo_data: function(){
        if(this.chosenwo().id() != null){
            $.ajax({
                type: 'post',
                async: false,
                dataType: 'json',
                url: get_workorder_support_id_url(),
                data: {id: this.chosenwo().id()},
                success: function(response) {
                    viewModel.chosenwo().set_my_data(response.data);
                },
                error:function() {
                    alert("Error");
                }
            });
        }
    },
    get_wo_data_id: function(id){
        if(id != null){
            $.ajax({
                type: 'post',
                async: false,
                dataType: 'json',
                url: get_workorder_support_id_url(),
                data: {id: id},
                success: function(response) {
                    viewModel.chosenwo().set_my_data(response.data);
                },
                error:function() {
                    alert("Error");
                }
            });
        }
    },
    update_uploaded_stocks: function(){
        $.ajax({
            type: 'post',
            async: true,
            dataType: 'json',
            url: getURLUpdateUploadedStocks(),
            data: {},
            success: function(response) {},
            error:function() {
                alert("Error");
            }
        });
    }
};

function loadPageFeatures(){
    if(check_device() == 2){
        var min_date = new Date();
        min_date = new Date(min_date.setMonth(min_date.getMonth() - 3));
        var max_date = new Date();
        max_date = new Date(max_date.setFullYear(max_date.getFullYear() + 2));
        $('.datepicker').datetimepicker({
            language:  'en',
            format: 'mm/dd/yyyy',
            weekStart: 0,
            startDate: min_date,
            endDate: max_date,
            daysOfWeekDisabled: [0],
            autoclose: true,
            startView: 2,
            minView: 2,
            todayHighlight: true,
            forceParse: true,
            todayBtn:  true
        });
    }
    else{
        $('.datepicker').each(function(){
            var value = new Date($(this).val());
            this.type="date";
            value = value.getFullYear() + '-'
                + (value.getMonth() < 9 ? '0' + (value.getMonth() + 1) : (value.getMonth() + 1)) + "-"
                + (value.getDate() < 10 ? '0' + value.getDate() : value.getDate());
            $(this).val(value);});
    }
    /*$('#wo-numberx').inputmask("9999",
     {placeholder:"-",
     oncomplete: function(){
     if(this.selectionStart == this.value.length && $(this).is(":focus")){
     if(viewModel.current_wo_number_to_creation() != null)
     if(parseInt(this.value) > parseInt(viewModel.current_wo_number_to_creation())
     && parseInt(this.value) != 9999){
     alert("The current number for Work Order creation is "
     + viewModel.current_wo_number_to_creation()
     + ". Please contact your administrator.");
     this.value = viewModel.current_wo_number_to_creation();
     viewModel.chosenwo().wo_number(viewModel.current_wo_number_to_creation());
     }
     else
     viewModel.chosenwo().checkWOExist(this.value);
     }
     }});*/
    $('#stocks-qty').inputmask("9[9]",
        {placeholder:"-",greedy: false});
    $('#search-add-stock').on('shown.bs.modal',function (e) {
        $( "#stock-number-4-search" ).focus();
    });
    $('#search-add-stock,#showing-stock,#editing-stock').on('hidden.bs.modal',function (e) {
        $( "#show-workorder-modal" ).modal('show');
    });
}

function applyFeturesToStockIndex(index){
    $('#stock-number-' + index).inputmask("9[9]",
        {placeholder:"-",greedy: false});
    //Data pickers
    if(check_device() == 2){
        var min_date = new Date();
        min_date = new Date(min_date.setMonth(min_date.getMonth() - 3));
        $('#stock-delivery-date-' + index).datetimepicker({
            language:  'en',
            format: 'mm/dd/yy',
            weekStart: 0,
            startDate: min_date,
            endDate: new Date(),
            daysOfWeekDisabled: [0],
            autoclose: true,
            startView: 2,
            minView: 2,
            todayHighlight: true,
            forceParse: true,
            todayBtn:  true
        });
        $('#stock-due-date-' + index +',#stock-invoice-date-' + index).datetimepicker({
            language:  'en',
            format: 'mm/dd/yy',
            weekStart: 0,
            daysOfWeekDisabled: [0],
            autoclose: true,
            startView: 2,
            minView: 2,
            todayHighlight: true,
            forceParse: true,
            todayBtn:  true
        });
    }
    else{
        $('#stock-delivery-date-' + index +',#stock-due-date-' + index +',#stock-invoice-date-' + index).each(function(){
            var value = new Date($(this).val());
            this.type="date";
            value = value.getFullYear() + '-'
                + (value.getMonth() < 9 ? '0' + (value.getMonth() + 1) : (value.getMonth() + 1)) + "-"
                + (value.getDate() < 10 ? '0' + value.getDate() : value.getDate());
            $(this).val(value);});
    }
}
function applyFeturesToStockList(){
    $('.stock-number').inputmask("9[9]",
        {placeholder:"-",greedy: false});
    //Data pickers
    if(check_device() == 2){
        var min_date = new Date();
        min_date = new Date(min_date.setMonth(min_date.getMonth() - 3));
        $('stock-delivery-date').datetimepicker({
            language:  'en',
            format: 'mm/dd/yy',
            weekStart: 0,
            startDate: min_date,
            endDate: new Date(),
            daysOfWeekDisabled: [0],
            autoclose: true,
            startView: 2,
            minView: 2,
            todayHighlight: true,
            forceParse: true,
            todayBtn:  true
        });
        $('.stock-due-date,.stock-invoice-date').datetimepicker({
            language:  'en',
            format: 'mm/dd/yy',
            weekStart: 0,
            daysOfWeekDisabled: [0],
            autoclose: true,
            startView: 2,
            minView: 2,
            todayHighlight: true,
            forceParse: true,
            todayBtn:  true
        });
    }
    else{
        $('.stock-datepicker').each(function(){
            var value = new Date($(this).val());
            this.type="date";
            value = value.getFullYear() + '-'
                + (value.getMonth() < 9 ? '0' + (value.getMonth() + 1) : (value.getMonth() + 1)) + "-"
                + (value.getDate() < 10 ? '0' + value.getDate() : value.getDate());
            $(this).val(value);});
    }
}

