// detect prefixURL
var prefixURL = (location.pathname.substring(1, 4) == 'cli' ? 'clients' : 'admin');

/* SHARED SELECT: client / cc / company / code ------------------------------ */
var ss_ids = {
    'client': {
        'id_clients': 'id_clients',
        'id_clients_name': 'id_clients_name',
        'id_accounts': 'id_accounts',
        'account': 'account',
        'tz': 'tz',
        'query-id_currencies': 'query-id_currencies',
        'id_currencies': 'id_currencies',
        'id_code_decks': 'id_code_decks',
        'autoinvoice_cdr_output' : 'cdr_output',
        'autoinvoice_cdr_file' : 'cdr_generate',
        'autoinvoice_output'  : 'invoice_output',
        'id_dr_plans': 'id_dr_plans',
        'client_type': 'client_type',
        'id_invoices_templates' : 'id_invoices_templates'
    }, 
    'code': {
        'id_code_decks': 'id_code_decks',
        'code_deck': 'code_deck',
        'code': 'code',
        'code_name': 'code_name',
        'code_country': 'code_country'
    },
    'rate_table': {
        'id_rate_tables' : 'id_rate_tables',
        'rate_tables_name' : 'rate_tables_name'
    },
    'did': {
        'id_dids' : 'id_dids',
        'did' : 'did'
    }
};
var ss_ids_custom = {};

function ss_getIds(type)
{
    var _ss_ids = ss_ids[type];
    if (ss_ids_custom[type] !== undefined) {
        if (ss_ids_custom instanceof Array) {
            _ss_ids = {};
            for(var i = 0; i < ss_ids_custom.length; i++) {
                _ss_ids[ss_ids_custom[i]] = ss_ids[type][ss_ids_custom[i]];
            }
        } else {
            _ss_ids = {};
            for (k in ss_ids_custom[type]) {
                _ss_ids[k] = ss_ids_custom[type][k];
            }
        }

    }

    return _ss_ids;
}
/*
Types are represented as bitmask:
 0001 - clients
 0010 - clients & accounts
 0100 - calling cards
 1000 - resellers
Examples:
 1 - show only clients, 
 5 - show clients and calling cards, 
 7 - show clients+accounts and calling cards
 9 - show resellers and clients
 
 256 - do not show self in resellers list
*/

var tz = '';
function ss_client(types, _ss_ids, qparams)
{
    ss_ids_custom['client'] = _ss_ids;
    if (!types) {
        types = 1;
    }
    tz = $('#query-tz').val()
    winOpen('/'+prefixURL+'/clients/ss_client?types='+types+(qparams ? '&'+qparams : ''), 600, 600);
}

function ss_did(_ss_ids, qparams)
{
    ss_ids_custom['did'] = _ss_ids;
    winOpen('/'+prefixURL+'/dids/ss_did'+(qparams ? '?'+qparams : ''), 600, 600);
}

function ss_rt(types, qparams)
{
    winOpen('/'+prefixURL+'/rate_tables/ss_rt?types='+types+(qparams ? '&'+qparams : ''), 600, 600);
}

function ss_code(id_code_decks, _ss_ids, _q) 
{
    ss_ids_custom['code'] = _ss_ids;
    if (!id_code_decks) {
        id_code_decks = '';
        
        // try to get current code deck
        cd = $('#' + _ss_ids['id_code_decks']);
        if (_ss_ids && _ss_ids['id_code_decks'] !== undefined && cd && !cd.hasClass('x-ignore-code-decks')) {
            id_code_decks = cd.val();
        }
    }
    
    // build url
    var url = '/'+prefixURL+'/code_decks/ss_code?id_code_decks='+id_code_decks;
    
    // add query
    if (_q) {
        url += '&search[_q]='+encodeURIComponent(_q);
    }
    
    winOpen(url, 600, 600);
}
function ss_clear(type, _ss_ids) 
{
    ss_ids_custom[type] = _ss_ids;
    var _ss_ids = ss_getIds(type);

    for (k in _ss_ids) {
        if (k == 'id_dr_plans') continue;
        var el = $('#'+_ss_ids[k]);
        if (!el.length) {
            continue;
        }
        el.val('');
        if (k == 'tz') {
            if(tz.length > 0) {
                $('#query-tz').val(tz);
            } else {
                $('#query-tz').val($('#tz-default').attr('mb:tz-default'));
                $('#tz').val($('#tz-default').attr('mb:tz-default'));
            }
        }
    }
}

function ss_process(type, data)
{
    var _ss_ids = ss_getIds(type);
    
    for (k in _ss_ids) {
        if (data[k] == undefined) {
            data[k] = '';
        }
        var el = $('#'+_ss_ids[k]);
        
        if (!el.length) {
            continue;
        }     

        if (el.is('input[type=text],input[type=hidden],select')) {
            // Decode HTML-encoded strings and assign the result to an element value.
            el.val($('<div/>').html(data[k]).text()).change();
        } else if (el.is('input[type=checkbox]')) {
            el.attr('checked', Boolean(data[k]));
        } else {
            el.text(data[k]);
        }
        el.keyup();
        
    }    
}

/**
 * Handle interface output of code / name inputs
 */
$(function () {
    $('input.x-code,input.x-code-name').each(function () {
        // create container
        var eDiv = $('<div class="x-code-block"/>').css('position', 'relative');
        eDiv.append($(this).clone());
        
        // create search button
        var eButton = $('<div/>').css({
            'display': 'inline-block',
            'position': 'absolute',
            'right': '1px',
            'top': '1px',
            'bottom': '1px',
            'background': '#eef0f2',
            'border-top-right-radius': '3px',
            'border-bottom-right-radius': '3px'
        });
        var eButtonImg = $('<img src="/static/_view/buttons/search-small.png" width="12" height="12" class="op-fade4" />').css({
            'padding': '4px 3px 1px 3px',
            'cursor': 'pointer'
        }).appendTo(eButton);
        eDiv.append(eButton);
        
        $(this).replaceWith(eDiv);
    });
    
    // handle search button
    $(document).on('click', '.x-code-block img', function () {
        var eDiv = $(this).parents('.x-code-block');
        var eField = eDiv.find('input');
        
        var ss_ids = {
            'id_code_decks': eField.attr('x:id_code_decks') ? eField.attr('x:id_code_decks') : 'id_code_decks',
            'code_deck': eField.attr('x:code_deck') ? eField.attr('x:code_deck') : 'code_deck',
            'code': eField.attr('x:code') ? eField.attr('x:code') : (eField.hasClass('x-code') ? eField.attr('id') : 'code'),
            'code_name': eField.attr('x:code_name') ? eField.attr('x:code_name') : (eField.hasClass('x-code-name') ? eField.attr('id') : 'code_name'),
            'code_country': eField.attr('x:code_country') ? eField.attr('x:code_country') : 'code_country'
        };
        
        if (eField.hasClass('x-ignore-previous-input') ) {
        	ss_clear('code_name', ss_ids);
        } 
        
        // get parameters for query        
        var id_code_decks = null;
        if (eField.attr('x:id_code_decks')) {
        	id_code_decks = $('#' + eField.attr('x:id_code_decks')).val();
        }
        
        ss_code(id_code_decks, ss_ids, eField.val() ? eField.val()+'*' : '');
    });
});


/**
 * Handle interface output of client inputs
 */
$(function () {
    $('input.x-client').each(function () {
        // create container
        var eDiv = $('<div class="x-client-block"/>').css('position', 'relative');
        eDiv.append($(this).clone().attr('readonly', 'readonly'));
        
        // create clear button
        var eButton = $('<div/>').css({
            'position': 'absolute',
            'right': '1px',
            'top': '1px',
            'bottom': '1px',
            'background': '#eef0f2',
            'border-top-right-radius': '3px',
            'border-bottom-right-radius': '3px'
        });
        var eButtonImg = $('<img src="/static/_view/buttons/delete-small.png" width="9" height="9" class="op-fade4" />').css({
            'padding': '6px 4px 3px 5px',
            'cursor': 'pointer'
        }).appendTo(eButton);
        eDiv.append(eButton);
        
        $(this).replaceWith(eDiv);
    });
    
    // handle field click
    $(document).on('click', '.x-client-block input', function () {
        var eDiv = $(this).parents('.x-client-block');
        var eField = eDiv.find('input');
        
        // get parameters for query
        var ss_ids = {
            'id_clients': eField.attr('x:id_clients') ? eField.attr('x:id_clients') : 'id_clients',
            'id_accounts': eField.attr('x:id_accounts') ? eField.attr('x:id_accounts') : 'id_accounts',
            'account': eField.attr('x:account') ? eField.attr('x:account') : 'account',
            'id_clients_name': eField.attr('x:client_name') ? eField.attr('x:client_name') : eField.attr('id'),
            'query-id_currencies': eField.attr('x:query-id_currencies') ? eField.attr('x:query-id_currencies') : 'query-id_currencies',
            'id_currencies': eField.attr('x:id_currencies') ? eField.attr('x:id_currencies') : 'id_currencies',
            'tz': eField.attr('x:tz') ? eField.attr('x:tz') : 'tz',
            'cc_serial': eField.attr('x:cc_serial') ? eField.attr('x:cc_serial') : 'cc_serial',
            'id_code_decks': eField.attr('x:id_code_decks') ? eField.attr('x:id_code_decks') : 'id_code_decks',
            'autoinvoice_cdr_output': eField.attr('x:cdr_output') ? eField.attr('x:cdr_output') : 'cdr_output',
            'autoinvoice_cdr_file': eField.attr('x:cdr_generate') ? eField.attr('x:cdr_generate') : 'cdr_generate',
            'autoinvoice_output': eField.attr('x:invoice_output') ? eField.attr('x:invoice_output') : 'invoice_output',
            'id_dr_plans': eField.attr('x:id_dr_plans') ? eField.attr('x:id_dr_plans') : 'id_dr_plans',
            'client_type': eField.attr('x:client_type') ? eField.attr('x:client_type') : 'client_type',
            'id_invoices_templates': eField.attr('x:id_invoices_templates') ? eField.attr('x:id_invoices_templates') : 'id_invoices_templates'
        };
        ss_client(parseInt(eField.attr('x:mode'), 10), ss_ids, eField.attr('x:qparams'))
    });
    
    // handle clear button
    $(document).on('click', '.x-client-block img', function () {
        var eDiv = $(this).parents('.x-client-block');
        var eField = eDiv.find('input');
        
        // get parameters for query
        var ss_ids = {
            'id_clients': eField.attr('x:id_clients') ? eField.attr('x:id_clients') : 'id_clients',
            'id_accounts': eField.attr('x:id_accounts') ? eField.attr('x:id_accounts') : 'id_accounts',
            'account': eField.attr('x:account') ? eField.attr('x:account') : 'account',
            'id_clients_name': eField.attr('x:client_name') ? eField.attr('x:client_name') : eField.attr('id'),
            'query-id_currencies': eField.attr('x:query-id_currencies') ? eField.attr('x:query-id_currencies') : 'query-id_currencies',
            'id_currencies': eField.attr('x:id_currencies') ? eField.attr('x:id_currencies') : 'id_currencies',
            'tz': eField.attr('x:tz') ? eField.attr('x:tz') : 'tz',
            'cc_serial': eField.attr('x:cc_serial') ? eField.attr('x:cc_serial') : 'cc_serial',
            'id_code_decks': eField.attr('x:id_code_decks') ? eField.attr('x:id_code_decks') : 'id_code_decks',
            'autoinvoice_cdr_output': eField.attr('x:cdr_output') ? eField.attr('x:cdr_output') : 'cdr_output',
            'autoinvoice_cdr_file': eField.attr('x:cdr_generate') ? eField.attr('x:cdr_generate') : 'cdr_generate',
            'autoinvoice_output': eField.attr('x:invoice_output') ? eField.attr('x:invoice_output') : 'invoice_output',
            'id_dr_plans': eField.attr('x:id_dr_plans') ? eField.attr('x:id_dr_plans') : 'id_dr_plans',
            'client_type': eField.attr('x:client_type') ? eField.attr('x:client_type') : 'client_type',
            'invoices_templates': eField.attr('x:invoices_templates') ? eField.attr('x:invoices_templates') : 'invoices_templates'
        };
        
        ss_clear('client', ss_ids);
    });
});


/**
 * Handle interface output of did inputs
 */
$(function () {
    $('input.x-did').each(function () {
        // create container
        var eDiv = $('<div class="x-did-block"/>').css('position', 'relative');
        eDiv.append($(this).clone().attr('readonly', 'readonly'));
        
        // create search button
        var eButton = $('<div/>').css({
            'display': 'inline-block',
            'position': 'absolute',
            'right': '1px',
            'top': '1px',
			'bottom': '1px',
            'background': '#eef0f2',
            'border-top-right-radius': '3px',
            'border-bottom-right-radius': '3px'
        });
        var eButtonImg = $('<img src="/static/_view/buttons/search-small.png" width="12" height="12" class="op-fade4" />').css({
            'padding': '4px 3px 1px 3px',
            'cursor': 'pointer'
        }).appendTo(eButton);
        eDiv.append(eButton);
        
        $(this).replaceWith(eDiv);
    });
    
    // handle search button
    $(document).on('click', '.x-did-block input,.x-did-block img', function () {
        var eDiv = $(this).parents('.x-did-block');
        var eField = eDiv.find('input');
        
        // get parameters for query
        var ss_ids = {
            'id_dids': eField.attr('x:id_dids') ? eField.attr('x:id_dids') : 'id_dids',
            'did': eField.attr('x:did') ? eField.attr('x:did') : eField.attr('id')
        };
        
        ss_did(ss_ids, eField.attr('x:qparams'));
    });
});
