var roleIds = new Array();
var companyNames = new Array();
var positionNames = new Array();
var Emails = new Array();

window.afterInitTable = function () {
    InitResizableGrid('table.resizable-grid', getHeightTableHolder(95));
}
//opera 11.11 fail :(
/* Array.prototype.lastIndexOf = function(n, f) {
     for (var l = this.length, j = ~ ~f, i = (1 in arguments && j <= l) ? j < 0 ? j + l : j : l - 1; i > -1; i--) {
        if (i in this && this[i] === n) {
            return i;
        }
    }  
    return -1;
}  */
//https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/lastIndexOf
 Array.prototype.lastIndexOf = function(searchElement /*, fromIndex*/)
   {
    "use strict";

    if (this === void 0 || this === null)
      throw new TypeError();

    var t = Object(this);
    var len = t.length >>> 0;
    if (len === 0)
      return -1;

    var n = len;
    if (arguments.length > 1)
    {
      n = Number(arguments[1]);
      if (n !== n)
        n = 0;
      else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0))
        n = (n > 0 || -1) * Math.floor(Math.abs(n));
    }

    var k = n >= 0
          ? Math.min(n, len - 1)
          : len - Math.abs(n);

    for (; k >= 0; k--)
    {
      if (k in t && t[k] === searchElement)
        return k;
    }
    return -1;
  };
 
Array.prototype.filter = function(fn, obj) {
    for (var l = this.length, i = 0, a = []; i < l; i++) {
        fn.apply(obj, [this[i], i, this]) && a.push(this[i]);
    }
    return a;
}


Array.prototype.unique = function() {
    return this.filter(function(e, i, a) {
        return a.lastIndexOf(e) == i;
    });
}

function addSelectedUsers(id) {
    if (id) { selectedIds.length = 0; selectedIds.push(id); rowChecked(id, true); }        
	if (selectedIds.length == 0) { alert(UserResources.NoUsersSelected); return false; }	
    var roleids = new Array();
    selectedIds = selectedIds.unique();
    $(selectedIds).each(function(i, id) { roleids.push(roleIds[id]); });
	
    var rids = roleids.join(',');
    var pid = $('#permissionid').length > 0 ? $('#permissionid').val() : 0;

    var result = new Array();
    result["selectedIds"] = selectedIds;
    result["selectedNames"] = selectedNames;
    result["selectedCompanies"] = companyNames;
    result["permissionId"] = pid;

    if (getURLParameter('msName') != null && getURLParameter('msName') != '') {
        result["msName"] = getURLParameter('msName');
    }

    var targetBlock = getURLParameter('targetBlock');
    if ((self.callback == null || (self.callback == undefined && navigator.appName == 'Opera')) && targetBlock != null && targetBlock != '') {
        if (targetBlock == 'ExecutorsItemData') {
            self.callback = opener.ExecutorsItemData.selectExecutorsCallback;
        }
        else if (targetBlock == 'ParticipantsItemData') {
            self.callback = opener.ParticipantsItemData.selectParticipantsCallback;
        }
        else {
            self.callback = opener.taskUsersCallback;
        }
    }
    else if (self.callback == null || (self.callback == undefined && navigator.appName == 'Opera')) {
        self.callback = opener.taskUsersCallback;
    }

    //fix for opera 11.11
    //if (navigator.appName == 'Opera' && self.callback == undefined) self.callback = opener.taskUsersCallback;

    self.callback(result);


    if (self.test && self.test.callback) {
        self.test.callback(result);
    }

    self.close();
    return false;
}

function changeRole(link) {
    var link = $(link);
    var td = link.parent();
    var html = '<div class="popupwrapper"><div class="popup">' + $('#selectroletemplate').html() + '</div></div>';
    td.append(html).find('.popupwrapper').show();
    selectRow(getId(link.attr('id')),true);
    return false;
}

function hideRoles(link) {
    $(link).parents('.popupwrapper').hide();
    return false;
}

function setRole(link, roleid) {
    var td = $(link).parents('td');
    $(link).parents('.popupwrapper').remove();
    var url = base + 'serviceuser.ivp/changerole';
    td.find('a:first').text($(link).text());
    td.find('input').val(roleid);
    td.addClass('changed');

    var id = td.find('a:first').attr('id').split('_')[1];
    roleIds[id] = roleid;
    
    return false;
}

function rowChecked(id, check) {
    if ($('#id' + id).length > 0) {
        selectedNames['id' + id] = $('#id' + id).attr('fullname');
        selectedPaths["id" + id] = $("#id" + id).attr('path');
        companyNames['id' + id] = $('#id' + id).attr('companyname');
        positionNames['id' + id] = $('#id' + id).attr('positionname');
        Emails['id' + id] = $('#id' + id).attr('email');
        roleIds['id' + id] = $('#id' + id).attr('roleid');
    }
}

//для выбора исполнителей на заявке
function showUserSchedule(userId, isAvailable) {
    if (isAvailable != "") {
        var url = 'schedule.ivp/showUserSchedule/' + userId;
        dlg = openDialog(url, 'showSchedule', { width: 900, height: 650 });
    }
    return false;
}


//#region KB permissions
function changePermission(link) {
    var link = $(link);
    var parent = link.parent();
    $('.popupwrapper').hide();
    if (parent.find('.popupwrapper').length > 0)
        parent.find('.popupwrapper').show();
    else {
        var html = '<div class="popupwrapper"><div class="popup">' + $('#selectpermissiontemplate').html() + '</div></div>';
        parent.append(html).find('.popupwrapper').css({left:link.position().left, top: link.position().top + 10}).show();
    }
    return false;
}

function hidePermission(link) {
    $(link).parents('.popupwrapper').hide();
    return false;
}

function setPermission(link, permissionid) {
    var parent = $(link).parents('h1');
    $(link).parents('.popupwrapper').remove();	
	$('#permissionid').val(permissionid);	
	parent.find('a#kbpermissionlink:first').text($(link).text());
    return false;
}
//#endregion

function taskUserChangePage(page) {    
    var url = tableUrl();

    var customPart = $("#customRequestPart").val();

    customPart = encodeURI(customPart);

    url += "?" + customPart;

    if (page) {
        $(tableRootDiv).load(url, { tb_page: page, nolayout: true, timestamp: new Date().toString() }, initTable);
    } else {
        $(tableRootDiv).load(url, { nolayout: true, timestamp: new Date().toString() }, initTable);
    }
    return false;
}

function taskUserOrderBy(sort) {
    //На случай если фильтр уже открыт, установим сортировку по выбранной колонке в фильтре
    if ($('#columns').length > 0) {
        var col = sort.substr(0, sort.indexOf(' '));
        var desc = (sort.indexOf('desc') > 0);
        $('select.orderby').val('');
        $('select.orderby[column="' + col + '"]').get(0).selectedIndex = (desc ? 2 : 1);
    }
    var params = { tb_orderby: sort, nolayout: true };

    var url = tableUrl();

    var customPart = $("#customRequestPart").val();

    customPart = encodeURI(customPart);

    url += "?" + customPart;

    $(tableRootDiv).load(url, params, initTable);
    return false;
}

function taskuserdosearch(evt) {
    var e = ($.browser.msie) ? event : evt;
    var keycode = ($.browser.msie) ? e.keyCode : e.which;
    if (keycode == 13)
        return _taskusersearch();
    else {
        enableOrDisableClear();
        return true;
    }
}

function _taskusersearch() {
    var url = tableUrl();

    var customPart = $("#customRequestPart").val();

    customPart = encodeURI(customPart);

    url += "?" + customPart;

    $.ajax({
        url: url,
        data: { tb_search: $('#search').val(), nolayout: true, timestamp: new Date().toDateString(), initsearch: true },
        success: function (data) {
            try {
                var dataJ = eval('(' + data + ')');;
            }
            catch (e) { }
            if (dataJ != null && dataJ.hasOwnProperty('IsOK')) {
                try { window.afterSearch(dataJ); } catch (e) { }
            }
            else {
                $(tableRootDiv).empty().append(data);
                initTable();
            }
        }
    });
    return false;
}

function taskUserClearFilter() {
    if ($('#clearfilter').hasClass('disabled')) return false;

    var params = mergeTableDefaultLoadParams();

    params["reset"] = true;
    params["nolayout"] = true;

    var url = tableUrl();    

    var customPart = $("#customRequestPart").val();

    customPart = encodeURI(customPart);

    url += "?" + customPart;

    //Уберем фильтр чтобы сбросить его состояние
    $('#filterholder').remove(); $('ul.filterlist li.selected').removeClass('selected');
    $('#columnsholder').remove();
    $('#showfilter img').attr('src', $('#showfilter img').attr('src').replace('_active', ''));
    $('#showcolumns img').attr('src', $('#showcolumns img').attr('src').replace('_active', ''));
    $('#search').val('');
    disableSaveAndClear();

    $(tableRootDiv).load(url, params, function () {
        initTable();
    });
    return false;
}

function taskUserApplyFilter() {
    var params = $('#filter form :not(.date)').serializeArray();
    var dates = [];
    $('#filter form .date').each(function () {
        if ($(this).attr('date')) {
            var date = { name: $(this).attr('name'), value: $(this).attr('date') };
            dates[dates.length] = date;
        } else {
            var date = { name: $(this).attr('name'), value: $(this).val() };
            dates[dates.length] = date;
        }
    });

    params = mergeTableDefaultLoadParams($.merge(params, dates), true);

    var orderby = '';
    $('select.orderby').find('option:selected').each(function (i, el) { if (el.value) orderby += ((orderby.length > 0) ? ',' : '') + el.value; });

    params[params.length] = { name: 'tb_stateid', value: '' };
    if ($('#search').length > 0) params[params.length] = { name: 'tb_search', value: $('#search').val() };
    params[params.length] = { name: 'timestamp', value: new Date().toString() };
    params[params.length] = { name: 'nolayout', value: true };

    var url = tableUrl();

    var customPart = $("#customRequestPart").val();

    customPart = encodeURI(customPart);

    url += "?" + customPart;

    $('div.multipleselectpopup').hide();
    $('#filterholder').hide(); $('ul.filterlist li.selected').removeClass('selected');
    $('#showfilter img').attr('src', $('#showfilter img').attr('src').replace('_active', '').replace('.gif', '_active.gif'));
    enableSaveAndClear();
    $(tableRootDiv).load(url, params, initTable);
    return false;
}

function taskUserApplyColumns() {
    if (window.beforeApplyColumns) {
        try {
            if (!window.beforeApplyColumns())
                return false;
        } catch (e) { }
    }
    var params = $('#columns form').serializeArray();
    var orderby = '';
    $('select.orderby option:selected').each(function (i, el) { if (el.value) orderby += ((orderby.length > 0) ? ',' : '') + el.value; });

    params[params.length] = { name: 'tb_orderby', value: orderby };
    params[params.length] = { name: 'tb_stateid', value: '' };
    if ($('#search').length > 0) params[params.length] = { name: 'tb_search', value: $('#search').val() };
    params[params.length] = { name: 'timestamp', value: new Date().toString() };
    params[params.length] = { name: 'nolayout', value: true };

    $('#columnsholder').hide(); $('ul.filterlist li.selected').removeClass('selected');
    $('#showcolumns img').attr('src', $('#showcolumns img').attr('src').replace('_active', '').replace('.gif', '_active.gif'));
    enableSaveAndClear();

    params = mergeTableDefaultLoadParams(params, true);

    var url = tableUrl();

    var customPart = $("#customRequestPart").val();

    customPart = encodeURI(customPart);

    url += "?" + customPart;

    $(tableRootDiv).load(url, params, initTable);
    return false;
}