/* Extensions to prototype */

Element.setText = function(el, text)
{
	el = $(el); 
	if (!el) throw "Element.setText: element not found.";
	if (!text) text = '';
	switch (el.tagName)
	{
		case "INPUT":
		case "TEXTAREA":
		case "OPTION":
		case "SELECT":
			el.value = text;
			break;
		default:
			if (typeof(el.innerText) == "undefined")
			{
				el.textContent = text;
			}
			else
			{
				el.innerText = text;
			}
	}
}

Element.findParent = function(el, parentTagName)
{  
	var parent = el;
	while (parent = parent.parentNode)
	{
		if (parent.tagName == parentTagName) return parent;
	}
	
	return null;
}


var map;
var slider1;
var baseIcon;
var fieldOfView;
var selectedLocation = null;
var fieldOfView = null;

window.onload = function() 
{
	// Initialize slider
   slider1 = new Control.Slider('viewer-handle', 'viewer-track',
      {  
         sliderValue : 0,
         onSlide: sliderSlideHandler1,
         onChange: sliderSlideHandler1
      });

	// Initialize map
	if (!GBrowserIsCompatible()) 
	{
		var el = document.getElementById('nogmaps');
		if (el) el.style.display = 'block';
		return;
	}
	
	// Create map
	map = new GMap2($('map'));
	map.setCenter(new GLatLng(52.469397, 5.509644), 16);// NL
	map.setMapType(G_SATELLITE_MAP);
	map.enableScrollWheelZoom();
   
   adjustMapStyle();
   
	// Initialize icons
	baseIcon = new GIcon();
	baseIcon.image = "resources/images/location.png";
	baseIcon.iconSize = new GSize(15, 15);
	baseIcon.iconAnchor = new GPoint(7, 7);    
	baseIcon.infoWindowAnchor = new GPoint(7, 7);
        	
	// Initialize markers
	var location, marker;
	for (var i = 0, l = locations.length; i < l; ++i)
	{
		location = locations[i];
		if ((location.lat != 0) && (location["long"] != 0))
		{
			location.marker = addLocationMarker(location);
		}
	} 
	
	// Process query prams
	var params = document.location.search.toQueryParams();
	var locationId, location;
	// Check for location parameter
	if (params.location) 
	{	
		locationId = Number(params.location);
		if (!findLocation(locationId, 0)) locationId = null;
	}
	// Check for search results
	if (!locationId && typeof(searchResults) != 'undefined') 
	{
		// Choose random from search results
		locationId = searchResults[Math.floor(Math.random() * searchResults.length)];
		if (!findLocation(locationId, 0)) locationId = null;
	}
	if (!locationId) 
	{
		// Choose random from all locations
		locationId = Math.floor(Math.random() * locations.length);
	}
	showLocation(locationId, 'init'); 
	
	// Init contact link
	$('contact').href = String.fromCharCode(0155,0141,0151,0154,0164,0157,072,0164,0157,0145,0156,0156,0165,0100,0163,0165,0160,0145,0162,0162,0145,0155,0142,0157,056,0143,0157,0155);
}

window.onunload = function() 
{
	GUnload();
}

function adjustMapStyle()
{
	var map = $('map');
	var nodes = map.childNodes;
	Element.setOpacity(nodes[1], 0.8);
}

function openGoogleMaps()
{
	var params = new Hash();
	//params.set("hl", "nl");
	params.set("ll", map.getCenter().toUrlValue());
	params.set("z", map.getZoom());
	params.set("t", map.getCurrentMapType().getUrlArg());
	if (selectedLocation.marker)
	{
		params.set("q", selectedLocation.marker.getLatLng().toUrlValue());
		params.set("mtr", "loc");
	}

	var url = "http://maps.google.nl/?" + params.toQueryString();
	window.open(url);	
}

function addLocationMarker(location)
{
	var marker = new GMarker(new GLatLng(location.lat, location["long"]), 
		{"title": location.title, "icon": baseIcon});
	GEvent.addListener(marker, "click", function(){showLocation(location.id, 'map')});
	map.addOverlay(marker);
	return marker;
}


function sliderSlideHandler1(v)
{
   Element.setOpacity('img1', 1 - v);
   $('viewer-handle').title = (v * 100).toFixed() +'%'
}


function showLocation(locationId, source, dir)
{
	if (!source) source = 'list';
	if (typeof(dir) == "undefined") dir = 0;

	var location = findLocation(locationId, dir);
	if (!location) throw "location not found";
	
	var img1 = $('img1');
	var img2 = $('img2');
	
	// Reset slider
	slider1.setValue(0);
   //TODO: hide current images and handle onload of new images
   
	// Update images
	Element.setText('descr', location.description);
	Element.setText('time1', location.pictures[0].year);
	Element.setText('time2', location.pictures[1].year);
	img1.src = 'picture.php?id=' + location.pictures[0].id + '&target=index';
	img1.alt = img1.src;
	img2.src = 'picture.php?id=' + location.pictures[1].id + '&target=index';
	img2.alt = img2.src;
	if (Prototype.Browser.WebKit)
	{
		// Stupid image size fix for WebKit
		//setTimeout(function(){ imageSizeFix('img1') }, 100);
		//setTimeout(function(){ imageSizeFix('img2') }, 100);
		img1.onload = function(){ imageSizeFix('img1') };
		img2.onload = function(){ imageSizeFix('img2') };
	}

	// Show location
	if (selectedLocation)
	{
		$('l' + selectedLocation.id).className = '';
	}
	var l = $('l' + location.id);
	l.className = 'selected';
	if (source != 'list') l.scrollIntoView(true);
	
	// Show marker  
	if (selectedLocation && selectedLocation.marker)
	{
	   selectedLocation.marker.setImage("resources/images/location.png");
	   if (fieldOfView) 
	   {
	   	map.removeOverlay(fieldOfView);
	   	fieldOfView = null;
	   }
	}

	if (location.marker)
	{
		location.marker.setImage("resources/images/location-selected.png");
		var center = location.marker.getLatLng();
		if (source != 'map') map.panTo(center);
		
		if (location.dir != null && location.dir != 0)
		{
			// Show field of view
			var mapProj = G_NORMAL_MAP.getProjection();
			var mapZoom = 16;
		   
		   var radius = 50;
		   var angle1 = location.dir * Math.PI / 180;
		   var angle2 = 25 * Math.PI / 180;
		   
		   var points = [];
		   var p0 = mapProj.fromLatLngToPixel(center, mapZoom);
			
			var px, py;
			px = p0.x + radius * Math.cos(angle1 - angle2);
			py = p0.y + radius * Math.sin(angle1 - angle2);
			points.push(mapProj.fromPixelToLatLng(new GPoint(px, py), mapZoom));
		   
			points.push(center);
		
			px = p0.x + radius * Math.cos(angle1 + angle2);
			py = p0.y + radius * Math.sin(angle1 + angle2);
			points.push(mapProj.fromPixelToLatLng(new GPoint(px, py), mapZoom));
		
		  	fieldOfView = new GPolygon(points, "#004A82", 1, 0.3, "#004F8B", 0.5);
			map.addOverlay(fieldOfView);			
		}
		
	}

	// Update link
	var params = new Hash();
	params.set("location", location.id);
	$('linkTo').href = document.location.pathname + "?" + params.toQueryString();

	// Save selection
	selectedLocation = location;
}

function findLocation(locationId, dir)
{

	for (var i = 0, l = locations.length; i < l; ++i)
	{
		if (locations[i].id == locationId) 
		{  
			i += dir;
			if (i < 0) i = l - 1;
			else if (i >= l) i = 0;
			return locations[i];
		}
	}
	if (location.length != 0) return locations[0];
	return null;
}

function showNextLocation()
{
	var locId = null;
	if (selectedLocation) locId = selectedLocation.id;
	showLocation(locId, 'toolbar', 1);
}

function showPrevLocation()
{
	var locId = null;
	if (selectedLocation) locId = selectedLocation.id;
	showLocation(locId, 'toolbar', -1);
}

function imageSizeFix(img)
{
	img = $(img);
	//document.title = 'imageSizeFix: '+ img.width +' < '+ img.naturalWidth +'?';
	if (img.width < img.naturalWidth) img.width = img.naturalWidth;
	if (img.height < img.naturalHeight) img.height = img.naturalHeight;
}