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

var shift = function(id, labor_id, department, worker, workorder, assigned_stock_no, area, description, date,
                     starts, ends, hour_cost, rTime, lunch){
    var self = this;

    self.id = ko.observable(id);
    self.labor_id = labor_id;
    self.department = department;
    self.worker = worker;
    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);

    //Control
    self.full_editable = ko.observable(false);
    self.partial_editable = ko.observable(false);
    self.changed = ko.observable(false);

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

    //Subscription
    self.workorder.subscribe(function(new_value){
        if(new_value)
            if(new_value.trim() != "")
                self.changed(true);
    });
    self.assigned_stock_no.subscribe(function(new_value){
        if(new_value)
            if(new_value.trim() != "")
                self.changed(true);
    });
    self.area.subscribe(function(new_value){
        if(new_value)
            if(new_value.trim() != "")
                self.changed(true);
    });
    self.description.subscribe(function(new_value){
        if(new_value)
            if(new_value.trim() != "")
                self.changed(true);
    });
    self.date.subscribe(function(new_value){
        if(new_value)
            if(new_value.trim() != "")
                self.changed(true);
    });
    self.starts.subscribe(function(new_value){
        if(new_value)
            if(new_value.trim() != ""){
                self.changed(true);
                if(self.full_editable() || self.partial_editable())
                    self.recalculateTime();
            }
    });
    self.ends.subscribe(function(new_value){
        if(new_value)
            if(new_value.trim() != ""){
                self.changed(true);
                if(self.full_editable() || self.partial_editable())
                    self.recalculateTime();
            }
    });
    self.lunch.subscribe(function(new_value){
        if(new_value != null){
            self.changed(true);
            if(self.full_editable() || self.partial_editable())
                self.recalculateTime();
        }
    });

    //Operations
    self.recalculateTime = function(){
        if(self.starts() != null && self.ends() != null){
            var result = 0;
            var h1 = parseInt(self.starts().split(':')[0], 10) * 60 + parseInt(self.starts().split(':')[1], 10);
            var h2 = parseInt(self.ends().split(':')[0], 10) * 60 + parseInt(self.ends().split(':')[1], 10);
            if(self.lunch())
                h2 = h2 - 30;
            result = (h2 - h1) / 60;
            self.rTime(parseFloat(result.toFixed(2)));
        }
    };
    self.enable_full_edit = function(){
        this.full_editable(true);
        this.partial_editable(false);
        applyFeturesToShiftIndex(viewModel.chosenworker().shifts().indexOf(this));
        applyFocus2Element("#shift-workorder-" + viewModel.chosenworker().shifts().indexOf(this));
    };
    self.enable_partial_edit = function(){
        this.partial_editable(true);
        this.full_editable(false);
        applyFeturesToShiftIndex(viewModel.chosenworker().shifts().indexOf(this));
        applyFocus2Element("#shift-date-" + viewModel.chosenworker().shifts().indexOf(this));
    };
    self.disable_editable = function(){
        this.full_editable(false);
        this.partial_editable(false);
    };
    self.validate_my_datetime = function(){
        var result = false;
        $.ajax({
            type: 'post',
            async: false,
            dataType: 'json',
            url: getURLValidateLoopDateTime(),
            data: {loop_id: self.id(),
                   labor_id: self.labor_id,
                   worker_id: viewModel.chosenworker().id,
                   date: self.date(),
                   starts: self.starts(),
                   ends: self.ends()},
            success: function(response) {
                //alert(response.valid);
                result = response.valid == true;
            },
            error:function() {
                alert("Error");
                result = false;
            }
        });
        return result;
    };
    self.save_me = function(){
        var x = self.validate_my_datetime();
        if( x == true){
            $.ajax({
                type: 'post',
                async: true,
                dataType: 'json',
                url: getURLSaveSingleLoop(),
                data: {loop_id: self.id(),
                       labor_id: self.labor_id,
                       worker_id: viewModel.chosenworker().id,
                       workorder: self.workorder(),
                       assigned_stock_no: self.assigned_stock_no(),
                       area: self.area(),
                       description: self.description(),
                       date: self.date(),
                       starts: self.starts(),
                       ends: self.ends(),
                       rTime: self.rTime(),
                       hour_cost: self.hour_cost(),
                       lunch: self.lunch()},
                success: function(response) {
                    self.id(response.loop_id);
                    self.changed(false);
                    self.disable_editable();
                    //alert(response.message);
                    return true;
                },
                error:function() {
                    alert("Error");
                    return false;
                }
            });
        }
    };
    self.clone_me = function(){
        viewModel.chosenworker().new_shift_attached(this);
    };
    self.delete_me = function(){
        if(self.id()){
            $.ajax({
                type: 'post',
                async: true,
                dataType: 'json',
                url: getURLDeleteSingleLoop(),
                data: {loop_id: self.id()},
                success: function(response) {
                    self.id(response.id);
                    return true;
                },
                error:function() {
                    alert("Error");
                    return false;
                }
            });
        }
        viewModel.chosenworker().delete_shift(this);
    };
}

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

var viewModel = {
    name_code: ko.observable(null),
    chosendp: ko.observable(null),
    chosenworker: ko.observable(null),
    large_picture: ko.observable(null),
    show_worker: ko.observable(false),
    default_date: ko.observable(new Date()),

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

    //Filters
    filter_code: ko.observable(new filter_code()),
    filter_name: ko.observable(new filter_name()),
    filter_dep: ko.observable(new filter_dep()),

    //Sorters
    sorter_code: ko.observable(new sorter_code()),
    sorter_name: ko.observable(new sorter_name()),
    sorter_dep: ko.observable(new sorter_dep()),

    //Arrays
    departments: ko.observableArray(new Array()),
    workers: ko.observableArray(new Array()),

    //Operations
    unchoseworker: function(){
        this.chosenworker(null);
    },
    refresh_all_shifts: function(){
        this.chosenworker().refresh_shifts();
    },
    save_all_shifts: function(){
        this.chosenworker().save_shifts();
        $("#name_search").focus();
        $("#name_search").select();
    },
    new_shift_top: function(){
        this.chosenworker().new_shift_top();
    },
    new_shift_bottom: function(){
        this.chosenworker().new_shift_bottom();
    },
    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("workers_list", "Loading workers");
        this.filteredWorkers();
        hideMask("workers_list");
    },
    removeFilters: function() {
        this.filter_code().setBLANK();
        this.filter_name().setBLANK();
        this.filter_dep().setBLANK();
    },
    blankSorters: function() {
        this.sorter_code().setBLANK();
        this.sorter_name().setBLANK();
        this.sorter_dep().setBLANK();
    },
    filtered_workers_4_xls: function(){
        var list = $.map(this.workers(), function(w) {
            return {id: w.id()};
        });

        return list;
    },

    //Generated lists
    filters: function(){
        var filters_list = {filter_code: this.filter_code().isSet() ? this.filter_code().code() : null,
            filter_name: this.filter_name().isSet() ? this.filter_name().name() : null,
            filter_dep: this.filter_dep().isSet() ? this.filter_dep().department().id() : null};

        var result_list = $.makeArray(filters_list);

        return result_list;
    },
    sorters: function(){
        var sorters_list = {sorter_code: this.sorter_code().sort() != "" ? this.sorter_code().sort() : null,
            sorter_name: this.sorter_name().sort() != "" ? this.sorter_name().sort() : null,
            sorter_dep: this.sorter_dep().sort() != "" ? this.sorter_dep().sort() : null};

        var result_list = $.makeArray(sorters_list);

        return result_list;
    },

    //Ajax
    filteredWorkers: function(){
        $.ajax({
            type: 'post',
            async: false,
            dataType: 'json',
            url: getURLFilteredWorkers(),
            data: {filters: JSON.stringify(this.filters()),
                   sorters: JSON.stringify(this.sorters()),
                   page: this.wo_page()},
            success: function(response) {
                if(response.workers.length == 1){
                    var chosenworker_id = viewModel.chosenworker() ? viewModel.chosenworker().id() : null;
                    if(response.workers[0].id != chosenworker_id){
                        RefreshWorkersList(response);
                        var worker = $.grep(viewModel.workers(), function(s){ return s.id() == response.workers[0].id; })[0];
                        worker.choseme();
                    }
                }
                else{
                    viewModel.unchoseworker();
                    RefreshWorkersList(response);
                }


                //alert(response.message);
            },
            error:function() {
                alert("Error");
            }
        });
    },

    //Exportin
    export_workers_xls: function() {
        if(this.workers().length > 0){
            $.ajax({
                type: 'post',
                async: false,
                dataType: 'json',
                url: getURLExportWorkersXLS(),
                data: {workers: JSON.stringify(this.filtered_workers_4_xls())},
                success: function(response) {
                    window.open(response.url,"_blanck");
                },
                error:function() {
                    alert("Error");
                }
            });
        }
    },
    export_workers_labors_xls: function() {
        if(this.workers().length > 0){
            $.ajax({
                type: 'post',
                async: false,
                dataType: 'json',
                url: getURLExportWorkersLaborsXLS(),
                data: {workers: JSON.stringify(this.filtered_workers_4_xls())},
                success: function(response) {
                    window.open(response.url,"_blanck");
                },
                error:function() {
                    alert("Error");
                }
            });
        }
    },
    export_chosen_worker_labors_xls: function(){
        $.ajax({
            type: 'post',
            async: false,
            dataType: 'json',
            url: getURLExportWorkersLaborsXLS(),
            data: {workers: JSON.stringify([{id: this.chosenworker().id()}])},
            success: function(response) {
                window.open(response.url,"_blanck");
            },
            error:function() {
                alert("Error");
            }
        });
    }
};

//Others functions
function applyFeturesToShiftIndex(index){
    //Data pickers
    if(check_device() == 2){
        $('#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
        });
    }
    else{
        $('#shift-date-' + index).each(function(){
            var value = new Date($(this).val());this.type="date";
            value = value.getFullYear() + '-'
                + (value.getMonth() < 9 ? '0' + (value.getMonth() + 1) : (value.getMonth() + 1)) + "-"
                + (value.getDate() < 10 ? '0' + value.getDate() : value.getDate());
            $(this).val(value);});
        $('#shift-starts-' + index).each(function(){var value = $(this).val();this.type="time";$(this).val(value);});
        $('#shift-ends-' + index).each(function(){var value = $(this).val();this.type="time";$(this).val(value);});
    }

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