
function BTreeNode (px,py,po) {
	this.x = px; this.y = py; this.o = po;
	var sameLevel = new Array();
	sameLevel[0] = this;
	
	var leftNode, rightNode;

	var MySelf = this;

	function bTreeNodeInsert(node) {
		if(node.x == MySelf.x) {
			sameLevel.push(node);
		} else if(node.x < MySelf.x) { // Go Left
			if(leftNode) { leftNode.insert(node); }
			else { leftNode = node; }
		} else { // Go Right
			if(rightNode) { rightNode.insert(node); }
			else { rightNode = node; }
		}
	}

	MySelf.insert = function (node) {
		bTreeNodeInsert(node);
	}
	
	MySelf.searchByRange = function(min,max) {
		return bTreeSearchByRange(min,max);
	}

	MySelf.searchByRange2D = function(minx, miny, maxx, maxy) {
		return bTreeSearchByRange2D(minx,miny,maxx,maxy);
	}

	function bTreeSearchByRange2D(minx,miny,maxx,maxy) {
		var returnArray = new Array();
		var x = MySelf.x;
		var xmin = (x > minx);
		var xmax = (x < maxx);
		if(xmin && xmax) { // X is in in bounds!
			for(var i = 0; i < sameLevel.length; i++) {
				if(sameLevel[i].y > miny && sameLevel[i].y < maxy) {
					returnArray.push(sameLevel[i]);
				}
			}
		}

		// Travel the Tree!
		if(leftNode && (minx < x || maxx < x)) {
			var leftArray = leftNode.searchByRange2D(minx,miny,maxx,maxy);
			if(leftArray) { returnArray = returnArray.concat(leftArray); }
		}
		if(rightNode && (minx > x || maxx > x)) {
			var rightArray = rightNode.searchByRange2D(minx,miny,maxx,maxy);
			if(rightArray) { returnArray = returnArray.concat(rightArray); }
		}
		return returnArray;	
	}

	function bTreeSearchByRange(min,max) {
		var returnArray = new Array();
		var x = MySelf.x;
		var xmin = (x > min);
		var xmax = (x < max);
		if(xmin && xmax) { // X is in in bounds!
			returnArray = sameLevel;
		}

		// Travel the Tree!
		if(leftNode && (min < x || max < x)) {
			var leftArray = leftNode.searchByRange(min,max);
			if(leftArray) { returnArray = returnArray.concat(leftArray); }
		}
		if(rightNode && (min > x || max > x)) {
			var rightArray = rightNode.searchByRange(min,max);
			if(rightArray) { returnArray = returnArray.concat(rightArray); }
		}
		return returnArray;	
	}
}



function BTree () {
	var root = null;
	
	function bTreeInsert(node) {
		if(root) {
			root.insert(node);
		} else {
			root = node;
		}
	}

	this.insert = function(x,y,o) {
		bTreeInsert(new BTreeNode(x,y,o));
	}

	this.searchByRange = function(min,max) {
		if(!root) { alert('B-Tree has no elements to search!'); return null; }
		return root.searchByRange(min,max);
	}
	this.searchByRange2D = function(minx,miny,maxx,maxy) {
		if(!root) { alert('B-Tree has no elements to search!'); return null; }
		return root.searchByRange2D(minx,miny,maxx,maxy);
	}


}
