/**
 * Utils
 * @param prop
 * @param data
 * @returns {*}
 */
ko.observableArray.fn.find = function(prop, data) {
    var valueToMatch = data[prop];
    return ko.utils.arrayFirst(this(), function(item) {
        return item[prop] === valueToMatch;
    });
};
String.format = function() {
    // The string containing the format items (e.g. "{0}")
    // will and always has to be the first argument.
    var theString = arguments[0];

    // start with the second argument (i = 1)
    for (var i = 1; i < arguments.length; i++) {
        // "gm" = RegEx options for Global search (more than one instance)
        // and for Multiline search
        var regEx = new RegExp("\\{" + (i - 1) + "\\}", "gm");
        theString = theString.replace(regEx, arguments[i]);
    }

    return theString;
}

/**
 * Search workorders by supervisors
 */
var supervisor = function(id, picture, code, name, fullname, department){
    var self = this;

    self.id = id;
    self.picture =  picture;
    self.code =  code;
    self.name = name;
    self.fullname =  fullname;
    self.department =  department;

    //Operations
    self.to_filter = function(){
        viewModel.chosensup(this);
        viewModel.filter_sup().id(this.id);
        viewModel.filter_sup().name(this.fullname);
        viewModel.filter_sup().isSet(true);
        viewModel.wo_page(1);
        viewModel.appyFilters();
    };
};
var stock = function(own_id, asdb_id, stock, serial, number, hours_miles, model, cap, year, cond, brand, tgc, engine,
                     loc, acond, actual_workorder, equipment_id, status, client_id){
    var self = this;

    self.own_id = ko.observable(own_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.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.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.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.enlarge_picture = function(event){
        viewModel.large_picture(self.picture());
        ShowPicture();
    };

    self.show_me = function(){
        viewModel.chosenwo().showStock(this);
    };
    self.edit_me = function(){
        viewModel.chosenwo().editStock(this);
    };
    self.delete_me = function(){
        viewModel.chosenwo().deleteStock(this);
    };
    self.save_me = function(){
        if(self.own_id() != null){
            $.ajax({
                type: 'post',
                async: true,
                dataType: 'json',
                url: getURLSaveStock(),
                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},
                success: function(response) {
                    //self.fill_stock(response.result, response.message);
                },
                error:function() {
                    alert("Looking for stock error ");
                }
            });
        }
    };

    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);
        }
    });
}
var task = function(own_id, 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.area = ko.observable(area);
    self.description = ko.observable(description);
    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.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.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);
    };
}
//Work Order
var wo_sup_data = function(id, name, code){
    var self = this;
    self.id = id;
    self.name = name;
    self.code = code;
};
var unit = function(id, name, fullname){
    var self = this;

    self.id = id;
    self.name = name;
    self.fullname = fullname;
};
var wo_eqpt_data = function(id, name, code){
    var self = this;

    self.id = id;
    self.name = name;
    self.code = code;
};
var wo_dep_data = function(id, name){
    var self = this;

    self.id = id;
    self.name = name;
};
var wo_clt_data = function(id, name){
    var self = this;

    self.id = id;
    self.name = name;
};
var wo_tsales_data = function(id, name){
    var self = this;

    self.id = id;
    self.name = name;
};
var wo_tworks_data = function(id, name){
    var self = this;

    self.id = id;
    self.name = name;
};
var workorder = function(id, picture, wo_number, origin, equipment_id, stocks_qty, created, started, price, deliverydt,
                         supervisor_id, client_id, t_sale_id, t_work_id, status, obs, cost){
    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.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.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.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 '$' + self.cost().toFixed(2);
        }
        var result = 0;
        return '$' + result.toFixed(2);
    });

    self.client.subscribe(function(new_cl){
        if(new_cl != null)
            $.each( self.stocks(), function( i, val ) {
                val.client(new_cl);
            });
    });
    self.status.subscribe(function(new_status){
        if(new_status != null)
            $.each( self.stocks(), function( i, val ) {
                val.status(new_status);
            });
    });
    self.equipment.subscribe(function(new_eqt){
        if(new_eqt != null)
            $.each( self.stocks(), function( i, val ) {
                val.equipment(new_eqt);
            });
    });

    self.editable = ko.observable(id == null ? true : false);

    self.checkWOExist = function(new_value){
        $.ajax({
            type: 'post',
            async: false,
            dataType: 'json',
            url: getURLCheckWOExist(),
            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.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(),
                equipment: st.equipment() ? st.equipment().id : null,
                status: st.status() ? st.status() : null,
                client: st.client() ? st.client().id : null};
        });

        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 list = $.map(self.tasks(), function(st) {
            return {own_id: st.own_id(),
                    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.obs4delete = function(){
        var list = $.map(self.deleted_obs(), function(st) {
            if(st.id)
                return {id: st.id};
        });

        return list;
    };

    //Operations
    self.enlarge_picture = function(event){
        viewModel.large_picture(self.picture());
        ShowPicture();
    };
    self.save4PDF = function(){
        alert("TODO");
    };
    self.save4XLS = function(){
        alert("TODO");
    };
    self.edit = function(){
        alert("TODO");
    };
    self.show_me = function(){
        /*if(!viewModel.large_picture())
            generate_wo_url(self.id);*/
        viewModel.chosenwo(self);
        $('#show-workorder-modal').modal('show');
    };
    self.editable_change = function(){
        self.editable(!self.editable());
        if(self.editable()){
            /*loadPageFeatures();
            $('#wo-number').inputmask("9999",
                {placeholder:"-",
                    oncomplete: function(){
                        if(this.selectionStart == this.value.length){
                            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');
            });*/
        }
    };

    self.search_stock = function(){
        if(self.stock4search().replaceAll(" ","").length > 1){
            self.blanck_new_found_stocks();
            $.ajax({
                type: 'post',
                async: true,
                dataType: 'json',
                url: getURLSearchStock(),
                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:{
                alert("Contact your administrator. This is being used in another WO/OT.");
                self.found_stock(new stock(fstock.own_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));
                break;
            }
            case 0:{
                self.found_stock(new stock(fstock.own_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));
                break;
            }
            case 1:{
                //$('#search-add-stock').modal('hide');
                $('#alternative-message').modal('toggle');
                break;
            }
            case 2:{
                alert("Contact your stocks administrator. Stock number " + stockNo + " seems to be duplicated.");
                break;
            }
            default :{
                alert("The stock your are looking for is sold.");
                self.found_stock(new stock(fstock.own_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));
                break;
            }
        }
    };
    self.create_stock = function(){
        self.new_stock(new stock(null, null, self.stock4search(), null, null, null, null, null, null, null, null,
            null, null, null, null, null, null, "Current", 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.addStock = function(){
        var stock2add = null;
        if(self.found_stock() != null){
            stock2add = new stock(self.found_stock().own_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);
        }
        else if(self.new_stock() != null){
            stock2add = new stock(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);
        }
        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);
                applyFeturesToStockIndex(self.stocks().length -1);
                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());
            }
        }

        //http://www.aeroservicios.com/system/images/'.(string)$this->stocks_full[0]->getStock()->getAsdbId().'_0.jpg'
    };
    self.add_task = function(){
        self.task_4_update(new task(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.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: getURLCreateWorkOrder(),
                data: {wo_number: self.wo_number(),
                    origin: self.origin(),
                    supervisor: self.supervisor() != null ? self.supervisor().id : null,
                    equipment: self.equipment() ? self.equipment().id : 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(),
                    obs: self.obs_plus(),
                    stocks_qty: self.stocks_qty(),
                    stocks4save: JSON.stringify(self.stocks4save()),
                    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: getURLUpdateWorkOrder(),
                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,
                    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(),
                    obs: self.obs_plus(),
                    obs4delete: JSON.stringify(self.obs4delete()),
                    stocks_qty: self.stocks_qty(),
                    stocks4save: JSON.stringify(self.stocks4save()),
                    stocks4delete: JSON.stringify(self.stocks4delete()),
                    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: getURLUpdateWorkOrder(),
                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,
                    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(),
                    obs: self.obs_plus(),
                    obs4delete: JSON.stringify(self.obs4delete()),
                    stocks_qty: self.stocks_qty(),
                    stocks4save: JSON.stringify(self.stocks4save()),
                    stocks4delete: JSON.stringify(self.stocks4delete()),
                    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: getURLObs(),
                data: {id: self.id()},
                success: function(response) {
                    $.each( response.data, function( i, val ) {
                        self.obs.push({id: val.id, obs: val.obs,
                            remove: function(){
                                viewModel.chosenwo().deleted_obs.push(this);
                                viewModel.chosenwo().obs.remove(this);
                            }});
                    });
                },
                error:function() {
                    alert("Error");
                }
            });
        }
    };
    self.get_my_tasks = function(){
        if(self.id() != null){
            $.ajax({
                type: 'post',
                async: true,
                dataType: 'json',
                url: getURLTasks(),
                data: {id: self.id()},
                success: function(response) {
                    $.each( response.data, function( i, val ) {
                        self.tasks.push(new task(val.own_id, 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));
                    });
                },
                error:function() {
                    alert("Error");
                }
            });
        }
    };
    self.get_my_stocks = function(){
        if(self.id() != null){
            $.ajax({
                type: 'post',
                async: true,
                cache:false,
                dataType: 'json',
                url: getURLStocks(),
                data: {id: self.id()},
                success: function(response) {
                    $.each( response.data, function( i, val ) {
                        self.stocks.push(new stock(val.own_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));
                    });
                },
                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.picture(data.picture);
        self.created(data.created);
        self.started(data.started);
        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();

        /*self.stocks.removeAll();
        $.each( data.stocks, function( i, val ) {
            self.stocks.push(new stock(val.own_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));
        });
        self.tasks.removeAll();
        $.each( data.tasks, function( i, val ) {
            self.tasks.push(new task(val.own_id, 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.obs.removeAll();
        self.deleted_obs.removeAll();
        $.each( data.obs, function( i, val ) {
            self.obs.push({id: val.id, obs: val.obs,
                remove: function(){
                    viewModel.chosenwo().deleted_obs.push(this);
                    viewModel.chosenwo().obs.remove(this);
                }});
        });*/
    };
};


var page = function(page){
    var self = this;
    self.page = ko.observable(page);
    self.see_me = function(){
        viewModel.wo_page(this.page());
        viewModel.appyFilters();
    };
};

//Filters available
var filter_created = function(){
    var self = this;
    self.sdate = ko.observable(null);
    self.edate = ko.observable(null);
    self.editable = ko.observable(0);
    self.isSet = ko.observable(false);
    self.date_activated = ko.observable(false);
    self.range_activated = ko.observable(false);
    self.activate_date = function(){
        viewModel.hidefiltersinputs();
        this.range_activated(false);
        this.date_activated(true);
        this.editable(1);
        this.isSet(false);
        this.sdate(null);
        this.edate(null);
    };
    self.unactivate_date = function(){
        viewModel.hidefiltersinputs();
    };
    self.activate_range = function(){
        viewModel.hidefiltersinputs();
        this.date_activated(false);
        this.range_activated(true);
        this.editable(2);
        this.isSet(false);
        this.sdate(null);
        this.edate(null);
    };
    self.unactivate_range = function(){
        viewModel.hidefiltersinputs();
    };
    self.setBLANK = function(){
        this.edate(null);
        this.sdate(null);
        this.date_activated(false);
        this.range_activated(false);
        this.editable(0);
        this.isSet(false);
        viewModel.appyFilters();
    };
    self.apply_data = function(){
        if(this.editable() == 1 && this.sdate()){
            this.editable(0);
            this.isSet(true);
            viewModel.wo_page(1);
            viewModel.appyFilters();
        }
        else if(this.editable() == 2 && this.sdate() && this.edate()){
            this.editable(0);
            this.isSet(true);
            viewModel.wo_page(1);
            viewModel.appyFilters();
        }
    };
    self.sdate.subscribe(function(new_value) {
        if(new_value)
            if(new_value.trim() != "")
                self.apply_data();
    });
    self.edate.subscribe(function(new_value) {
        if(new_value)
            if(new_value.trim() != "")
                self.apply_data();
    });
};
var filter_started = function(){
    var self = this;
    self.sdate = ko.observable(null);
    self.edate = ko.observable(null);
    self.editable = ko.observable(0);
    self.isSet = ko.observable(false);
    self.date_activated = ko.observable(false);
    self.range_activated = ko.observable(false);
    self.activate_date = function(){
        viewModel.hidefiltersinputs();
        this.range_activated(false);
        this.date_activated(true);
        this.editable(1);
        this.isSet(false);
        this.sdate(null);
        this.edate(null);
    };
    self.activate_range = function(){
        viewModel.hidefiltersinputs();
        this.date_activated(false);
        this.range_activated(true);
        this.editable(2);
        this.isSet(false);
        this.sdate(null);
        this.edate(null);
    };
    self.setBLANK = function(){
        this.edate(null);
        this.sdate(null);
        this.date_activated(false);
        this.range_activated(false);
        this.editable(0);
        this.isSet(false);
        viewModel.appyFilters();
    };
    self.apply_data = function(){
        if(this.editable() == 1 && this.sdate()){
            this.editable(0);
            this.isSet(true);
            viewModel.wo_page(1);
            viewModel.appyFilters();
        }
        else if(this.editable() == 2 && this.sdate() && this.edate()){
            this.editable(0);
            this.isSet(true);
            viewModel.wo_page(1);
            viewModel.appyFilters();
        }
    };
    self.sdate.subscribe(function(new_value) {
        if(new_value)
            if(new_value.trim() != "")
                self.apply_data();
    });
    self.edate.subscribe(function(new_value) {
        if(new_value)
            if(new_value.trim() != "")
                self.apply_data();
    });
};
var filter_wo = function(){
    var self = this;
    self.number = ko.observable(null);
    self.editable = ko.observable(0);
    self.isSet = ko.observable(false);
    self.activate_number = function(){
        viewModel.hidefiltersinputs();
        this.editable(1);
        this.number(null);
        this.isSet(false);
        applyFocus2Element("#filter_wo_number_input");
    };
    self.unactivate_number = function(){
        viewModel.hidefiltersinputs();
    };
    self.apply_data = function(){
        if(this.editable() == 1 && this.number()){
            this.editable(0);
            this.isSet(true);
            viewModel.wo_page(1);
            viewModel.appyFilters();
        }
    };
    self.number.subscribe(function(new_value) {
        if(new_value)
            if(new_value.trim() != "")
                self.apply_data();
    });
    self.setBLANK = function(){
        this.number(null);
        this.isSet(false);
        viewModel.appyFilters();
    };
};
var filter_stock = function(){
    var self = this;
    self.number = ko.observable(null);
    self.editable = ko.observable(0);
    self.isSet = ko.observable(false);
    self.activate_number = function(){
        viewModel.hidefiltersinputs();
        this.editable(1);
        this.number(null);
        this.isSet(false);
        applyFocus2Element("#filter_stock_number_input");
    };
    self.unactivate_number = function(){
        viewModel.hidefiltersinputs();
    };
    self.apply_data = function(){
        if(this.editable() == 1 && this.number()){
            this.editable(0);
            this.isSet(true);
            viewModel.wo_page(1);
            viewModel.appyFilters();
        }
    };
    self.number.subscribe(function(new_value) {
        if(new_value)
            if(new_value.trim() != "")
                self.apply_data();
    });
    self.setBLANK = function(){
        this.number(null);
        this.isSet(false);
        viewModel.appyFilters();
    };
};
var filter_wt = function(){
    var self = this;
    self.work_type = ko.observable(null);
    self.name = ko.observable(null);
    self.editable = ko.observable(0);
    self.isSet = ko.observable(false);
    self.activate_work_type = function(){
        viewModel.hidefiltersinputs();
        this.editable(1);
        this.work_type(null);
        this.isSet(false);
        applyFocus2Element("#filter_work_type_select");
    };
    self.unactivate_work_type = function(){
        viewModel.hidefiltersinputs();
    };
    self.apply_data = function(){
        if(this.editable() == 1 && this.work_type()){
            this.editable(0);
            this.isSet(true);
            this.name(this.work_type().name);
            viewModel.wo_page(1);
            viewModel.appyFilters();
        }
    };
    self.work_type.subscribe(function(new_value){
        if(new_value)
            self.apply_data();
    });
    self.setBLANK = function(){
        this.work_type(null);
        this.name(null);
        this.isSet(false);
        viewModel.appyFilters();
    };
};
var filter_sup = function(){
    var self = this;
    self.id = ko.observable(null);
    self.name = ko.observable(null);
    self.isSet = ko.observable(false);
    self.setBLANK = function(){
        this.id(null);
        this.name(null);
        this.isSet(false);
        viewModel.appyFilters();
    };
};
var filter_eqt = function(){
    var self = this;
    self.equipment = ko.observable(null);
    self.name = ko.observable(null);
    self.editable = ko.observable(0);
    self.isSet = ko.observable(false);
    self.activate_equipment = function(){
        viewModel.hidefiltersinputs();
        this.editable(1);
        this.equipment(null);
        this.isSet(false);
        applyFocus2Element("#filter_equipment_select");
    };
    self.unactivate_equipment = function(){
        viewModel.hidefiltersinputs();
    };
    self.apply_data = function(){
        if(this.editable() == 1 && this.equipment()){
            this.editable(0);
            this.isSet(true);
            this.name(this.equipment().name);
            viewModel.wo_page(1);
            viewModel.appyFilters();
        }
    };
    self.equipment.subscribe(function(new_value){
        if(new_value)
            self.apply_data();
    });
    self.setBLANK = function(){
        this.equipment(null);
        this.name(null);
        this.isSet(false);
        viewModel.appyFilters();
    };
};
var filter_status = function(){
    var self = this;
    self.status = ko.observable(null);
    self.editable = ko.observable(0);
    self.isSet = ko.observable(false);
    self.activate_status = function(){
        viewModel.hidefiltersinputs();
        this.editable(1);
        this.status(null);
        this.isSet(false);
        applyFocus2Element("#filter_status_select");
    };
    self.unactivate_status = function(){
        viewModel.hidefiltersinputs();
    };
    self.apply_data = function(){
        if(this.editable() == 1 && this.status()){
            this.editable(0);
            this.isSet(true);
            viewModel.wo_page(1);
            viewModel.appyFilters();
        }
    };
    self.status.subscribe(function(new_value){
        if(new_value)
            self.apply_data();
    });
    self.setBLANK = function(){
        this.status(null);
        this.isSet(false);
        viewModel.appyFilters();
    };
};
var filter_clt = function(){
    var self = this;
    self.client = ko.observable(null);
    self.editable = ko.observable(0);
    self.isSet = ko.observable(false);
    self.activate_client = function(){
        viewModel.hidefiltersinputs();
        this.editable(1);
        this.client(null);
        this.isSet(false);
        applyFocus2Element("#filter_client_input");
    };
    self.unactivate_client = function(){
        viewModel.hidefiltersinputs();
    };
    self.apply_data = function(){
        if(this.editable() == 1 && this.client()){
            this.editable(0);
            this.isSet(true);
            viewModel.wo_page(1);
            viewModel.appyFilters();
        }
    };
    self.client.subscribe(function(new_value){
        if(new_value)
            if(new_value.trim() != "")
                self.apply_data();
    });
    self.setBLANK = function(){
        this.client(null);
        this.isSet(false);
        viewModel.appyFilters();
    };
};
var filter_make = function(){
    var self = this;
    self.make = ko.observable(null);
    self.editable = ko.observable(0);
    self.isSet = ko.observable(false);
    self.activate_make = function(){
        viewModel.hidefiltersinputs();
        this.editable(1);
        this.make(null);
        this.isSet(false);
        applyFocus2Element("#filter_make_input");
    };
    self.unactivate_make = function(){
        viewModel.hidefiltersinputs();
    };
    self.apply_data = function(){
        if(this.editable() == 1 && this.make()){
            this.editable(0);
            this.isSet(true);
            viewModel.wo_page(1);
            viewModel.appyFilters();
        }
    };
    self.make.subscribe(function(new_value){
        if(new_value)
            if(new_value.trim() != "")
                self.apply_data();
    });
    self.setBLANK = function(){
        this.make(null);
        this.isSet(false);
        viewModel.appyFilters();
    };
};
var filter_model = function(){
    var self = this;
    self.model = ko.observable(null);
    self.editable = ko.observable(0);
    self.isSet = ko.observable(false);
    self.activate_model = function(){
        viewModel.hidefiltersinputs();
        this.editable(1);
        this.model(null);
        this.isSet(false);
        applyFocus2Element("#filter_model_input");
    };
    self.unactivate_model = function(){
        viewModel.hidefiltersinputs();
    };
    self.apply_data = function(){
        if(this.editable() == 1 && this.model()){
            this.editable(0);
            this.isSet(true);
            viewModel.wo_page(1);
            viewModel.appyFilters();
        }
    };
    self.model.subscribe(function(new_value){
        if(new_value)
            if(new_value.trim() != "")
                self.apply_data();
    });
    self.setBLANK = function(){
        this.model(null);
        this.isSet(false);
        viewModel.appyFilters();
    };
};

//Sorters Availables
var sorter_created = function(){
    var self = this;
    self.sort = ko.observable("");
    self.visible = ko.observable(false);
    self.setASC = function() {
        viewModel.blankSorters();
        this.sort("ASC");
        viewModel.wo_page(1);
        viewModel.appyFilters();
    };
    self.setDESC = function() {
        viewModel.blankSorters();
        this.sort("DESC");
        viewModel.wo_page(1);
        viewModel.appyFilters();
    };
    self.setBLANK = function() {
        if(this.sort != ""){this.sort("");}
    };
};
var sorter_started = function(){
    var self = this;
    self.sort = ko.observable("");
    self.visible = ko.observable(false);
    self.setASC = function() {
        viewModel.blankSorters();
        this.sort("ASC");
        viewModel.wo_page(1);
        viewModel.appyFilters();
    };
    self.setDESC = function() {
        viewModel.blankSorters();
        this.sort("DESC");
        viewModel.wo_page(1);
        viewModel.appyFilters();
    };
    self.setBLANK = function() {
        if(this.sort != ""){this.sort("");}
        //viewModel.appyFilters();
    };
};
var sorter_wo = function(){
    var self = this;
    self.sort = ko.observable("");
    self.visible = ko.observable(false);
    self.setASC = function() {
        viewModel.blankSorters();
        this.sort("ASC");
        viewModel.wo_page(1);
        viewModel.appyFilters();
    };
    self.setDESC = function() {
        viewModel.blankSorters();
        this.sort("DESC");
        viewModel.wo_page(1);
        viewModel.appyFilters();
    };
    self.setBLANK = function() {
        if(this.sort != ""){this.sort("");}
        //viewModel.appyFilters();
    };
};
/*var sorter_stock = function(){
    var self = this;
    self.sort = ko.observable("");
    self.visible = ko.observable(false);
    self.setASC = function() {
        viewModel.blankSorters();
        this.sort("ASC");
        viewModel.wo_page(1);
        viewModel.appyFilters();
    };
    self.setDESC = function() {
        viewModel.blankSorters();
        this.sort("DESC");
        viewModel.wo_page(1);
        viewModel.appyFilters();
    };
    self.setBLANK = function() {
        if(this.sort != ""){this.sort("");}
        //viewModel.appyFilters();
    };
};*/
var sorter_wt = function(){
    var self = this;
    self.sort = ko.observable("");
    self.visible = ko.observable(false);
    self.setASC = function() {
        viewModel.blankSorters();
        this.sort("ASC");
        viewModel.wo_page(1);
        viewModel.appyFilters();
    };
    self.setDESC = function() {
        viewModel.blankSorters();
        this.sort("DESC");
        viewModel.wo_page(1);
        viewModel.appyFilters();
    };
    self.setBLANK = function() {
        if(this.sort != ""){this.sort("");}
        //viewModel.appyFilters();
    };
};
var sorter_sup = function(){
    var self = this;
    self.sort = ko.observable("");
    self.visible = ko.observable(false);
    self.setASC = function() {
        viewModel.blankSorters();
        this.sort("ASC");
        viewModel.wo_page(1);
        viewModel.appyFilters();
    };
    self.setDESC = function() {
        viewModel.blankSorters();
        this.sort("DESC");
        viewModel.wo_page(1);
        viewModel.appyFilters();
    };
    self.setBLANK = function() {
        if(this.sort != ""){this.sort("");}
        //viewModel.appyFilters();
    };
};
var sorter_eqt = function(){
    var self = this;
    self.sort = ko.observable("");
    self.visible = ko.observable(false);
    self.setASC = function() {
        viewModel.blankSorters();
        this.sort("ASC");
        viewModel.wo_page(1);
        viewModel.appyFilters();
    };
    self.setDESC = function() {
        viewModel.blankSorters();
        this.sort("DESC");
        viewModel.wo_page(1);
        viewModel.appyFilters();
    };
    self.setBLANK = function() {
        if(this.sort != ""){this.sort("");}
        //viewModel.appyFilters();
    };
};
var sorter_clt = function(){
    var self = this;
    self.sort = ko.observable("");
    self.visible = ko.observable(false);
    self.setASC = function() {
        viewModel.blankSorters();
        this.sort("ASC");
        viewModel.wo_page(1);
        viewModel.appyFilters();
    };
    self.setDESC = function() {
        viewModel.blankSorters();
        this.sort("DESC");
        viewModel.wo_page(1);
        viewModel.appyFilters();
    };
    self.setBLANK = function() {
        if(this.sort != ""){this.sort("");}
        //viewModel.appyFilters();
    };
};
var sorter_make = function(){
    var self = this;
    self.sort = ko.observable("");
    self.visible = ko.observable(false);
    self.setASC = function() {
        viewModel.blankSorters();
        this.sort("ASC");
        viewModel.wo_page(1);
        viewModel.appyFilters();
    };
    self.setDESC = function() {
        viewModel.blankSorters();
        this.sort("DESC");
        viewModel.wo_page(1);
        viewModel.appyFilters();
    };
    self.setBLANK = function() {
        if(this.sort != ""){this.sort("");}
        //viewModel.appyFilters();
    };
};
var sorter_model = function(){
    var self = this;
    self.sort = ko.observable("");
    self.visible = ko.observable(false);
    self.setASC = function() {
        viewModel.blankSorters();
        this.sort("ASC");
        viewModel.wo_page(1);
        viewModel.appyFilters();
    };
    self.setDESC = function() {
        viewModel.blankSorters();
        this.sort("DESC");
        viewModel.wo_page(1);
        viewModel.appyFilters();
    };
    self.setBLANK = function() {
        if(this.sort != ""){this.sort("");}
        //viewModel.appyFilters();
    };
};

/**
 * Refresh work orders list after supervisor select
 * @param workorders
 * @constructor
 */
function RefreshWorkOrderList(response){
    viewModel.work_orders.removeAll();
    viewModel.visible_pages.removeAll();

    viewModel.last_page(response.last_page);
    viewModel.previous_page(response.previous_page);
    viewModel.next_page(response.next_page);
    viewModel.cant_wos(response.cant_wos);
    if(viewModel.last_page() > 1){
        var init = 1;
        var fin = 5;
        if(viewModel.last_page() <= 5)
            fin = viewModel.last_page();
        else if(viewModel.wo_page() > 3 && (viewModel.wo_page() + 2) <= viewModel.last_page()){
            init = viewModel.wo_page() - 2;
            fin =  viewModel.wo_page() + 2;
        }
        else if(viewModel.wo_page() > 3 && (viewModel.wo_page() + 2) > viewModel.last_page()){
            fin =  viewModel.last_page();
            init = fin - 4;
        }

        for(i = init; i <= fin; i++){
            viewModel.visible_pages.push(new page(i));
        }
    }

    $.each( response.workorders, function( i, val ) {
        var to_add = viewModel.filter_make().make() == null
            && viewModel.filter_model().model() == null
            && viewModel.filter_stock().number() == null
            && viewModel.filter_eqt().equipment() == null
            && viewModel.filter_status().status() == null
            && viewModel.filter_clt().client() == null;
        var new_workorder = new workorder(val.id,
            val.picture,
            val.wo_number,
            val.equipment_id,
            val.stocks_qty,
            val.created,
            val.started,
            val.price,
            val.deliverydt,
            val.supervisor_id,
            val.client_id,
            val.sale_type_id,
            val.work_type_id,
            val.status,
            val.obs,
            val.cost);

        if(val.stocks.length > 0)
            $.each( val.stocks, function( j, st ) {
                var st_to_add = viewModel.filter_make().make() == null
                    && viewModel.filter_model().model() == null
                    && viewModel.filter_stock().number() == null
                    && viewModel.filter_eqt().equipment() == null
                    && viewModel.filter_status().status() == null
                    && viewModel.filter_clt().client() == null;
                if(viewModel.filter_make().make() != null){
                    if(st.make != null){
                        if(st.make.contains(viewModel.filter_make().make())){
                            st_to_add = true;
                            to_add = true;
                        }
                        else{
                            st_to_add = false;
                            to_add = false;
                        }
                    }
                }
                if(viewModel.filter_model().model() != null){
                    if(st.model != null){
                        if(st.model.contains(viewModel.filter_model().model())){
                            st_to_add = true;
                            to_add = true;
                        }
                        else{
                            st_to_add = false;
                            to_add = false;
                        }
                    }
                }
                if(viewModel.filter_stock().number() != null){
                    if(st.stock != null){
                        if(st.stock.contains(viewModel.filter_stock().number())){
                            st_to_add = true;
                            to_add = true;
                        }
                        else{
                            st_to_add = false;
                            to_add = false;
                        }
                    }
                }
                if(viewModel.filter_eqt().equipment() != null){
                    if((st.equipment_id != null && st.equipment_id == viewModel.filter_eqt().equipment().id)
                       || (st.equipment_id == null && val.equipment_id != null
                           && val.equipment_id == viewModel.filter_eqt().equipment().id)
                       || (st.equipment_id == null && val.equipment_id == null)){
                            st_to_add = true;
                            to_add = true;
                    }
                    else{
                        st_to_add = false;
                        to_add = false;
                    }
                }
                if(viewModel.filter_status().status() != null){
                    if(st.status != null){
                        if(st.status.contains(viewModel.filter_status().status())){
                            st_to_add = true;
                            to_add = true;
                        }
                        else{
                            st_to_add = false;
                            to_add = false;
                        }
                    }
                }
                if(viewModel.filter_clt().client() != null){
                    if(st.client_id != null){
                        var client_name = $.grep(viewModel.clients(),
                            function(s){ return s.id == st.client_id;})[0].name;
                        if(client_name.contains(viewModel.filter_clt().client())){
                            st_to_add = true;
                            to_add = true;
                        }
                        else{
                            st_to_add = false;
                            to_add = false;
                        }
                    }
                }

                if(to_add && st_to_add){
                    new_workorder.stocks.push(new stock(st.own_id, st.asdb_id, st.stock, st.serial, st.number, st.hours_miles,
                        st.model, st.capacity, st.year, st.description, st.make, st.tgc, st.engine, st.localization,
                        st.a_condition, null, st.equipment_id, st.status, st.client_id));
                }
            });
        if(to_add)
            viewModel.work_orders.push(new_workorder);
        else if(viewModel.filter_eqt().equipment())
            if(!to_add && val.equipment_id == viewModel.filter_eqt().equipment().id)
                viewModel.work_orders.push(new_workorder);
    });
}
function setSupervisors(sups){
    viewModel.supervisors.removeAll();
    $.each( sups, function( i, val ) {
        viewModel.supervisors.push(new supervisor(val.id, val.picture, val.code, val.name, val.fullname, val.department));
    });
}

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()),


    current_wo_number_to_creation: ko.observable(null),
    chosensup: ko.observable(null),
    chosenwo: ko.observable(null),
    reciving_wo: ko.observable(null),
    work_orders: ko.observableArray(new Array()),
    work_orders_stocks: ko.observableArray(new Array()),

    //Pagination
    wo_page: ko.observable(1),
    last_page: ko.observable(1),
    previous_page: ko.observable(1),
    next_page: ko.observable(1),
    cant_wos: ko.observable(0),
    visible_pages: ko.observableArray(new Array()),

    large_picture: ko.observable(null),

    reciving_wo_search: ko.observable(null),
    stoc2transfer: ko.observable(null),

    //Filters
    filter_created: ko.observable(new filter_created()),
    filter_started: ko.observable(new filter_started()),
    filter_wo: ko.observable(new filter_wo()),
    filter_stock: ko.observable(new filter_stock()),
    filter_wt: ko.observable(new filter_wt()),
    filter_sup: ko.observable(new filter_sup()),
    filter_eqt: ko.observable(new filter_eqt()),
    filter_clt: ko.observable(new filter_clt()),
    filter_make: ko.observable(new filter_make()),
    filter_model: ko.observable(new filter_model()),
    filter_status: ko.observable(new filter_status()),

    //Sorters
    sorter_created: ko.observable(new sorter_created()),
    sorter_started: ko.observable(new sorter_started()),
    sorter_wo: ko.observable(new sorter_wo()),
    sorter_wt: ko.observable(new sorter_wt()),
    sorter_sup: ko.observable(new sorter_sup()),
    sorter_eqt: ko.observable(new sorter_eqt()),
    sorter_clt: ko.observable(new sorter_clt()),

    //Apply Filters
    clear_large_image: function(){
        this.large_picture(null);
    },
    go_first_page: function(){
        this.wo_page(1);
        this.appyFilters();
    },
    go_prev_page: function(){
        this.wo_page(this.previous_page());
        this.appyFilters();
    },
    go_next_page: function(){
        this.wo_page(this.next_page());
        this.appyFilters();
    },
    go_last_page: function(){
        this.wo_page(this.last_page());
        this.appyFilters();
    },

    appyFilters: function(){
        loadMask("work_orders_list", "Loading work orders")
        this.filteredWorkOrders();
        //this.filteredWorkOrdersStocks();
        hideMask("work_orders_list");
    },
    getSupervisors: function(){
        $.ajax({
            type: 'post',
            async: true,
            dataType: 'json',
            url: getURLSupervisors(),
            data: {},
            success: function(response) {
                setSupervisors(response.supervisors)
            },
            error:function() {
                alert("Error");
            }
        });
    },
    filteredWorkOrders: function(){
        $.ajax({
            type: 'post',
            async: true,
            dataType: 'json',
            url: getURLFilterWorkOrders(),
            data: {filters: JSON.stringify(this.filters()),
                   sorters: JSON.stringify(this.sorters()),
                   page: this.wo_page()},
            success: function(response) {
                RefreshWorkOrderList(response)
                //alert(response.message);
            },
            error:function() {
                alert("Error");
            }
        });
    },
    removeFilters: function() {
        this.filter_created().setBLANK();
        this.filter_started().setBLANK();
        this.filter_wo().setBLANK();
        this.filter_sup().setBLANK();
        this.filter_eqt().setBLANK();
        this.filter_clt().setBLANK();
    },
    hidefiltersinputs: function() {
        this.filter_created().editable(0);
        this.filter_started().editable(0);
        this.filter_wo().editable(0);
        this.filter_stock().editable(0);
        this.filter_wt().editable(0);
        this.filter_eqt().editable(0);
        this.filter_clt().editable(0);
        this.filter_make().editable(0);
        this.filter_model().editable(0);
        this.filter_status().editable(0);
    },
    blankSorters: function() {
        this.sorter_created().setBLANK();
        this.sorter_started().setBLANK();
        this.sorter_wo().setBLANK();
        this.sorter_wt().setBLANK();
        this.sorter_sup().setBLANK();
        this.sorter_eqt().setBLANK();
        this.sorter_clt().setBLANK();
    },

    filters: function(){
        var filters_list = {filter_wo: this.filter_wo().isSet() ? this.filter_wo().number() : null,
            filter_stock: this.filter_stock().isSet() ? this.filter_stock().number() : null,
            filter_created: this.filter_created().isSet() ?
            {sdate: this.filter_created().sdate(),
                edate: this.filter_created().edate()} : null,
            filter_started: this.filter_started().isSet() ?
            {sdate: this.filter_started().sdate(),
                edate: this.filter_started().edate()} : null,
            filter_sup: this.filter_sup().isSet() ? this.filter_sup().id() : null,
            filter_eqt: this.filter_eqt().isSet() ? this.filter_eqt().equipment().id : null,
            filter_wt: this.filter_wt().isSet() ? this.filter_wt().work_type().id : null,
            filter_clt: this.filter_clt().isSet() ? this.filter_clt().client() : null};

        var result_list = $.makeArray(filters_list);

        return result_list;
    },
    sorters: function(){
        var sorters_list = {sorter_wo: this.sorter_wo().sort() != "" ? this.sorter_wo().sort() : null,
            sorter_eqt: this.sorter_eqt().sort() != "" ? this.sorter_eqt().sort() : null,
            sorter_wt: this.sorter_wt().sort() != "" ? this.sorter_wt().sort() : null,
            sorter_created: this.sorter_created().sort() != "" ? this.sorter_created().sort() : null,
            sorter_started: this.sorter_started().sort() != "" ? this.sorter_started().sort() : null,
            sorter_sup: this.sorter_sup().sort() != "" ? this.sorter_sup().sort() : null,
            sorter_clt: this.sorter_clt().sort() != "" ? this.sorter_clt().sort() : null};

        var result_list = $.makeArray(sorters_list);

        return result_list;
    },

    //Work Order related functions
    create_workorder: function(){
        var number = null;
        $.ajax({
            type: 'post',
            async: false,
            dataType: 'json',
            url: getURLNextWONumber(),
            data: {},
            success: function(response) {
                number = response.wo_number;
            },
            error:function() {
                alert("Error");
            }
        });
        this.chosenwo(new workorder(null, null, number, null, null, null, null, null,
            null, null));
        this.chosenwo().show_me();
    },
    get_support: function(){
        $.ajax({
            type: 'post',
            async: false,
            dataType: 'json',
            url: getURLSupport(),
            data: {},
            success: function(response) {
                $.each( response.supervisors, function( i, val ) {
                    viewModel.supervisors.push(new supervisor(val.id, val.picture, val.code, val.name, val.fullname, val.department));
                });
                $.each( response.units, function( i, val ) {
                    viewModel.units.push(new unit(val.id, val.name, val.fullname));
                });
                $.each( response.equipments, function( i, val ) {
                    viewModel.equipments.push(new wo_eqpt_data(val.id, val.name, val.code));
                });
                $.each( response.departments, function( i, val ) {
                    viewModel.departments.push(new wo_dep_data(val.id, val.name));
                });
                $.each( response.clients, function( i, val ) {
                    viewModel.clients.push(new wo_clt_data(val.id, val.name));
                });
                $.each( response.t_sales, function( i, val ) {
                    viewModel.t_sales.push(new wo_tsales_data(val.id, val.name));
                });
                $.each( response.t_works, function( i, val ) {
                    viewModel.t_works.push(new wo_tworks_data(val.id, val.name));
                });
            },
            error:function() {
                alert("Error");
            }
        });
        $.each( stock_status, function( i, val ) {
            viewModel.stocks_status.push(val);
        });
        $.each( wo_status, function( i, val ) {
            viewModel.wo_status.push(val);
        });
        $.each( task_status, function( i, val ) {
            viewModel.task_status.push(val);
        });
    },
    get_wo_data: function(){
        if(this.chosenwo().id() != null){
            $.ajax({
                type: 'post',
                async: false,
                dataType: 'json',
                url: getURLSupportById(),
                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: getURLSupportById(),
                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");
            }
        });
    },
    xxx: function(){
        $.ajax({
            type: 'get',
            async: false,
            dataType: 'json',
            url: getURLXXX(),
            data: {},
            success: function(response) {
                return response;
            },
            error:function() {
                alert("Error");
            }
        });
    }
};

//Other functions
function loadPageFeatures(){
    if(check_device() == 2){
        $('.datepicker').datetimepicker({
            language:  'en',
            weekStart: 0,
            todayBtn:  1,
            autoclose: 1,
            todayHighlight: 1,
            startView: 2,
            minView: 2,
            forceParse: 0
        });
    }
    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-number').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){
    //Masks
    $('#stock-number-' + index).inputmask("9[9]",
        {placeholder:"-", greedy: false});
}

function ShowPicture(event, picture){
    viewModel.large_picture(picture);
    $('#large-picture').modal('show');
    event.stopImmediatePropagation();
}
function loadMask(area_id, message){
    $('#' + area_id).waitMe({
        effect: 'ios',
        text: message + '...',
        bg: 'rgba(255,255,255,0.7)',
        color:'#014576'
    });
}
function hideMask(area_id){
    $('#' + area_id).waitMe('hide');
}