var map = null;
var xml = null;
var datas = null;
var deleted = new Array();

extend = function (subClass, baseClass) {
   function inheritance () {}
   inheritance.prototype = baseClass.prototype;
   subClass.prototype = new inheritance ();
   subClass.prototype.constructor = subClass;
   subClass.baseConstructor = baseClass;
   subClass.superClass = baseClass.prototype;
}

function VGLoad(isAdmin) {
	map = gInitMap ();
	if (map != null) {
		map.isAdmin = isAdmin;
	
		//map.create (new GLatLng(37.4419, -122.1419), 13);
		map.setCenter(new GLatLng(43.431524, 6.417008), 8);	
	GEvent.addListener (map, "infowindowclose", function(){
			document.getElementById('i').value = '';
			//document.form.reset();
		});
		
		//map.enableControls (true, true, true, true, true, true);
		//map.enableGoogleBar();
		map.addControl(new DragZoomControl());
		map.addControl(new GLargeMapControl());
		map.addControl(new GMapTypeControl());
		//map.addControl(new GOverviewMapControl (new GSize(200,200)));
		
		map.importXML("includes/astros.xml");
		//xml = new Array();
		//xml = importXML("http://www.vigneron-independant.com/googlemap/example.xml", XmlToMap);
	}
}

function VGoogleMap (container) {
	this.isAdmin = false;
	this.bounds  = new GLatLngBounds();
	this.markers = new Array();
	this.htmls = new Array();
	this.icons = new Array();
	
	GMap2.call (this, container);
	
	this.importXML = function (url) {
		if (document.implementation && document.implementation.createDocument) {
			xmlDoc = document.implementation.createDocument ("", "", null);
			xmlDoc.onload = _xmlToMap;
		}
		else if (window.ActiveXObject) {
			xmlDoc = new ActiveXObject ("Microsoft.XMLDOM");
			xmlDoc.onreadystatechange = function () {
				if (xmlDoc.readyState == 4) this._xmlToMap ();
			};
		}
		else {
			alert ('Your browser can\'t handle this script');
			return;
		}
		
		xmlDoc.load (url);
		
		xml = xmlDoc;
	}
	
	_xmlToMap = function ()
	{
		function _getNodeValue (element) {
			return (element.hasChildNodes() ? element.firstChild.nodeValue : '');
		}
		
		var mark = xml.getElementsByTagName ('Placemark');
		var name = xml.getElementsByTagName ('name');
		var address_line_1 = xml.getElementsByTagName ('address_line_1');
		var address_line_2 = xml.getElementsByTagName ('address_line_2');
		var city = xml.getElementsByTagName ('city');
		var state = xml.getElementsByTagName ('state');
		var postal_code = xml.getElementsByTagName ('postal_code');
		var main_phone = xml.getElementsByTagName ('main_phone');
		var fax = xml.getElementsByTagName ('fax');
		var url = xml.getElementsByTagName ('url');
		var description = xml.getElementsByTagName ('description');
		var coordinates = xml.getElementsByTagName ('coordinates');
		var icon = xml.getElementsByTagName ('icon');
	
	
	/*	function _getXmlValues (obj) {
			var res = new Array();
			
			for (var j=0; j<obj.childNodes.length; ++j) {
				if (obj.childNodes[j].nodeType == 3)
					return obj.childNodes[j].nodeValue;
				else
					res[j] = _getXmlValues (obj.childNodes[j]);
			}
			
			return res;
		}
		
		datas = new Array (mark.length);
		for (var i=0; i<mark.length; ++i) {
			datas[i] = _getXmlValues (mark[i]);
		}*/
		
/*for (i=0; i<datas.length; ++i)
{
	var ligne = '';
	for (j=0; j<datas[i].length; ++j)

		ligne += j + ' -> ' + datas[i][j] + '\n';
	
	alert(ligne);
}*/
	
		datas = new Array (mark.length);
		for (var i=0; i<datas.length; ++i)
		{
			datas[i] = new Array();
			datas[i][0] = _getNodeValue (name[i]);
			datas[i][1] = _getNodeValue (address_line_1[i]);
			datas[i][2] = _getNodeValue (address_line_2[i]);
			datas[i][3] = _getNodeValue (city[i]);
			datas[i][4] = _getNodeValue (state[i]);
			datas[i][5] = _getNodeValue (postal_code[i]);
			datas[i][6] = _getNodeValue (main_phone[i]);
			datas[i][7] = _getNodeValue (fax[i]);
			datas[i][8] = _getNodeValue (url[i]);
			datas[i][9] = _getNodeValue (description[i]);
			
			var coords = new String ((coordinates[i].hasChildNodes() ? coordinates[i].firstChild.nodeValue : '0,0,0'));
			var LngLatZm = coords.split (',');
			
			datas[i][10] = LngLatZm[0]; //lng
			datas[i][11] = LngLatZm[1]; //lat
			datas[i][12] = LngLatZm[2]; //zoom
			
			datas[i][13] = (icon[i].hasChildNodes() ? icon[i].firstChild.nodeValue : ''); //icon filename
	
			address = datas[i][1] + ' ' +
					  datas[i][2] + ' ' +
					  //datas[i][5] + ' ' +
					  datas[i][3] + ' ' +
					  datas[i][4];
		
			//gFindMarker (map, address, htmls[i], i);
			map.addMarker (new GLatLng (datas[i][11], datas[i][10]), i,true,false);
			//document.getElementById ('VGM_panel').innerHTML += '<a href="javascript:map.markerClicked(map,' + i + ')">' + datas[i][0]+'</a><br/>';
		}
	}
	
	this.zoomFit = function() {
		map.setCenter (this.bounds.getCenter(), map.getBoundsZoomLevel (this.bounds));
	}
		
	this.updateLatLngData = function (data) {
		data[10] = document.getElementById('lng').value;
		data[11] = document.getElementById('lat').value;
	}
	
	this.addMarker = function (coord, i, isDraggable, isUpdateZoom) {
		this.closeInfoWindow();
		
		if (!this.isAdmin)
			isDraggable = false;
		
		this.icons[i] = map.getIcon(i, datas[i][13]);
		this.markers[i] = new GMarker(coord);//, {icon:this.icons[i], draggable: isDraggable});
		this.htmls[i] = map.getHtmlFromData(this,datas[i]);
		deleted[i] = false;
		
		GEvent.addListener (this.markers[i], "click", function(){map.markerClicked(map,i);});
		
		GEvent.addListener (this.markers[i], "infowindowopen", function() {
			document.getElementById('i').value = i;
		});
		
		if (isDraggable) {
			this.markers[i].enableDragging();
			
			GEvent.addListener (this.markers[i], "drag", function(){
				this.closeInfoWindow();
				map.updateLatLngForm(i);
			});
			
			GEvent.addListener (this.markers[i], "dragend", function(){
				map.updateLatLngData(datas[i]);
			});
		}
		
		if (this.isAdmin)
			GEvent.addListener (this.markers[i], "visibilitychanged", function(isVisible){
					deleted[i] = !isVisible;
					map.closeInfoWindow();
			});
		
		this.addOverlay(this.markers[i], 15);
		
		if (isUpdateZoom) {
			this.bounds.extend(coord);
			this.zoomFit();
		}
	}

	this.reInit = function () {
		document.form.reset();
	
		var i = document.getElementById('i').value;
		if (i == '') return;
		
		this.markers[i].setLatLng (new GLatLng(datas[i][11],datas[i][10]));
		map.openInfoWindow(this.htmls[i], i);
		map.setFormFromData(datas[i], i);
	}
	
	this.submitData = function () {
		map.updateData(this);
		document.getElementById('VGM_datas').value = datasToString ('_','|');
		return true;
	}
	
	this.FormToData = function (map) {
		var data = new Array();
		
		data[0] = document.getElementById('name').value;
		data[1] = document.getElementById('address_line_1').value;
		data[2] = document.getElementById('address_line_2').value;
		data[3] = document.getElementById('city').value;
		data[4] = document.getElementById('state').value;
		data[5] = document.getElementById('postal_code').value;
		data[6] = document.getElementById('main_phone').value;
		data[7] = document.getElementById('fax').value;
		data[8] = document.getElementById('url').value;
		data[9] = document.getElementById('description').value;
		data[13] = document.getElementById('icon').value;
		map.updateLatLngData(data);
		
		return data;
	}
	
	this.updateLatLngForm = function (i) {
		document.getElementById('lng').value = this.markers[i].getLatLng().lng();
		document.getElementById('lat').value = this.markers[i].getLatLng().lat();
	}
	
	this.getHtmlFromData = function (map, data) {
		var html = '';
		if (data[0] != '') html = '<strong>'+data[0]+'</strong><br/><br/>';
		html += '<i>';
		if (data[1] != '') html += data[1]+'<br/>';
		if (data[2] != '') html += data[2]+'<br/>';
		if (data[5] != '') html += data[5]+' ';
		if (data[3] != '') html += data[3]+' ';
		if (data[4] != '') html += '('+data[4]+')';
		html += '</i><br/>';
		if (data[6] != '') html += 'tel : '+data[6]+'<br/>';
		if (data[7] != '') html += 'fax : '+data[7]+'<br/>';
		if (data[8] != '') html += '<a target="_blank" href="http://'+data[8]+'">'+data[8]+'</a>';
		
		if (map.isAdmin)
			html += '<br/><br/><a href="javascript:map.deleteMarker()">X</a>';
		
		return html;
	}
	
	this.updateData = function (map) {
		var i = document.getElementById('i').value;
		if (i == '') return;
	
		datas[i] = map.FormToData (map);
		this.htmls[i] = map.getHtmlFromData(map,datas[i]);
	}
	
	this.setFormFromData = function (data, i) {
		document.getElementById('name').value = data[0];
		document.getElementById('address_line_1').value = data[1];
		document.getElementById('address_line_2').value = data[2];
		document.getElementById('city').value = data[3];
		document.getElementById('state').value = data[4];
		document.getElementById('postal_code').value = data[5];
		document.getElementById('main_phone').value = data[6];
		document.getElementById('fax').value = data[7];
		document.getElementById('url').value = data[8];
		document.getElementById('description').value = data[9];
		document.getElementById('lng').value = data[10];
		document.getElementById('lat').value = data[11];
		document.getElementById('icon').value = datas[i][13];
	
		map.updateLatLngForm(i);
	}
	
	this.openInfoWindow = function (html, i) {
		this.markers[i].openInfoWindowHtml (html);
	}
	
	this.markerClicked = function (map, i) {
		map.openInfoWindow(this.htmls[i], i);
		
		if (map.isAdmin)
			map.setFormFromData(datas[i], i);
		//map.setCenter(markers[i].getLatLng(), map.getZoom());
	}
	
	
	this.formToHtml = function (map) {
		var i = document.getElementById('i').value;
		if (i == '') return;
		
		datas[i] = map.FormToData(map);
		this.htmls[i] = map.getHtmlFromData(map,datas[i]);
		map.openInfoWindow(this.htmls[i], i);
	}
	
	this.createMaker = function () {
		var last = this.markers.length;
		var center = map.getCenter();
		document.getElementById('lng').value = center.lng();
		document.getElementById('lat').value = center.lat();
		
		datas[last] = new Array(/*datas[0].length*/13);
		datas[last] = map.FormToData(map);
		
		map.addMarker (center, last, true, false);
		map.openInfoWindow(this.htmls[last], last);
	}
	
	this.deleteMarker = function () {
		this.markers[document.getElementById('i').value].hide();
	}
	
	this.modifyMarkerFromForm = function () {
		var i = document.getElementById('i').value;
		if (i == '') return;
		
		datas[i] = map.FormToData(map);
		var coord = this.markers[i].getLatLng();
		
		map.removeOverlay(this.markers[i]);
		map.addMarker(coord, i, true, false);
		
		map.openInfoWindow(this.htmls[i], i);
	}
	
	this.getIcon = function (i, filename) {
		icon = new GIcon(G_DEFAULT_ICON,(filename == '' ? '' : 'images/icons/'+filename));
		/*icon.image = "iconr.png";
		icon.shadow = "shadow-leaf_marker.png";
		icon.iconSize = new GSize(21.0, 68.0);
		icon.shadowSize = new GSize(56.0, 68.0);
		icon.iconAnchor = new GPoint(10.0, 34.0);
		icon.infoWindowAnchor = new GPoint(10.0, 34.0);*/
		
		return icon;
	}
}

extend (VGoogleMap, GMap2);


function gInitMap () {
	return GBrowserIsCompatible() ? new VGoogleMap(document.getElementById('VGM_map')) : null;
}

function tableToString (tbl, sep) {
	var res = (tbl[0]==''||!tbl[0]?' ':tbl[0]);
	
	for (var i=1; i<tbl.length; ++i)
		res += sep+(tbl[i]==''||!tbl[i]?' ':tbl[i]);

	return res;
}

function datasToString(sepLvl1, sepLvl2)
{
	var res = '';
	
	if (!deleted[0])
		res = tableToString (datas[0],sepLvl2);

	for (var i=1; i<datas.length; ++i)
		if (!deleted[i])
			res += sepLvl1+tableToString (datas[i],sepLvl2);

	return res;
}
