var Log = {
	elem: $('log'),
	write: function(text) {
		if(!this.elem) this.elem = $('log');
		this.elem.set('html', text);
	}
};
var canvas;
function init() {
	if (canvas) {
		canvas.clear();
		$('mycanvas-label').innerHTML = '';
	}
	Infovis.initLayout();
      var infovis = $('infovis');
      var w = infovis.offsetWidth, h = infovis.offsetHeight;
      var fStyle, sStyle, lineWidth;
	  var json= Feeder.makeTree();
      canvas = new Canvas('mycanvas', {
		'injectInto':'infovis',
		'width':w,
        'height':h,
        'backgroundColor': '#999999',
        'styles': {
            'fillStyle': '#EEEEEE',
            'strokeStyle': '#FF0000'
        }   
      });
	  if ($('orientation1').checked) var orientation = $('orientation1').value;
	  if ($('orientation2').checked) var orientation = $('orientation2').value;
	  if ($('orientation3').checked) var orientation = $('orientation3').value;
	  if ($('orientation4').checked) var orientation = $('orientation4').value;
	  if (orientation == '') orientation = 'left';
	  Config.orientation = orientation;
	  Config.levelsToShow = 1;
	  Config.Label.realWidth = 150;
	  Config.Label.width = 155;
	  var st= new ST(canvas, {
		onBeforeCompute: function(node) {
				Log.write("<img src='css/ajax-loader.gif' />&nbsp;&nbsp;&nbsp;Loading " + node.name);
		},
		
		onAfterCompute: function() {
			var Tips3 = new Tips($$('.node'), {
				className: 'custom_tip'
			});
			Log.write("Done");
		},
			
		request: function(nodeId, level, onComplete) {
			Feeder.request(nodeId, level, onComplete);
		},
        onCreateLabel: function(label, node) {
            var d = $(label);
            label.id = node.id;
            d.setStyle('cursor', 'pointer').set('html', node.name)
			 .addEvent('click', function() {
                st.onClick(d.id);
            });
			if (node.data.length > 0 && node.data[0].title) {
				d.title = node.data[0].title;
			}
        },
        onBeforePlotNode: function(node) {
            var ctx = canvas.getCtx();
            fStyle = ctx.fillStyle;
            sStyle = ctx.strokeStyle;
            if(node.selected) {
                ctx.fillStyle = "#FFFFFF";
                ctx.strokeStyle = "#FFFFFF";
            }
        },
        onAfterPlotNode: function(node) {
            var ctx = canvas.getCtx();
            ctx.fillStyle = fStyle;
            ctx.strokeStyle = sStyle;
        },
        onBeforePlotLine: function(adj) {
            var ctx = canvas.getCtx();
            lineWidth = ctx.lineWidth;
            sStyle = ctx.strokeStyle;
            if(adj.nodeFrom.selected && adj.nodeTo.selected) {
                ctx.strokeStyle = "#FF0000";
                ctx.lineWidth = 2;
            }
        },
        onAfterPlotLine: function(adj) {
            var ctx = canvas.getCtx();
            ctx.lineWidth = lineWidth;
            ctx.stroleStyle = sStyle;
        }

	  });
	  st.loadFromJSON(json);
	  st.compute();
	  Tree.Geometry.translate(st.tree, new Complex(-200, 0), "startPos");
	  st.onClick(st.tree.id);
	  
}

function getInlinksData(url) {
	if ($('res1').checked) var max = $('res1').value;
	if ($('res2').checked) var max = $('res2').value;
	if ($('res3').checked) var max = $('res3').value;
	if (max == '') max = '5';

	var req = new Request({
		method: 'get',
		url: '/libraries/links-tree/fetch.php?url=' + url + '&max=' + max,
		dataType: 'jsonp',
		async: false,
		onRequest: function() {
			//
		},
		onComplete: function(response) {
			resultsObj = eval('(' + response + ')');
			return resultsObj;
		}
	}).send();
	resultsObj = eval('(' + req.response.text + ')');
	return resultsObj;

}

var Feeder = {
	counter:0,
	
	p: {
		idPrefix: "node",
		levelStart: 0,
		levelEnd: 3,
		maxChildrenPerNode: 5,
		counter: 0
	},
	
	makeTree: function () {
		var le = this.p.levelEnd;
		if(le == 0) return {children: []};
		this.counter = 1;
		return this.makeTreeWithParameters(this.p.idPrefix,
										   this.p.levelStart,
										   this.p.levelEnd, 
										   this.p.maxChildrenPerNode);
	},
	
	makeTreeWithParameters: function(idPrefix, levelStart, levelEnd, maxChildrenPerNode) {
		if(levelStart == levelEnd) return null;
		this.counter++;
		if (levelStart == 0) {
			var mainUrl = adjustUrl($('url').value);
			var ans = {
				id:   idPrefix + levelStart + "_" + mainUrl,
				name: mainUrl,
				data: [
					
				],
				children: []
			};
		}
		
		var ind1 = idPrefix.lastIndexOf('_');
		if (ind1 < 0) {
			var urlToPass = $('url').value;
		} else {
			var urlToPass = idPrefix.substring(ind1 + 1);
		}
		var resultsObj = getInlinksData(urlToPass);

		if (resultsObj.ResultSet) {
			var childCount = resultsObj.ResultSet.totalResultsReturned;
			levelStart++;

			if (childCount > 1) {
				for(var i=0; i<childCount; i++) {
					var url = adjustUrl(resultsObj.ResultSet.Result[i].Url);
					ans.children[i] = {
						id:   idPrefix + levelStart + "" + i + "_" + url,
						name: url,
						data: [
							{'title' : resultsObj.ResultSet.Result[i].Title}
						],
						children: []
					};
				}
			} else if (childCount == 1) {
				var url = adjustUrl(resultsObj.ResultSet.Result.Url);
				ans.children[0] = {
					id:   idPrefix + levelStart + "" + i + "_" + url,
					name: url,
					data: [
						{'title' : resultsObj.ResultSet.Result.Title}
					],
					children: []
				};
			}
		} else {		
			ans.children = {};
		}
		return ans;

   },
  
   request: function (nodeId, level, onComplete) {
   		this.p.idPrefix = nodeId;
   		this.p.levelEnd = level + 1;
   		var json = this.makeTree();
		if (json != '') {
			onComplete.onComplete(nodeId, json);
		}
   }
};

function adjustUrl(urlString) {
	urlString = urlString.replace ('http://www.', '');
	urlString = urlString.replace ('https://www.', '');
	urlString = urlString.replace ('http://', '');
	urlString = urlString.replace ('www.', '');
	var ind = urlString.indexOf('/');
	if (ind < 0) ind = urlString.indexOf('?');
	if (ind >= 0) {
		ret_url = urlString.substring(0, ind);
	} else {
		ret_url = urlString;
	}
	return ret_url;
}