/**
 * 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;
    });
};

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

    self.id = id;
    self.picture =  picture;
    self.code =  code;
    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();
    };
};
//Objects
var wo_eqpt_data = function(id, equipment){
    var self = this;

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

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

    self.id = id;
    self.name = name;
};
var wo_department_data = function(id, name){
    var self = this;
    self.id = id;
    self.name = name;
};
var workorder = function(id, picture, wo_number, equipment, stock_qty, created, started, price, supervisor, client,
                         delivery_date, sale_type, work_type, stocks, obs){
    var self = this;

    self.id = id;
    self.picture = picture;
    self.wo_number = wo_number;
    self.equipment = equipment;
    self.stock_qty = stock_qty;
    self.created = created;
    self.started = started;
    self.price = price;
    self.supervisor = supervisor;
    self.client = client;
    self.delivery_date = delivery_date;
    self.sale_type = sale_type;
    self.work_type = work_type;
    self.stocks = stocks;
    self.obs = obs;
    self.shifts = ko.observableArray(new Array());

    self.totalTime = ko.computed(function() {
        var tt = 0;
        if(self.shifts().length > 0)
            $.each( self.shifts(), function( i, shift ) {
                tt = tt + shift.rTime;
            });
        var cad = "" + tt.toFixed(2);
        if(cad.length > 6)
            cad = cad.insert(cad.length - 6, ',');
        if(cad.length > 10)
            cad = cad.insert(cad.length - 10, ',');
        if(cad.length > 14)
            cad = cad.insert(cad.length - 14, ',');
        return cad + " hrs";
    });
    self.totalCost = ko.computed(function() {
        var tc = 0;
        if(self.shifts().length > 0)
            $.each( self.shifts(), function( i, shift ) {
                tc = tc + shift.cost;
            });
        var cad = "" + tc.toFixed(2);
        if(cad.length > 6)
            cad = cad.insert(cad.length - 6, ',');
        if(cad.length > 10)
            cad = cad.insert(cad.length - 10, ',');
        if(cad.length > 14)
            cad = cad.insert(cad.length - 14, ',');
        return "$" + cad;
    });

    //Filters
    self.filter_shift_dep = ko.observable(new filter_shift_dep());
    self.filter_shift_worker = ko.observable(new filter_shift_worker());
    self.filter_shift_description = ko.observable(new filter_shift_description());
    self.filter_shift_asn = ko.observable(new filter_shift_asn());
    self.filter_shift_area = ko.observable(new filter_shift_area());
    self.filter_shift_date = ko.observable(new filter_shift_date());

    self.filters_shifts = function(){
        var filters_list = {filter_shift_asn: this.filter_shift_asn().isSet() ? this.filter_shift_asn().asn() : null,
            filter_shift_dep: this.filter_shift_dep().isSet() ?
                this.filter_shift_dep().department().id : null,
            filter_shift_worker: this.filter_shift_worker().isSet() ? this.filter_shift_worker().worker() : null,
            filter_shift_description: this.filter_shift_description().isSet() ?
                this.filter_shift_description().description() : null,
            filter_shift_area: this.filter_shift_area().isSet() ? this.filter_shift_area().area() : null,
            filter_shift_date: this.filter_shift_date().isSet() ?
                {sdate: this.filter_shift_date().sdate(),
                edate: this.filter_shift_date().edate()} : null};

        var result_list = $.makeArray(filters_list);

        return result_list;
    };
    self.sorters_shifts = function(){
        var sorters_list = {sorter_shift_dep: this.sorter_shift_dep().sort() != "" ?
            this.sorter_shift_dep().sort() : null,
            sorter_shift_asn: this.sorter_shift_asn().sort() != "" ?
                this.sorter_shift_asn().sort() : null,
            sorter_shift_area: this.sorter_shift_area().sort() != "" ?
                this.sorter_shift_area().sort() : null,
            sorter_shift_worker: this.sorter_shift_worker().sort() != "" ?
                    this.sorter_shift_worker().sort() : null,
            sorter_shift_description: this.sorter_shift_description().sort() != "" ?
                    this.sorter_shift_description().sort() : null,
            sorter_shift_date: this.sorter_shift_date().sort() != "" ?
                    this.sorter_shift_date().sort() : null};

        var result_list = $.makeArray(sorters_list);

        return result_list;
    };

    //Sorters
    self.sorter_shift_dep = ko.observable(new sorter_shift_dep());
    self.sorter_shift_worker = ko.observable(new sorter_shift_worker());
    self.sorter_shift_description = ko.observable(new sorter_shift_description());
    self.sorter_shift_asn = ko.observable(new sorter_shift_asn());
    self.sorter_shift_area = ko.observable(new sorter_shift_area());
    self.sorter_shift_date = ko.observable(new sorter_shift_date());

    //Operations
    self.choseme = function(){
        if(!viewModel.large_picture()){
            loadMask("work_orders_list", "Loading work order details");
            viewModel.chosenwo(this);
            self.getMyShifts();
            hideMask("work_orders_list");
        }
    };
    self.enlarge_picture = function(){
        viewModel.large_picture(this.picture);
        ShowPicture();
    };
    self.blankSorters = function(){
        self.sorter_shift_dep().setBLANK();
        self.sorter_shift_worker().setBLANK();
        self.sorter_shift_description().setBLANK();
        self.sorter_shift_date().setBLANK();
        self.sorter_shift_asn().setBLANK();
        self.sorter_shift_area().setBLANK();
    };
    self.getMyShifts = function(){
        loadMask("shifts", "Loading work order labors");
        self.shifts.removeAll();
        $.ajax({
            type: 'post',
            async: false,
            dataType: 'json',
            url: getURLWorkOrderLoops(),
            data: {work_order_id: this.id,
             filters: JSON.stringify(this.filters_shifts()),
             sorters: JSON.stringify(this.sorters_shifts())},
            success: function(response){
                $.each( response.loops, function( i, loop ) {
                    self.shifts.push(new shift(loop.department,
                        loop.worker,
                        loop.assigned_stock_no,
                        loop.area,
                        loop.description,
                        loop.date,
                        loop.starts,
                        loop.ends,
                        loop.rTime,
                        loop.cost));
                });
            },
            error:function(){
                alert("Error");
            }
        });
        loadPageFeatures();
        hideMask("shifts");
    };
    self.save4PDF = function(){
        alert("TODO");
    };
    self.save4XLS = function(){
        alert("TODO");
    };
    self.edit = function(){
        alert("TODO");
    };
    self.show = function(){
        alert("TODO");
    };

};
var stock = function(image, stock, serial, hours_miles, make, model, capacity, tgc, engine, year, localization,
                     a_condition, description){
    var self = this;
    self.picture = image;
    self.stock = stock;
    self.serial = serial;
    self.hours_miles = hours_miles;
    self.make = make;
    self.model = model;
    self.capacity = capacity;
    self.tgc = tgc;
    self.engine = engine;
    self.year = year;
    self.localization = localization;
    self.a_condition = a_condition;
    self.description = description;
    self.showme = function(){
        viewModel.stock2show(this);
        ShowStock();
    };
};
var shift = function(department, worker, assigned_stock_no, area, description, date, starts, ends, rTime, cost){
    var self = this;
    self.department = department;
    self.worker = worker;
    self.assigned_stock_no = assigned_stock_no;
    self.area = area;
    self.description = description;
    self.date = date;
    self.starts = starts;
    self.ends = ends;
    self.rTime = rTime ? rTime : 0;
    self.cost = cost ? cost : 0;
    self.formatedTime = ko.computed(function() {
        return self.rTime.toFixed(2);
    });
    self.formatedCost = ko.computed(function() {
        return "$" + self.cost.toFixed(2);
    });
}
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
//Work Orders
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(){
        this.range_activated(false);
        this.date_activated(true);
        this.editable(1);
        this.isSet(false);
        this.sdate(null);
        this.edate(null);
    };
    self.activate_range = function(){
        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_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(){
        this.range_activated(false);
        this.date_activated(true);
        this.editable(1);
        this.isSet(false);
        this.sdate(null);
        this.edate(null);
    };
    self.activate_range = function(){
        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(){
        this.editable(1);
        this.number(null);
        this.isSet(false);
    };
    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_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.editable = ko.observable(0);
    self.isSet = ko.observable(false);
    self.activate_equipment = function(){
        this.editable(1);
        this.equipment(null);
        this.isSet(false);
    };
    self.apply_data = function(){
        if(this.editable() == 1 && this.equipment()){
            this.editable(0);
            this.isSet(true);
            viewModel.wo_page(1);
            viewModel.appyFilters();
        }
    };
    self.equipment.subscribe(function(new_value){
        if(new_value)
            if(new_value.trim() != "")
                self.apply_data();
    });
    self.setBLANK = function(){
        this.equipment(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(){
        this.editable(1);
        this.client(null);
        this.isSet(false);
    };
    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();
    };
};
//Shifts
var filter_shift_dep = function(){
    var self = this;
    self.department = ko.observable(null);
    self.name = ko.observable(null);
    self.editable = ko.observable(0);
    self.isSet = ko.observable(false);
    self.activate_department = function(){
        this.editable(1);
        this.department(null);
        this.isSet(false);
    };
    self.apply_data = function(){
        if(this.editable() == 1 && this.department() != null){
            this.editable(0);
            this.isSet(true);
            this.name(this.department().name);
            viewModel.chosenwo().getMyShifts();
        }
    };
    self.department.subscribe(function(new_value){
        if(new_value)
            self.apply_data();
    });
    self.setBLANK = function(){
        this.department(null);
        this.isSet(false);
        viewModel.chosenwo().getMyShifts();
    };
};
var filter_shift_worker = function(){
    var self = this;
    self.worker = ko.observable(null);
    self.editable = ko.observable(0);
    self.isSet = ko.observable(false);
    self.activate_worker = function(){
        this.editable(1);
        this.worker(null);
        this.isSet(false);
    };
    self.apply_data = function(){
        if(this.editable() == 1 && this.worker()){
            this.editable(0);
            this.isSet(true);
            viewModel.chosenwo().getMyShifts();
        }
    };
    self.worker.subscribe(function(new_value){
        if(new_value)
            if(new_value.trim() != "")
                self.apply_data();
    });
    self.setBLANK = function(){
        this.worker(null);
        this.isSet(false);
        viewModel.chosenwo().getMyShifts();
    };
};
var filter_shift_description = function(){
    var self = this;
    self.description = ko.observable(null);
    self.editable = ko.observable(0);
    self.isSet = ko.observable(false);
    self.activate_description = function(){
        this.editable(1);
        this.description(null);
        this.isSet(false);
    };
    self.apply_data = function(){
        if(this.editable() == 1 && this.description()){
            this.editable(0);
            this.isSet(true);
            viewModel.chosenwo().getMyShifts();
        }
    };
    self.description.subscribe(function(new_value){
        if(new_value)
            if(new_value.trim() != "")
                self.apply_data();
    });
    self.setBLANK = function(){
        this.description(null);
        this.isSet(false);
        viewModel.chosenwo().getMyShifts();
    };
};
var filter_shift_asn = function(){
    var self = this;
    self.asn = ko.observable(null);
    self.editable = ko.observable(0);
    self.isSet = ko.observable(false);
    self.activate_asn = function(){
        this.editable(1);
        this.asn(null);
        this.isSet(false);
    };
    self.apply_data = function(){
        if(this.editable() == 1 && this.asn()){
            this.editable(0);
            this.isSet(true);
            viewModel.chosenwo().getMyShifts();
        }
    };
    self.asn.subscribe(function(new_value){
        if(new_value)
            if(new_value.trim() != "")
                self.apply_data();
    });
    self.setBLANK = function(){
        this.asn(null);
        this.isSet(false);
        viewModel.chosenwo().getMyShifts();
    };
};
var filter_shift_area = function(){
    var self = this;
    self.area = ko.observable(null);
    self.editable = ko.observable(0);
    self.isSet = ko.observable(false);
    self.activate_area = function(){
        this.editable(1);
        this.area(null);
        this.isSet(false);
    };
    self.apply_data = function(){
        if(this.editable() == 1 && this.area()){
            this.editable(0);
            this.isSet(true);
            viewModel.chosenwo().getMyShifts();
        }
    };
    self.area.subscribe(function(new_value){
        if(new_value)
            if(new_value.trim() != "")
                self.apply_data();
    });
    self.setBLANK = function(){
        this.area(null);
        this.isSet(false);
        viewModel.chosenwo().getMyShifts();
    };
};
var filter_shift_date = 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(){
        this.range_activated(false);
        this.date_activated(true);
        this.editable(1);
        this.isSet(false);
        this.sdate(null);
        this.edate(null);
    };
    self.activate_range = function(){
        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.chosenwo().getMyShifts();
    };
    self.apply_data = function(){
        if(this.editable() == 1 && this.sdate()){
            this.editable(0);
            this.isSet(true);
            viewModel.chosenwo().getMyShifts();
        }
        else if(this.editable() == 2 && this.sdate() && this.edate()){
            this.editable(0);
            this.isSet(true);
            viewModel.chosenwo().getMyShifts();
        }
    };
    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();
    });
};

//Sorters Availables
//Work Orders
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_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();
    };
};
//Shifts
var sorter_shift_dep = function(){
    var self = this;
    self.sort = ko.observable("");
    self.visible = ko.observable(false);
    self.setASC = function() {
        viewModel.chosenwo().blankSorters();
        this.sort("ASC");
        viewModel.chosenwo().getMyShifts();
    };
    self.setDESC = function() {
        viewModel.chosenwo().blankSorters();
        this.sort("DESC");
        viewModel.chosenwo().getMyShifts();
    };
    self.setBLANK = function() {
        if(this.sort != ""){this.sort("");}
    };
};
var sorter_shift_worker = function(){
    var self = this;
    self.sort = ko.observable("");
    self.visible = ko.observable(false);
    self.setASC = function() {
        viewModel.chosenwo().blankSorters();
        this.sort("ASC");
        viewModel.chosenwo().getMyShifts();
    };
    self.setDESC = function() {
        viewModel.chosenwo().blankSorters();
        this.sort("DESC");
        viewModel.chosenwo().getMyShifts();
    };
    self.setBLANK = function() {
        if(this.sort != ""){this.sort("");}
    };
};
var sorter_shift_description = function(){
    var self = this;
    self.sort = ko.observable("");
    self.visible = ko.observable(false);
    self.setASC = function() {
        viewModel.chosenwo().blankSorters();
        this.sort("ASC");
        viewModel.chosenwo().getMyShifts();
    };
    self.setDESC = function() {
        viewModel.chosenwo().blankSorters();
        this.sort("DESC");
        viewModel.chosenwo().getMyShifts();
    };
    self.setBLANK = function() {
        if(this.sort != ""){this.sort("");}
    };
};
var sorter_shift_asn = function(){
    var self = this;
    self.sort = ko.observable("");
    self.visible = ko.observable(false);
    self.setASC = function() {
        viewModel.chosenwo().blankSorters();
        this.sort("ASC");
        viewModel.chosenwo().getMyShifts();
    };
    self.setDESC = function() {
        viewModel.chosenwo().blankSorters();
        this.sort("DESC");
        viewModel.chosenwo().getMyShifts();
    };
    self.setBLANK = function() {
        if(this.sort != ""){this.sort("");}
    };
};
var sorter_shift_area = function(){
    var self = this;
    self.sort = ko.observable("");
    self.visible = ko.observable(false);
    self.setASC = function() {
        viewModel.chosenwo().blankSorters();
        this.sort("ASC");
        viewModel.chosenwo().getMyShifts();
    };
    self.setDESC = function() {
        viewModel.chosenwo().blankSorters();
        this.sort("DESC");
        viewModel.chosenwo().getMyShifts();
    };
    self.setBLANK = function() {
        if(this.sort != ""){this.sort("");}
    };
};
var sorter_shift_date = function(){
    var self = this;
    self.sort = ko.observable("");
    self.visible = ko.observable(false);
    self.setASC = function() {
        viewModel.chosenwo().blankSorters();
        this.sort("ASC");
        viewModel.chosenwo().getMyShifts();
    };
    self.setDESC = function() {
        viewModel.chosenwo().blankSorters();
        this.sort("DESC");
        viewModel.chosenwo().getMyShifts();
    };
    self.setBLANK = function() {
        if(this.sort != ""){this.sort("");}
    };
};

//View Model
var viewModel = {
    chosensup: ko.observable(null),
    chosenwo: ko.observable(null),
    supervisors: ko.observableArray(new Array()),
    work_orders: ko.observableArray(new Array()),
    departments: ko.observableArray(new Array()),

    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),
    stock2show: 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_sup: ko.observable(new filter_sup()),
    filter_eqt: ko.observable(new filter_eqt()),
    filter_clt: ko.observable(new filter_clt()),

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

    //Operations
    unchoseworkorder: function(){
        this.chosenwo(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();
    },
    clear_stock2show: function(){
        this.stock2show(null);
    },
    clear_large_image: function(){
        this.large_picture(null);
    },
    appyFilters: function(){
        loadMask('work_orders_list', 'Loading work orders');
        this.filteredWorkOrders();
        loadPageFeatures();
        hideMask('work_orders_list');
    },
    getDepartments: function(){
        $.ajax({
            type: 'post',
            async: false,
            dataType: 'json',
            url: getURLDepartments(),
            data: {},
            success: function(response) {
                RefreshDepartmentsList(response);
            },
            error:function() {
                alert("Error");
            }
        });
    },
    filteredWorkOrders: function(){
        $.ajax({
            type: 'post',
            async: false,
            dataType: 'json',
            url: getURLFilteredWorkOrders(),
            data: {filters: JSON.stringify(this.filters()),
                   sorters: JSON.stringify(this.sorters()),
                   page: this.wo_page()},
            success: function(response) {
                RefreshWorkOrderList(response);
            },
            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();
    },
    blankSorters: function() {
        this.sorter_created().setBLANK();
        this.sorter_started().setBLANK();
        this.sorter_wo().setBLANK();
        this.sorter_sup().setBLANK();
        this.sorter_eqt().setBLANK();
        this.sorter_clt().setBLANK();
    },
    work_order_getShifts: function() {
        this.chosenwo().getMyShifts();
    },

    export_wos2excel: function() {
        if(this.work_orders().length > 0){
            $.ajax({
                type: 'post',
                async: false,
                dataType: 'json',
                url: getURLExport2ExcelFilteredWorkOrders(),
                data: {wos: JSON.stringify(this.filteredwos2excel())},
                success: function(response) {
                    window.open(response.url,"_blanck");
                },
                error:function() {
                    alert("Error");
                }
            });
        }
    },
    export_consolidatedwos2excel: function() {
        if(this.work_orders().length > 0){
            $.ajax({
                type: 'post',
                async: false,
                dataType: 'json',
                url: getURLExport2ExcelConsolidatedFilteredWorkOrders(),
                data: {wos: JSON.stringify(this.filteredwos2excel())},
                success: function(response) {
                    window.open(response.url,"_blanck");
                },
                error:function() {
                    alert("Error");
                }
            });
        }
    },
    export_wos_labors2excel: function() {
        if(this.work_orders().length > 0){
            $.ajax({
                type: 'post',
                async: false,
                dataType: 'json',
                url: getURLExport2ExcelFilteredWorkOrdersLabors(),
                data: {wos: JSON.stringify(this.filteredwos2excel())},
                success: function(response) {
                    window.open(response.url,"_blanck");
                },
                error:function() {
                    alert("Error");
                }
            });
        }
    },
    export_chosen_workorder2xls: function(){
        $.ajax({
            type: 'post',
            async: false,
            dataType: 'json',
            url: getURLExport2ExcelFilteredWorkOrdersLabors(),
            data: {wos: JSON.stringify([{id: this.chosenwo().id}])},
            success: function(response) {
                window.open(response.url,"_blanck");
            },
            error:function() {
                alert("Error");
            }
        });
    },
    export_wos2pdf: function() {
        this.chosenwo().getMyShifts();
    },

    filters: function(){
        var filters_list = {filter_wo: this.filter_wo().isSet() ? this.filter_wo().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() : 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_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;
    },
    filteredwos2excel: function(){
        var list = $.map(this.work_orders(), function(wo) {
            return {id: wo.id};
        });

        return list;
    }
};

//Others functions
function loadPageFeatures(){
    if(check_device() == 2){
        $('.datepicker').datetimepicker({
            language:  'fr',
            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() < 10 ? '0' + value.getMonth() : value.getMonth()) + "-"
                + (value.getDate() < 10 ? '0' + value.getDate() : value.getDate());
            $(this).val(value);});
    }
}
function ShowPicture(){
    $('#large-picture').modal('show')
}
function ShowStock(){
    $('#show_stock').modal('show')
}
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');
}
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 stocks = new Array();
        $.each( val.stocks, function( i, st ) {
            stocks.push(new stock(st.image,
                st.stock,
                st.serial,
                st.hours_miles,
                st.make,
                st.model,
                st.capacity,
                st.tgc,
                st.engine,
                st.year,
                st.localization,
                st.a_condition,
                st.description));
        });

        viewModel.work_orders.push(new workorder(val.id,
            val.picture,
            val.wo_number,
            val.equipment ? new wo_eqpt_data(val.equipment.id,
                val.equipment.equipment) : null,
            val.stock_qty,
            val.created,
            val.started,
            val.price,
            val.supervisor ? new wo_sup_data(val.supervisor.id,
                val.supervisor.name,
                val.supervisor.worker_code) : null,
            val.client ? new wo_clt_data(val.client.id,
                val.client.name) : null,
            val.delivery_date,
            val.sale_type,
            val.work_type,
            stocks));
    });
}
function RefreshDepartmentsList(response){
    $.each( response.departments, function( i, val ) {
        viewModel.departments().push(new wo_department_data(val.id, val.name));
    });
}
