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 restoreHome() {
	$('#inner-details').html("<p style=\"text-align:center;\"><img src=\"" + $("#jsSpin").attr("src") + "\"  style=\"position:relative;top:4px;\" /> Loading Top News</p>");
            
     /*       
	$.ajax({
	    	url: 'news/fetch_word?word=' + escape('Top News'), 
	    	async: true,
	    	success: function(data) {
	    		//var html = $("<h4>" + node.name + "</h4>");
	    		var html = $("<div/>");
	    		
	    		var news = eval(data);
	    		$.each(news, function(i, object) {
	    			//console.log(object);
					
	    			$el = $("<div><p><a href=\"" + object.link_url + "\">" + object.headline + "</a> (" + object.published + ")</p></div>");
	    			$el.appendTo(html);
	    		});
	    		
	    		//if(html)
	    			$('#inner-details').html(html);
	    	}
	    	});
	    */
	    	
	  //ht.loadJSON(json);
    //compute positions and plot.
    //ht.refresh();
    
    //Very bad, duplicate code
    $.ajax({
    	url: 'news/graph', 
    	async: false,
    	success: function(data) {
			
	  
		  var json = eval(data)[0];
		  
		  var infovis = document.getElementById('infovis');
		  $("#infovis").html('');
		  
		    var w = infovis.offsetWidth - 0, h = infovis.offsetHeight - 0;
		    
		    //init Hypertree
		    var ht = new $jit.Sunburst({
		      //id of the visualization container
		      injectInto: 'infovis',
		      
		      levelDistance: 98,
		      
		      Node: {
	          overridable: true,
	          type: useGradients? 'gradient-multipie' : 'multipie'
	        },
	        	
	        	Label: {
          type: "Native"
        },
        
        		NodeStyles: {
          enable: true,
          type: 'Native',
          stylesClick: {
            'color': '#33dddd'
          },
          stylesHover: {
            'color': '#33dddd'
          }
        },
        //Add tooltips
        Tips: {
          enable: true,
          onShow: function(tip, node) {
            var html = "<div class=\"tip-title\">" + node.name + "</div>"; 
            var data = node.data;
            if("impact" in data) {
              html += "<b>Impact:</b> " + data.impact;
            }
            if("sentiment" in data) {
              html += "<br /><b>Sentiment:</b> " + data.sentiment;
            }
            //html += "<br />(Click to Load)";
            tip.innerHTML = html;
          }
        },
        
        
        
        	//implement event handlers
        Events: {
          enable: true,
          
          
          onClick: function(node) {
            if(!node) return;
            
            
            $('#inner-details').html("<p style=\"text-align:center;\"><img src=\"" + $("#jsSpin").attr("src") + "\"  style=\"position:relative;top:4px;\" /> Loading " + node.name + "</p>");
            
            
            $.ajax({
	    	url: 'news/fetch_word?word=' + escape(node.name), 
	    	async: true,
	    	success: function(data) {
	    		//var html = $("<h4>" + node.name + "</h4>");
	    		var html = $("<div><h3>" + node.name + "</div>");
	    		
	    		var news = eval(data);
	    		$.each(news, function(i, object) {
	    			//console.log(object);
					
	    			$el = $("<div><p><a href=\"" + object.link_url + "\" target=\"_blank\">" + object.headline + "</a> " + object.published + "</p></div>");
	    			$el.appendTo(html);
	    		});
	    		
	    		$('#inner-details').html(html);
	    	}
	    	});
            
            
            
            
            //hide tip
            ht.tips.hide();
            //rotate
            ht.rotate(node, animate? 'animate' : 'replot', {
              duration: 1000,
              transition: $jit.Trans.Quart.easeInOut
            });
          }
        },
        // Only used when Label type is 'HTML' or 'SVG'
        // Add text to the labels. 
        // This method is only triggered on label creation
        onCreateLabel: function(domElement, node){
          var labels = sb.config.Label.type,
              aw = node.getData('angularWidth');
          if (labels === 'HTML' && (node._depth < 2 || aw > 2000)) {
            domElement.innerHTML = node.name;
          } else if (labels === 'SVG' && (node._depth < 2 || aw > 2000)) {
            domElement.firstChild.appendChild(document.createTextNode(node.name));
          }
        },
        // Only used when Label type is 'HTML' or 'SVG'
        // Change node styles when labels are placed
        // or moved.
        onPlaceLabel: function(domElement, node){
          var labels = sb.config.Label.type;
          if (labels === 'SVG') {
            var fch = domElement.firstChild;
            var style = fch.style;
            style.display = '';
            style.cursor = 'pointer';
            style.fontSize = "16px";
            //fch.setAttribute('fill', "#fff");
          } else if (labels === 'HTML') {
            var style = domElement.style;
            style.display = '';
            style.cursor = 'pointer';
            style.fontSize = "16px";
            //style.color = "#ddd";
            var left = parseInt(style.left);
            var w = domElement.offsetWidth;
            style.left = (left - w / 2) + 'px';
          }
          
          
        },
        
        
		      
		      //canvas width and height
		      width: w,
		      height: h
		      
		      //Change node and edge styles such as
		      //color, width and dimensions.
		     
		     /* Node: {
		          dim: 9,
		          color: "#D7EFF5"
		      },
		      Edge: {
		          lineWidth: 1,
		          color: "#E6E6E6"
		      },
		      onBeforeCompute: function(node){
		          //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");
		          
		          
		          
		          //html += "</ul>";
		          
		          
		          
		          
		      },
		      //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 () {
		              ht.onClick(node.id);
		          });
		      },
		      //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 = "0.9em";
		              style.color = "#555";
		              style.fontWeight = "normal";
		
		          } else if(node._depth == 2){
		              style.fontSize = "0.7em";
		              style.color = "#555";
		
		          } else {
		              style.display = 'none';
		          }
		          
		          if(node._depth < 1) {
		          	style.fontSize = "1em";
		              style.fontWeight = "bold";
		          }
		
		          var left = parseInt(style.left);
		          var w = domElement.offsetWidth;
		          style.left = (left - w / 2) + 'px';
		      },
		      
		      onAfterCompute: function(){
		 
		         
		      }*/
		      
		    });
		    //load JSON data.
		    ht.loadJSON(json);
		    //compute positions and plot.
		    ht.refresh();
		    //end
		    ht.controller.onAfterCompute();
		    
		   /* 
		    $.get('news/graph', function(data) {
			 // $('.result').html(data);
			  //alert(data);
			  //alert('Load was performed.');
			  data = eval(data);
			  
				ht.op.sum(data, {  
			        type: 'fade:con',  
			        fps: 30,  
			        duration: 1000,  
			        hideLabels: false,  
			        onComplete: function(){  
			            
			        }  
			    });
			    
			});
		  	*/
		  	
		  	 var node = ht.graph.getClosestNodeToOrigin("current");
		           $.ajax({
			    	url: 'news/fetch_word?word=' + escape("Top News"), 
			    	async: true,
			    	success: function(data) {
			    		var html = $("<div><h3>Top News</h3></div>");
			    		
			    		var news = eval(data);
			    		$.each(news, function(i, object) {
			    			//console.log(object);
			    			$el = $("<div><p><a href=\"" + object.link_url + "\" target=\"_blank\">" + object.headline + "</a> " + object.published + "</p></div>");
			    			$el.appendTo(html);
			    		});
			    		
			    		$('#inner-details').html(html);
			    	}
			    	});
		  
		  
		  
	    }
	});
    
    
    
    
}


$(document).ready(function() {
    //init data
    
    
	$.ajax({
    	url: 'news/graph', 
    	async: false,
		success: function(data) {
			
	  
		  var json = eval(data)[0];
		  
		  var infovis = document.getElementById('infovis');
		    var w = infovis.offsetWidth - 0, h = infovis.offsetHeight - 0;
		    

		   
		    
		    //init Hypertree
			var ht = new $jit.Sunburst({
				injectInto: 'infovis',
				levelDistance: 98,
				Node: {
					overridable: true,
		          	type: useGradients? 'gradient-multipie' : 'multipie'
		        },
	        	Label: {
		          type: "Native"
		        },
        		NodeStyles: {
		        	enable: true,
		        	type: 'Native',
		          	stylesClick: {
		            	'color': '#33dddd'
		          	},
		          	stylesHover: {
		            	'color': '#33dddd'
		          	}
		        },
		        Tips: {
		        	enable: true,
		        	onShow: function(tip, node) {
			            var html = "<div class=\"tip-title\">" + node.name + "</div>"; 
			            var data = node.data;
			            if("impact" in data) {
			              html += "<b>Impact:</b> " + data.impact;
			            }
			            if("sentiment" in data) {
			              html += "<br /><b>Sentiment:</b> " + data.sentiment;
			            }
			            //html += "<br />(Click to Load)";
		            	tip.innerHTML = html;
		          	}
				},
		        Events: {
		        	enable: true,
		          
		          
		          onClick: function(node) {
		            if(!node) return;
		            
		            
		            $('#inner-details').html("<p style=\"text-align:center;\"><img src=\"" + $("#jsSpin").attr("src") + "\"  style=\"position:relative;top:4px;\" /> Loading " + node.name + "</p>");
		            
		            
		            $.ajax({
			    	url: 'news/fetch_word?word=' + escape(node.name), 
			    	async: true,
			    	success: function(data) {
			    		//var html = $("<h4>" + node.name + "</h4>");
			    		var html = $("<div><h3>" + node.name + "</h3></div>");
			    		
			    		var news = eval(data);
			    		$.each(news, function(i, object) {

							
			    			$el = $("<div><p><a href=\"" + object.link_url + "\" target=\"_blank\">" + object.headline + "</a> " + object.published + "</p></div>");
			    			$el.appendTo(html);
			    		});
			    		
			    		$('#inner-details').html(html);
			    	}
			    	});
		            
		            
		            
		            
		            //hide tip
		            ht.tips.hide();
		            //rotate
		            ht.rotate(node, animate? 'animate' : 'replot', {
		              duration: 1000,
		              transition: $jit.Trans.Quart.easeInOut
		            });
		          }
		        },

		        onCreateLabel: function(domElement, node){
		          var labels = sb.config.Label.type,
		              aw = node.getData('angularWidth');
		          if (labels === 'HTML' && (node._depth < 2 || aw > 2000)) {
		            domElement.innerHTML = node.name;
		          } else if (labels === 'SVG' && (node._depth < 2 || aw > 2000)) {
		            domElement.firstChild.appendChild(document.createTextNode(node.name));
		          }
		        },

		        onPlaceLabel: function(domElement, node){
		          var labels = sb.config.Label.type;
		          if (labels === 'SVG') {
		            var fch = domElement.firstChild;
		            var style = fch.style;
		            style.display = '';
		            style.cursor = 'pointer';
		            style.fontSize = "16px";
		            //fch.setAttribute('fill', "#fff");
		          } else if (labels === 'HTML') {
		            var style = domElement.style;
		            style.display = '';
		            style.cursor = 'pointer';
		            style.fontSize = "16px";
		            //style.color = "#ddd";
		            var left = parseInt(style.left);
		            var w = domElement.offsetWidth;
		            style.left = (left - w / 2) + 'px';
		          }
		          
		        }
		    });
		    
		    

		    
		    
		    ht.loadJSON(json);
		    //compute positions and plot.
		    ht.refresh();
		    //end
		    ht.controller.onAfterCompute();

		  	 var node = ht.graph.getClosestNodeToOrigin("current");
		           $.ajax({
			    	url: 'news/fetch_word?word=' + escape("Top News"), 
			    	async: true,
			    	success: function(data) {
			    		var html = $("<div><h3>Top News</h3></div>");
			    		
			    		var news = eval(data);
			    		$.each(news, function(i, object) {
			    			//console.log(object);
			    			$el = $("<div><p><a href=\"" + object.link_url + "\" target=\"_blank\">" + object.headline + "</a> " + object.published + "</p></div>");
			    			$el.appendTo(html);
			    		});
			    		
			    		$('#inner-details').html(html);
			    	}
			    	});
		  
		  
		  
	    }
	});
    
    
    


    //var newGraph = $.get('http://localhost/~Steve/stockpredictor/news/graph');
    //console.log(newGraph);
    
    /*
    ht.op.sum(trueGraph, {  
        type: type,  
        fps: getFPS(),  
        duration: getDuration(),  
        hideLabels: hideLabels(),  
        onComplete: function(){  
            Log.write("sum complete!");  
        }  
    });
    */
    
    
    
});

/*


        "id": "347_0",
        "name": "Nine Inch Nails",
        "children": [{
            "id": "126510_1",
            "name": "Jerome Dillon",
            "data": {
                "band": "Nine Inch Nails",
                "relation": "member of band"
            },
            "children": [{
                "id": "52163_2",
                "name": "Howlin' Maggie",
                "data": {
                    "band": "Jerome Dillon",
                    "relation": "member of band"
                },
                "children": []
            }, {
                "id": "324134_3",
                "name": "nearLY",
                "data": {
                    "band": "Jerome Dillon",
                    "relation": "member of band"
                },
                "children": []
            }]
        }, {
            "id": "173871_4",
            "name": "Charlie Clouser",
            "data": {
                "band": "Nine Inch Nails",
                "relation": "member of band"
            },
            "children": []
        }, {
            "id": "235952_5",
            "name": "James Woolley",
            "data": {
                "band": "Nine Inch Nails",
                "relation": "member of band"
            },
            "children": []
        }, {
            "id": "235951_6",
            "name": "Jeff Ward",
            "data": {
                "band": "Nine Inch Nails",
                "relation": "member of band"
            },
            "children": [{
                "id": "2382_7",
                "name": "Ministry",
                "data": {
                    "band": "Jeff Ward",
                    "relation": "member of band"
                },
                "children": []
            }, {
                "id": "2415_8",
                "name": "Revolting Cocks",
                "data": {
                    "band": "Jeff Ward",
                    "relation": "member of band"
                },
                "children": []
            }, {
                "id": "3963_9",
                "name": "Pigface",
                "data": {
                    "band": "Jeff Ward",
                    "relation": "member of band"
                },
                "children": []
            }, {
                "id": "7848_10",
                "name": "Lard",
                "data": {
                    "band": "Jeff Ward",
                    "relation": "member of band"
                },
                "children": []
            }]
        }, {
            "id": "235950_11",
            "name": "Richard Patrick",
            "data": {
                "band": "Nine Inch Nails",
                "relation": "member of band"
            },
            "children": [{
                "id": "1007_12",
                "name": "Filter",
                "data": {
                    "band": "Richard Patrick",
                    "relation": "member of band"
                },
                "children": []
            }, {
                "id": "327924_13",
                "name": "Army of Anyone",
                "data": {
                    "band": "Richard Patrick",
                    "relation": "member of band"
                },
                "children": []
            }]
        }, {
            "id": "2396_14",
            "name": "Trent Reznor",
            "data": {
                "band": "Nine Inch Nails",
                "relation": "member of band"
            },
            "children": [{
                "id": "3963_15",
                "name": "Pigface",
                "data": {
                    "band": "Trent Reznor",
                    "relation": "member of band"
                },
                "children": []
            }, {
                "id": "32247_16",
                "name": "1000 Homo DJs",
                "data": {
                    "band": "Trent Reznor",
                    "relation": "member of band"
                },
                "children": []
            }, {
                "id": "83761_17",
                "name": "Option 30",
                "data": {
                    "band": "Trent Reznor",
                    "relation": "member of band"
                },
                "children": []
            }, {
                "id": "133257_18",
                "name": "Exotic Birds",
                "data": {
                    "band": "Trent Reznor",
                    "relation": "member of band"
                },
                "children": []
            }]
        }, {
            "id": "36352_19",
            "name": "Chris Vrenna",
            "data": {
                "band": "Nine Inch Nails",
                "relation": "member of band"
            },
            "children": [{
                "id": "1013_20",
                "name": "Stabbing Westward",
                "data": {
                    "band": "Chris Vrenna",
                    "relation": "member of band"
                },
                "children": []
            }, {
                "id": "3963_21",
                "name": "Pigface",
                "data": {
                    "band": "Chris Vrenna",
                    "relation": "member of band"
                },
                "children": []
            }, {
                "id": "5752_22",
                "name": "Jack Off Jill",
                "data": {
                    "band": "Chris Vrenna",
                    "relation": "member of band"
                },
                "children": []
            }, {
                "id": "33602_23",
                "name": "Die Warzau",
                "data": {
                    "band": "Chris Vrenna",
                    "relation": "member of band"
                },
                "children": []
            }, {
                "id": "40485_24",
                "name": "tweaker",
                "data": {
                    "band": "Chris Vrenna",
                    "relation": "is person"
                },
                "children": []
            }, {
                "id": "133257_25",
                "name": "Exotic Birds",
                "data": {
                    "band": "Chris Vrenna",
                    "relation": "member of band"
                },
                "children": []
            }]
        }, {
            "id": "236021_26",
            "name": "Aaron North",
            "data": {
                "band": "Nine Inch Nails",
                "relation": "member of band"
            },
            "children": []
        }, {
            "id": "236024_27",
            "name": "Jeordie White",
            "data": {
                "band": "Nine Inch Nails",
                "relation": "member of band"
            },
            "children": [{
                "id": "909_28",
                "name": "A Perfect Circle",
                "data": {
                    "band": "Jeordie White",
                    "relation": "member of band"
                },
                "children": []
            }, {
                "id": "237377_29",
                "name": "Twiggy Ramirez",
                "data": {
                    "band": "Jeordie White",
                    "relation": "is person"
                },
                "children": []
            }]
        }, {
            "id": "235953_30",
            "name": "Robin Finck",
            "data": {
                "band": "Nine Inch Nails",
                "relation": "member of band"
            },
            "children": [{
                "id": "1440_31",
                "name": "Guns N' Roses",
                "data": {
                    "band": "Robin Finck",
                    "relation": "member of band"
                },
                "children": []
            }]
        }, {
            "id": "235955_32",
            "name": "Danny Lohner",
            "data": {
                "band": "Nine Inch Nails",
                "relation": "member of band"
            },
            "children": [{
                "id": "909_33",
                "name": "A Perfect Circle",
                "data": {
                    "band": "Danny Lohner",
                    "relation": "member of band"
                },
                "children": []
            }, {
                "id": "1695_34",
                "name": "Killing Joke",
                "data": {
                    "band": "Danny Lohner",
                    "relation": "member of band"
                },
                "children": []
            }, {
                "id": "1938_35",
                "name": "Methods of Mayhem",
                "data": {
                    "band": "Danny Lohner",
                    "relation": "member of band"
                },
                "children": []
            }, {
                "id": "5138_36",
                "name": "Skrew",
                "data": {
                    "band": "Danny Lohner",
                    "relation": "member of band"
                },
                "children": []
            }, {
                "id": "53549_37",
                "name": "Angkor Wat",
                "data": {
                    "band": "Danny Lohner",
                    "relation": "member of band"
                },
                "children": []
            }, {
                "id": "113510_38",
                "name": "Puscifer",
                "data": {
                    "band": "Danny Lohner",
                    "relation": "member of band"
                },
                "children": []
            }, {
                "id": "113512_39",
                "name": "Renhold\u00ebr",
                "data": {
                    "band": "Danny Lohner",
                    "relation": "is person"
                },
                "children": []
            }]
        }],
        "data": []
        
        */
