// Map functions start

var LT_CENTER = new Array(494289.1652781151, 6158341.809328579); 
var LT_INITIAL_ZOOM = 2;
var LT_MAX_ZOOM = 11;
var mapCenterX;
var mapCenterY;
var objectX;
var objectY;
var mapZoom;
var address;
var popup = false;
var embedded = true;
var mapnotfound = "";
var mapfound = "";
var map;
var locator;
var markerImgUrl;
var DEBUG = true;
var locationCallback; // function
var manualLocatingStarted = false;
var manualLocationImg = new Array();

/** Get initial map extent */
function initialExtent() {			
	return new esri.geometry.Extent(255634.5213021603, 5957787.241552778, 731885.4738040656, 6275287.876554048);
}

/** Zoom map to wanted position */
function zoomInitial() {
	// here initial center point
	map.centerAndZoom(new esri.geometry.Point(mapCenterX, mapCenterY, map.spatialReference), mapZoom);	
}

/** Zoom map and show object */
function zoomAndShow() {
	zoomInitial();
	showObject();
}

/** Show object */
function showObject() {
	createLocation(new esri.geometry.Point(objectX, objectY, map.spatialReference), null, false);
}

/** Default zoom */
function zoomDefault() {
	map.centerAndZoom(new esri.geometry.Point(LT_CENTER[0], LT_CENTER[1], map.spatialReference), LT_INITIAL_ZOOM);			
}

/** Uses 'address' field to search  */
function findAddress() {
	startProgressBar();	
	//var search = "Konarskio 28a, Vilnius";
	console.log(new Date().getTime() + " searching " + address);
	locator.addressToLocations({text:address}, null);
	
}

/** Map position change events end up calling this function. Here we update our info about map 
  extent, center point and possible object location point.	*/
function updatePosition() {
	// .....
}

/** Get centerpoint, using given spacial ref */
function getCenterpoint(x1, y1, x2, y2, spatialReference) {
	var point = new esri.geometry.Point(((x2-x1)/2)+x1, ((y2-y1)/2)+y1, spatialReference);
	return point;
}

/** Get centerpoint, using given spacial ref */
function getCenterpointExt(extent, spatialReference) {	  
	var point = getCenterpoint(extent.xmin, extent.ymin, extent.xmax, extent.ymax, spatialReference);
	return point;
}

/** Debug to 'debug' div */
function debug(s) {		
	dojo.byId("debug").innerHTML = new Date() + "<br>" + s;		
}


/** Called when map is pan-ed */
function updatePan(extent, endPoint) {	  
  updatePosition();
}

/** Called when map is zoomed in/out */
function updateZoom(extent, zoomFactor, anchor, level) {
	updatePosition();
}
/** 
 Clear map from any graphics (markers)
*/
function clearMap() {	  
	map.graphics.clear();
}

/** Called if city, street, house fields might changed */
function updateLocation(search) {
	clearNotification();	
	startProgressBar();	
	//var search = "Konarskio 28a, Vilnius";
	console.log(new Date().getTime() + " searching " + search);
	address = search;
	locator.addressToLocations({text:search}, null);
	
}

/** After geolocating is completed this function is called with found candidate,
 * 	if parameter is null, then there were no candidates found. 
 * */
function notifyAboutDiscovery(found) {
	if (found) {
		dojo.byId("mapnotification").innerHTML = mapfound + ' ' + found.address;
	} else {
		dojo.byId("mapnotification").innerHTML = mapnotfound + ' ' + address;
	}	
}

/** Clear geocoding notification */
function clearNotification() {
	dojo.byId("mapnotification").innerHTML = "";		
}

/**  */
function objectLocationUpdatePopup(point) {	
	dojo.byId("COORDINATES").value = point.x + ":" + point.y;	
}

/** Geocoding results. We use only first, no mather how bad quality score. */
function showResults(candidates) {
	var candidate;
	console.log("found results " + candidates.length);
	
	stopProgressBar();
	
	if (candidates.length == 0) {		
		notifyAboutDiscovery(null);		
	}
	
	for (var i=0, il=candidates.length; i<il; i++) {
		clearMap(); // We can clear map cause we use only first result.
		candidate = candidates[i];
		console.log("best score " + candidate.score);
		var attributes = { address: candidate.address, score:candidate.score, locatorName:candidate.attributes.Loc_name };
		createLocation(candidate.location, attributes, false);
		centerAndZoom(candidate.location, LT_MAX_ZOOM);
		
		//locationCallback.call(candidate.location.x + "," + candidate.location.y);
		if (!popup) {			
			objectLocationUpdate(candidate.location.x + ":" + candidate.location.y);			
		} else {			
			objectLocationUpdatePopup(candidate.location);
			showSaveButton();
		}	
		notifyAboutDiscovery(candidate);
		
		break; // only best result!
	}
	
}	

/** */
function toggleManualLocating() {
	if (manualLocatingStarted) {
		stopManualLocating();
	} else {
		startManualLocating();
	}
}

/** @deprecated */
function manualLocatingCursor() {
	console.log("manualLocatingCursor called");
		
}

/** When user use manually locating tool, change its background color*/
function startManualLocating() {
	map.reposition();	// Needed for out-of-position map div problem, when we change dynamically forms.
	manualLocatingStarted = true;
	dojo.byId("manuallocateimg").src = manualLocationImg[1];	
	//map.setMapCursor("pointer");
}
/** When user has manually chosen location, reset  background color*/
function stopManualLocating() {
	manualLocatingStarted = false;
	dojo.byId("manuallocateimg").src = manualLocationImg[0];
	//map.setMapCursor("default");
}

/**  */
function showSaveButton() {
	dojo.byId("savemapsection").style.visibility = "visible";
}

/** Show progress bar animation */
function startProgressBar() {
	dojo.byId("waitbar").style.display = "inline";
}

/** Show progress bar animation */
function stopProgressBar() {
	dojo.byId("waitbar").style.display = "none";
}

/** Creates point marker */
function createLocation(point, attributes, showText) {
			
	var symbol = new esri.symbol.PictureMarkerSymbol(markerImgUrl, 24,24);
	var graphic = new esri.Graphic(point, symbol, attributes);		
	map.graphics.add(graphic);
	if (showText) {
		map.graphics.add(new esri.Graphic(point, new esri.symbol.TextSymbol(attributes.address).setOffset(0, 8)));
	}
}

/** Centers and max zooms to point*/
function centerAndZoom(point, zoom) {			
	map.centerAndZoom(point, zoom);			
}

/** Called when user has chosen map location by clicking on map */
function createLocationFromClick(evt) {	  
	if (manualLocatingStarted) {
		clearNotification();
		clearMap();
		var point = evt.mapPoint;
		createLocation(point, null, null);
		centerAndZoom(point, LT_MAX_ZOOM);
		if (!popup) {
			objectLocationUpdate(point.x + ":" + point.y);
		} else {
			objectLocationUpdatePopup(point);
			showSaveButton();
		}
		stopManualLocating();		
		
	}	
  }

// Map functions end

