$(document).ready(function() {
    var treeStack=[];
    function getClassName(path) {
        var a = path.split('.');
        return a[a.length-1];
    }
    function escapeHTML(s) {
        if (typeof(s)==typeof('string'))
            return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
        else
            return s;
    }
    function loadChartImage(zoom)
    {
        if($(this)._loading) return;
        $(this)._loading=true;
        $('#loader').addClass('loading').
        zoom = typeof(zoom) != 'undefined' ? zoom: scaleFactor;
        $('#chartimage').remove();
        var img = new Image();
        $(img).load(function (response, status, xhr) {
            $(this).hide();
            $('#loader').removeClass('loading').append(this);
            $(this).fadeIn();
            $('#chart-tools').css('display', 'block');
        })
        .error(function (event) {
            alert('due to chart errors, the chart image could not be retrived from the server');
        })
        .attr('id', 'chartimage')
        .attr('src', '/chartgallery/api/image/'+gallery+'/'+chart+'?scale='+zoom+'&format='+format);
        $(this)._loading=false;
    }
    function sortedkeys(item) {
        var keys = [];
        for (var k in item)
            keys.push(k);
        keys.sort();
        return keys;
    }
    function expandChartAttrs(item) {
        var l = "",K=sortedkeys(item),i,k;
        for(i=0;i<K.length;i++){
            k=K[i];
            var expandable = false;
            if (k.indexOf('_')==0) continue;
            if (item[k] && item[k]['__expandable__']) {
                vString = item[k]['__class__'];
                vString = getClassName(vString);
                expandable = true;
            }
            else {
                vString = item[k];
                if (vString instanceof Array)
                    //vString = JSON.stringify(vString, null, '&nbsp;');
                    vString = dump(vString);
            }
            var helpMsg = item['__help__'][k];
            l = l + "<tr "+(helpMsg?" title='"+helpMsg+"'":"")+"><td class='py-key' name='"+escapeHTML(k)+"'>"+(expandable?"<a>"+k+"</a>":k)+"</td><td class='py-val'>"+escapeHTML(vString)+"</td></tr>";
        }
        var bc="";
        var i=treeStack.length;
        for(var b in treeStack)
            bc = bc + '<a name="'+i--+'" title="'+escapeHTML(treeStack[b].__class__) +'">'+getClassName(treeStack[b].__class__) +'</a>'+' &raquo; ';
        $('#content-related').html('<p id="breadcrumbs">'+bc+'</p>'+'<div id="chart-attrs-container"><table id="chart-attrs" class="zebra">'+l+'</table></div>');
        $('#chart-attrs td a').click( function() {
            name = $(this).parent().attr('name');
            obj = treeStack[treeStack.length-1][name];
            if (obj.hasOwnProperty('__expandable__')){
                treeStack.push(obj);
                expandChartAttrs(obj);
            }
        });
        $('#breadcrumbs a').click( function() {
            depth = $(this).attr('name');
            depth = parseInt(depth);
            for(var i=0; i<depth; i++)
            obj = treeStack.pop();
            treeStack.push(obj);
            expandChartAttrs(obj);
        });
    }
    function loadChartAttrs() {
        $.getJSON('/chartgallery/api/'+gallery+'/'+chart, function(data) {
            treeStack=[data];
            expandChartAttrs(data);
        });
    }
    loadChartImage(scaleFactor);
    loadChartAttrs();
    $('#chart-tools a').click(function() {
        $('#chart-tools').css('display','none')
        but = $(this).attr('id');
        if (but == 'zoom-in')
            {currentZoom = currentZoom+1;}
        else if (but == 'zoom-out')
            {currentZoom = currentZoom/2;}
        else
            {currentZoom=scaleFactor;}
        loadChartImage(currentZoom);
    });
});
