/**
 * Adds new assignment after the current one or duplicates it.
 */
window.add_new_assignment = function (type, assignment, append) {
    var clone = assignment.cloneNode(true),
        parent = $(type),
        e,
        location_field = 'C__MODULE__JDISC__OBJECT_TYPE_ASSIGNMENTS__OBJECT_LOCATION',
        jdisc_ajax_url = '[{$jdisc_ajax_url}]';

    if (assignment.nextSibling) {
        e = parent.insertBefore(clone, assignment.nextSibling);
    } else {
        e = parent.appendChild(clone);
    }

    if (append) {
        // Reset fields:
        var nodes = e.childNodes;
        for (i = 1; i < (nodes.length - 2); i += 2) {
            var input = nodes[i].getElementsByTagName('input')[0];
            if (input) {
                if (!input.hasClassName('portFilter')) {
                    input.value = '';
                    if ((!input.hasClassName('jdisc_location')) && (!input.hasClassName('fqdn_addition')))
                    {
                        input.hide();
                    }
                    else if (input.hasClassName('jdisc_location'))
                    {
                        if(nodes[i].down('div'))
                        {
                            // Object browser location
                            location_field = location_field + '[_' + (parseInt(parent.childElementCount) - 1) + ']';

                            nodes[i].down('div').down('div').setAttribute('id', 'div_browser_location');
                            $('div_browser_location').update('');
                            new Ajax.Updater('div_browser_location', jdisc_ajax_url + '&func=location_browser&editMode=1', {
                                evalScripts: true,
                                parameters: {
                                    'field':location_field
                                },
                                onComplete: function() {
                                    $('div_browser_location').removeAttribute('id');
                                }
                            });
                        }
                    }
                }
                else
                {
                    var input_parent = input.parentNode;
                    input.value = '';
                    input.readOnly=true;
                    input.name = input.name.replace(/[0-9]/, parent.childElementCount-1);
                    input.setStyle({'background':'none repeat scroll 0 0 #DDDDDD'});
                    input.next('select').name = input.next('select').name.replace(/[0-9]/, parent.childElementCount-1);

                    input.next('select').on('change', function(){
                        if(this.value == 0)
                        {
                            this.previous('input').readOnly=true;
                            this.previous('input').value='';
                            this.previous('input').setStyle({'background':'none repeat scroll 0 0 #DDDDDD'});
                        }
                        else
                        {
                            this.previous('input').readOnly=false;
                            this.previous('input').setStyle({'background':'none repeat scroll 0 0 #FBFBFB'});
                        }
                    });

                    if(input_parent.next('div') != '')
                    {
                        while(input_parent = input_parent.next('div'))
                        {
                            input_parent.down('input').value = '';
                            input_parent.down('input').name = input_parent.down('input').name.replace(/[0-9]/, parent.childElementCount-1);
                            input_parent.down('select').name = input_parent.down('select').name.replace(/[0-9]/, parent.childElementCount-1);
                        }
                    }
                }
            }
            var select = nodes[i].getElementsByTagName('select')[0];
            if(select) {
                select.options[0].selected = true;
                select.show();
            }
        }
    } else {
        var originalNodes = assignment.childNodes;
        var clonedNodes = e.childNodes;
        for (i = 1; i < (originalNodes.length - 2); i += 2) {
            var select = originalNodes[i].getElementsByTagName('select')[0];

            if(select) {
                var clonedSelect = clonedNodes[i].getElementsByTagName('select')[0];
                for (j = 0; j < select.length; j++) {
                    if (select.options[j].selected == true) {
                        clonedSelect.options[j].selected = true;
                    }
                }
            }
            var input_clone = clonedNodes[i].getElementsByTagName('input')[0];
            var input_original = originalNodes[i].getElementsByTagName('input')[0];
            if (input_clone) {
                if (input_clone.hasClassName('portFilter')) {
                    var input_parent = input_clone.parentNode;
                    var input_parent_original = input_original.parentNode;

                    input_clone.name = input_clone.name.replace(/[0-9]/, parent.childElementCount-1);
                    input_clone.next('select').name = input_clone.next('select').name.replace(/[0-9]/, parent.childElementCount-1);
                    input_clone.next('select').on('change', function(){
                        if(this.value == 0)
                        {
                            this.previous('input').readOnly=true;
                            this.previous('input').value='';
                            this.previous('input').setStyle({'background':'none repeat scroll 0 0 #DDDDDD'});
                        }
                        else
                        {
                            this.previous('input').readOnly=false;
                            this.previous('input').setStyle({'background':'none repeat scroll 0 0 #FBFBFB'});
                        }
                    });

                    if(input_parent.next('div') != '')
                    {
                        while((input_parent = input_parent.next('div')) && (input_parent_original = input_parent_original.next('div')))
                        {
                            input_parent.down('input').name = input_parent.down('input').name.replace(/[0-9]/, parent.childElementCount-1);
                            input_parent.down('select').name = input_parent.down('select').name.replace(/[0-9]/, parent.childElementCount-1);
                            input_parent.down('select').options[input_parent_original.down('select').selectedIndex].selected = true;
                        }
                    }
                }
                else if(input_clone.hasClassName('jdisc_location')) {
                    var location_div = input_clone.up();
                    var location_id = input_clone.next('input').value;
                    location_field = location_field + '[_' + (parseInt(parent.childElementCount) - 1) + ']';
                    location_div.setAttribute('id', 'div_browser_location');
                    $('div_browser_location').update('');
                    new Ajax.Updater('div_browser_location', jdisc_ajax_url + '&func=location_browser&editMode=1', {
                        evalScripts: true,
                        parameters: {
                            'field':location_field,
                            'selected_object': location_id
                        },
                        onComplete: function() {
                            $('div_browser_location').removeAttribute('id');
                        }
                    });
                }
            }
        }
    }

    e.appear({duration:0.3});
};

/**
 * Deletes assignment.
 */
window.delete_assignment = function (type, assignment) {
    var parent = $(type),
        length = parent.parentNode.getElementsByTagName("TR").length;

    if (length > 2) {
        assignment.fade({duration:0.3});
        parent.removeChild(assignment);
    } else {
        var nodes = assignment.childNodes;
        for (i = 1; i < (nodes.length - 2); i += 2) {
            var input = nodes[i].getElementsByTagName('input')[0];
            if (input) {
                if (!input.hasClassName('portFilter')) {
                    input.value = '';
                    input.hide();
                }
            }
            var select = nodes[i].getElementsByTagName('select')[0];
            if(select) {
                select.options[0].selected = true;
                select.show();
            }
        }
    }
    // Refresh tooltips
    $('body').fire('update:tooltips');
};

/**
 * Replaces select field with text field to edit assignment.
 */
window.edit_assignment_field = function (element, setFocus) {
    element.hide();
    var inputField = element.parentNode.getElementsByTagName('input')[0];
    inputField.show();
    if (setFocus) {
        inputField.focus();
    }
};

/**
 * Adds a new filter for ports
 * @param element
 */
window.add_port_condition = function(p_element, p_port_txt, p_port_type_selection, p_hide) {
    var cloned_element = p_element.cloneNode(true),
        input_field = cloned_element.firstElementChild,
        select_field = input_field.next();

    input_field.value = p_port_txt;

    if(p_port_type_selection != null)
        select_field.value = p_port_type_selection;

    if(select_field.value == 0)
    {
        input_field.readOnly=true;
        input_field.value='';
        input_field.setStyle({'background':'none repeat scroll 0 0 #DDDDDD'});
    }
    else
    {
        input_field.readOnly=false;
        input_field.setStyle({'background':'none repeat scroll 0 0 #FBFBFB'});
    }

    select_field.on('change', function(){
        if(this.value == 0)
        {
            this.previous('input').readOnly=true;
            this.previous('input').value='';
            this.previous('input').setStyle({'background':'none repeat scroll 0 0 #DDDDDD'});
        }
        else
        {
            this.previous('input').readOnly=false;
            this.previous('input').setStyle({'background':'none repeat scroll 0 0 #FBFBFB'});
        }
    });

    if(p_hide == true)
        cloned_element.lastElementChild.show();

    p_element.parentNode.insert(cloned_element);
};

/**
 * Removes the selected port filter
 * @param element
 */
window.delete_port_condition = function(element) {
    element.remove();
};

/**
 * Reloads the profile
 * @param p_jdisc_server
 */
window.reload_profile = function(p_jdisc_server) {

    $('switch-server-loader').removeClassName('hide');

    new Ajax.Request('?call=jdisc&ajax=1&func=get_profile_data', {
        method:"post",
        parameters:{
            jdisc_server:p_jdisc_server
        },
        onSuccess: function(transport){
            var json = transport.responseJSON;
            $('switch-server-loader').addClassName('hide');
            if(json.success){
                var option_counters = $H(json.data.options_counters);
                var operating_system = $H(json.data.operating_systems);
                var celements = $A($('object_type_assignments').children);

                /**
                 * reload operating system for each assignment row
                 */
                celements.each(function(ele){
                    var sel_ele = ele.down('select', 1);
                    if (sel_ele) {
                        var cloned_first_ele = sel_ele.options[0].cloneNode();
                        var cloned_second_ele = sel_ele.options[1].cloneNode();
                        var selected_text = sel_ele.options[sel_ele.selectedIndex].text;
                        var index_counter = 0;

                        sel_ele.update(cloned_first_ele).insert(cloned_second_ele);

                        operating_system.each(function(ele1){
                            var is_selected = false;
                            if(ele1.value == selected_text)
                            {
                                is_selected = true;
                            }
                            sel_ele.insert(new Element('option', {value:ele1.key, selected:is_selected}).insert(ele1.value));
                            index_counter++;
                        });
                    }
                });

                /**
                 * update counters
                 */
                option_counters.each(function(ele){
                    $(ele.key).update(ele.value);
                });
            } else {
                idoit.Notify.error(json.message);
            }
        }
    });
}

window.applyColumnSettings = function(columnSettings) {
    for (let key in columnSettings) {
        if (columnSettings[key] == 0) {
            $$('.' + key).invoke('hide');
            continue;
        }
        $$('.' + key).invoke('show');
    }
}
