/**
 * 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 area = function(id, name, active){
    var self = this;

    self.id = id;
    self.name = ko.observable(name);
    self.active = ko.observable(active);
    self.collapsed = ko.observable(false);
    self.editable = ko.observable(id ? false : true);
    self.works = ko.observableArray(new Array());

    self.collapse = function(){
        self.collapsed(!self.collapsed());
    };
    self.add_work = function(){
        self.works.push(new work(null, null, null));
    };
}

var work = function(id, code, name, active){
    var self = this;

    self.id = id;
    self.code = ko.observable(code);
    self.name = ko.observable(name);
    self.active = ko.observable(active ? active : true);
    self.editable = ko.observable(id ? false : true);

    self.activate = function(){
        self.active(!self.active());
    };
    self.edit = function(){
        self.editable(!self.editable());
    };
}

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

    get_areas: function(){
        $.ajax({
            type: 'post',
            async: false,
            dataType: 'json',
            url: getURLGETAreas(),
            data: {},
            success: function(response) {
                $.each( response.areas, function( i, val ) {
                    var new_area = new area(val.id, val.name, val.active);

                    $.each( val.works, function( i, wk ) {
                        new_area.works.push(new work(wk.id, wk.name, wk.active));
                    });

                    viewModel.areas.push(new_area);
                });
            },
            error:function() {
                alert("Error");
            }
        });
    },
    add_area: function(){
        this.areas.push(new area(null, null,  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');
}
