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

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

    return theString;
}

var unit = function(id, name){
    var self = this;

    self.id = id;
    self.name = name;
    self.tasks_open = ko.observableArray(new Array());
    self.tasks_dismissed = ko.observableArray(new Array());
    self.tasks_finished = ko.observableArray(new Array());
    //self.units = ko.observableArray(new Array());

    /*self.add_unit = function(punit){
        var sunit = new unit(punit.id, punit.name);

        $.each( punit.tasks_open, function( i, tsk ) {
            var new_task = new task(tsk.id, tsk.description1, tsk.description2,
                tsk.status, tsk.starts, tsk.ends);

            $.each( tsk.workorders, function( i, wo ) {
                new_task.workorders.push(wo);
            });

            sunit.tasks_open.push(new_task);
        });
        $.each( punit.tasks_dismissed, function( i, tsk ) {
            var new_task = new task(tsk.id, tsk.description1, tsk.description2,
                tsk.status, tsk.starts, tsk.ends);

            $.each( tsk.workorders, function( i, wo ) {
                new_task.workorders.push(wo);
            });

            sunit.tasks_dismissed.push(new_task);
        });
        $.each( punit.tasks_finished, function( i, tsk ) {
            var new_task = new task(tsk.id, tsk.description1, tsk.description2,
                tsk.status, tsk.starts, tsk.ends);

            $.each( tsk.workorders, function( i, wo ) {
                new_task.workorders.push(wo);
            });

            sunit.tasks_finished.push(new_task);
        });

        $.each( punit.units, function( i, sub_unit ) {
            sunit.add_unit(sub_unit);
        });

        self.units.push(sunit);
    };*/

    self.create_task_form = function(){
        viewModel.task_4_updater(new task(null, null, null, 'Open', null, null));
        viewModel.task_updater_title('New Task');
        viewModel.unit_in_use(self);
        viewModel.show_task_updater();
    };
    self.add_task = function(task){
        self.tasks_open.push(task);
    };
}

var task = function(id, description1, description2, status, starts, ends){
    var self = this;

    self.id = id;
    self.description1 = ko.observable(description1);
    self.description2 = ko.observable(description2);
    self.status = ko.observable(status);
    self.starts = ko.observable(starts);
    self.ends = ko.observable(ends);

    self.new_workorder = ko.observable(null);

    self.workorders = ko.observableArray(new Array());
    self.selected_workorders = ko.observableArray(new Array());

    self.show_workorders = ko.computed(function() {
        var cad = "";
        $.each( self.workorders(), function( i, val ) {
            if(self.workorders().length - 1 > i)
                cad += val + ', ';
            else
                cad += val;
        });
        return cad;
    });

    self.add_workorder = function(){
        if(self.new_workorder() != null)
            if(self.new_workorder().length == 4){
                self.workorders.push(self.new_workorder());
                self.new_workorder(null);
            }
    };

    self.show_me = function(unit){
        if(unit != null){
            viewModel.unit_in_use(unit);
            viewModel.task_4_updater(self);
            viewModel.task_updater_title('Update Task')
            viewModel.show_task_updater();
        }
    };
}

var viewModel = {
    units: ko.observableArray(new Array()),
    tasks_statuses: ['Open', 'Dismissed', 'Finished'],

    unit_in_use: ko.observable(null),
    task_4_updater: ko.observable(null),
    task_updater_title: ko.observable(null),


    get_tasks: function(){
        $.ajax({
            type: 'post',
            async: false,
            dataType: 'json',
            url: getURLGETTasks(),
            data: {},
            success: function(response) {
                $.each( response.units, function( i, val ) {
                    var new_unit = new unit(val.id, val.name);

                    $.each( val.tasks_open, function( i, tsk ) {
                        var new_task = new task(tsk.id, tsk.description1, tsk.description2,
                            tsk.status, tsk.starts, tsk.ends);

                        $.each( tsk.workorders, function( i, wo ) {
                            new_task.workorders.push(wo);
                        });

                        new_unit.tasks_open.push(new_task);
                    });
                    $.each( val.tasks_dismissed, function( i, tsk ) {
                        var new_task = new task(tsk.id, tsk.description1, tsk.description2,
                            tsk.status, tsk.starts, tsk.ends);

                        $.each( tsk.workorders, function( i, wo ) {
                            new_task.workorders.push(wo);
                        });

                        new_unit.tasks_dismissed.push(new_task);
                    });
                    $.each( val.tasks_finished, function( i, tsk ) {
                        var new_task = new task(tsk.id, tsk.description1, tsk.description2,
                            tsk.status, tsk.starts, tsk.ends);

                        $.each( tsk.workorders, function( i, wo ) {
                            new_task.workorders.push(wo);
                        });

                        new_unit.tasks_finished.push(new_task);
                    });
                    /*$.each( val.units, function( i, sub_unit ) {
                        new_unit.add_unit(sub_unit);
                    });*/

                    viewModel.units.push(new_unit);
                });
            },
            error:function() {
                alert("Error");
            }
        });
    },
    show_task_updater: function(){
        $('#task-updater').modal('show');
        loadPageFeatures();
    },
    updater_create: function(){
        this.unit_in_use().add_task(this.task_4_updater());
        this.unit_in_use(null);
        this.task_4_updater(null);
        this.task_updater_title(null);
    },
    updater_cancel: function(){
        this.unit_in_use(null);
        this.task_4_updater(null);
        this.task_updater_title(null);
    }
};

//Other functions
function loadPageFeatures(){
    if(check_device() == 2){
        $('.datepicker').datetimepicker({
            language:  'en',
            weekStart: 0,
            todayBtn:  1,
            autoclose: 1,
            todayHighlight: 1,
            startView: 2,
            minView: 2,
            forceParse: 0
        });
    }
    else{
        $('.datepicker').each(function(){
            var value = new Date($(this).val());
            this.type="date";
            value = value.getFullYear() + '-'
                + (value.getMonth() < 10 ? '0' + value.getMonth() : value.getMonth()) + "-"
                + (value.getDate() < 10 ? '0' + value.getDate() : value.getDate());
            $(this).val(value);});
    }

    $('option').mousedown(function(e) {
        e.preventDefault();
        $(this).prop('selected', !$(this).prop('selected'));
        return false;
    });
}
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');
}
