var taskExternalContractorsDialog = {
    dlg: undefined,

    init: function () {
        this.cacheElements();
    },

    cacheElements: function () {
        this.$formbody = $('#content .formbody');
        this.$formbottom = $('#content .formbottom');
        this.$shadowbg = $('#content .shadowbg');       
        this.taskId = $('#id').val();
        this.$workflow = $('#workflowid');
        this.getStatus = function () { return $('#statusid'); };
        this.serviceId = $('#serviceid').val();
        this.companyId = undefined;       
    },

    cacheElementsAfterShowDialog: function () {
        taskExternalContractorsDialog.$addExternalCompanyExecutors = $('.js-add-external-company-executors');
        taskExternalContractorsDialog.$companyId = $('input[name="ExternalContractors.CompanyId"]');
        taskExternalContractorsDialog.$companyAutocomplete = $('.js-choose-external-company-autocomplete');
        taskExternalContractorsDialog.$externalCompanyExecutors = $('.external-company-executors');
        taskExternalContractorsDialog.$externalCompanyExecutorAutocomplete = $('.js-add-external-company-executor');
        taskExternalContractorsDialog.$chooseExternalCompany = $('.js-choose-external-company');
        taskExternalContractorsDialog.$chooseExternalCompanyAutocomplete = $('input.js-choose-external-company-autocomplete');
        taskExternalContractorsDialog.$executorUl = taskExternalContractorsDialog.$externalCompanyExecutors.find('ul');
    },
    
    bindEventsAfterShowDialog: function () {
        taskExternalContractorsDialog.$chooseExternalCompany.off('click').on('click', function () {
            var url = 'company.ivp/select?cbmode=taskExternalContractorsDialog&tb_custom_mode=externalcontractors&sid=' + taskExternalContractorsDialog.serviceId;
            taskExternalContractorsDialog.dlg = openDialog(url, 'selectcompanies', { width: 980, height: 650 });
            taskExternalContractorsDialog.dlg.callback = taskExternalContractorsDialog.companiesCallback;

            return false;
        });
               
        taskExternalContractorsDialog.$chooseExternalCompanyAutocomplete.devbridgeAutocomplete({
            serviceUrl: 'Task/FindExternalCompanies/' + taskExternalContractorsDialog.serviceId,
            minChars: 1,
            autoClearInputOnSelect: true,
            onSelect: function (suggestion) {
                var companyName = suggestion.value;
                var companyId = suggestion.data.id;
                taskExternalContractorsDialog.setExternalCompany(companyId, companyName);
            }
        });

    },
    
    chooseExternalCompanies:function(companyId, companyName) {
        taskExternalContractorsDialog.setExternalCompany(companyId, companyName);
    },    

    setExternalCompany: function (companyId, companyName) {
        taskExternalContractorsDialog.companyId = companyId;

        taskExternalContractorsDialog.$companyAutocomplete.val(companyName);

        taskExternalContractorsDialog.$companyId.val(companyId);

        taskExternalContractorsDialog.$externalCompanyExecutors.show();

        taskExternalContractorsDialog.clearExecutors();
        
        taskExternalContractorsDialog.$externalCompanyExecutorAutocomplete.devbridgeAutocomplete({
            serviceUrl: 'Task/FindExternalExecutors/' + taskExternalContractorsDialog.serviceId,
            minChars: 1,
            params: { companyId: taskExternalContractorsDialog.companyId },
            autoClearInputOnSelect: true,
            onSelect: function (suggestion) {
                var userName = suggestion.value;
                var userEmail = suggestion.data.email;
                var userId = suggestion.data.id;                
                taskExternalContractorsDialog.addExecutor(userId, userName, userEmail);
                var exeturnsNamesSB = taskExternalContractorsDialog.addInputExecutroAfterComplite(userId, userName);
                $(this).val(exeturnsNamesSB);
            }
        });

        taskExternalContractorsDialog.$addExternalCompanyExecutors.off('click').on('click', function () {

            var url = 'user.ivp/select?cbmode=taskExternalContractorsDialog&reset=true&tb_mode=companyexecutors&tb_serviceid=' + taskExternalContractorsDialog.serviceId + '&tb_companyid=' + taskExternalContractorsDialog.companyId;
            taskExternalContractorsDialog.dlg = openDialog(url, 'selectusers', { width: 900, height: 650 });
            taskExternalContractorsDialog.dlg.callback = taskExternalContractorsDialog.usersCallback;

            return false;
        });

        $.get('Task/GetExternalCompanyTemplate', { companyId: companyId }, function (html) {
            $('.js-external-template').html(html);

            $('#notifyByEmail').on('change', taskExternalContractorsDialog.notifyByEmail);

            $('.js-ec-add-file').on('click', taskExternalContractorsDialog.addFile);
            
            $('.js-external-template').find('textarea.autogrow').elastic();            

        });
    },
    addInputExecutroAfterComplite:function(executorId,executroName){
        var $ar = $('.js-change-external-conpany-executors');
        var inputNameArr = new Array();
        inputNameArr.push(executroName);
        $ar.each(function (i, v) {
            var userId = v.getAttribute('data-id');
            if (userId != executorId) {
                if ($(v).prop('checked'))
                    inputNameArr.push(v.getAttribute('data-user-name'));
            }        
        })
        var i = 1;
        var sb = '';
        var count = inputNameArr.length;
        $.each(inputNameArr, function (index, val) {
            if (i == count)
                sb += val;
            else
                sb += val + ', ';
            i++;
        });
       return sb;
    },
    addExecutors: function (ids, names, emails) {
        if (ids) {
            var sb = '';
            var i=1;
            var count = ids.length;
            $.each(ids, function (index, id) {
                var userName = names['id' + id];
                var userEmail = emails['id' + id];
                if (i == count)                 
                    sb += userName;      
                else
                   sb += userName + ', ';             
                taskExternalContractorsDialog.addExecutor($.trim(id), $.trim(userName), $.trim(userEmail));
                i++;
            });
            taskExternalContractorsDialog.appendExecutorName(sb);
        }
    },
    
    addExecutor: function (userId, userName, userEmail) {
        var $element = $('input[data-id="' + userId + '"]');
        
        if (!$element.length) {
            taskExternalContractorsDialog.$executorUl.append(taskExternalContractorsDialog.getLiTemplate(userId, userName, userEmail));
            taskExternalContractorsDialog.setSelectedEmails();           
        }        
    },
    
    clearExecutors:function() {
        taskExternalContractorsDialog.$executorUl.empty();
    },
    appendExecutorName: function (s) {        
        $('#inputCompanyNameId').val(s);

    },
    
    changeExecutor: function(e) {
        taskExternalContractorsDialog.setSelectedEmails();
    },
    
    getSelectedEmails: function () {
        var value = '';       
        $('input.js-change-external-conpany-executors:checked').each(function () {
            var $element = $(this);
            
            if (value) {
                value = value + ', ' + $element.data('email');
            } else {
                value = value + $element.data('email');
            }
        });
        return value;
    },

    getSelectedNames: function () {
        var value = '';
        $('input.js-change-external-conpany-executors:checked').each(function () {
            var $element = $(this);

            if (value) {
                value = value + ', ' + $element.data('user-name');
            } else {
                value = value + $element.data('user-name');
            }
        });
        return value;
      
    },
    
    setSelectedEmails:function() {
        var emails = taskExternalContractorsDialog.getSelectedEmails();
        var names = taskExternalContractorsDialog.getSelectedNames();
        $('#inputCompanyNameId').val(names);
        $('#ExternalContractors_Emails').val(emails);
    },
    
    getLiTemplate: function (userId, userName,userEmail) {

        var template = '<li><label><input data-user-name="' + userName + '" data-email="' + userEmail + '" type="checkbox" class="cb js-change-external-conpany-executors" checked="checked" data-id="' + userId + '" /><input class="hidden" name="ExternalContractors.ExecutorFromEmailId" value="' + userId + '">' + userName + ' (' + userEmail + ')</label></li>';
        
        return $(template);
    },

    validate: function () {
        return true;
    },

    close: function () {
        $('#external-contractors-dialog').remove();

        taskExternalContractorsDialog.$formbody.show();
        taskExternalContractorsDialog.$formbottom.show();

        var $removedStatusId = $('#removedStatusId');

        if ($removedStatusId.length > 0) {
            taskExternalContractorsDialog.getStatus().remove();
            $removedStatusId.attr('id', 'statusid').attr('name', 'statusid').removeAttr('disabled');
        }

        $('.save,.saveandreturn').attr('disabled', false);               
        
        $('body').trigger('closeExternalContractorsDialog');
    },
    
    notifyByEmail:function(e) {
        var $self = $(e.target);
        var $subject = $('#ExternalContractors_Subject');
        var $message = $('#ExternalContractors_Message');
        var $files = $('.js-external-contractors-files input');
        var $addfile = $('.js-ec-add-file');
        
        if ($self.is(':checked')) {
            $subject.removeAttr('disabled').addClass('required');
            $message.removeAttr('disabled').addClass('required');
            $files.removeAttr('disabled');
            $addfile.on('click', taskExternalContractorsDialog.addFile);
            
        } else {
            $subject.attr('disabled', 'disabled').removeClass('required');
            $message.attr('disabled', 'disabled').removeClass('required');
            $files.attr('disabled', 'disabled');
            $addfile.off('click');
        }
    },
    
    addFile:function() {
        var $filesWrap = $('.js-external-contractors-files');
        $filesWrap.append(taskExternalContractorsDialog.getFileTemplate());
    },
    
    getFileTemplate:function() {
        return $('<div class="changed padded5"><input type="file" name="ExternalContractors.Files" size="50" class="valid"></div>');
    },

    showExternalContractorsDialog: function () {        
        $.get('Task/GetExternalContractorsDialog', function (html) {
            taskExternalContractorsDialog.$formbody.hide();
            taskExternalContractorsDialog.$formbottom.hide();

            var $externalContractorsDialog = $('<div id="external-contractors-dialog"></div>');
            taskExternalContractorsDialog.$shadowbg.append($externalContractorsDialog);

            $externalContractorsDialog.append(html);
            
            taskExternalContractorsDialog.cacheElementsAfterShowDialog();

            taskExternalContractorsDialog.bindEventsAfterShowDialog();

        });
    },

    //#endregion

    usersCallback: function usersCallback(result) {
        var ids = result["selectedIds"];
        var names = result["selectedNames"];
        var emails = result["selectedEmails"];
        taskExternalContractorsDialog.addExecutors(ids, names, emails);      
    },

    companiesCallback: function companiesCallback(result) {
        var id = result["selectedIds"][0];
        var name = result["selectedNames"]['id'+id];
        taskExternalContractorsDialog.chooseExternalCompanies(id, name); 
    }
};

jQuery(function($) {
    taskExternalContractorsDialog.init();
    $('body').on('showExternalContractorsDialog', taskExternalContractorsDialog.showExternalContractorsDialog);
    $('body').on('change', '.js-change-external-conpany-executors', taskExternalContractorsDialog.changeExecutor);
    $('body').on('click', '.js-close-external-contractors-dialog', taskExternalContractorsDialog.close);
});