var guids = new Array();
var names = new Array();
var types = new Array();

if (!Array.indexOf) {
    Array.prototype.indexOf = function(obj, start) {
        for (var i = (start || 0); i < this.length; i++) {
            if (this[i] == obj) {
                return i;
            }
        }
        return -1;
    }
}

$(function() {
    if ($('#excludedgroupsguids').length > 0) {
        guids = $('#excludedgroupsguids').val().split(',');
        names = $('#excludedgroupsnames').val().split(',');
        types = $('#excludedgroupstypes').val().split(',');
        
        if (guids.length == 1 && guids[0] == '') {
            guids = new Array();
            names = new Array();
            types = new Array();
        }
    }

    $('#companyid').change(changeCompany);

    $('#addCompany').autocomplete(base + 'company.ivp/searchidname/', { minChars: 1 }).result(companySelectedFromAutoComplete);

    $.validator.addMethod("validateCompany", function (value, element) {
        var result = Number($("#companyid").val()) > 0;

        return result;
    })

    $("#addCompany").rules("add", {
        validateCompany: true,
        messages: {
            validateCompany: FormResources.FieldRequired
        }
    });
});

function changeCompany() {
    if ($('#companyid').val() != null && $('#companyid').val() != '' && $('#oldcompanyid').val() != null && $('#oldcompanyid').val() != '' && $('#oldldap').val() == $('#ldappath').val() && $('#oldcompanyid').val() != $('#companyid').val())
        alert(AdSync.ChangeRoot);
}

function synctoggle(link) {
    var imgs = link.parents('li:first').find('img.icon10');
    var src = imgs[0].src;
    if (src.indexOf('plus') > 0) {
        src = src.replace('plus', 'minus');

        var nodeid = link.attr('nodeid');
        var type = link.attr('type');
        var i = guids.indexOf(nodeid);
        if (i < 0) {
            guids.push(nodeid);
            names.push(link.find('span:first').html());
            types.push(type);
        }

        var children = link.parents('li:first').find('li');
        for (var j = 0; j < children.length; j++) {
            var nodeid = children[j].id.replace('node_', '');
            var i = guids.indexOf(nodeid);
            if (i < 0) {
                guids.push(nodeid);
                names.push($('a.link[nodeid=' + nodeid + ']').find('span:first').html());
                types.push($('a.link[nodeid=' + nodeid + ']').attr('type'));
            }
        } 
    }
    else {
        src = src.replace('minus', 'plus');

        var i = guids.indexOf(link.attr('nodeid'));
        if (i >= 0) {
            guids.splice(i, 1);
            names.splice(i, 1);
            types.splice(i, 1);
        }

        var children = link.parents('li:first').find('li');
        for (var j = 0; j < children.length; j++) {
            var i = guids.indexOf(children[j].id.replace('node_', ''));
            if (i >= 0) {
                guids.splice(i, 1);
                names.splice(i, 1);
                types.splice(i, 1);
            }
        } 
    }
    imgs.attr('src', src);
    $('#excludedgroupsguids').val(guids.join(','));
    $('#excludedgroupsnames').val(names.join(','));
    $('#excludedgroupstypes').val(types.join(','));
    return false;
}

function deleteExcludedGroup(id) {
    if (!confirm(AdSync.SureDeleteGroup)) return false;

    $.getJSON('activedirectorysync.ivp/deleteexcludedgroup/' + id, { date: new Date().toString() }, function(result) {
        if (result.hasOwnProperty('IsOK') && result.IsOK == true) {
            $('#group' + result.Id).fadeOut('fast').remove();
            $('#next').attr("disabled", "true");
        }
        else
            alert(result.Description);
    });
    return false;
}

function addExcludedGroup(guid, name, type, profileid) {
    $.getJSON('activedirectorysync.ivp/addexcludedgroup/' + guid, { profileid: profileid, name: name, type: type, date: new Date().toString() }, function(result) {
        if (result.hasOwnProperty('IsOK') && result.IsOK == true) {
            $('#excludedgroups').load(base + 'activedirectorysync.ivp/getexcludedgroups/' + profileid, { date: new Date().toString() }, null);
            $('#next').attr("disabled", "true");
        }
        else
            alert(result.Description);
    });
    return false;
}

function chooseEmployee(guid, profileid) {
    $('#chooseemployee').load(base + 'activedirectorysync.ivp/getaduserinfo/' + guid, { profileid: profileid, date: new Date().toString() }, function() {
        var offset = $('a[nodeid=' + guid + ']').offset();
        $('#chooseemployee').css('top', offset.top - 60).css('left', offset.left).fadeIn('fast');
        $('#chooseemployee').show();
    });
    return false;
}

function toggleADUsers(link, departmentguid, profileid) {
    var departmentemployees = $('#departmentemployees' + departmentguid);
    if (departmentemployees.is(':visible')) {
        departmentemployees.hide('fast');
        link.html(' &darr; ' + AdSync.ShowEmployees);
    }
    else {
        if (departmentemployees.html().length == 0) {
            departmentemployees.load(base + 'activedirectorysync.ivp/loadadusers/' + departmentguid, { profileid: profileid, date: new Date().toString() }, function() {
                departmentemployees.show('fast');
                link.html(' &uarr; ' + AdSync.HideEmployees);
            });
        }
        else {
            departmentemployees.show('fast');
            link.html(' &uarr; ' + AdSync.HideEmployees);
        }
    }
    return false;
}

function selectCompany() {
    dlg = openDialog('company.ivp/selectlist');
    dlg.callback = companiesCallback;
    return false;
}

function companiesCallback(result) {
    var ids = result["selectedIds"];
    var names = result["selectedNames"];
    companySelected(ids, names);
};

function companySelected(ids, names) {
    var id = ids[0];
    var sn = names['id'+id];
    _companySelected(id, sn);
}

function _companySelected(id, name, canRemove) {
    removeCompany();
    $('#companyid').val(id).attr('changed', true);
    var $ag = $('<a/>').addClass('nounderline changed').text(name).attr('href', '#').click(function () { return companyDetails(id); });
    $('#companyholder').append($ag);

    $('#companyholder').removeClass("removed");
}

function removeCompany() {
    $('#companyid').attr('changed', true).val('');
    $('#companyholder').empty();

    return false;
}

function companySelectedFromAutoComplete(e, d) {
    _companySelected(d[1], d[0], $('#readonly').length > 0);
    $('#addCompany').val('');
    return false;
}