/******************************************************************************\
*  geoxml.js		                               by Lance Dyas          *
*  A Google Maps API Extension  GeoXml parser                                 *
*  GeoXml Parser based on my maps kml parser by Mike Williams called egeoxml  *
*  Additions include:   GML/WFS/GeoRSS/GPX expanded GE KML style support      *                                            
\******************************************************************************/
function KMLObj(title,desc) {
	this.title = title;
	this.description = escape(desc);
	this.marks = [];
	this.folders = [];
	this.groundOverlays = [];
}
function GeoXml(myvar, map, url, opts,chaine_id) {
	// store the parameters
	this.myvar = myvar;
	this.opts = opts || {};	
	this.map = map;	
	this.url = url;
	this.tab_marker = new Array();	
	this.bounds = new GLatLngBounds();	
	this.kml = [new KMLObj("GeoXML","")];	
	this.styles = new Array();
}
function gebyi(mid){ return document.getElementById(mid);}
GeoXml.prototype.parse = function(titles) {
	var that = this;
	that.loadXMLUrl(this.url);
};
var xml_doc_temp ;
GeoXml.prototype.loadXMLUrl = function (url, title, latlon, desc, idx) {
	var that = this;	
	that.DownloadURL(url, function(doc) { that.processing(doc, title, latlon, desc, idx) }, title);
}
GeoXml.prototype.DownloadURL = function (url, callback, title) {
	var xmlDoc, t; 
	var that = this;
	var req;		
	if (! req && typeof XMLHttpRequest != 'undefined') {
		req = new XMLHttpRequest();
	}
	else {
		if (typeof ActiveXObject != "undefined") {
			req = new ActiveXObject("Microsoft.XMLHTTP");
		}
	}
	method = "GET";
	if(req.overrideMimeType)req.overrideMimeType("text/plain");
	req.open(method,url, true);
	req.onreadystatechange = function () {
		
		
		switch (req.readyState) {
		case 4:
			
			if (typeof ActiveXObject != "undefined") {
				callback(req.responseText);					
			}
			else {
				if (req.responseText) {
					
					xmlDoc = req.responseText;
					xml_doc_temp = xmlDoc ;
					callback(xmlDoc, title);
					cmlrepeats = 0;
				}
				else {
					if (req.status == 200) {
						var resp = req.responseText;
						var sresp = resp.substring(0, 400);
						var eresp = resp.substring(400);
						var isXML = resp.substring(0, 5);
						if (isXML == "<?xml") {
							if (typeof DOMParser != "undefined") {
								var parser = new DOMParser();
								xmlDoc = parser.parseFromString(resp, "text/xml");
								var roottag = xmlDoc.documentElement;
								if (roottag.tagName != "parserError") {
									callback(xmlDoc,title); 
								}
							}
						}							
					}
					else {
						if (req.responseText) alert(req.responseText);
					}                       
				}
			}
			break;
		}
	};
	
	req.send(null);
}
var json_temp ;
GeoXml.prototype.processing = function(xmlDoc,title, latlon, desc, sbid) {
		jsonfromxml = xml2json.parser(xmlDoc);
		json_temp = jsonfromxml ;
	if(!desc)desc = title;
	var that = this;
	if(!sbid)sbid = 0;
	var root = jsonfromxml.kml;
	var placemarks = [];
	basename = jsonfromxml.kml;
	var styles = basename.document.style; 
	if(styles){
	    if(styles.length){
		    for (var i = 0; i <styles.length; i++) {
			    var sid= styles[i].id;
			    if(sid){ 
				    this.handleStyle(styles[i],sid);
			    }
		    }	
	    }
	    else{
		    var sid= styles.id;
		    this.handleStyle(styles,sid);
	    }
	}
		if(!title)title = name;
	this.title = title;
	if(title.length >this.maxtitlewidth){
		this.maxtitlewidth = title.length;
	}
	this.processJSON(basename.document);	
	GEvent.trigger(that,"parsed");		
};
GeoXml.prototype.processJSON = function(node) {  
	this.nodes = node ;
	if(this.nodes && node.placemark){
		if(node.placemark.length){
		var len = node.placemark.length ;
			for(i=0;i<len;i++) {				
				//setTimeout("geoXml.handlePlacemark2("+i+")",i);
				this.handlePlacemark2(i);
			}
		}
		else{
			//setTimeout("geoXml.handlePlacemark2(-1)",i*30);
			this.handlePlacemark2(-1);
		}
	}
	
};
GeoXml.prototype.afficher_temp = function(){
    var l = this.tab_marker.length ;
    for(var i = 0;i<l;i++){
        this.map.addOverlay(this.tab_marker[i]);
    }
}
GeoXml.prototype.handlePlacemark = function (mark) {	
	var that = this;
	var desc, title, name, style;
	title = "";
	desc = "";
	var styleid = 0;
	var lat, lon;
	var visible = true;
	var newcoords = false;
	var coordset=mark.point.coordinates;
	var coords = "";
	name = (mark.name) ? mark.name : "";		
	desc = (mark.description) ? mark.description : "";
	var cor = mark.point.coordinates.split(',');		
	styleid = mark.styleUrl ;
	if(!name && title)name = title; 	
	if(styleid){
		style = this.styles[styleid];		
	}
	else{
	    style = "";
	}	
	var point = new GLatLng(parseFloat(cor[1]),parseFloat(cor[0]));	
	that.createMarker(point, name, desc, style);		
};
GeoXml.prototype.handlePlacemark2 = function(index){
	if(index >= 0){
		this.handlePlacemark(this.nodes.placemark[index]);
	}
	else{
		this.handlePlacemark(this.nodes.placemark);
	}
}
var temp_drag ;
var mark_temp ;
GeoXml.prototype.createMarker = function(point,name,desc,instyle) {
	var icon;	
	var markeroptions =  {};
	var icontype =  "style";
	if(instyle != "")		
	markeroptions.icon = instyle;	
	markeroptions.title = (name.length >= 4) ? name : "";
	markeroptions.zIndexProcess = importanceOrder;
	var m = new GMarker(point, markeroptions);
	var taille = parseInt(name) ;
	m.title = (name.length >= 4) ? name : "";
	//m.title =  name;
	var obj = {"type":"point","title":name,"description":escape(desc),"href":instyle.image,"shadow": null,"visibility":true,"x":point.x,"y": point.y};
	this.kml[0].marks.push(obj);
	var rendu ;
	var desc_temp ="";
	this.desc_temp = desc ; 
	var un_tab = jeval(desc);
	desc_temp = {tab:un_tab};

	
	rendu = TrimPath.processDOMTemplate("tpl_bulle_map", desc_temp);
	var html1 = "<div class='infowindow' >"+rendu+"<img class='fleche_infowindow' src='./style/infowindow_fleche.png'/></div>";
	m.importance = 3 ;		
	m.desc = desc_temp;
	
	GEvent.addListener(m, "click", function() {
		if (typeof MyOverlay !== 'undefined') {
			if (currentMarker  ) {
				closeOverlay();
			}
			if (!m.overlay) {
				// just recording this for use in the closeOverlay function
				this.overlay = new MyOverlay(this, html1);
			}
			currentMarker = this;
			map.addOverlay(this.overlay);
		} else {
			marker.openInfoWindowHtml(html);
		}
	});
    this.tab_marker.push(m);
	this.map.addOverlay(m);
};
GeoXml.prototype.SetCenterAutomaticly = function(){
    var bou = new GLatLngBounds();
    for(var i = 0;i<this.tab_marker.length;i++){
        var m = this.tab_marker[i];
        
        bou.extend(m.getLatLng());
    }
    this.map.setCenter(bou.getCenter(),this.map.getBoundsZoomLevel(bou));
}
GeoXml.prototype.handleStyle = function(style,sid){
	var icons=style.IconStyle.Icon;
	var tempstyle;
	var href=icons.href;			
	tempstyle = this.makeIcon(tempstyle,href);		
	if(sid){this.styles["#"+sid] = tempstyle;			}
	return tempstyle;
}
var temp_icon ;
GeoXml.prototype.makeIcon = function(tempstyle, href){
	if (!!href) {
		tempstyle = new GIcon();
		var taille = ImageSize(href);
		var width_icon ;
		var height_icon ;
		if(taille.width == 0 || taille.height == 0){
			taille = {width:32,height:32};	
		}
		//cas ou je done une largeur mais que ça n'agrandi pas l'icone
		if(this.opts.width_icon && this.opts.width_icon < taille.width){
			//si on a pas pu renseigner les dimension de l'icone			
			width_icon = this.opts.width_icon ;
			height_icon = ((taille.height * width_icon) / taille.width ) ;
		}
		else{			
			width_icon = taille.width  ;
			height_icon = taille.height  ;
		}
		
		tempstyle.infoWindowAnchor = new GPoint(width_icon/2,height_icon/2);
		tempstyle.iconSize = new GSize(width_icon,height_icon);
		tempstyle.iconAnchor = new GPoint(width_icon/2,height_icon/2);
		tempstyle.imageMap = [0,0,(width_icon - 1),0,(height_icon - 1),(width_icon - 1),0,(height_icon - 1)];
		tempstyle.image = href;	
		tempstyle.shadow="";		
		temp_icon = tempstyle;
	}
	return tempstyle;
};

var currentMarker ;
var MyOverlay = function(marker, html) {
	this.marker = marker;
	this.html = html;
}
MyOverlay.prototype = new GOverlay();
MyOverlay.prototype.initialize = function(map2) {
	var div = document.createElement("div");
	div.className = 'mywindow';
	div.innerHTML = this.html;
	// offsets based on popup div dimensions
	offsetX = 45;
	var  point = map2.fromLatLngToDivPixel(this.marker.getLatLng());
	var point_center =  map2.getPane(G_MAP_FLOAT_PANE);
	var y =  - point.y  + 49;
	div.style.bottom = y + 'px';
	div.style.left = (point.x - offsetX) + 'px';
	div.style.position="absolute";
	this._map = map2;
	this._div = div;  
	map2.getPane(G_MAP_FLOAT_PANE).appendChild(div);
	var TlcLatLng = map.fromContainerPixelToLatLng(new GPoint(0,0),true);
	var TlcDivPixel = map.fromLatLngToDivPixel(TlcLatLng);
	var pointContainerPixel = subGPoints(point, TlcDivPixel); 
	var div_top = pointContainerPixel.y - div.offsetHeight - 30 - 43;
	var div_left = pointContainerPixel.x - offsetX;
	var marger_gauche = 30 ;
	var marge_droit = 20 ;
	if(div_top < 0 || (div_left - marger_gauche)  < 0 || (div_left + div.offsetWidth+ marge_droit) > map2.getSize().width)
	{
		var center = map2.getSize();
		var point_milieu = new GPoint(center.width/2,center.height/2);
		var point2 = addGPoints(point_milieu, TlcDivPixel); 
		if(div_top < 0 ){
			point2.y += div_top ;
		}      
		if(div_left < 0){
			point2.x += div_left - marger_gauche ;
		}
		if((div_left + div.offsetWidth) > map2.getSize().width){
			point2.x -=  map2.getSize().width - (div_left + div.offsetWidth) - marge_droit;
		}        
		map.panTo(map.fromDivPixelToLatLng(point2));        
	}  
	map2.getPane(G_MAP_FLOAT_PANE).appendChild(div);
}
MyOverlay.prototype.remove = function(){
	//this._div.parentNode.removeChild(this._div);
}
MyOverlay.prototype.redraw = function() {
}
MyOverlay.prototype.handleEvent = function(event){}


function closeOverlay() {
	if (currentMarker &&  currentMarker.overlay._div.parentNode) {
		currentMarker.overlay._div.parentNode.removeChild(currentMarker.overlay._div);
		//map.removeOverlay(currentMarker.overlay);
		currentMarker.show();
		overlay_temp = null;
	}
}
