var posterNav = undefined;
var poiHandlers = {}
var stationMarkers = {}

// var initPosition = {'x': -1.6785900836, 'y': 48.1112317125, 'epsg': '4326'};
var initPosition = {'x':1353010, 'y':7222902, 'epsg':'3948'};
var dbprefix = "Rennes";
var mapType = "ortho";


var poiStyleOpts = {
	"default": {"url":"images/poi_repere.png","width":20,"height":24,"iconAnchor":{'x':10,'y':22},"labelAnchor":{'x':-60,'y':-40}}, 
	"metro": {"url":"images/poi_metro.png","width":28,"height":28,"iconAnchor":{'x':14,'y':14},"labelAnchor":{'x':-60,'y':-40}, "zIndex":200}, 
	"metro_p": {"url":"images/poi_metro_p.png","width":40,"height":40,"iconAnchor":{'x':14,'y':26},"labelAnchor":{'x':-60,'y':-40}, "zIndex":200},
	"metro_a": {"url":"images/poi_metro_a.png","width":28,"height":28,"iconAnchor":{'x':14,'y':14},"labelAnchor":{'x':-60,'y':-40}}, 
	"metro_p_a": {"url":"images/poi_metro_p_a.png","width":40,"height":40,"iconAnchor":{'x':14,'y':26},"labelAnchor":{'x':-60,'y':-40}}
	};

function getMarker(name,x,y,epsg,style,link)
{
	var markerObj = new arMarker(name,new arPoint(x,y,epsg),poiStyleOpts[style]);
	switch (typeof(link)) {
		case 'string' :
			markerObj.infoWindowUrl = link;
			break;
		case 'function' :
			markerObj.infoWindowOpen = link;
			break;
	}
	return markerObj;
}

function addPlacemarks(markerContainer, json, epsg, style)
{
	var markerList = json.Document.Placemark;
	for(var i = 0; i < markerList.length; i += 1)
	{
		var markerInfo = markerList[i];
		var coordinates = markerInfo.Point.coordinates;
		var coords = coordinates.split(',',3);
		var markerObj = getMarker(markerInfo.name,coords[0],coords[1],epsg,style);
		// markerObj.moreinfoimg.src = "images/spacer.gif";
		markerObj.mouseover = function(evt) {this.showLabel();}
		markerObj.mouseout = function(evt) {this.hideLabel();}
		markerObj.click = function(evt) {this.hideLabel();}
		
		markerContainer.addMarker(markerObj);
	}    		
}		

function addStations(markerContainer, json, markerRefList)
{
	var prefix = 'ligne '+json.name+'<br/>station ';
	var ligne_id = json['@attributes'].id;
	for(var i = 0; i < json.station.length; i += 1)
	{
		var json_station = json.station[i];
		var station_id = json_station['@attributes'].id
		var style = 'metro';
		if (Boolean(parseInt(json_station.parking))) style += '_p';
		var station_fn = undefined;
		if (ligne_id == '2') {
			// dynamic function must be defined here for each value or i in the looping
			// in order to do this, dynamic function must be evaluated immediately within another function getting each value of i so of id
			// here we define a temporary function returning the needed function for the arMarker that will be evaluated later.
			// this temporary function is evaluated immediately with id=json_station.@attributes.id to get the appropriate id
			// use of parentheses allows us to call the temporary function once without affecting it to a variable
			// good explanation of this can be found at : http://calculist.blogspot.com/2005/12/gotcha-gotcha.html
			station_fn = (function(id) {return function() {openInfoStation(id)};})(station_id);
			//station_fn = 'station.php?id='+json_station.@attributes.id
			var station_name = poiInfos[station_id].name;
			if (json_station.name != station_name) json_station.name = station_name;
		}
		else style += '_a';
		
		var markerObj = getMarker(prefix+json_station.name,json_station.x,json_station.y,json.epsg,style,station_fn);
		markerObj.mouseover = function(evt) {this.showLabel();}
		markerObj.mouseout = function(evt) {this.hideLabel();}
		var fn = (function(id) {return function() {displayInfoStation(id, ligne_id)};})(station_id);
		markerObj.click = fn;
		if (markerRefList != undefined) markerRefList[json_station['@attributes'].id] = markerObj;
		markerContainer.addMarker(markerObj);
		
	}    		
}		

function initialize()
{
	if (window.ieAdjustDivHeight) ieAdjustDivHeight();

	hideAddressBar();
	
	posterNav = new arPosterNav("poster");
	posterNav.disableControls();
	window.onresize = handleEvent(posterNav,"checkResize"); 
	posterNav.forceDbName(dbprefix);
	markerHandler = new arMarkerHandler(posterNav);
	addPlacemarks(markerHandler, poiReperes, "4326", "default");
	poiHandlers['repere'] = markerHandler;
	markerHandler = new arMarkerHandler(posterNav);
	addStations(markerHandler, poiStationsA);
	poiHandlers['a'] = markerHandler;
	markerHandler = new arMarkerHandler(posterNav);
	addStations(markerHandler, poiStationsB, stationMarkers);
	poiHandlers['b'] = markerHandler;
	markerHandler = new arMarkerHandler(posterNav);
	poiHandlers['adresse'] = markerHandler;
	posterNav.goTo(new arPoint(initPosition.x,initPosition.y,initPosition.epsg),{"resolution":16});
}

function togglePoster(imgNode)
{
	var cartoStatus;
	var newMapType;
	var buttonTitle;
	if (mapType == "carto") {
		cartoStatus = "off";
		newMapType = "ortho";
		buttonTitle = "afficher la vue cartographiée";
		showDiv('copyright');
	}
	else {
		cartoStatus = "on";
		newMapType = "carto";
		buttonTitle = "afficher la vue photographique";
		hideDiv('copyright');
	}
	var prefix = dbprefix;
	reloadPoster(prefix, newMapType);
	imgNode.src='images/boutons/carto_'+cartoStatus+'.png';
	imgNode.title = buttonTitle;
}

function reloadPoster(newdbprefix,newmapType)
{
	if( (newdbprefix!=dbprefix) || (newmapType!=mapType) )
	{
		dbprefix = newdbprefix;
		mapType = newmapType;
		var dbname = dbprefix;
		if(mapType=="carto")
			dbname += "_carto";
		//alert(dbname);
		posterNav.forceDbName(dbname);
		posterNav.getCurrentMapCenter(posterNav,"setCurrentMapCenter");
	}
}

function backToStart()
{
	posterNav.panTo(new arPoint(lng,lat,epsg));
}

function openInfoStation(id)
{
	window.open('station.php?id='+id, 'station');
}

function centerAndFocusStation(id)
{
	var markerObj = stationMarkers[id];
	var pos = markerObj.getWorldPosition();
	/* var json = poiStationsB.station[id];
	pos = new arPoint(parseFloat(json.x), parseFloat(json.y), poiStationsB.epsg); */
	// alert(pos.getX()+','+pos.getY()+','+pos.getProjection());
	posterNav.panTo(pos); //, {"resolution":1});
	displayInfoStation(id, '2');
}

function displayInfoStation(id, id_ligne)
{
	var json;
	switch (id_ligne) {
		case '1' : json = poiStationsA; break;
		case '2' : json = poiStationsB; break;
	}
	var i = parseInt(id)-1;
	if (id_ligne == '2') {
		var xhtml = '<p class="titre bleu centre">'+json.station[i].name+'</p>';
		// summary of station description
		xhtml += poiInfos[id].summary;
		// link to station page
		xhtml += '<p class="droite"><a href="station.php?id='+id+'" target="station">En savoir plus...</a></p>';
		// first 3 images related to the station
		var visus = poiInfos[id].visu;
		if (visus.length > 0) {
			xhtml += '<p class="visu">';
			for(var i_visu = 0; i_visu < 3; i_visu++)
			{
				if (i_visu >= visus.length) break;
				var visu = visus[i_visu];
				xhtml += '<a href="station.php?id='+id+'&visu='+(i_visu+1)+'" target="station"><img src="thumb.php?src='+visu+'&w=60" width="60" /></a>';
			}    		
			xhtml += '</p>';
		}
		
		$('info-station').innerHTML = xhtml;
		showDiv('menu-station');
	}
}

function showDiv(div_id)
{
	switch (div_id) {
		case 'menu-station' : hideDiv('menu-ligne'); break;
		case 'menu-ligne' : hideDiv('menu-station'); break;
	}
	$(div_id).style.display = 'block';
}
function hideDiv(div_id)
{
	$(div_id).style.display = 'none';
}
function toggleDiv(div_id)
{
	var div = $(div_id);
	var current_display = div.style.display;
	if (current_display == undefined || current_display == '') current_display=div.getStyle("display");
	if (current_display == 'none') showDiv(div_id);
	else hideDiv(div_id);
}

function collapseDiv(div_node)
{
	var div_id = div_node.id;
	div_node.style.height = '14px';
    $(div_id+'-collapse').style.display = 'none';
    $(div_id+'-expand').style.display = 'block';
}
function expandDiv(div_node)
{
	var div_id = div_node.id;
	div_node.style.height = '';
    $(div_id+'-expand').style.display = 'none';
    $(div_id+'-collapse').style.display = 'block';
}

// already defined in prototype.js
/*if (!window.getStyle) {
function getStyle(el,styleProp)
{
	var x = document.getElementById(el);
	if (x.currentStyle)
		var y = x.currentStyle[styleProp];
	else if (window.getComputedStyle)
		var y = window.getComputedStyle(x,null).getPropertyValue(styleProp);
	return y;
}
}*/

