/**
 * 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 workers 4 time record manager
 */

/*function worker(id, name, department, picture, code, pay_by_hour, pay_rate){
    var self = this;
    self.id = ko.observable(id);
    self.name = ko.observable(name);
    self.department = ko.observable(department);
    self.picture = ko.observable(picture);
    self.code = ko.observable(code);
    self.pay_by_hour = pay_by_hour;
    self.pay_rate = pay_rate;
    self.shifts_changed = ko.observable(false);
    self.shifts = ko.observableArray(new Array());

    self.total_cost = ko.computed(function() {
        var result = 0;
        if(self.shifts().length > 0){
            $.each(self.shifts(), function( i, val ) {
                result = result + val.cost();
            });
        }
        return "$" + result.toFixed(2);
    });
    self.total_hours = ko.computed(function() {
        var result = 0;
        if(self.shifts().length > 0){
            $.each( self.shifts(), function( i, val ) {
                result = result + val.rTime();
            });
        }
        return result.toFixed(2);
    });

    //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_workorder = ko.observable(new filter_shift_workorder());
    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_workorder: this.filter_shift_workorder().isSet() ? this.filter_shift_workorder().workorder() : 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_workorder: this.sorter_shift_workorder().sort() != "" ?
                this.sorter_shift_workorder().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_workorder = ko.observable(new sorter_shift_workorder());
    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());

    self.choseme = function(){
        loadMask("workers_list", "Loading labors");
        self.sorter_shift_date().sort("DESC");
        viewModel.chosenworker(this);
        self.getMyShifts();
        hideMask("workers_list");
    };
    self.refresh_shifts = function(){
        self.getMyShifts();
    };
    self.save_shifts = function(){
        $.each( self.shifts(), function( i, shift ) {
            if(shift.changed())
                shift.save_me();
            else
                shift.disable_editable();
        });
        //self.refresh_shifts();
    };
    self.new_shift_top = function(){
        if(self.shifts().length > 0)
            self.shifts.splice(0, 0, new shift(null, null, null, null, null, null, null, null,
                self.shifts()[0].date(), null, null, this.pay_rate, null, null));
        else
            self.shifts.push(new shift(null, null, null, null, null, null, null, null, null, null, null, this.pay_rate,
                null, null));
        self.shifts()[0].enable_full_edit();
    };
    self.new_shift_bottom = function(){
        if(self.shifts().length > 0)
            self.shifts.push(new shift(null, null, null, null, null, null, null, null,
                self.shifts()[self.shifts().length -1].date(), null, null, this.pay_rate, null, null));
        else
            self.shifts.push(new shift(null, null, null, null, null, null, null, null, null, null, null, this.pay_rate,
                null, null));
        self.shifts()[self.shifts().length - 1].enable_full_edit();
    };
    self.new_shift_attached = function(original_shift){
        var pos = self.shifts().indexOf(original_shift) + 1;
        self.shifts.splice(pos, 0, new shift(null, null, null,
            original_shift.worker, original_shift.workorder(), original_shift.assigned_stock_no(),
            original_shift.area(), original_shift.description(), original_shift.date(), null, null, this.pay_rate, null,
            null));

        self.shifts()[pos].enable_partial_edit();
    };
    self.delete_shift = function(shift){
        self.shifts.remove(shift);
    };
    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.sorter_shift_workorder().setBLANK();
    };

    //Ajax
    self.getMyShifts = function(){
        loadMask("shifts", "Loading work order labors");
        self.shifts.removeAll();
        $.ajax({
            type: 'post',
            async: false,
            dataType: 'json',
            url: getURLWorkerShifts(),
            data: {worker_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.id,
                        loop.labor_id,
                        loop.department,
                        loop.worker,
                        loop.workorder,
                        loop.assigned_stock_no,
                        loop.area,
                        loop.description,
                        loop.date,
                        loop.starts,
                        loop.ends,
                        loop.hour_cost ? loop.hour_cost : viewModel.chosenworker().pay_rate,
                        loop.rTime,
                        loop.lunch));
                });
            },
            error:function() {
                alert("Error");
                return false;
            }
        });
        hideMask("shifts");
    };
}
function department(id, name){
    var self = this;
    self.id = ko.observable(id);
    self.name = ko.observable(name);
}

*/

//Filters available
/*var filter_code = function(){
    var self = this;
    self.code = ko.observable(null);
    self.editable = ko.observable(0);
    self.isSet = ko.observable(false);
    self.activate_code = function(){
        this.editable(1);
        this.code(null);
        this.isSet(false);
        applyFocus2Element("#filter_code_input");
    };
    self.apply_data = function(){
        if(this.code()){
            this.editable(0);
            this.isSet(true);
            viewModel.wo_page(1);
            viewModel.appyFilters();
        }
        else{
            this.editable(0);
            this.isSet(false);
        }
    };
    self.code.subscribe(function(new_value){
        if(new_value)
            if(new_value.trim() != "")
                self.apply_data();
    });
    self.setBLANK = function(){
        this.code(null);
        this.isSet(false);
        viewModel.appyFilters();
    };
};
var filter_name = function(){
    var self = this;
    self.name = ko.observable(null);
    self.editable = ko.observable(0);
    self.isSet = ko.observable(false);
    self.activate_name = function(){
        this.editable(1);
        this.name(null);
        this.isSet(false);
        applyFocus2Element("#filter_name_input");
    };
    self.apply_data = function(){
        if(this.name()){
            this.editable(0);
            this.isSet(true);
            //viewModel.wo_page(1);
            viewModel.appyFilters();
        }
        else{
            this.editable(0);
            this.isSet(false);
        }
    };
    self.name.subscribe(function(new_value){
        if(new_value)
            if(new_value.trim() != "")
                self.apply_data();
    });
    self.setBLANK = function(){
        this.name(null);
        this.isSet(false);
        viewModel.appyFilters();
    };
};
var filter_dep = function(){
    var self = this;
    //self.id = ko.observable(null);
    self.department = ko.observable(null);
    self.editable = ko.observable(0);
    self.isSet = ko.observable(false);
    self.name = function() {
        if(self.department())
            return self.department().name();
        return "nono";
    };
    self.activate_department = function(){
        this.editable(1);
        this.department(null);
        viewModel.chosendp(null);
        this.isSet(false);
        applyFocus2Element("#filter_department_select");
    };
    self.apply_data = function(){
        if(this.department()){
            this.editable(0);
            this.isSet(true);
            viewModel.wo_page(1);
            viewModel.appyFilters();
        }
        else{
            this.editable(0);
            this.isSet(false);
        }
    };
    self.department.subscribe(function(new_value){
        viewModel.chosendp(new_value);
        if(new_value){
            self.apply_data();
        }
    });
    self.setBLANK = function(){
        this.department(null);
        viewModel.chosendp(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.chosenworker().getMyShifts();
        }
    };
    self.department.subscribe(function(new_value){
        if(new_value)
            self.apply_data();
    });
    self.setBLANK = function(){
        this.department(null);
        this.isSet(false);
        viewModel.chosenworker().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.chosenworker().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.chosenworker().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);
        $("#filter_shift_description_input").focus();
    };
    self.apply_data = function(){
        if(this.editable() == 1 && this.description()){
            this.editable(0);
            this.isSet(true);
            viewModel.chosenworker().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.chosenworker().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);
        //applyFeturedMask2Element("#filter_shift_asn_input", "9[9]", { "placeholder": "-", greedy: false});
        applyFocus2Element("#filter_shift_asn_input");
    };
    self.apply_data = function(){
        if(this.editable() == 1 && this.asn()){
            this.editable(0);
            this.isSet(true);
            viewModel.chosenworker().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.chosenworker().getMyShifts();
    };
};
var filter_shift_workorder = function(){
    var self = this;
    self.workorder = ko.observable(null);
    self.editable = ko.observable(0);
    self.isSet = ko.observable(false);
    self.activate_workorder = function(){
        this.editable(1);
        this.workorder(null);
        this.isSet(false);
        //applyFeturedMask2Element("#filter_shift_workorder_input", "9999", {placeholder:"-"});
        applyFocus2Element("#filter_shift_workorder_input");
    };
    self.apply_data = function(){
        if(this.editable() == 1 && this.workorder()){
            this.editable(0);
            this.isSet(true);
            viewModel.chosenworker().getMyShifts();
        }
    };
    self.workorder.subscribe(function(new_value){
        if(new_value)
            if(new_value.trim() != "")
                self.apply_data();
    });
    self.setBLANK = function(){
        this.workorder(null);
        this.isSet(false);
        viewModel.chosenworker().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);
        $("#filter_shift_area_input").focus();
    };
    self.apply_data = function(){
        if(this.editable() == 1 && this.area()){
            this.editable(0);
            this.isSet(true);
            viewModel.chosenworker().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.chosenworker().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);
        loadPageFeatures();
        *//*applyFeturedMask2Element("#filter_shift_date_sdate_input", "mm/dd/yyyy",
         { "placeholder": "-", "yearrange": { "minyear": 2014, "maxyear": 2099 } });*//*
        applyFocus2Element("#filter_shift_date_sdate_input");
    };
    self.activate_range = function(){
        this.date_activated(false);
        this.range_activated(true);
        this.editable(2);
        this.isSet(false);
        this.sdate(null);
        this.edate(null);
        loadPageFeatures();
        *//*applyFeturedMask2Element("#filter_shift_created_sdate1_input", "mm/dd/yyyy",
         { "placeholder": "-", "yearrange": { "minyear": 2014, "maxyear": 2099 } });
         applyFeturedMask2Element("#filter_shift_created_edate1_input", "mm/dd/yyyy",
         { "placeholder": "-", "yearrange": { "minyear": 2014, "maxyear": 2099 } });*//*
        applyFocus2Element("#filter_shift_created_sdate1_input");
    };
    self.setBLANK = function(){
        this.edate(null);
        this.sdate(null);
        this.date_activated(false);
        this.range_activated(false);
        this.editable(0);
        this.isSet(false);
        viewModel.chosenworker().getMyShifts();
    };
    self.apply_data = function(){
        if(this.editable() == 1 && this.sdate()){
            this.editable(0);
            this.isSet(true);
            viewModel.chosenworker().getMyShifts();
        }
        else if(this.editable() == 2 && this.sdate() && this.edate()){
            this.editable(0);
            this.isSet(true);
            viewModel.chosenworker().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
var sorter_code = 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_name = 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_dep = 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("");}
    };
};
//Shifts
var sorter_shift_dep = function(){
    var self = this;
    self.sort = ko.observable("");
    self.visible = ko.observable(false);
    self.setASC = function() {
        viewModel.chosenworker().blankSorters();
        this.sort("ASC");
        viewModel.chosenworker().getMyShifts();
    };
    self.setDESC = function() {
        viewModel.chosenworker().blankSorters();
        this.sort("DESC");
        viewModel.chosenworker().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.chosenworker().blankSorters();
        this.sort("ASC");
        viewModel.chosenworker().getMyShifts();
    };
    self.setDESC = function() {
        viewModel.chosenworker().blankSorters();
        this.sort("DESC");
        viewModel.chosenworker().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.chosenworker().blankSorters();
        this.sort("ASC");
        viewModel.chosenworker().getMyShifts();
    };
    self.setDESC = function() {
        viewModel.chosenworker().blankSorters();
        this.sort("DESC");
        viewModel.chosenworker().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.chosenworker().blankSorters();
        this.sort("ASC");
        viewModel.chosenworker().getMyShifts();
    };
    self.setDESC = function() {
        viewModel.chosenworker().blankSorters();
        this.sort("DESC");
        viewModel.chosenworker().getMyShifts();
    };
    self.setBLANK = function() {
        if(this.sort != ""){this.sort("");}
    };
};
var sorter_shift_workorder = function(){
    var self = this;
    self.sort = ko.observable("");
    self.visible = ko.observable(false);
    self.setASC = function() {
        viewModel.chosenworker().blankSorters();
        this.sort("ASC");
        viewModel.chosenworker().getMyShifts();
    };
    self.setDESC = function() {
        viewModel.chosenworker().blankSorters();
        this.sort("DESC");
        viewModel.chosenworker().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.chosenworker().blankSorters();
        this.sort("ASC");
        viewModel.chosenworker().getMyShifts();
    };
    self.setDESC = function() {
        viewModel.chosenworker().blankSorters();
        this.sort("DESC");
        viewModel.chosenworker().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.chosenworker().blankSorters();
        this.sort("ASC");
        viewModel.chosenworker().getMyShifts();
    };
    self.setDESC = function() {
        viewModel.chosenworker().blankSorters();
        this.sort("DESC");
        viewModel.chosenworker().getMyShifts();
    };
    self.setBLANK = function() {
        if(this.sort != ""){this.sort("");}
    };
};

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


//Notifications
var loop = function(id, labor_id, department, worker, workorder, assigned_stock_no, area, description, date,
                     starts, ends, hour_cost, rTime, lunch, p_overtime, c_overtime, overtime_cost){
    var self = this;

    self.id = ko.observable(id);
    self.labor_id = labor_id;
    self.department = department;
    self.worker = worker;
    self.p_overtime = p_overtime;
    self.c_overtime = c_overtime;
    self.overtime_cost = overtime_cost;
    self.workorder = ko.observable(workorder);
    self.assigned_stock_no = ko.observable(assigned_stock_no);
    self.area = ko.observable(area);
    self.description = ko.observable(description);
    self.date = ko.observable(date);
    self.starts = ko.observable(starts);
    self.ends = ko.observable(ends);
    self.rTime = ko.observable(rTime);
    self.lunch = ko.observable(lunch != null ? lunch : false);
    self.hour_cost = ko.observable(hour_cost);
    self.cost = ko.observable(0);

    //Formated
    self.formatedTime = ko.computed(function() {
        if(self.rTime()){
            return self.rTime().toFixed(2);
        }
        var result = 0;
        return result.toFixed(2);
    });
    self.formatedCost = ko.computed(function() {
        result = 0;
        if(self.hour_cost() && self.rTime())
            result = self.rTime() * self.hour_cost();

        self.cost(result);
        return "$" + result.toFixed(2);
    });

    self.formatedPOTime = ko.computed(function() {
        return self.p_overtime.toFixed(2);
    });
    self.formatedPOCost = ko.computed(function() {
        var pocost = self.p_overtime < 0 ? self.p_overtime * self.hour_cost()
            : self.p_overtime * self.overtime_cost;
        return self.p_overtime < 0 ? "-$" + (pocost * -1).toFixed(2) : "$" + pocost.toFixed(2);
    });
    self.formatedCOTime = ko.computed(function() {
        return self.c_overtime.toFixed(2);
    });
    self.formatedCOCost = ko.computed(function() {
        var cocost = self.c_overtime > 0 ? self.c_overtime * self.overtime_cost: 0;
        return "$" + cocost.toFixed(2);
    });
}
function notice(own_id, worker_id, worker, loop_id, generated, loop_date, dismissed, alert_type, time, text, hour_cost){
    var self = this;

    self.own_id = own_id;
    self.worker_id = worker_id;
    self.worker = worker;
    self.loop_id = loop_id;
    self.generated = generated;
    self.loop_date = loop_date;
    self.hour_cost = hour_cost;
    self.alert_type = alert_type;
    self.dismissed = ko.observable(dismissed);
    self.time = ko.observable(time);
    self.text = ko.observable(text);

    self.my_loops = ko.observableArray(new Array);

    self.getMyLoops = function(){
        $.ajax({
            type: 'post',
            async: false,
            dataType: 'json',
            url: getURLNoticeLoops(),
            data: {loop_id: self.loop_id, alert_type: self.alert_type},
            success: function(response) {
                self.my_loops.removeAll();
                if(response.loops.length > 0){
                    $.each(response.loops, function(i, val){
                        self.my_loops.push(new loop(val.id, val.labor_id, val.department, val.worker,
                            val.workorder, val.assigned_stock_no, val.area, val.description, val.date,
                            val.starts,  val.ends,  val.hour_cost,  val.rTime,  val.lunch,  val.overtime,
                            val.c_overtime,  val.overtime_cost))
                    });
                }
            },
            error:function() {
                alert("Error");
            }
        });
    }
    self.activate = function(){
        $.ajax({
            type: 'post',
            async: false,
            dataType: 'json',
            url: getURLActivateNotice(),
            data: {notice_id: self.own_id},
            success: function(response) {
                baseViewModel.notifications().getRefreshNewNotices();
                viewModel.filter_notices();
            },
            error:function() {
                alert("Error");
            }
        });
        //alert("X");
    };
    self.dismiss = function(){
        $.ajax({
            type: 'post',
            async: false,
            dataType: 'json',
            url: getURLDismissNotice(),
            data: {notice_id: self.own_id},
            success: function(response) {
                baseViewModel.notifications().getRefreshNewNotices();
                viewModel.filter_notices();
            },
            error:function() {
                alert("Error");
            }
        });
        //alert("X");
    };

    self.week_day = ko.computed(function(){
        var date = new Date(self.loop_date);
        return date.getDay();
    });
    self.works = ko.computed(function(){
        var t = parseFloat(self.time().toFixed(2));
        var hw = self.alert_type == 0 ? 8 - t
                :self.alert_type == 1 ? 8 + (self.week_day() == 0 || self.week_day() == 6) ? 0 : t
                :40 + t;
        return hw.toFixed(2) + 'h';
    });
    self.expected_time= ko.computed(function(){
        var hw = 8;
        if(self.alert_type == 1)
            if(self.week_day == 6 || self.week_day == 0)
                hw = 0;
        else if(self.alert_type == 2)
            hw = 40;
        return hw.toFixed(2) + 'h';
    });
    self.expected_period= ko.computed(function(){
        var p = 'Week';
        if(self.alert_type == 1){
            if(self.week_day == 0){
                p = 'Sun';
            }
            else{
                if(self.week_day == 6)
                    p = 'Sat';
                else
                    p = 'Day';
            }
        }
        else
            if(self.alert_type == 0)
                p = 'Day';
        return p;
    });
    self.formatedTime = ko.computed(function(){
        return parseFloat(self.time().toFixed(2));
    });
    self.cost = ko.computed(function(){
        return '$' + (self.time() * self.hour_cost).toFixed(2);
    });
};

var viewModel = {
    active_notices: ko.observableArray(new Array()),
    dismissed_notices: ko.observableArray(new Array()),

    filter_notices: function(){
        loadMask("active_notices_list", "Loading active notifications");
        this.get_active_notices();
        this.get_dismissed_notices();
        //addUploadLoopsfeature();
        hideMask("active_notices_list");
    },
    get_active_notices: function(){
        $.ajax({
            type: 'post',
            async: false,
            dataType: 'json',
            url: getURLActiveNotifications(),
            data: {},
            success: function(response) {
                viewModel.active_notices.removeAll();
                if(response.notifications.length > 0){
                    var notifications = response.notifications;
                    viewModel.active_notices.push(new notice(notifications[0].own_id, notifications[0].worker_id,
                        notifications[0].worker, notifications[0].loop_id, notifications[0].generated,
                        notifications[0].loop_date, null, notifications[0].alert_type, notifications[0].time,
                        notifications[0].text, notifications[0].hour_cost))
                    for (i = 1; i < notifications.length; i++){
                        //alert(getFirstWeekDay(notifications[0].generated) + ' - ' + getFirstWeekDay(notifications[1].generated));
                        var added = $.grep(viewModel.active_notices(), function(s){
                            return (s.worker_id == response.notifications[i].worker_id
                            && s.alert_type ==  notifications[i].alert_type)
                            && ((s.alert_type == 2
                            && getFirstWeekDay(s.loop_date).getTime() == getFirstWeekDay(notifications[i].loop_date).getTime())
                            || (s.alert_type == 1
                            && s.loop_date == notifications[i].loop_date)); });
                        if(added.length == 1){
                            viewModel.active_notices()[viewModel.active_notices.indexOf(added[0])].time(
                                viewModel.active_notices()[viewModel.active_notices.indexOf(added[0])].time()
                                + notifications[i].time);
                        }
                        else
                            viewModel.active_notices.push(new notice(notifications[i].own_id,
                                notifications[i].worker_id, notifications[i].worker, notifications[i].loop_id,
                                notifications[i].generated, notifications[i].loop_date, null,
                                notifications[i].alert_type, notifications[i].time, notifications[i].text,
                                notifications[i].hour_cost));
                    }
                }
                $.each( viewModel.active_notices(), function( i, val ) {
                    $('#' + val.own_id).on('show.bs.collapse', function () {
                        val.getMyLoops();
                    })
                });
            },
            error:function() {
                alert("Error");
            }
        });
    },
    get_dismissed_notices: function(){
        $.ajax({
            type: 'post',
            async: true,
            dataType: 'json',
            url: getURLDismissedNotifications(),
            data: {},
            success: function(response) {
                viewModel.dismissed_notices.removeAll();
                if(response.notifications.length > 0){
                    var notifications = response.notifications;
                    viewModel.dismissed_notices.push(new notice(notifications[0].own_id, notifications[0].worker_id,
                        notifications[0].worker, notifications[0].loop_id, notifications[0].generated,
                        notifications[0].loop_date, notifications[0].dismissed, notifications[0].alert_type,
                        notifications[0].time, notifications[0].text, notifications[0].hour_cost))
                    for (i = 1; i < notifications.length; i++){
                        //alert(getFirstWeekDay(notifications[0].generated) + ' - ' + getFirstWeekDay(notifications[1].generated));
                        var added = $.grep(viewModel.dismissed_notices(), function(s){
                            return (s.worker_id == response.notifications[i].worker_id
                                && s.alert_type ==  notifications[i].alert_type)
                                && ((s.alert_type == 2
                                && getFirstWeekDay(s.loop_date).getTime() == getFirstWeekDay(notifications[i].loop_date).getTime())
                                || (s.alert_type == 1
                                && s.loop_date == notifications[i].loop_date)); });
                        if(added.length == 1){
                            viewModel.dismissed_notices()[viewModel.dismissed_notices.indexOf(added[0])].time(
                                viewModel.dismissed_notices()[viewModel.dismissed_notices.indexOf(added[0])].time()
                                    + notifications[i].time);
                        }
                        else
                            viewModel.dismissed_notices.push(new notice(notifications[i].own_id,
                                notifications[i].worker_id, notifications[i].worker, notifications[i].loop_id,
                                notifications[i].generated, notifications[0].loop_date, notifications[i].dismissed,
                                notifications[i].alert_type, notifications[i].time, notifications[i].text,
                                notifications[i].hour_cost));
                    }
                }
                $.each( viewModel.dismissed_notices(), function( i, val ) {
                    $('#' + val.own_id).on('show.bs.collapse', function () {
                        val.getMyLoops();
                    })
                });
            },
            error:function() {
                alert("Error");
            }
        });
    }
};

//Others functions
function applyFeturesToShiftIndex(index){
    //Data pickers
    $('#shift-date-' + index).datetimepicker({
        language:  'en',
        weekStart: 0,
        todayBtn:  1,
        autoclose: 1,
        todayHighlight: 1,
        startView: 2,
        minView: 2,
        forceParse: 0,
        startDate: '01/01/2015'
    });
    $('#shift-starts-' + index).datetimepicker({
        language:  'en',
        weekStart: 0,
        todayBtn:  0,
        autoclose: 1,
        todayHighlight: 1,
        startView: 1,
        minView: 0,
        forceParse: 0
    });
    $('#shift-ends-' + index).datetimepicker({
        language:  'en',
        weekStart: 0,
        todayBtn:  0,
        autoclose: 1,
        todayHighlight: 1,
        startView: 1,
        minView: 0,
        forceParse: 0
    });

    //Masks
    $('#shift-workorder-' + index).inputmask("9999",
        {placeholder:"-",
            oncomplete: function(){
                //$('#shift-asn-' + index).focus();
                if(this.selectionStart == this.value.length){
                    var nextInput = $(':input').get($(':input').index(this) + 1);
                    if (nextInput)
                        nextInput.focus();
                }
            }});
    $('#shift-asn-' + index).inputmask("9[9]", { "placeholder": "-", greedy: false});
    $('#shift-date-' + index).inputmask("mm/dd/yyyy",
        { placeholder: "-", "yearrange": { "minyear": 2014, "maxyear": 2099 },
            oncomplete: function(){
                //$('#shift-date-' + index).datetimepicker("hide");
                if(this.selectionStart == this.value.length){
                    $("#" + this.attributes['id'].value).datetimepicker("hide");
                    var nextInput = $(':input').get($(':input').index(this) + 1);
                    if (nextInput)
                        nextInput.focus();
                }
            }});
    $('#shift-starts-' + index).inputmask("hh:mm",
        {placeholder: "-",
            oncomplete: function(){
                //$('#shift-starts-' + index).datetimepicker("hide");
                if(this.selectionStart == this.value.length){
                    $("#" + this.attributes['id'].value).datetimepicker("hide");
                    var nextInput = $(':input').get($(':input').index(this) + 1);
                    if (nextInput)
                        nextInput.focus();
                }
            }});
    $('#shift-ends-' + index).inputmask("hh:mm",
        {placeholder: "-",
            oncomplete: function(){
                //$('#shift-ends-' + index).datetimepicker("hide");
                if(this.selectionStart == this.value.length){
                    $("#" + this.attributes['id'].value).datetimepicker("hide");
                    var nextInput = $(':input').get($(':input').index(this) + 1);
                    if (nextInput)
                        nextInput.focus();
                }
            }});
}
function applyFeturedMask2Element(element, mask, options){
    $(element).inputmask(mask, options);
}
function loadPageFeatures(){
}
function addUploadLoopsfeature(){
    $.each( viewModel.active_notices(), function( i, val ) {
        $('#' + val.own_id).on('show.bs.collapse', function () {
            val.getMyLoops();
        })
    });
    $.each( viewModel.dismissed_notices(), function( i, val ) {
        $('#' + val.own_id).on('show.bs.collapse', function () {
            val.getMyLoops();
        })
    });
}
function ShowPicture(){
    $('#large-picture').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 RefreshWorkersList(response){
    viewModel.workers.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.workers, function( i, val ) {
        viewModel.workers.push(new worker(val.id, val.name, val.department, val.picture, val.code,
            val.pay_by_hour, val.pay_rate));
    });
}