var dlg;
$(function() {
$('#externalconttractors').autocomplete(base + 'task.ivp/findcompanies?sid=' + $('#serviceid').val(), { minChars: 1 }).result(companySelected);
});

function chooseCompany() {
    var url = 'company.ivp/select?tb_custom_mode=externalcontractors&sid=' + $('#serviceid').val();
    var dialog = openDialog(url, 'selectcompanies', { width: 980, height: 650 });
    dialog.callback = companiesCallback;
    return false;
}

function companiesCallback(result) {
    var id = result["selectedIds"][0];
    addSelectedCompanies(id);
}

function addSelectedCompanies(cid) {
    $('#ecid').find("option[value='" + cid + "']").attr("selected", true);
    $('#externalconttractors').val($("#ecid option:selected").text());
    $('#emails').val('').removeAttr('disabled');
    updateUsers();
    updateTemplates();
}

function companySelected(e, d) {
    var id = d[1];
    addSelectedCompanies(id);
}

function updateUsers() {
    $('#executors').empty().load(base + 'task.ivp/addcompanyexecutors', { companyid: $('#ecid').val(), serviceid: $('#serviceid').val() }, function() {
    $('.cb').click(addEmail);
    $('#emails').val($('#useremail').val());
     });
    return false;
}

function addEmail() {
    var $cb = $(this);
    var emailString = $('#emails').val();
    if ($cb.is(':checked')) {
        if (emailString.length > 0)
            emailString += ',';
        emailString += $cb.val();   
    }
    else {
       emailString = emailString.replace($cb.val(), "");
   }
   emailString = emailString.replace(",[^,]+$", ",");
   emailString = emailString.replace(/[,\s]{2,}/, ","); //Removes double or more commas / spaces
   emailString = emailString.replace(/^,*/, ""); //Removes all commas from the beginning
   emailString = emailString.replace(/,*$/, ""); //Removes all commas from the end
    $('#emails').val(emailString);
}

function selectUsers() {
    var url = 'user.ivp/select?reset=true&tb_mode=companyexecutors&tb_serviceid=' + $('#serviceid').val() + '&tb_companyid=' + $('#ecid').val();
    dlg = openDialog(url, 'selectusers', { width: 900, height: 650 });
    dlg.callback = usersCallback;
    return false;
}

function usersCallback(result) {
    var uids = result["selectedIds"];
    var names = result["selectedNames"];
    var emails = result["selectedEmails"];
    addSelected(uids, names, emails);
}

function addSelected(uids, names, emails) {
    uids.forEach(function(i, id) {
        var un = names['id' + id];
        var email = emails['id' + id];
        _addUserToList(id, un, email);
    });
}

function _addUserToList(id, un, email) {
    if (!$('#userids option[value="' + id + '"]').is(':selected')) {
        $('#userids option[value="' + id + '"]').attr('selected',true);
        var html = '<li><input id="uid' + id + '" class="cb" checked="true" type="checkbox" value="' + $.trim(email) + '">' + un + '(' + $.trim(email) + ')</input></li>';
        $('.users').append(html);
        $('#uid' + id).click(addEmail).click().attr('checked', true);
    }
    return false;
}

function updateTemplates() {
    $('#companytemplates').empty().load(base + 'task.ivp/addcompanytemplates', { companyid: $('#ecid').val(), taskid: $('#id').val() }, function() { $('textarea.autogrow').elastic(); $('#templateid').change(changeTemplate); $('#disableemail').click(disableEmail); });
    return false;
}

function changeTemplate() {
    $.getJSON(base + 'task.ivp/changetemplate/' + $('#templateid').val(), { timestamp: new Date().toString() }, function(result) {
        if (result.hasOwnProperty('IsOK') && !result.IsOK)
            alert(result.Description);
        else {
            var subject = result.Subject;
            var message = result.Message;
            subject = subject.replace('%id%', $('#id').val());
            message = message.replace('%description%', $('#description').val());
            message = message.replace('%id%', $('#id').val());
            message = message.replace('%name%', $('#taskname').val());
            $('#subject').val(subject);
            $('#message').val(message);
        }
    });
}

function disableEmail() {
    if (!$(this).is(':checked')) {
        $('label[for="subject"]').removeClass('required');
        $('label[for="message"]').removeClass('required');
        $('label[for="templates"]').removeClass('required');
        $('#templateid').removeClass('required');
        $('#subject').removeClass('required');
        $('#message').removeClass('required');
    }
    else {
        $('label[for="subject"]').addClass('required');
        $('label[for="message"]').addClass('required');
        $('label[for="templates"]').addClass('required');
        $('#templateid').addClass('required');
        $('#subject').addClass('required');
        $('#message').addClass('required');
    }
    $('input[name="fid"]').attr('checked',false).attr('disabled', !$(this).is(':checked'));
    $('input[name="nfid"]').attr('checked', false).attr('disabled', !$(this).is(':checked'));
    $('#templateid').attr('disabled', !$(this).is(':checked'));
    $('#subject').attr('disabled', !$(this).is(':checked'));
    $('#message').attr('disabled', !$(this).is(':checked'));
    $('#filesholder a.button').toggle();
}

function attachFile() {
    var n = $('#addfiles>div').length + 1;
    if ($('#addfiles').find('.changed') == null)
        $('#addfiles').empty();
    $('#addfiles').append('<div class="changed padded5"><input size="50" type="file" id="file' + n + '" name="file' + n + '" /></div>');
    $('input[type="file"]').change(fileSelect);
    return false;
}

function fileSelect() {
    var username =  $.trim($('#userdata>div>a:first').text());
    var n = $('#addfiles>div').length + 1;
    var currentTime = new Date();
    var month = currentTime.getMonth() + 1;
    var day = currentTime.getDate();
    var year = currentTime.getFullYear();

    var date = day + '.' + month + '.' + year;

    var html = '<li id="newfile' + n + '" class="file"><input type="checkbox" checked="true" id="nfid" class="middle" value="' + $(this).val() + '" name="nfid"/><span class="middle">';
    html += '<span class="newfile">' + $(this).val() + '</span><span class="details"> ('+username+', ' + date + ')</span></span></li>';

    $('ul#files').append(html);
    $(this).hide();
}

function closeExternalContractorsForm() {
    document.location.href = base + "task.ivp/view/" + $('#id').val();
}