map = Array();
map['current_travel_active'] = 0;
map['data_obj'] = false;
map['tmp_marker'] = false;
map['text'] = Array();
function init_google_maps(x,y,z) {
	map['data_obj'] = document.getElementById('map_value_data');
	var latlng = new google.maps.LatLng(x,y);
	var options = {
		zoom: z,
		center: latlng,
		mapTypeId: google.maps.MapTypeId.ROADMAP,
		scrollwheel:false,
		base_domain: 'google.se'
	};

	map['map'] = new google.maps.Map(document.getElementById("google_maps_canvas"),options);
	// Load dynamic CMS data
	map_load_values();
	
	// directions
	map.gdir_service = new google.maps.DirectionsService();
	map.gdir_display = new google.maps.DirectionsRenderer();
	map.gdir_display.setMap(map.map);
	map.gdir_display.setPanel(document.getElementById("map_directions"));
	google.maps.event.addListener(map.gdir_service, "error", map_error);

	// place the markers
	markers = Array();
	markers_num = map['data_obj'].children.length;
	if(map['encodedPolyline']) {
		map['map'].addOverlay(map['encodedPolyline']);
	}
	c = 0;
	while(c < markers_num && gm_x[c]) {
		// data_row_obj = map['data_obj'].children[c];
		var point = new google.maps.LatLng(gm_x[c],gm_y[c]);
		createMarker(point, c);
		c++;
	}

}
function createMarker(point, number) {
	var marker = new google.maps.Marker({
		position: point,
		map: map.map,
		icon: map.icon_image
	});
	marker.value = number;
	// map['tmp_marker'] = marker;
	google.maps.event.addListener(marker, "mouseover", function() {
		var myHtml = '<a href="javascript:load_location_info('+gm_id[number]+','+number+')">'+html_value(document.getElementById('map_id_'+gm_id[number]).getElementsByTagName('h2')[0])+'</a>';
		map_tooltip(marker, myHtml);
	});
	google.maps.event.addListener(marker, "click", function() {
		id = gm_id[number];
		load_location_info(id, number);
	});
	return marker;
}
function map_start_close_tooltip(evt) {
	map.close_tooltip = setTimeout(map_do_close_tooltip,300);
	map.evt = evt;
}
function map_cancel_close_tooltip(evt) {
	clearTimeout(map.close_tooltip);
}
function map_do_close_tooltip(evt) {
	document.getElementById('map_tooltip').style.display = 'none';
}
function map_tooltip(marker, html) {
	obj_name = 'map_tooltip';
	if(!document.getElementById(obj_name)) {
		embryo = document.createElement('div');
		embryo.id = obj_name;
		embryo.style.position = 'absolute';
		obj = map.map.getDiv().appendChild(embryo);
		obj.onmouseout = map_start_close_tooltip;
		obj.onmouseover = map_cancel_close_tooltip;
		embryo = document.createElement('div');
		child = obj.appendChild(embryo);
	}
	else {
		obj = document.getElementById(obj_name)
		child = obj.children[0];
	}
	obj.style.display = 'block';
	arr = map.map.getProjection().fromLatLngToPoint(marker.getPosition())
	
	var scale = Math.pow(2, map.map.getZoom());
	var nw = new google.maps.LatLng(
		map.map.getBounds().getNorthEast().lat(),
		map.map.getBounds().getSouthWest().lng()
		);
	var worldCoordinateNW = map.map.getProjection().fromLatLngToPoint(nw);
	var worldCoordinate = map.map.getProjection().fromLatLngToPoint(marker.getPosition());
	var x = Math.floor((worldCoordinate.x - worldCoordinateNW.x) * scale)
	var y = Math.floor((worldCoordinate.y - worldCoordinateNW.y) * scale)

	obj.style.left = (x + map['title_offset_x']) + 'px';
	obj.style.top = (y + map['title_offset_y']) + 'px';
	child.innerHTML = html;
}
function load_location_info(id,index) {
	if(map['current_active']) {
		document.getElementById('map_id_'+map['current_active']).className = 'inactive';
	}
	obj = document.getElementById('map_id_'+id);
	obj.className = 'active';
	images = obj.getElementsByTagName('img');
	for(i=0;i<images.length;i++) {
		image = images[i];
		if(image.className == 'blind') {
			image.src = image.getAttribute('alt');
			image.className = '';
		}
	}
	if(obj.getAttribute('widget') != '') {
		source = document.getElementById('map_widget_'+obj.getAttribute('widget')).getElementsByTagName('div')[0];
		divs = obj.getElementsByTagName('div').length;
		found = false;
		i = 0;
		while(!found && i < divs) {
			if(obj.getElementsByTagName('div')[i].className == 'map_widget') {
				found = obj.getElementsByTagName('div')[i];
			}
			i++;
		}
		embryo = source.cloneNode(true);
		found.appendChild(embryo);
		obj.setAttribute('widget','');
	}
	if(map['current_active'] != id) {
		map_gdir_close()
	}
	map['current_active'] = id;
	document.getElementById('gdir_form_header').innerHTML = 'Vägbeskrivning till '+gm_title[index];
	map.toAddress = new google.maps.LatLng(gm_x[index],gm_y[index]);
	if(document.getElementById('map_tooltip')) {
		adulterine = document.getElementById('map_tooltip');
		adulterine.parentNode.removeChild(adulterine);
	}
}
function load_travel_info(obj) {
	if(map['current_travel_active']) {
		document.getElementById(map['current_travel_active']).className = 'inactive';
	}
	pobj = obj;
	while(pobj.nodeName != 'DT') {
		pobj = pobj.parentNode;
	}
	while(pobj.nodeName != 'DD') {
		pobj = pobj.nextSibling;
	}
	pobj.className = 'active';
	map['current_travel_active'] = pobj.id
}

function html_value(obj) {
	var text;
	if(obj.children.length == 0) {
		text = (obj.textContent) ? obj.textContent : obj.innerHTML;
	}
	else {
		new_obj = obj.children[0].childNodes[1]
		text = (new_obj.textContent) ? new_obj.textContent : new_obj.innerHTML;
	}
	if(!text) { 
		text = obj.childNodes[0].innerHTML;
	}
	return text;
}
function debug(obj) {
	nodes = Array();
	nodes.push(obj);
	out = '';
	limit = 20;
	path = '';
	while((limit > 0) && (node = nodes.shift())) {
		out += path + ' ' + node.nodeName + ':'+node.innerHTML+'<br>';
		if(node.childNodes.length > 0) {
			path = node.nodeName;
			for(i=0;i<node.childNodes.length;i++) {
				nodes.push(node.childNodes[i]);
			}
		}
		limit--;
	}
	return out;
}
function suicide(obj) {
	obj.parentNode.className = 'inactive';
}
function map_dir_form() {
	map.gdir_display.setPanel(document.getElementById("map_directions"));
	obj = document.getElementById('overlay_directions')
	obj.style.display = 'block';
	obj.className = '';
}
function map_gdir_close() {
	map.gdir_display.setPanel(null);
	document.getElementById('overlay_directions').style.display = 'none';
}
function map_gdir_minimize() {
	obj = document.getElementById('overlay_directions');
	obj.className = 'minimized';
	obj.title = map.text.restore;
	if(obj.attachEvent ){
		obj.attachEvent('onclick', map_gdir_restore);
	} else {
		obj.setAttribute('onclick', 'map_gdir_restore()'); 
	}
}
function map_gdir_restore() {
	document.getElementById('overlay_directions').className = '';
	obj.title = '';
	if(obj.detachEvent){
		obj.detachEvent('onclick', map_gdir_restore);
	} else {
		obj.setAttribute('onclick', ''); 
	}
}

function overlay_directions() {
	map.fromAddress = document.getElementById("city").value;
	if(map.fromAddress == 'Järna') {
		map.fromAddress = 'Järna, Södertälje';
	}
	map.fromAddress += ", Sverige";
	if(map['current_active']) {
		document.getElementById('map_id_'+map['current_active']).className = 'inactive';
	}
	document.getElementById('gdir_a').href = 'javascript:map_gdir_minimize()';
	var request = {
		origin:map.fromAddress,
		destination:map.toAddress,
		travelMode: google.maps.DirectionsTravelMode.DRIVING
	};

	map.gdir_service.route(request, function(result, status) {
		if (status == google.maps.DirectionsStatus.OK) {
			map.gdir_display.setDirections(result);
		}
		else {alert ('status is '+status)}
	});

// map.gdir.load("from: " + map.fromAddress + " to: " + map.toAddress);
}

function map_error(){
	gdir = map.gdir_service;
	if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
		alert('Fel #1: Adressen "'+map.fromAddress+"\" kunde inte tolkas. Det kan bero på felstavning eller på att adressen är ny.\nError code: " + gdir.getStatus().code);
	else if (gdir.getStatus().code == G_GEO_SERVER_ERROR)
		alert("Fel #2: A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known.\n Error code: " + gdir.getStatus().code);
	else if (gdir.getStatus().code == G_GEO_MISSING_QUERY)
		alert("Fel #3: The HTTP q parameter was either missing or had no value. For geocoder requests, this means that an empty address was specified as input. For directions requests, this means that no query was specified in the input.\n Error code: " + gdir.getStatus().code);
	else if (gdir.getStatus().code == G_GEO_BAD_KEY)
		alert("Fel #4: Felaktig API-nyckel. \n Error code: " + gdir.getStatus().code);
	else if (gdir.getStatus().code == G_GEO_BAD_REQUEST)
		alert("Fel #5: A directions request could not be successfully parsed.\n Error code: " + gdir.getStatus().code);
	else alert("Fel #6: Okänt fel: "+gdir.getStatus().code);
}


