/**
 * @author jarmo
 */

	//Move this definition to the configfile
	var measureDistLineMarkerDivClassName = "measureDistLineMarkerDiv";	

	var ajaxApi = null;
	var mapClickFuncId= null;
	var zoomChangeFuncId= null;
	var mapMovedFuncId= null;
	var mapDraggedFuncId= null;
	var map = null;
	var dist = 0.0;
	var distTxtDiv = null;
	var realCoords =  new Array();
	var jg = null;	
	var divMarkerOffsetX=0;
	var divMarkerOffsetY=0;
	var lineColor = "#000000";
	var lineStroke = 1;
	var markerNode;
	var lastCenter;
	var topLeftX;
	var topLeftY;
	var startX;
	var startY;

function MeasureDistTool(naviciAjaxApi){
	
	ajaxApi = naviciAjaxApi;		
	map = ajaxApi.getMap();	
	
	//Public methods of this object
	this.startMeasure = startMeasure;
	this.stopMeasure = stopMeasure;
	this.setStroke = setStroke;
	this.setColor = setColor;
	this.setDistTxtDiv = setDistTxtDiv;
}

function setDistTxtDiv(div){
	distTxtDiv = div;	
}



function startMeasure(){
	ajaxApi.getPoiManager().disable();			
	//mapMovedFuncId = map.addMapMovedCallback(mapChanged);	
	mapDraggedFuncId = map.addMapDraggedCallback(mapChanged);
	mapClickFuncId = map.addClickCallback(point_it);
	zoomChangeFuncId= map.addZoomChangeCallback(mapChanged);
	map.setSingleClickSensitivity(2);	
	jg = new jsGraphics(makeDivMarkerToTopLeft());
	jg.setColor(lineColor);
	jg.setStroke(lineStroke);
	setLastCenter();
}

function stopMeasure(){	
	jg.clear();
	ajaxApi.getPoiManager().enable();
	//map.deleteMapMovedCallback(mapMovedFuncId);	
	map.deleteClickCallback(mapClickFuncId);
	map.deleteZoomChangeCallback(zoomChangeFuncId);	
	map.deleteMapDraggedCallback(mapDraggedFuncId);
	map.setSingleClickSensitivity(0);
	dist = 0.0;
	realCoords = new Array();	
	ajaxApi.deleteDivMarker(markerNode);	
}

function setColor(color){	
	lineColor = color;	
}

function setStroke(stroke){		
	lineStroke = stroke;	
	}

function refresDistTxt(){
	if(distTxtDiv != null){
		
		if(dist > 1000){
			distTxtDiv.innerHTML = (dist/1000).toFixed(3) +' km';
			}	
			
		else {
			distTxtDiv.innerHTML=dist.toFixed(0) +' m';
		}		
	}	
}

function point_it(mapInfo){
	
	//var mapInfo = ajaxApi.getMapInfos();
	
	var x1 = mapInfo.mouseCoordX;
	var y1 = mapInfo.mouseCoordY;
	var x2 = 0.0;
	var y2 = 0.0;
	
	if(realCoords.length >= 1){					
		x2 = realCoords[realCoords.length-1]['x'];
		y2 = realCoords[realCoords.length-1]['y'];							
		drawLine2(x1,y1,x2,y2);
		dist += countDist(x1,y1,x2,y2);		 
		refresDistTxt();	
	}
	//Draw only a dot that marks the starting point.
	else {
		//drawLine2(x1,y1,x1,y1);
		startX = x1;
		startY = y1;
		drawStartPoint();		 
	}
		
	//alert("push:  " +x1 +" " +y1 +" " +x2 +" " +y2);	
	realCoords.push({'x':x1,'y':y1});			
	
}

function undoLastPoint(){
	if(realCoords.length > 0 && realCoords != null){		
		var lastPoint = realCoords.pop();
		if(realCoords.length > 0){
			dist -= countDist(realCoords[realCoords.length-1]['x'],realCoords[realCoords.length-1]['y'],lastPoint['x'],lastPoint['y']);
			refresDistTxt();
		}
		if(realCoords.length == 0){
			jg.clear();	
		}
		else if(realCoords.length == 1){
			jg.clear();		
		 	//drawLine2(realCoords[0]['x'],realCoords[0]['y'],realCoords[0]['x'],realCoords[0]['y']);
			drawStartPoint();
		}
		else{
			jg.clear();	
			drawStartPoint();
			drawPath();			
			}
	}
}

function countDist(x1,y1,x2,y2){			
		
		var a = Math.max(y1,y2)-Math.min(y1,y2);		
			
		var b = Math.max(x1,x2)-Math.min(x1,x2);	
		
		return Math.sqrt(((a*a) + (b*b)));	
}

function drawLine2(x1,y1,x2,y2){	
	
	var mapInfo = ajaxApi.getMapInfos();		
	
	jg.drawLine((x1/AjaxMapsConfig.scales[mapInfo.zoom]-topLeftX/AjaxMapsConfig.scales[mapInfo.zoom]),
				(topLeftY/AjaxMapsConfig.scales[mapInfo.zoom]-y1/AjaxMapsConfig.scales[mapInfo.zoom]),
				(x2/AjaxMapsConfig.scales[mapInfo.zoom]-topLeftX/AjaxMapsConfig.scales[mapInfo.zoom]),
				(topLeftY/AjaxMapsConfig.scales[mapInfo.zoom] - y2/AjaxMapsConfig.scales[mapInfo.zoom]));		
	
				
	
				
	jg.paint();	
}

function drawFilledRect(centerX,centerY,width,height){
	var mapInfo = ajaxApi.getMapInfos();
	
	leftX = centerX/AjaxMapsConfig.scales[mapInfo.zoom]-topLeftX/AjaxMapsConfig.scales[mapInfo.zoom]-(width/2);
	leftY = topLeftY/AjaxMapsConfig.scales[mapInfo.zoom]-centerY/AjaxMapsConfig.scales[mapInfo.zoom]-(height/2);
		
	jg.fillEllipse(leftX,leftY,width,height);
	
	jg.paint();	
}

function drawStartPoint(){
	//witdh and height must have odd value!
	drawFilledRect(startX,startY,5,5);
}

function drawPath(){	
	
	var mapInfo = ajaxApi.getMapInfos();
		
	var lines = new Array();
	
	for(var i = 0; i < realCoords.length-1; i++){	
		lines.push({'x1':realCoords[i]['x'],'y1':realCoords[i]['y'],'x2':realCoords[i+1]['x'],'y2':realCoords[i+1]['y']});
	}	
	
	var bottomRightX = mapInfo.centerX+(mapInfo.width*AjaxMapsConfig.scales[mapInfo.zoom])/2;
	var bottomRightY = mapInfo.centerY-(mapInfo.height*AjaxMapsConfig.scales[mapInfo.zoom])/2;
	
	var a_hor_top = 0;
	var b_hor_top = topLeftX - bottomRightX;
	var c_hor_top = b_hor_top * topLeftY;
	
	var a_hor_bottom = 0;
	var b_hor_bottom = topLeftX-bottomRightX;
	var c_hor_bottom = b_hor_bottom * bottomRightY;
	
	var a_ver_left = topLeftY-bottomRightY; 
	var b_ver_left = 0;
	var c_ver_left = a_ver_left * topLeftX;
	
	var a_ver_right = bottomRightY-topLeftY; 
	var b_ver_right = 0;
	var c_ver_right = a_ver_right * bottomRightX;
	
	
	
	for(var i = 0; i < lines.length; i++){	
			
			//Isf point outside of the viewarea. Them should't be drawed.			
			if(lines[i]['x1'] > bottomRightX && lines[i]['x2'] > bottomRightX){} 
			else if(lines[i]['x1'] < topLeftX && lines[i]['x2'] < topLeftX ){} 
			else if(lines[i]['y1'] > topLeftY && lines[i]['y2'] > topLeftY){} 
			else if(lines[i]['y1'] < bottomRightY && lines[i]['y2'] < bottomRightY){}		
			else{			
				  
				//Does line intersect viewarea					
					var a = lines[i]['y2']-lines[i]['y1'];
					var b = lines[i]['x1']-lines[i]['x2'];
					var c = a*lines[i]['x1'] + b*lines[i]['y1'];
					
					var det;
					
					//Does intersect:
					//a)top horizontal border
					det = a_hor_top * b - a * b_hor_top;
					if(det == 0){
						//Lines are parallel						
					}
					else{
						var x = (b*c_hor_top - b_hor_top * c)/det;
						var y = (a_hor_top * c - a * c_hor_top)/det;
						if(lines[i]['y1'] < lines[i]['y2'] && lines[i]['y2'] > y){
							//alert("1 x:" +x +" y:" +y);
							lines[i]['x2']= x;
							lines[i]['y2']= y;	
						}
						else if(lines[i]['y1'] > lines[i]['y2'] && lines[i]['y1'] > y)
							{
								//alert("2 x:" +x +" y:" +y);
								lines[i]['x1']= x;
								lines[i]['y1']= y;	
							}				
					}
					
					//b) bottom horizontal border
					det = a_hor_bottom * b - a * b_hor_bottom;
					if(det == 0){
						//Lines are parallel						
					}
					else{
						var x = (b*c_hor_bottom - b_hor_bottom * c)/det;
						var y = (a_hor_bottom * c - a * c_hor_bottom)/det;
						
						if(lines[i]['y1'] < lines[i]['y2'] && lines[i]['y1'] < y){
							//alert("3 x:" +x +" y:" +y);
							lines[i]['x1']= x;
							lines[i]['y1']= y;	
						}
						else if(lines[i]['y1'] > lines[i]['y2'] && lines[i]['y2'] < y)
							{
								//alert("4 x:" +x +" y:" +y);
								lines[i]['x2']= x;
								lines[i]['y2']= y;	
							}				 
					}
					
					//c) left vertical border
					det = a_ver_left * b - a * b_ver_left;
					if(det == 0){
						//Lines are parallel						
					}
					else{
						var x = (b*c_ver_left - b_ver_left * c)/det;
						var y = (a_ver_left * c - a * c_ver_left)/det;
						
						if(lines[i]['x1'] < lines[i]['x2'] && lines[i]['x1'] < x){
							//alert("5 x:" +x +" y:" +y);
							lines[i]['x1']= x;
							lines[i]['y1']= y;	
						}
						else if(lines[i]['x1'] > lines[i]['x2'] && lines[i]['x2'] < x)
							{
								//alert("6 x:" +x +" y:" +y);
								lines[i]['x2']= x;
								lines[i]['y2']= y;	
							}				 
					}
					
					//d) right vertical border
					det = a_ver_right * b - a * b_ver_right;
					if(det == 0){
						//Lines are parallel						
					}
					else{
						var x = (b*c_ver_right - b_ver_right * c)/det;
						var y = (a_ver_right * c - a * c_ver_right)/det;
						 
						if(lines[i]['x1'] < lines[i]['x2'] && lines[i]['x2'] > x){
							//alert("7 x:" +x +" y:" +y);
							lines[i]['x2']= x;
							lines[i]['y2']= y;	
						}
						else if(lines[i]['x1'] > lines[i]['x2'] && lines[i]['x1'] > x)
							{
								//alert("8 x:" +x +" y:" +y);
								lines[i]['x1']= x;
								lines[i]['y1']= y;	
							}				
					}						
								
				//alert("x1: " +lines[i]['x1'] +" y1: " +lines[i]['y1'] +" x2: " +lines[i]['x2'] +" y2: " +lines[i]['y2']);
				drawLine2(lines[i]['x1'],lines[i]['y1'],lines[i]['x2'],lines[i]['y2']);	
			
			
		}							
			
	}		
	
	jg.paint();
		
}


function makeDivMarkerToTopLeft(){
	
	var mapInfo = ajaxApi.getMapInfos();		
	topLeftX= mapInfo.centerX-(mapInfo.width*AjaxMapsConfig.scales[mapInfo.zoom])/2-divMarkerOffsetX;
	topLeftY= mapInfo.centerY+(mapInfo.height*AjaxMapsConfig.scales[mapInfo.zoom])/2+divMarkerOffsetY;	
	
	var mapSurface = map.getActiveSurface();	
	markerNode = document.createElement('div');
	markerNode.style.left = topLeftX +"px";
	markerNode.style.top = topLeftY +"px";
	mapSurface.appendChild(markerNode);	
	
	//markerNode = ajaxApi.addDivMarker(measureDistLineMarkerDivClassName,topLeftX,topLeftY,"",0,0,"");
	return markerNode;		
}

function moveMarkerNode(){
		
	if(markerNode == null || markerNode == undefined){		
		return null;
	}
	
	var mapInfo = ajaxApi.getMapInfos();
	
	topLeftX= mapInfo.centerX-(mapInfo.width*AjaxMapsConfig.scales[mapInfo.zoom])/2-divMarkerOffsetX;
	topLeftY= mapInfo.centerY+(mapInfo.height*AjaxMapsConfig.scales[mapInfo.zoom])/2+divMarkerOffsetY;
	
	markerNode.style.left = topLeftX +"px";
	markerNode.style.top = topLeftY +"px";
	
	setLastCenter();

}

function mapChanged(){
	jg.clear();
	moveMarkerNode();	
	drawPath();
	drawStartPoint();
	setLastCenter();		
}

/*function movePath(){
	
	if(markerNode == null || markerNode == undefined){		
		return null;
	}
	
	if(lastCenter == null || lastCenter == undefined){		
		return null;
	}
	
	var mapInfo = ajaxApi.getMapInfos();
	
	var temp= markerNode.childNodes;
	temp[0].style.display ="none";
	var pathdivs = temp[0].childNodes;
	
	var dX = (mapInfo.centerX-lastCenter['x'])/AjaxMapsConfig.scales[mapInfo.zoom];	
	var dY = (mapInfo.centerY-lastCenter['y'])/AjaxMapsConfig.scales[mapInfo.zoom];

	//alert(dX +" " +dY);

	
	for(var i = 0; i < pathdivs.length;i++){
		
		pathdivs[i].style.left = (parseFloat(pathdivs[i].style.left)-dX) +"px";		
		pathdivs[i].style.top =  (parseFloat(pathdivs[i].style.top)+dY) +"px";
	}
	temp[0].style.display ="block";
	moveMarkerNode();
	setLastCenter();
}*/

function setLastCenter(){
	var mapInfo = ajaxApi.getMapInfos();
	lastCenter=({'x':mapInfo.centerX,'y':mapInfo.centerY});
}





