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 == 'Native';
  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';
  }
};


function iniciar(){
    //init data
    var json = {
   		"id": "id_0",
        "name": "Home",
		"data": {
        	"url": "/"
        },
        "children": [
			 {
            "id": "id_0_4",
            "name": "Notícias",
            "data": {
            	"url": "/noticias/"
            },
            "children": []
        }, {
            "id": "id_0_2",
            "name": "<div style='margin:0 0 0 40px;'>Artigos/<br />Publicações</div>",
            "data": {
            	"url": "/artigos-publicacoes/"
            },
            "children": []
        }, {
            "id": "id_0_5",
            "name": "Eventos",
            "data": {
                "url": "/eventos/"
            },
            "children": []
        }, {
            "id": "id_0_8",
            "name": "Dúvidas <br /> Frequentes",
            "data": {
            	"url": "/duvidas-frequentes/"
            },
            "children": []
        }, {
            "id": "id_0_9",
            "name": "Elsimar Coutinho",
            "data": {
            	"url": "/dr-elsimar-coutinho/"
            },
            "children": []
        }, {
            "id": "id_0_7",
            "name": "Contato",
            "data": {
                "url": "/sac/"
            },
            "children": []
        },{
            "id": "id_0_1",
            "name": "Institucional",
            "data": {
                	"url": "/institucional/"
				},
            "children": [{
                "id": "id_0_1_1",
                "name": "A Fazenda",
                "data": {
                	"url": "/institucional/a-fazenda/"
                },
                "children": []
            }, {
                "id": "id_0_1_2",
                "name": "Estrutura",
                "data": {
                    "url": "/institucional/estrutura/"
                },
                "children": []
            }, {
                "id": "id_0_1_4",
                "name": "Equipe",
                "data": {
                    "url": "/institucional/equipe/"
                },
                "children": []
            }]
        },{
            "id": "id_0_6",
            "name": "Serviços",
            "data": {
				"url": "/servicos/"
				},
            "children": [{
                "id": "id_0_6_1",
                "name": "<div style='padding-left: 40px;'>Aspiração<br />Folicular</div>",
                "data": {
                	"url": "/servicos/aspiracao-folicular/"
                },
                "children": []
            }, {
                "id": "id_0_6_2",
                "name": "<div style='padding-left: 30px;'>Fecundação <br />in Vitro</div>",
                "data": {
                    "url": "/servicos/fecundacao-in-vitro/"
                },
                "children": []
            }, {
                "id": "id_0_6_3",
                "name": "<div style='padding-left: 30px;'>Central <br />de Doadoras</div>",
                "data": {
                    "url": "/servicos/central-de-doadoras/"
                },
                "children": []
            }, {
                "id": "id_0_6_4",
                "name": "Central de Receptoras",
                "data": {
                    "url": "/servicos/central-de-receptoras/"
                },
                "children": []
            },{
                "id": "id_0_6_5",
                "name": "Outras Tecnologias",
                "data": {
                    "url": "/servicos/outras-tecnologias-disponiveis/"
                },
                "children": []
            },{
                "id": "id_0_6_6",
                "name": "<div style='margin-top:-20px;'>Prenhez Completa</div>",
                "data": {
                    "url": "/servicos/prenhez-completa/"
                },
                "children": []
            },{
                "id": "id_0_6_7",
                "name": "Genética <br /> Elsimar Coutinho",
                "data": {
                    "url": "/servicos/genetica-elsimar-coutinho/"
                },
                "children": []
            }]
        }]
    };
    //end
    var infovis = document.getElementById('infovis');
    var w = infovis.offsetWidth - 50, h = infovis.offsetHeight - 50;
    
    //init Hypertree
    var ht = new $jit.Hypertree({
      //id of the visualization container
      injectInto: 'infovis',
      //canvas width and height
      width: w,
      height: h,
      //Change node and edge styles such as
      //color, width and dimensions.
      Node: {
          dim: 5,
          color: "#c22f33",
          lineWidth: .5
      },
      Edge: {
          lineWidth: .5,
          color: "#dd9fa3"
      },
      duration:500,
     transition: $jit.Trans.Back.easeOut, 
      
      onBeforeCompute: function(node){
         // Log.write("centering");
      },
      //Attach event handlers and add text to the
      //labels. This method is only triggered on label
      //creation
      onCreateLabel: function(domElement, node){
          domElement.innerHTML = node.name;
          $jit.util.addEvent(domElement, 'click', function () {
          	  
          	jQuery('#infovis-label').find('.active').removeClass('active');
          	jQuery('#' + node.id).addClass('active');
          	
          	loadHistory(node.data.url);// carregando conteudo via ajax
          	
          	/*if(node.data.url == undefined){
          		ht.onClick(node.id);
          		jQuery('#bg').animate({left: "-400px"}, "slow");
          		jQuery('#bois').animate({left: "-800px"}, "slow");
      		} else {
      		
      		}*/
				if(node.data.url == "/"){
					ht.onClick(node.id);
					//jQuery('#bg').animate({left: "-10px"}, "slow");
         			//jQuery('#bois').animate({left: "-400px"}, "slow");
  				 } else{
					ht.onClick(node.id.substring(0,6));
					//jQuery('#bg').animate({left: "-800px"}, "slow");
					//jQuery('#bois').animate({left: "-1200px"}, "slow");
  				 }
          });

      },
      //Change node styles when labels are placed
      //or moved.
      onPlaceLabel: function(domElement, node){
          var style = domElement.style;
          style.display = '';
          style.cursor = 'pointer';
          if (node._depth <= 1) {
              style.fontSize = "12px";
              style.color = "#c22f33";
              style.fontWeight = "bold"

          } else if(node._depth == 2){
              style.fontSize = "0.5em";
              style.color = "#ccc";
              //style.display = 'none';

          } else {
              style.display = 'none';
          }

          var left = parseInt(style.left);
          var w = domElement.offsetWidth;
          style.left = (left - w / 2) + 'px';
      },
      
      onAfterCompute: function(){
         /* Log.write("done");          
          //Build the right column relations list.
          //This is done by collecting the information (stored in the data property) 
          //for all the nodes adjacent to the centered node.
          var node = ht.graph.getClosestNodeToOrigin("current");
          var html = "<h4>" + node.name + "</h4><b>Info:</b>";
          html += "<ul>";
          node.eachAdjacency(function(adj){
              var child = adj.nodeTo;
              if (node.data) {
                  var rel = node.data.url;
                  html += "<li>" + node.name + " " + "<div class=\"relation\">(link: " + rel + ")</div></li>";
              }
          });
          html += "</ul>";
          $jit.id('inner-details').innerHTML = html;
          */
      }
         
    });
    //load JSON data.
    ht.loadJSON(json);
    //compute positions and plot.
    ht.refresh();
    //end
    ht.controller.onAfterCompute();
}
