﻿function MireoRouter(div, geoAddressDrawer, routeDrawer, infoWindow){
	this.routeDrawer = routeDrawer;
	this.geoAddressDrawer = geoAddressDrawer;
	var mainTable = document.createElement("table");
	div.appendChild(mainTable);
	mainTable.id = "_headerRouterTable";
	mainTable.cellSpacing="0";
	mainTable.cellPadding="0";
	mainTable.style.width = "100%";
	mainTable.style.cssText = "width:100%;position:absolute";
	
	var tblHead = document.createElement('THEAD');
	mainTable.appendChild(tblHead);
	var captRow = tblHead.insertRow(-1);
	captRow.style.cssText = "width:100%";
	var caption = captRow.insertCell(-1);
	caption.vAlign = "top";
	caption.style.cssText = "border:1px solid rgb(192, 192, 192); font-family:Arial, Helvetica, Verdana; font-size:14px; padding:0.2em; background-color:rgb(0,128,174);color:white; height:1.4em;width:100%";
	caption.innerHTML = "Router";
	
	var inputRow = tblHead.insertRow(-1);
	
	var tBar = inputRow.insertCell(-1);
	tBar.style.cssText = "border-bottom:1px solid rgb(192,192,192);padding:0px;";
	
	var tBarTable = document.createElement("table");
	tBarTable.style.cssText = "width:100%;height:100%;";
	tBar.appendChild(tBarTable);
	
	var tBarRow = tBarTable.insertRow(-1);
	
	var calcCmd = tBarRow.insertCell(-1);
	calcCmd.style.cssText = 'width:22px;height:22px;border:1px solid white;background-color:white;text-align:center;padding:2px;cursor:pointer';
	var calculateDiv = ElementCreator.createImageRelative('search/images/calculate.png', 22, 22, true);
	calculateDiv.title = 'Calculate';
	calcCmd.appendChild(calculateDiv);
	
	var clearCmd = tBarRow.insertCell(-1);
	clearCmd.style.cssText = 'width:22px;height:22px;border:1px solid white;background-color:white;text-align:center;padding:2px;cursor:pointer';
	var clearDiv = ElementCreator.createImageRelative('search/images/clear.png', 22, 22, true);
	clearDiv.title = 'Clear';
	clearCmd.appendChild(clearDiv);
	tBarRow.insertCell(-1); // falsch cell
	
	calcCmd.onmouseout = function(){ calcCmd.style.backgroundColor = 'white'; calcCmd.style.borderColor = 'white'};
	calcCmd.onmouseover = function(){ calcCmd.style.backgroundColor = '#C1D2EE'; calcCmd.style.borderColor = '#316AC5'};
	calcCmd.onmousedown = function(){ calcCmd.style.backgroundColor = '#98B5E2'; calcCmd.style.borderColor = '#316AC5'};

	clearCmd.onmouseout = function(){ clearCmd.style.backgroundColor = 'white'; clearCmd.style.borderColor = 'white'};
	clearCmd.onmouseover = function(){ clearCmd.style.backgroundColor = '#C1D2EE'; clearCmd.style.borderColor = '#316AC5'};
	clearCmd.onmousedown = function(){ clearCmd.style.backgroundColor = '#98B5E2'; clearCmd.style.borderColor = '#316AC5'};
	
	var rLength = mainTable.insertRow(-1).insertCell(-1);
	rLength.id = '_rLengthCell';
	rLength.style.cssText = 'font-family: Arial, Helvetica, Verdana; font-size:12px;padding-top:0.3em;';
//	rLength.innerHTML = "<font color='gray'>Route length: </font><b>234.56 km</b>";
	rLength.innerHTML = "&nbsp;";

	var rTime = mainTable.insertRow(-1).insertCell(-1);
	rTime.id = '_rTimeCell';
	rTime.style.cssText = 'font-family: Arial, Helvetica, Verdana; font-size:12px;padding-bottom:0.3em;';
	rTime.innerHTML = "&nbsp;";
//	rTime.innerHTML = "<font color='gray'>Route time: </font><b>02:56:03<b>";

	var description = mainTable.insertRow(-1).insertCell(-1);
	description.style.paddingBottom = '0.3em';
	description.innerHTML = "<span style='font-size:9pt;'><font color='gray'>(drag points from search results below)</span>";
	// end of heading


	var sdiv = document.createElement('div');
	sdiv.id = '_routerDisplayDiv';
	sdiv.style.cssText = 'background-color:rgb(248,248,248);border:1px solid rgb(192,192,192);position:absolute;overflow:auto';
	sdiv.style.top = mainTable.offsetHeight + 'px';
	var w = (browser.type == 2 ? (div.offsetWidth - 2) : div.offsetWidth);
	sdiv.style.width = (w > 0 ? w : 0) + 'px';
	var h = (div.offsetHeight - mainTable.offsetHeight - (browser.type == 2 ? 2 : 0));
	sdiv.style.height = (h > 0 ? h : 0) + 'px';	
	div.appendChild(sdiv);

	var routeTable = document.createElement("table");
	routeTable.style.cssText = "background-color:rgb(252,252,252);width:100%;";
	routeTable.cellPadding="0";
	routeTable.cellSpacing="0";
	
	sdiv.appendChild(routeTable);
		
	
	this.calculateBtn = calcCmd;
	this.clearBtn = clearCmd;
	this.routeTable = routeTable;

	this.mainDiv = div;
	
	DragDropHelper.registerForDrop(div);
	
	div.dropObject = this;
	div.drop = function(obj, x, y){
		this.dropObject.drop(obj, x, y);
	}
	div.preDrop = function(obj, x, y){
		this.dropObject.preDrop(obj, x, y);
	}
	div.removeDrop = function(){
		this.dropObject.removeDrop();
	}
	attachToEvent(window, "resize", eventHandler(this, "onWindowResize"))

	attachToEvent(this.calculateBtn, "mouseup", eventHandler(this, "OnCalculate"));
	attachToEvent(this.clearBtn, "mouseup", eventHandler(this, "OnClear"));
	
	this.routeDisplayDiv = document.getElementById('_routerDisplayDiv');
	
	this.dropArrow = ElementCreator.createImage(0, 0, "search/images/dropArrow.png", 13, 9, 5, true);
	this.dropArrow.style.display = "none";
	document.body.appendChild(this.dropArrow);
	this.dropArrowShown = false;
	
	if(browser.type == 2){
		attachToEvent(window, "mouseout", eventHandler(this, "onWindowMouseOut"))
	}
	this.mouseDownHandler = eventHandler(this, "onMouseDown");
	this.mouseMoveHandler = eventHandler(this, "onMouseMove");
	this.mouseUpHandler = eventHandler(this, "onMouseUp");
}

MireoRouter.prototype.onWindowResize = function(e){
	var mtb = document.getElementById('_headerRouterTable');
	var sdiv = document.getElementById('_routerDisplayDiv');
	sdiv.style.height = (this.mainDiv.offsetHeight - mtb.offsetHeight - (browser.type == 2 ? 2 : 0)) + 'px';	
}

MireoRouter.prototype.drop = function(obj, x, y){
	y = y - findPosY(this.routeTable) + findPosY(this.mainDiv);
	if (y > 0){
		var idx = -1;
		var st = this.routeDisplayDiv.scrollTop;
		var row = null;
		for (var i = 0; i < this.routeTable.rows.length; ++i){
			row = this.routeTable.rows[i];
			if (row.offsetTop + row.clientHeight - st > y){
				idx = i;
				break;
			}
		}
		this.insertRow(obj, idx);
	}
}

MireoRouter.prototype.preDrop = function(obj, x, y){
	y = y - findPosY(this.routeTable) + findPosY(this.mainDiv);
	if (y > 0){
		if (this.routeTable.rows.length == 0){
			this.dropArrow.style.left = (findPosX(this.routeDisplayDiv) - 13) + 'px';
			this.dropArrow.style.top = (findPosY(this.routeDisplayDiv) - 4) + 'px';
		}else{
			var st = this.routeDisplayDiv.scrollTop;
			var row_h = this.routeTable.rows[0].offsetHeight;
			var idx = Math.floor((y + st)/row_h);
			if (idx > this.routeTable.rows.length)
				idx = this.routeTable.rows.length;
			this.dropArrow.style.left = (findPosX(this.routeTable) - 13) + 'px';
			this.dropArrow.style.top = (findPosY(this.routeTable) - 4 - st + idx*row_h) + 'px';
		}
		if (!this.dropArrowShown){
			this.dropArrow.style.display = "block";
			this.dropArrowShown = true;
		}
	}else{
		this.removeDrop();
	}
}

MireoRouter.prototype.removeDrop = function(){
	if (this.dropArrowShown){
		this.dropArrow.style.display = "none";
		this.dropArrowShown = false;
	}
}

MireoRouter.prototype.addAddress = function(addr, idx){
	var row = this.routeTable.insertRow(idx == null ? -1 : idx);
	this.geoAddressToTableRow(addr, row);
	attachToEvent(row.cells[2], "mousedown", this.mouseDownHandler);
	this.clearRouteResult();
}

MireoRouter.prototype.insertRow = function(obj, idx){
	if (obj.rowIndex != null) {
		if(this.routeTable.moveRow){
			this.routeTable.moveRow(obj.rowIndex, idx);
			this.clearRouteResult();
		}else {
			this.routeTable.deleteRow(obj.rowIndex);
			this.addAddress(obj.geoAddress, idx > obj.rowIndex && idx != -1 ? idx - 1 : idx);
		}
	}
	else 
		this.addAddress(obj.geoAddress, idx);
	this.changeNumbers();
}

MireoRouter.prototype.deleteRow = function(rowIndex){
	this.routeTable.deleteRow(rowIndex);
	this.changeNumbers();
	this.clearRouteResult();
}

MireoRouter.prototype.changeNumbers = function(){
	for (var i = 0; i < this.routeTable.rows.length; ++i){
		this.routeTable.rows[i].cells[0].innerHTML = (i+1)+'.';
	}
}

MireoRouter.prototype.geoAddressToTableRow = function(addr, row){
	row.geoAddress = addr;
	row.style.height = "1.3em";
	var cell = row.insertCell(-1);
	this.intToCell(row.rowIndex, cell, addr);
	var delcmd = row.insertCell(-1);
	delcmd.style.cssText += ';border-right:1px solid rgb(192,192,192);border-bottom:1px solid rgb(192,192,192);width:12px;height:12px;vertical-align:top';
	delcmd.style.cssText += ';cursor:pointer';
	delcmd.innerHTML =  '<img src="search/images/delete_rtpt.gif" style="align:top;cursor:pointer;" title="Remove point"/>';
	var _rt = this;
	delcmd.childNodes[0].onclick = function(){_rt.deleteRow(row.rowIndex);};
	cell = row.insertCell(-1);
	this.geoAddressToCell(addr, cell);
}

MireoRouter.prototype.geoAddressToCell = function(addr, cell){
	cell.style.cssText += ';font-family:Arial, Helvetica, Verdana;font-size:10pt;border-bottom:1px solid rgb(192,192,192);';
	cell.style.cssText += ';background-color:rgb(248, 248, 255); cursor:default; padding-left:0.3em;';
	cell.innerHTML = MireoRouter.ga2HTML(addr);
	cell.setAttribute("noWrap","true");
	cell.geoAddress = addr;
}

MireoRouter.prototype.displayInfoRows = function(slength, stime){
	var rc = document.getElementById('_rLengthCell');
	var rt = document.getElementById('_rTimeCell');
	rc.innerHTML = (slength == null ? '&nbsp;' : slength);
	rt.innerHTML = (stime == null ? '&nbsp;' : stime);
}

MireoRouter.prototype.intToCell = function(i, cell, addr){
	var cs = 'font-family:Arial, Helvetica, Verdana; font-size:12px; border-bottom:1px solid rgb(192,192,192);';
	cs += 'background-color:rgb(248, 248, 255); cursor:pointer;text-align:center;';
	cs += 'padding-left:2px; padding-top:0px; padding-right:2px;width:20px; text-decoration:underline; color:blue;';
	cell.style.cssText = cs;
	var drw = this.geoAddressDrawer;
	cell.onclick = function(){drw.zoomToGeoAddress(addr);};
	cell.innerHTML = (i+1)+".";
}


MireoRouter.ga2HTML = function(ga){
	if (ga._street && ga._street != ""){
		var ret = ga._street;
		if (ga._house_no)
			ret += " "+ga._house_no
		return ret + ", " + ga._PLZ + " " + ga._city;
	}else if (ga._POI && ga._POI != ""){
		return ga._POI;
	}else{
		return ga._PLZ + " "+ga._city;
	}
}

function uncompress_route2(route) {
	var ret = new WebRoute();
	ret.length = route.length;
	ret.time_length = route.time_length;
	ret.points = route.points;
	ret.zoom_factors = route.zoom_factors;
	ret.geometries = new Array();
	var geometry_x = route.geometry_x;
	var geometry_y = route.geometry_y;
	for (var i = 0; i < ret.zoom_factors.length; ++i){
		ret.geometries.push(new Array());
	}
	var zoom_levels = route.zoom_levels;
	var len = route.zoom_levels.length;
	var geometries = ret.geometries;
	for (var i = 0; i < len; ++i){
		var zoom_level = zoom_levels[i];
		var pt = { x:geometry_x[i], y:geometry_y[i] };
		for (var j = 0; j <= zoom_level; ++j){
			geometries[j].push(pt);
		}
	}
	return ret;
}

MireoRouter.prototype.OnCalculate = function(){
	if (this.routeTable.rows.length < 2)
		return;
	var arr = new Array();
	for (var i = 0; i < this.routeTable.rows.length; ++i){
		arr.push(this.routeTable.rows[i].geoAddress);
	}
	var routeDrawer = this.routeDrawer;
	this.displayInfoRows('Calculating...');
	var _parent = this;
	MapSearchWeb.GetRouteCompressed(arr, MireoMap.zfM, routeCallback);
	function routeCallback(route){
		try{
			WebException.validate(route);
			if (route.geometry_x.length < 2){
				_parent.displayInfoRows("Route doesn't exist");
			}else{
				var rlen = "<font color='gray'>Route length: </font><b>" + numFormat(route.length, 'DISTANCE') + "</b>";
				var rtm = "<font color='gray'>Route time: </font><b>" + numFormat(route.time_length, 'TMLEN') + "</b>";
				_parent.displayInfoRows(rlen, rtm);
				routeDrawer.zoomToRoute(uncompress_route2(route));
			}
		}catch(e){
			_parent.displayInfoRows("Route doesn't exist");
		}
	}
}

MireoRouter.prototype.OnClear = function(){
	this.clearRouteResult();
	while(this.routeTable.rows.length > 0){
		detachFromEvent(this.routeTable.rows[0].cells[2], "mousedown", this.mouseDownHandler);
		this.routeTable.deleteRow(0);
	}
}

MireoRouter.prototype.clearRouteResult = function(){
	this.displayInfoRows();
	this.routeDrawer.setRoute();
}

MireoRouter.prototype.onMouseDown = function(e){
	if (!e.target.geoAddress) return;
	
	this.eventSrc = e.target.setCapture ? e.target : window;
	
	attachToEvent(this.eventSrc, "mousemove", this.mouseMoveHandler);
	attachToEvent(this.eventSrc, "mouseup", this.mouseUpHandler);

	if(this.eventSrc.setCapture) this.eventSrc.setCapture();
	
	this.drag = true;
	var td = e.target;
	
	var dv = document.createElement("DIV");
	
	var posx = findPosX(e.target);
	var posy = findPosY(e.target) 

	posx -= td.offsetParent.offsetParent.scrollLeft;
	posy -= td.offsetParent.offsetParent.scrollTop;

	var dvcss = "text-indent:0.3em; font-family:Arial, Helvetica, Verdana; font-size:10pt;";
	dvcss += "background-color:rgb(248, 248, 255);cursor:default;padding-top:2px;";
	dvcss += "position:absolute;border:1px solid rgb(0, 0, 0);display:block";
	dv.style.cssText = dvcss;
	
	var iecorr = browser.type == 1 ? 2 : 0;
	dv.style.width = (td.offsetWidth + iecorr) + "px";
	dv.style.height = (td.offsetHeight - 3 + iecorr * 2) + "px";

	dv.style.left = posx+'px'; 
	dv.style.top = posy+'px';
	dv.innerHTML = td.innerHTML;
	dv.geoAddress = td.geoAddress;
	dv.rowIndex = td.parentNode.rowIndex;
	document.body.appendChild(dv);
	
	var pt = getMouseCoordinates(e);
	dv.offsetX = posx - pt.x;
	dv.offsetY = posy - pt.y;
	
	this.floatDiv = dv;
	this.eventSrc.setCapture != null ? this.eventSrc.style.cursor = 'move' : this.floatDiv.style.cursor = 'move';	
	cancelBubbling(e);
}

MireoRouter.prototype.onMouseMove = function(e){
	if (this.drag){
		var pt = getMouseCoordinates(e);
		this.floatDiv.style.left = (pt.x+this.floatDiv.offsetX)+"px";
		this.floatDiv.style.top = (pt.y+this.floatDiv.offsetY)+"px";
	}
	if (this.floatDiv){
		var pt = getMouseCoordinates(e);
		DragDropHelper.preDrop(this.floatDiv, pt.x, pt.y);
	}
}

MireoRouter.prototype.onMouseUp = function(e){
	this.drag = false;
	if(this.floatDiv){
		document.body.removeChild(this.floatDiv);
		var pt = getMouseCoordinates(e);
		DragDropHelper.drop(this.floatDiv, pt.x, pt.y);
		this.floatDiv = null;
	}

	detachFromEvent(this.eventSrc, "mousemove", this.mouseMoveHandler);
	detachFromEvent(this.eventSrc, "mouseup", this.mouseUpHandler);
	if (this.eventSrc.style != null)
		this.eventSrc.style.cursor = 'default';	

	if(this.eventSrc.releaseCapture)
		this.eventSrc.releaseCapture();
	this.eventSrc = null;
}

MireoRouter.prototype.onWindowMouseOut = function(e){
	if(!e.relatedTarget && this.drag)
		this.onMouseUp(e);
}
