$(function()
{
    document.getElementById('submit').addEventListener('click', function(e)
    {
        $.ajaxSettings.async = false;
        query();
        $.ajaxSettings.async = true;
        e.preventDefault();
        if($('#dataform .error').length == $('#dataform .error.hidden').length)
        {
            $('#dataform').submit();
        }
    });

    $('.nav-secondary li[data-id="datasource"]').addClass('active');

    $('#tableTree').tree('collapse');
    $(document).on('click', '.click-name', function()
    {
        var name = $(this).attr('text');
        var val  = $('#dataform #sql').val();
        $('#dataform #sql').val(val + ' ' + name);
    });

    $('#tableTree').on('expand.zui.tree', function(node)
    {
        var tableName = $(node).find('span').attr('table');
        var fields = $(node).find('ul').html();
        if(fields.length != 0) return;
        getTableInfo(tableName, node);
    });

});

function locate(method, params)
{
    var link = createLink('datasource', method, params);
    window.location.href = link;
}

function getTableInfo(table, node)
{
    var sql = 'select * from ' + table + ';';
    $.post(createLink('dataview', 'ajaxQuery'), {sql: sql, sourceID: sourceID}, function(resp)
    {
        resp = JSON.parse(resp);
        if(resp.result == 'success')
        {
            var htmls = [];
            for(var field in resp.columns)
            {
                var type = resp.columns[field];
                htmls.push('<li><p><a class="click-name" text="' + field + '">' + field + '(' + type + ')' + '</a></p></li>');
            }

            $(node).find('ul').empty();
            $(node).find('ul').append(htmls.join(''));
        }
    });
}
