//animation
var flashvars = {};
var params = {
	wmode: "transparent"
};
var attributes = {};
swfobject.embedSWF("/flash/guy.swf", "animation", "300", "400", "8.0.0","expressInstall.swf", flashvars, params, attributes);

//route search
var map;
var icons;
var marker_number = 1;
var marker_array = new Array();
var searchType="bothPoints";
var flashobj;


//route plot
var segmentpoints = new Array();
var segmentpoints_number = 0;
var routePath = new Array();
var matches_number = 0;


google.load("maps", "2", {"language" : LOCALE});

function initializeMap() {
	icons = new myedemIcons();
	var location = new userLocation();	

	map = new google.maps.Map2(document.getElementById("map_canvas"));	
	
	map.getDragObject().setDraggableCursor("url(/img/map/startIcon.cur),default");
	var center_point = new google.maps.LatLng(location.lat, location.lng);
	map.setCenter(center_point, 10);
	map.enableGoogleBar();

	map.clearOverlays();
//	map.enableScrollWheelZoom();

	//MAP INTERFACE
	map.addControl(new google.maps.LargeMapControl3D());
	map.addControl(new FancyMapTypeControl());
	
	
	function addMarker(latlng,icon) {
		marker_array[marker_number] = new google.maps.Marker(latlng, {draggable: true, icon:icon});
		map.addOverlay(marker_array[marker_number]);		
		marker_array[marker_number].value = marker_number;
		google.maps.Event.addListener(marker_array[marker_number], "dragend", markerDragend);

		//set latitude and longtitude in HTML form
		$("#lat"+marker_number).val(latlng.lat());
		$("#lng"+marker_number).val(latlng.lng());
	}
	
	//function adds marker on click
	function mapClick(overlay, latlng) {
		if (!overlay && marker_number<3) {
			switch (searchType) {
				case "bothPoints":
					if (marker_number==1) {
						addMarker(latlng, icons.startIcon);
						hintFinishpoint();
					}
					if (marker_number==2) {
						addMarker(latlng, icons.finishIcon);
						loadMatches();
					}
					break;
				case "startPoint":
					addMarker(latlng, icons.startIcon);
					loadMatches();
					//force switch ban 
					marker_number=3;
					break;
				case "finishPoint":	
					addMarker(latlng, icons.finishIcon);
					loadMatches();
					break;
				default: break;	
			}//switch
			
			
			marker_number++;

			$("#deleteAllPoints").removeClass("ui-state-disabled");
		}
	}
	
	function markerDragend(latlng) {
		$("#lat"+this.value).val(latlng.lat());
		$("#lng"+this.value).val(latlng.lng());
		loadMatches();
	}
	

	//EVENT LISTENERS
	//add markers on click
	google.maps.Event.addListener(map, "click", mapClick);
	
	$("#deleteAllPoints").click(function() {
		matchesFlush();
		removeMarkers();

		marker_number=1;
		
		if (searchType=="finishPoint")
			hintFinishpoint();
		else
			hintStartpoint();
		
		return false;
	});
	
	$("#startPoint_btn").click(function() {
		matchesFlush();
		removeMarkers();

		$("#startPoint_btn").addClass("ui-state-highlight");
		$("#finishPoint_btn").removeClass("ui-state-highlight");
		$("#bothPoints_btn").removeClass("ui-state-highlight");		
		
		searchType="startPoint";
		$("#searchType").val("startPoint");
		marker_number=1;
		hintStartpoint();
		
		return false;
	});
	
	$("#finishPoint_btn").click(function() {
		matchesFlush();
		removeMarkers();
		
		$("#finishPoint_btn").addClass("ui-state-highlight");
		$("#startPoint_btn").removeClass("ui-state-highlight");
		$("#bothPoints_btn").removeClass("ui-state-highlight");		
		
		searchType="finishPoint";
		$("#searchType").val("finishPoint");
		marker_number=2;
		hintFinishpoint();
		
		return false;
	});
	
	$("#bothPoints_btn").click(function() {
		matchesFlush();
		removeMarkers();
		
		$("#bothPoints_btn").addClass("ui-state-highlight");	
		$("#startPoint_btn").removeClass("ui-state-highlight");
		$("#finishPoint_btn").removeClass("ui-state-highlight");	
		
		searchType="bothPoints";
		$("#searchType").val("bothPoints");
		marker_number=1;
		hintStartpoint();
									
		return false;
	});
	
	flashobj = swfobject.getObjectById("animation"); 
	
}

google.setOnLoadCallback(initializeMap);



function userLocation() {
	//set Moscow as default location
	this.lat=55.7440;
	this.lng=37.6213;
	
	if(google.loader.ClientLocation!=null){
		this.lat = google.loader.ClientLocation.latitude;
		this.lng = google.loader.ClientLocation.longitude;
	}
}

function loadMatches() {
	hintSearching();
	matchesFlush();
	
	$.post("/api/loadRouteMatches", {lat1: $("#lat1").val(), lng1: $("#lng1").val(), lat2: $("#lat2").val(), lng2: $("#lng2").val(), searchType: searchType}, function(data) {
		$(data).find('route').each(function(){
			var routepoints_number=1;		
			routeVertices = [];
			var caption=$(this).attr("caption");
			var matchid=$(this).attr("routeid");
			
			var route=$(this).children();
			$(route).each(function(){
				var lat			= $(this).attr('lat');
				var lng			= $(this).attr('lng');
				var latlng		= new google.maps.LatLng(lat, lng);
				routeVertices[routepoints_number] = latlng;
					
				if($(this).attr('pointType')!="segmentPoint") {
					segmentpoints_number++;
					segmentpoints[segmentpoints_number] = new google.maps.Marker(latlng, {icon:icons.segmentpointIcon});
					map.addOverlay(segmentpoints[segmentpoints_number]);
				}
				
				routepoints_number++;
			});
			matches_number++;
			plotRoute();
			routePath[matches_number].routeid = matchid;
			//add events to сurrent match
			google.maps.Event.addListener(routePath[matches_number], "mouseover", function() {
  				this.setStrokeStyle({weight:5, opacity:0.8});
				map.getDragObject().setDraggableCursor("pointer"); 
			});
			
			google.maps.Event.addListener(routePath[matches_number], "mouseout", function() {
  				this.setStrokeStyle({weight:3, opacity:0.7});
				map.getDragObject().setDraggableCursor("url(http://maps.google.com/intl/en_us/mapfiles/openhand.cur),default");
			});		
			
			google.maps.Event.addListener(routePath[matches_number], "click", function() {
  				document.location="/routes/"+this.routeid;
			});					
			
		});
		hintDone();
		
		
	});
}

function plotRoute() {
	var color;
	switch (matches_number) {
		case 1:
			color="#002878";
			break;
		case 2:	
			color="#3333cc";
			break;
		case 3:	
			color="#4891dc";
			break;
		case 4:	
			color="#00aed9";
			break;
		case 5:	
			color="#e70f47";
			break;
		case 6:	
			color="#e70033";
			break;
		case 7:	
			color="#7d2b27";
			break;
		case 8:	
			color="#6e5819";
			break;			
		default:
			color="#3333cc";
			break;
	}
	
	routePath[matches_number] = new google.maps.Polyline(routeVertices, color, 3, 0.7);
	map.addOverlay(routePath[matches_number]);
}	

function matchesFlush() {
	for (var i=1; i<=matches_number; i++)
		map.removeOverlay(routePath[i]);
	for (var i=1; i<=segmentpoints_number; i++)		
		map.removeOverlay(segmentpoints[i]);
	segmentpoints_number=0;	

	routePath = [];
	matches_number = 0;
}

function removeMarkers() {
	map.clearOverlays();
	marker_array = [];
	$("#deleteAllPoints").addClass("ui-state-disabled");
}

function hintStartpoint() {
	$("#hint").html("<h6>"+MAP_HINT_START+" :</h6>");
	updateHoverState();
	map.getDragObject().setDraggableCursor("url(/img/map/startIcon.cur),default");
	if (flashobj) {
		flashobj.SetVariable("action", "startpoint");
	}
}

function hintFinishpoint() {
	$("#hint").html("<h6>"+MAP_HINT_FINISH+" :</h6>");
	updateHoverState();
	map.getDragObject().setDraggableCursor("url(/img/map/finishIcon.cur),default");
	if (flashobj) {
		flashobj.SetVariable("action", "finishpoint");
	}	
}

function hintSearching() {
	$("#hint").html('<img src="/img/ajax-loader-bert.gif" />');
	updateHoverState();
	map.getDragObject().setDraggableCursor("url(http://maps.google.com/intl/en_us/mapfiles/openhand.cur),default");
	if (flashobj) {
		flashobj.SetVariable("action", "searching");
	}	
}

function hintDone() {
	if (matches_number)
		$("#hint").html("<h6>"+MAP_HINT_FOUND+" : "+matches_number+"</h6>");
	else
		$("#hint").html('<h6>'+MAP_HINT_NOTFOUND+'</h6>');
		//$("#hint").html('<h6>В данном направлении еще не создано ни одного маршрута. </h6> <a class="fg-button ui-state-default ui-corner-all" href="/routes/new">создать маршрут</a>');
	updateHoverState();
	map.getDragObject().setDraggableCursor("url(http://maps.google.com/intl/en_us/mapfiles/openhand.cur),default");
	if (flashobj) {
		flashobj.SetVariable("action", "done");
		flashobj.SetVariable("searchresult", matches_number);
	}	
}

function updateHoverState() {
	//all hover and click logic for buttons
	$(".fg-button:not(.ui-state-disabled)")
	.hover(
		function(){ 
			$(this).addClass("ui-state-hover"); 
		},
		function(){ 
			$(this).removeClass("ui-state-hover"); 
		}
	)
}
