var labelType, useGradients, nativeTextSupport, animate;

(function() {
  var ua = navigator.userAgent,
      iStuff = ua.match(/iPhone/i) || ua.match(/iPad/i),
      typeOfCanvas = typeof HTMLCanvasElement,
      nativeCanvasSupport = (typeOfCanvas == 'object' || typeOfCanvas == 'function'),
      textSupport = nativeCanvasSupport 
        && (typeof document.createElement('canvas').getContext('2d').fillText == 'function');
  //I'm setting this based on the fact that ExCanvas provides text support for IE
  //and that as of today iPhone/iPad current text support is lame
  labelType = (!nativeCanvasSupport || (textSupport && !iStuff))? 'Native' : 'HTML';
  nativeTextSupport = labelType == 'HTML';
  useGradients = nativeCanvasSupport;
  animate = !(iStuff || !nativeCanvasSupport);
})();


var Log = {
  elem: false,
  write: function(text){
    if (!this.elem) 
      this.elem = document.getElementById('log');
    this.elem.innerHTML = text;
    this.elem.style.left = (500 - this.elem.offsetWidth / 2) + 'px';
  }
};

var rgraph=Object();
var rootid= 'root:root'

var glob_taglist = Array();

function init(){
    //init data
var json = {};
if ($('#content-query').length) {
  rootid = $('#content-query').attr('query')
}
else { rootid = 'root:root'; }


    //end
    
    //init RGraph
    rgraph = new $jit.RGraph({
        duration:500,
        levelDistance: 130,
        //Where to append the visualization
        injectInto: 'infovis',
        //Optional: create a background canvas that plots
        //concentric circles.
        background: {
          CanvasStyles: {
            strokeStyle: '#FCC',
            levelDistance:150
          }
        },
        //Add navigation capabilities:
        //zooming by scrolling and panning.
        Navigation: {
          enable: true,
          panning: true,
          zooming: 100
        },
        //Set Node and Edge styles.
        Node: {
            overridable: true,
            color: '#F00',
            type:  'square',
            dim:   5
        },
        
        Edge: {
          color: '#ccc',
          lineWidth:0.5
        },
        Label: {
          type: 'HTML', //Native or HTML
        },

        onBeforeCompute: function(node){
            Log.write("click on " + node.name + "...");
        },
        
        onAfterCompute: function(){
            Log.write("done");
        },
        //Add the name of the node in the correponding label
        //and a click handler to move the graph.
        //This method is called once, on label creation.
        onCreateLabel: function(domElement, node){

            function getMapJson(){
                var taglisturl = '/fnssite/modGetItemsByTag?';
                glob_taglist = node.data.query;
                for (tagid in node.data.query){
                  taglisturl = taglisturl +  'taglist:list='+encodeURI(node.data.query[tagid])+'&';
                }
                $.get(taglisturl, function(data){
                  $('#main-content, #listing-content').delay(200).fadeOut(200, function(){
                    $('#button-listing, #button-content').removeClass('selected');
                    $('#button-listing').addClass('selected');
                    $('#listing-content').html(data).slideDown(1000);
                  });
                });
            }
            domElement.innerHTML = '<span class="nodelabel">'+node.name+'</span>';
            domElement.className = 'node ' + node.data.type;
            if (!node.data.tagcat){            
            domElement.onclick = function(){
                 if (node.data.itemload) {
                   rgraph.onClick(node.id, {onComplete: function(){location.reload();return false;}});
                 } else { getMapJson(); }
 
                //get node ids to be removed.
                var map = [];
                rgraph.graph.eachNode(function(n){
                   if (n.id != node.id) {map.push(n.id);}
                });
                //perform node-removing animation.
                rgraph.onClick(node.id, { 
                        hideLabels:false,
                        onComplete: function() {
                          rgraph.op.removeNode(map.reverse(), {
                            type: 'fade:seq',
                            duration: 100,
                            fps: 30,
                            hideLabels:false,
                            onComplete: function() {
                              $.getJSON('/fnssite/ascrGetTagMapJSON', {tagid:node.id}, function(data) {
                              var trueGraph = data;
                              rgraph.op.morph(trueGraph, {
                                type: 'fade:seq',  
                                fps: 30,  
                                duration: 100,  
                                hideLabels: false,  
                                onComplete: function(){
                                    function appendHistory() {
                                      appendUrl = '/ascr/putHistory?';
                                      for (tagid in node.data.query){
                                        appendUrl = appendUrl + 'query:list='+node.data.query[tagid]+'&';
                                      }
                                      appendUrl = appendUrl + 'node=' + node.id;
                                      $.get(encodeURI(appendUrl), function() {
  									      getHistory();
                                                                              Log.write('history updated');
                                                                            });
                                    }
                                    appendHistory();
                                    Log.write("morph complete!");
                                    rootid=node.id;
                                }  
                              }); 
                              //rgraph.loadJSON(data);
                              //rgraph.refresh();      
                            });
                              
                            }
                          });
                        
                        }
                });

            };
            } // endif
            else {
              domElement.onclick = function(){
                getMapJson();
                rgraph.onClick(node.id);
              }
            }
        //end
        },
        //Change some label dom properties.
        //This method is called each time a label is plotted.
        onPlaceLabel: function(domElement, node){
            var style = domElement.style;
            style.display = '';
            style.cursor = 'pointer';

            if (node._depth < 1) {
                style.fontSize = "11px";
                style.color = "#000";
                style.fontWeight = "bold";
            
            } else if(node._depth == 1){
                style.fontSize = "11px";
                style.color = "#000";
            
            } else {
                style.fontSize = '11px';
                style.color = "#000";
            }

            var left = parseInt(style.left);
            var w = domElement.offsetWidth;
            style.left = (left - w / 2) + 'px';
        }
    });
    //load JSON data
    $.getJSON('/fnssite/ascrGetTagMapJSON',{tagid:rootid}, function(data) {
       rgraph.loadJSON(data);
       rgraph.refresh();
    });
    //end
    //append information about the root relations in the right column
   // $jit.id('inner-details').innerHTML = rgraph.graph.getNode(rgraph.root).id;

}



