var xmlDocument;

/**
 * kaXmlOverlay( oKaMap, xml_url )
 *
 * oKaMap 	A kaMap object
 * zIndex	The z index of the layer
 */
function kaXmlOverlay( oKaMap, zIndex )
{
    kaTool.apply( this, [oKaMap] );
    this.name = 'kaXmlOverlay';
	this.session_pid = 1000000;

    for (var p in kaTool.prototype)
    {
        if (!kaXmlOverlay.prototype[p]) 
            kaXmlOverlay.prototype[p]= kaTool.prototype[p];
    }
    
    this.browser = new _BrowserIdent();
    
    this.urlBase = this.kaMap.server;
    this.urlBase += (this.urlBase!=''&&this.urlBase.substring(-1)!='/')?'':'/';

	// The list of overlay points
	this.ovrObjects = new Array();   
	
	// The cavas of the overlay layer
	this.z_index = zIndex;
	this.overlayCanvas = this.kaMap.createDrawingCanvas( zIndex );
	
	// Register for events
    this.kaMap.registerForEvent( KAMAP_SCALE_CHANGED, this, this.scaleChanged );

}

kaXmlOverlay.prototype.scaleChanged = function( eventID, mapName ) {
	if (this.ovrObjects == null) return;
	for (var i=0; i < this.ovrObjects.length; i++) {
		this.ovrObjects[i].rescale();
	}
}

/**
 * Remove the overlay layer and free resources user by overlay objects.
 */
kaXmlOverlay.prototype.remove = function() {
    this.kaMap.deregisterForEvent( KAMAP_SCALE_CHANGED, this, this.scaleChanged );
	this.removePoint();
	this.kaMap.removeDrawingCanvas(this.overlayCanvas);
}

/**
 * Load XML from the server and update the overlay.
 *
 * xml_url	URL of th XML with points to plot
 */
kaXmlOverlay.prototype.loadXml = function(xml_url, isURL) {
 	
 	var _this = this;
 	showProgressIndicator ();	
    var loadHandler = function (){    
	    var objDomTree = xmlDocument.documentElement;
	    var dels = objDomTree.getElementsByTagName("delete");
	    for (var i=0; i<dels.length; i++) {
		    // read the id attribute
		    var a_id = dels[i].getAttributeNode("id");
		    if (a_id == null) {
			    // delete all points
			    _this.removePoint();
		    } else {
			    _this.removePoint(a_id.value);
		    }
	    }
    	
	    var need_update = false;
    		
	    var points = objDomTree.getElementsByTagName("point");
	    for (var i=0; i<points.length; i++) {
		    // read the mandatory attributes
		    var a_pid = points[i].getAttributeNode("id");
		    var a_sid = points[i].getAttributeNode("sid");		 	  	
		    var a_comment = points[i].getAttributeNode("text");		
		    var a_nick1 = points[i].getAttributeNode("nick1");		 	
		    var a_nick2 = points[i].getAttributeNode("nick2");		 	
		    var a_tag = points[i].getAttributeNode("tag"); 				
		    var a_pictureUrl = points[i].getAttributeNode("picture"); 	
		    var a_date = points[i].getAttributeNode("date");
		 	//var a_answer = points[i].getAttributeNode("answer");

			    if (a_pid == null) {
			    continue;
		    }
		    var pid = a_pid.value;
		    var np = _this.getPointObject(pid);
		    if (np == null) {
			    // Create a new point
			    np = new kaXmlPoint(pid,_this);
			    _this.ovrObjects.push(np);
		    }

		    np.sid = a_sid.value;
			np.comment = a_comment.value;
		    np.nick1 = a_nick1.value;			
		    np.nick2 = a_nick2.value;			
		    np.tag = a_tag.value;				
		    np.pictureURL = a_pictureUrl.value; 
		    np.date = a_date.value;
		    np.parse(points[i]);
		    need_update = true;
	    }
    	
	    if (need_update) _this.kaMap.updateObjects();
	};//end of load handler function

    this.urlBase = this.kaMap.server;
	this.urlBase += (this.urlBase!=''&&this.urlBase.substring(-1)!='/')?'':'/';
	
	if (isURL) {
		// The URL of the XML
		this.xmlOvrUrl = this.urlNormalize(xml_url);	
		loadXMLDoc(this.xmlOvrUrl,loadHandler);
	}
	else loadXMLStr(xml_url,loadHandler);

}

/**
 * 
 */
kaXmlOverlay.prototype.urlNormalize = function(url) {
	if (url == null) return "";
	if (url.substring(1)!='/') {
		return this.urlBase+url;
	}
	return url;
}
 
/**
 * pid		Point ID
 * return The DIV object of the given point ID. null if not found.
 */
kaXmlOverlay.prototype.getDiv = function(pid) {
	var div_id = this.getDivId(pid);
	return getRawObject(div_id);
}


/**
 * pid		Point ID
 * return The kaXmlPoint object given the point ID. null if not found.
 */
kaXmlOverlay.prototype.getPointObject = function(pid) {
	for (var i=0; i < this.ovrObjects.length; i++) {
		if (this.ovrObjects[i] != null && this.ovrObjects[i].pid == pid) {
			return this.ovrObjects[i];
	 	}
	}
	return null;
}

/**
 * Instantiate a new kaXmlPoint adn add it to the overlay. If the PID
 * already exists its deleted and recreated.
 *
 * pid			Point ID
 * x			X Coordinate
 * y			Y Coordinate
 * return A kaXmlPoint object with the given point ID.
 */
kaXmlOverlay.prototype.addNewPoint = function(pid,x,y) {
	this.removePoint(pid);
	var np = new kaXmlPoint(pid,this);
	np.placeOnMap(x,y);
	this.ovrObjects.push(np);
	return np;
}

/**
 * pid		Point ID
 * return the DIV id given the point ID
 */
kaXmlOverlay.prototype.getDivId = function(pid) {
	return 'xmlovr_'+pid+'_div';
}


/**
 * Remove one or more point div from the map.
 * If pid is null or not present remove all points.
 *
 * pid		Point ID or a regexp 
 */
kaXmlOverlay.prototype.removePoint = function( pid ) {

        if ( (this.removePoint.arguments.length < 1) || (pid == null) ) {
                for (var i=0; i < this.ovrObjects.length; i++) {
                        if (this.ovrObjects[i] != null) {
                                this.ovrObjects[i].removeFromMap();
                                delete this.ovrObjects[i];
                                this.ovrObjects[i] = null;
                        }
                        delete this.ovrObjects[i];
                        this.ovrObjects.splice(i,1); i--;
                }
                return;
        }
        
        var re = new RegExp(pid);
        for (var i=0; i < this.ovrObjects.length; i++) {
                if (this.ovrObjects[i] != null) {
                        if (re.test(this.ovrObjects[i].pid)) {
                                this.ovrObjects[i].removeFromMap();
                                delete this.ovrObjects[i];
                                this.ovrObjects[i] = null;
                                this.ovrObjects.splice(i,1); i--;
                        }
                } else {
                        delete this.ovrObjects[i];
                        this.ovrObjects.splice(i,1); i--;
                }
        }
}
  

/**
 * retrieve XML document as document object
 *
 * url		The XML URL
 * return 	The XML document object
 */
function loadXMLDoc(url, handler) {
	// XML document
	var req;
	if (window.XMLHttpRequest) {
		req = new XMLHttpRequest();
	       req.open("GET", url, true);
		//req.onreadystatechange = function () { alert("state changed "+req.readyState);};
		req.onreadystatechange = function() {
			// if req does not show "loaded"
    			if (req.readyState != 4) {
        		// if not "OK" yet
			    	showProgressIndicator ();	
        		} 
        		else {
                       if (req.status == 200) {
		           xmlDocument = req.responseXML;
			    if (xmlDocument && typeof xmlDocument.childNodes != "undefined" && xmlDocument.childNodes.length != 0) handler();
		           else xmlDocument = null;
			  }
			  else alert("There was a problem retrieving the XML data:\n" + req.statusText);	  					
			  hideProgressIndicator ();
       		}
		};
		req.send(null);
	} 
	else if (window.ActiveXObject) {
		req = new ActiveXObject("Microsoft.XMLHTTP");
		req.open("GET", url, true);
		req.onreadystatechange = function () {
			// if req does not show "loaded"
    			if (req.readyState != 4) {
        		// if not "OK" yet
			    	showProgressIndicator ();	
        		} 
        		else {
                       if (req.status == 200) {
		           xmlDocument = req.responseXML;
			    if (xmlDocument && typeof xmlDocument.childNodes != "undefined" && xmlDocument.childNodes.length != 0) handler();
		           else xmlDocument = null;
			  }
			  else alert("There was a problem retrieving the XML data:\n" + req.statusText);	  					
			  hideProgressIndicator ();
       		}
		};
		req.send();
		
	}
	else {
		alert("Sorry, this browser isnt equipped to read XML data.");
	}
}

/**
 * retrieve XML document as document object
 *
 * url		The XML URL
 * return 	The XML document object
 */
function loadXMLStr(xmlstr, handler) {
	// XML document
	// var xDoc;
	// var req;
	if (window.XMLHttpRequest) {
		var xmlDOM = new DOMParser();
		xmlDocument = xmlDOM.parseFromString(xmlstr,'text/xml');
	} else if (window.ActiveXObject) {
		var xmlDOM = new ActiveXObject("Microsoft.XMLDOM");
		xmlDOM.async=false;
		xmlDOM.loadXML(xmlstr);
		xmlDocument= xmlDOM;
	}
	handler();
	hideProgressIndicator ();
}
		

/**
 * Base class for all graphics elements.
 */
function kaXmlGraphicElement() {}

/**
 * Initialize the graphics element from an XML element
 *
 * point			The parent kaXmlPoint object
 * domElement	The XML DOM element that describe the graphic
 */
kaXmlGraphicElement.prototype.parseElement = function(point, domElement) {}

/**
 * Draw the graphics element
 *
 * point		The parent kaXmlPoint object
 */
kaXmlGraphicElement.prototype.draw = function(point) {}

/**
 * Draw the graphics element
 *
 * point		The parent kaXmlPoint object
 */
kaXmlGraphicElement.prototype.rescale = function(point) {}


/**
 * Construct a symbol 
 */
function kaXmlSymbol() {
	kaXmlGraphicElement.apply(this);
    for (var p in kaXmlGraphicElement.prototype) {
        if (!kaXmlSymbol.prototype[p]) 
            kaXmlSymbol.prototype[p]= kaXmlGraphicElement.prototype[p];
    }
	
	this.shape = "bullet";
	this.size = 10;
	this.color = "black";
}

kaXmlSymbol.prototype.parseElement = function(point, domElement) {
	this.shape = domElement.getAttribute("shape");
	this.size = parseInt(domElement.getAttribute("size"));
	var c = domElement.getAttribute("color");
	if (c != null) this.color = c;
}

kaXmlSymbol.prototype.draw = function(point) {
	var jsgObject = new jsGraphics(point.divId); 
	with (jsgObject) {
		setColor(this.color);
		var d = this.size / 2;     
		fillEllipse(-d, -d, this.size, this.size);
		paint();
	}
}

/**
 * Construct a geographic feature
 */
function kaXmlFeature( point ) {
	kaXmlGraphicElement.apply(this);
    for (var p in kaXmlGraphicElement.prototype) {
        if (!kaXmlFeature.prototype[p]) 
            kaXmlFeature.prototype[p]= kaXmlGraphicElement.prototype[p];
    }
    
    this.stroke = 1;
    this.color = null;
    this.bcolor = null;
    this.opacity = 1;

	this.cxmin = 0;
	this.cymax = 0;
	this.coords = "";
	this.img = null;
	
	// Calculate the min cellSize
	var map = point.xml_overlay.kaMap.getCurrentMap();
	var scales = map.getScales();
	this.maxScale = scales[scales.length - 1];
	this.mcs = point.xml_overlay.kaMap.cellSize / point.xml_overlay.kaMap.getCurrentScale() * this.maxScale;
}
	
kaXmlFeature.prototype.parseElement = function(point, domElement) {
	var t;
	t = parseInt(domElement.getAttribute("stroke"));
	if (! isNaN(t)) this.stroke = t;
	t = domElement.getAttribute("color");
	if (t != null) this.color = t;
	t = domElement.getAttribute("bcolor");
	if (t != null) this.bcolor = t;
	t = parseFloat(domElement.getAttribute("opacity"));
	if(! isNaN(t)) this.opacity = t; 
	
	var text = "";
	if (domElement.firstChild != null) {
		text = domElement.firstChild.data;
		this.readCoordinates(point, text)	;	
	}
}

kaXmlFeature.prototype.readCoordinates = function(point, text) {
	var cx = new Array();
	var cy = new Array();
	this.cxmin = 0;
	this.cymax = 0;
	this.coords = "";
	var pp = text.split(',');
	var i;
	for (i=0; i<pp.length; i++) {
		var s = pp[i];
		var xy = s.match(/[-\+\d\.]+/g);
		if (xy != null) {
			var x=parseFloat(xy[0]);
			var y=parseFloat(xy[1]);
			cx.push(x);
			cy.push(y);
			if (i==0 || x<this.cxmin) this.cxmin = x;
			if (i==0 || y>this.cymax) this.cymax = y;
		}
	}
	
	// Normalize the coordinates
	for (i=0; i<pp.length; i++) {
		var x = Math.round((cx[i] - this.cxmin) / this.mcs);
		var y = Math.round((this.cymax - cy[i]) / this.mcs);
		if (i>0) this.coords += ",";
			this.coords += x+","+y;
	}
}

/**
 * Construct a linestring 
 */
function kaXmlLinestring( point ) {
	kaXmlFeature.apply(this, [point]);
    for (var p in kaXmlFeature.prototype) {
        if (!kaXmlLinestring.prototype[p]) 
            kaXmlLinestring.prototype[p]= kaXmlFeature.prototype[p];
    }
}

kaXmlLinestring.prototype.draw = function(point) {
	var xy = point.xml_overlay.kaMap.geoToPix( this.cxmin, this.cymax );
	var x0 = xy[0];
	var y0 = xy[1];
	
	xy = point.xml_overlay.kaMap.geoToPix( point.div.lon, point.div.lat );
	var xr = xy[0];
	var yr = xy[1];
	
	var border = 5;
	
	if (this.img == null) {
    		this.img = document.createElement( 'img' );
	    point.div.appendChild( this.img );
	    this.img.style.position = 'absolute';
	}
	
    this.img.style.top = (y0 - yr - border)+'px';
    this.img.style.left = (x0 - xr - border)+'px';
    var scf = point.xml_overlay.kaMap.getCurrentScale() / this.maxScale;
    var it = point.xml_overlay.browser.getPreferredImageType();
    var u = "drawgeom.php?gt=L&st="+this.stroke+"&bp="+border+"&sc="+scf+"&cl="+this.coords;
    if (this.color != null) u += "&lc="+escape(this.color);
    if (it == "P") {
    		u += "&it=P";
    } else {
    		u += "&it=G";
    }
    if (point.xml_overlay.browser.getPreferredOpacity() == "server") {
    		if (this.opacity < 1) u += "&op="+(this.opacity*100);
    } else {
    		if (this.opacity < 1) point.xml_overlay.browser.setOpacity(this.img, this.opacity);
    }
    this.img.src = u;
}

kaXmlLinestring.prototype.rescale = function(point) {
	this.draw(point);
}

/**
 * Construct a Polygon from the XML element
 */
function kaXmlPolygon( point ) {
	kaXmlFeature.apply(this, [point]);
    for (var p in kaXmlFeature.prototype) {
        if (!kaXmlPolygon.prototype[p]) 
            kaXmlPolygon.prototype[p]= kaXmlFeature.prototype[p];
    }
}

kaXmlPolygon.prototype.draw = function(point) {
	var xy = point.xml_overlay.kaMap.geoToPix( this.cxmin, this.cymax );
	var x0 = xy[0];
	var y0 = xy[1];
	
	xy = point.xml_overlay.kaMap.geoToPix( point.div.lon, point.div.lat );
	var xr = xy[0];
	var yr = xy[1];
	
	var border = 5;
	
	if (this.img == null) {
    		this.img = document.createElement( 'img' );
	    this.img.style.position = 'absolute';
	    point.div.appendChild( this.img );
	}
	
    var scf = point.xml_overlay.kaMap.getCurrentScale() / this.maxScale;
    var it = point.xml_overlay.browser.getPreferredImageType();
    var u = "drawgeom.php?gt=P&st="+this.stroke+"&bp="+border+"&sc="+scf+"&cl="+this.coords;
    if (this.color != null) u += "&fc="+escape(this.color);
    if (this.bcolor != null && this.bcolor != "") u += "&lc="+escape(this.bcolor);
    if (it == "P") {
    		u += "&it=P";
    } else {
    		u += "&it=G";
    }
    if (point.xml_overlay.browser.getPreferredOpacity() == "server") {
    		if (this.opacity < 1) u += "&op="+(this.opacity*100);
    } else {
    		if (this.opacity < 1) point.xml_overlay.browser.setOpacity(this.img, this.opacity);
    }
    
    this.img.style.top = (y0 - yr - border)+'px';
    this.img.style.left = (x0 - xr - border)+'px';
    
    this.img.src = u;
}

kaXmlPolygon.prototype.rescale = function(point) {
	this.draw(point);
}

/**
 * Construct a label from the XML element
 */
function kaXmlLabel() {
	kaXmlGraphicElement.apply(this);
    for (var p in kaXmlGraphicElement.prototype) {
        if (!kaXmlLabel.prototype[p]) 
            kaXmlLabel.prototype[p]= kaXmlGraphicElement.prototype[p];
    }
	
	this.text = "";
	this.color = "black";
	this.boxcolor = null;
	this.w = 64;
	this.h = 24;
	this.xoff = 0;
	this.yoff = 0;
	this.fsize = "10px";
	this.font = "Arial";
}

kaXmlLabel.prototype.parseElement = function(point, domElement) {
	if (domElement.firstChild != null) {
		this.text = domElement.firstChild.data;
	}

	var t;		
	t = domElement.getAttribute("color");
	if (t != null) {
		this.color = t;
	}
	this.boxcolor = domElement.getAttribute("boxcolor");
	t = parseInt(domElement.getAttribute("w"));
	if (!isNaN(t)) {
		this.w = t;
	}
	t = parseInt(domElement.getAttribute("h"));
	if (!isNaN(t)) {
		this.h = t;
	}
	t = parseInt(domElement.getAttribute("px"));
	if (!isNaN(t)) {
		this.xoff = t;
	}
	t = parseInt(domElement.getAttribute("py"));
	if (!isNaN(t)) {
		this.yoff = t;
	}
	t = domElement.getAttribute("fsize");
	if (t != null) {
		this.fsize = t;
	}
	t = domElement.getAttribute("font");
	if (t != null) {
		this.font = t;
	}	
}

kaXmlLabel.prototype.draw = function(point) {
	var x = this.xoff;
	var y = this.yoff;
	
	var ldiv = document.createElement( 'div' );
	ldiv.style.fontFamily = this.font;
	ldiv.style.fontSize = this.fsize;
	ldiv.style.textAlign = 'center';
	ldiv.style.color = this.color;
    ldiv.style.left = x+'px';
    ldiv.style.top = y+'px';
	ldiv.style.position = 'absolute';
	if (this.boxcolor != null) ldiv.style.backgroundColor = this.boxcolor;
	if (this.w>0) ldiv.style.width = this.w+'px';
	else ldiv.style.whiteSpace = 'nowrap';
	if (this.h>0) ldiv.style.height = this.h+'px';
	
	var ltxt = document.createTextNode(this.text);
	ldiv.appendChild( ltxt );
	
	point.div.appendChild( ldiv );
}

/**
 * Construct an icon
 */
function kaXmlIcon() {
	kaXmlGraphicElement.apply(this);
    for (var p in kaXmlGraphicElement.prototype) {
        if (!kaXmlIcon.prototype[p]) 
            kaXmlIcon.prototype[p]= kaXmlGraphicElement.prototype[p];
    }
    
	this.icon_src = null;
	this.icon_w = 0;
	this.icon_h = 0;
	this.xoff = 0;
	this.yoff = 0;
}

kaXmlIcon.prototype.parseElement = function(point, domElement) {
	this.icon_src = point.xml_overlay.urlNormalize(domElement.getAttribute("src"));
	this.icon_w = parseInt(domElement.getAttribute("w"));
	this.icon_h = parseInt(domElement.getAttribute("h"));
	var t;
	t = parseInt(domElement.getAttribute("px"));
	if (!isNaN(t)) {
		this.xoff = t;
	}
	t = parseInt(domElement.getAttribute("py"));
	if (!isNaN(t)) {
		this.yoff = t;
	}
}

kaXmlIcon.prototype.draw = function(point) {
	var dx = -this.icon_w / 2 + this.xoff;     
	var dy = -this.icon_h / 2 + this.yoff;     
	
    var idiv = document.createElement( 'div' );
    idiv.style.position = 'absolute';
    idiv.style.top = dy+'px';
    idiv.style.left = dx+'px';
    
    var img = document.createElement( 'img' );
    img.src = this.icon_src;
    img.width = this.icon_w;
    img.height = this.icon_h;
    
    idiv.appendChild( img );
    point.div.appendChild( idiv );
}

/**
 * This object is a single point on the overlay.
 * The object hold the div and all the stuff to draw and move the point 
 * (symbol, label, icon, etc.).
 *
 * pid			The point ID (string)
 * xml_overlay	The kaXmlOverlay object owner of this point
 */
function showAnswers(pid){
     		var iframe = document.getElementById('antwort');
			iframe.src="antwort.php?insert=false&pid="+pid;
    	}

function kaXmlPoint(pid, xml_overlay) {
	this.xml_overlay = xml_overlay;
	this.pid = pid;
	this.divId = this.xml_overlay.getDivId(pid);
	this.geox = 0;
	this.geoy = 0;
	this.comment = 0;
	this.pictureURL = 0;
	this.tag = 0;
	this.nick1 = 0;
	this.nick2 = 0;
	this.date = 0;
	this.sid = 0;
	this.isManual=true;

	this.shown = false;
	
	this.graphics = new Array();
	
	this.div = document.createElement('div');
	this.div.setAttribute('id', this.divId);
	var _this=this;

//	onmouseover, see: http://lists.maptools.org/pipermail/ka-map-users/2006-April/001362.html

	this.div.onmouseover=function(){
		
		showAnswers(_this.pid);

		var getComment = document.getElementById('commentDiv');
		var platzhalterKommentar = "<small>Kommentar: </small><br />";
		getComment.innerHTML = platzhalterKommentar + _this.comment;

		var getPicUrl = document.getElementById('photoDiv');
		var image_src = "<img src=\""+_this.pictureURL+"\"/>";
		getPicUrl.innerHTML = image_src;

		var getTag = document.getElementById('tagsDiv');
		var platzhalterTag = "Tag: ";
		getTag.innerHTML = platzhalterTag + _this.tag + "<br />";
 		
		var getXY = document.getElementById('XYDiv');
		getXY.innerHTML =  "X: " + _this.geox + "&#160;&#160;Y:" + _this.geoy;

		var getsid = document.getElementById('symbol');
		var sid_src = "<img src=\""+_this.sid+"\"width=\"20\" height=\"20\"/>";
		getsid.innerHTML = sid_src;

		var getnick1 = document.getElementById('nick1');
		getnick1.innerHTML = _this.nick1+" - ";

		var getDate = document.getElementById('datum');
		getDate.innerHTML = _this.date;

		//var getAnswers = frames['antwort'].document.forms[0].

	}

}

kaXmlPoint.prototype.onmouseover = function(){
}


/**
 * Show the point in the specified geo-position.
 */
kaXmlPoint.prototype.placeOnMap = function( x, y ) {
	if (!this.shown) {
		this.geox = x;
		this.geoy = y;
		this.xml_overlay.kaMap.addObjectGeo( this.xml_overlay.overlayCanvas, x, y, this.div );
		this.shown = true;
	} 
}

/**
 * Delete the point.
 */
kaXmlPoint.prototype.removeFromMap = function( ) {
	if (this.shown) {
		this.xml_overlay.kaMap.removeObject( this.div );
		this.shown = false;
	} 
}

/**
 * Move the point in the specified geo-position.
 */
kaXmlPoint.prototype.setPosition = function( x, y ) {
	if (this.shown) {
		this.geox = x;
		this.geoy = y;
		this.div.lat = y;
		this.div.lon = x;
	}
}

/**
 * Add a new kaXmlGraphicElement to this kaXmlPoint.
 * kaXmlGraphicElement subclasses are:
 *  
 *  kaXmlSymbol
 *  kaXmlIcon
 *  kaXmlLabel
 *  kaXmlLinestring
 *  kaXmlPolygon
 *
 * obj	an object of class kaXmlGraphicElement
 */
kaXmlPoint.prototype.addGraphic = function( obj ) {
		this.graphics.push(obj);
		obj.draw(this);
}

/**
 * Clear all the graphic elements of this kaXmlPoint.
 */
kaXmlPoint.prototype.clear = function() {
	this.div.innerHTML = "";
	this.graphics.length = 0;
	//this.graphics = new Array();
}

/**
 * Set the HTML content of this kaXmlPoint.
 * This function delete any other content of the point.
 *
 * ihtml		A string containing the HTML
 */
kaXmlPoint.prototype.setInnerHtml = function(ihtml) {
	this.clear();
	this.div.innerHTML = ihtml;
}

/**
 * Parse the XML fragment describing the point. Then draw or translate
 * the point on the map.
 *
 * point_element	 A DOM element <point>
 */
kaXmlPoint.prototype.parse = function(point_element) {

	var i;
	var x = parseFloat(point_element.getAttribute("x"));
	var y = parseFloat(point_element.getAttribute("y"));
	var redraw_a = point_element.getAttribute("redraw");
	var redraw = false;
	if (redraw_a == "true")	redraw = true;
			
	if (!this.shown) {
		this.placeOnMap(x,y);
		this.shown = true;
	} else {
		this.setPosition(x,y);
		
		// Need redraw?
		if (!redraw) return;
		
		// clear and redraw the point
		this.clear();
	}
		
	// look for ihtml element
	var ihtml_element = point_element.getElementsByTagName("ihtml");
	for (i=0; i<ihtml_element.length; i++) {
		this.div.innerHTML = ihtml_element[i].firstChild.nodeValue;
	}
	
	var t;
	var elements;
	
	// look for symbol element
	elements = point_element.getElementsByTagName("symbol");
	for (i=0; i<elements.length; i++) {
		t = new kaXmlSymbol();
		t.parseElement(this, elements[i]);
		this.addGraphic(t);
	}
	
	// look for icon element
	elements = point_element.getElementsByTagName("icon");
	for (i=0; i<elements.length; i++) {
		t = new kaXmlIcon();
		t.parseElement(this, elements[i]);
		this.addGraphic(t);
	}


	// look for linestring element
	elements = point_element.getElementsByTagName("linestring");
	for (i=0; i<elements.length; i++) {
		t = new kaXmlLinestring(this);
		t.parseElement(this, elements[i]);
		this.addGraphic(t);
	}
	
	// look for polygon element
	elements = point_element.getElementsByTagName("polygon");
	for (i=0; i<elements.length; i++) {
		t = new kaXmlPolygon(this);
		t.parseElement(this, elements[i]);
		this.addGraphic(t);
	}
}

kaXmlPoint.prototype.rescale = function(point_element) {
	for (i=0; i<this.graphics.length; i++) {
		this.graphics[i].rescale(this);
	}
}

function RemoveBad(strTemp) { 
    strTemp = strTemp.replace(/\<|\>|\"|\'|\%|\;|\(|\)|\&|\+|\-/g,""); 
    return strTemp;
}

kaXmlPoint.prototype.save = function(url,kaMapXmlOverlay, tool){
		
	var images = this.div.getElementsByTagName("img");
	images[0].src=this.sid;

	var urlBase = kaMapXmlOverlay.kaMap.server;
	urlBase += (urlBase!=''&& urlBase.substring(-1)!='/')?'':'/';
	var params = "?sid="+this.sid+"&x="+this.geox+"&y="+this.geoy+"&text="+escape(RemoveBad(this.comment))+"&pictureURL="+this.pictureURL+"&tag="+escape(RemoveBad(this.tag))+"&nick1="+escape(RemoveBad(this.nick1))+"&nick2="+escape(RemoveBad(this.nick2))+"&date="+this.date+"&isManual="+this.isManual;
	// The URL of the XML
	var saveurl = kaMapXmlOverlay.urlNormalize(url+params);	
	var _this=this;
	var handler = function(){
		var objDomTree = xmlDocument.documentElement;
	    var nicks = objDomTree.getElementsByTagName("nick");
	    if (nicks[0].firstChild.nodeValue == "neu") {
    	    document.getElementById('umfrageStart').className = 'umfrage_visible';
		    var inputHid = document.createElement("input");
		    inputHid.type="hidden";
		    inputHid.name="hiddenNick1";
		    inputHid.value=_this.nick1;
			frames['iABCD'].document.forms[0].appendChild(inputHid);
		    inputHid = document.createElement("input");
		    inputHid.type="hidden";
		    inputHid.name="hiddenNick1";
		    inputHid.value=_this.nick1;
			frames['iCD'].document.forms[0].appendChild(inputHid);
		    inputHid = document.createElement("input");
		    inputHid.type="hidden";
		    inputHid.name="hiddenNick2";
		    inputHid.value=_this.nick2;
		    frames['iABCD'].document.forms[0].appendChild(inputHid);
 			inputHid = document.createElement("input");
		    inputHid.type="hidden";
		    inputHid.name="hiddenNick2";
		    inputHid.value=_this.nick2;		    
			frames['iCD'].document.forms[0].appendChild(inputHid);
		    tool.isNew=true;
		    alert("Punkt gespeichert!");
	    }
	    else if (nicks[0].firstChild.nodeValue == "error") 
					alert("Dieser Karteneintrag existiert bereits.");
	    else alert("Punkt gespeichert!");

	}
	document.forms[1].reset();
	document.getElementById('easting').value="";
	document.getElementById('northing').value="";
	var symbol_src = "<img src=\"images/backgroundAddObjTool1.jpg\"/>";
	var gewSym = document.getElementById('gewaehltesSymbol').innerHTML = symbol_src;

	xDoc = loadXMLDoc(saveurl,handler);
}

function _BrowserIdent() {
	this.detect = navigator.userAgent.toLowerCase();
	this.OS = null;
	this.browser = null;
	this.version = null;
	this.total = null;
	this.thestring = null;
	this.place = 0;


	if (this.checkIt('konqueror')) {
		this.browser = "Konqueror";
		this.OS = "Linux";
	} else if (this.checkIt('safari')) this.browser = "Safari";
	else if (this.checkIt('omniweb')) this.browser = "OmniWeb";
	else if (this.checkIt('opera')) this.browser = "Opera"
	else if (this.checkIt('webtv')) this.browser = "WebTV";
	else if (this.checkIt('icab')) this.browser = "iCab"
	else if (this.checkIt('msie')) this.browser = "Internet Explorer"
	else if (!this.checkIt('compatible')) {
		this.browser = "Netscape Navigator"
		this.version = this.detect.charAt(8);
	} else this.browser = "An unknown browser";

	if (!this.version) this.version = this.detect.charAt(this.place + this.thestring.length);

	if (!this.OS) {
		if (this.checkIt('linux')) this.OS = "Linux";
		else if (this.checkIt('x11')) this.OS = "Unix";
		else if (this.checkIt('mac')) this.OS = "Mac";
		else if (this.checkIt('win')) this.OS = "Windows";
		else this.OS = "an unknown operating system";
	}
}

_BrowserIdent.prototype.checkIt = function (string) {
	this.place = this.detect.indexOf(string) + 1;
	this.thestring = string;
	return this.place;
}

_BrowserIdent.prototype.setOpacity = function (imageobject, opacity) {
	if (opacity == undefined || this.opacity >= 1) return '';
	if (this.browser == "Netscape Navigator")
		imageobject.style.MozOpacity=opacity;
	else if (this.browser == "Internet Explorer" && parseInt(this.version)>=4) {
		//filter: alpha(opacity=50);
		var tmp = imageobject.style.cssText;
		tmp = "filter: alpha(opacity="+(opacity*100)+");" + tmp;
		imageobject.style.cssText = tmp;
	} else {
		var tmp = imageobject.style.cssText;
		tmp = "opacity: "+opacity+";" + tmp;	
		imageobject.style.cssText = tmp;
	}
}

_BrowserIdent.prototype.getPreferredImageType = function () {
	if (this.browser == "Netscape Navigator") return "P";
	else if (this.browser == "Opera") return "P";
	else if (this.browser == "Safari") return "P";
	else return "G"
}

_BrowserIdent.prototype.getPreferredOpacity = function () {
	if (this.browser == "Netscape Navigator") return "server";
	else if (this.browser == "Opera") return "server";
	else return "client"
}


/**
* Progress Indicator (viktor)
**/

function showProgressIndicator () {
				var proInDiv = document.getElementById('loader');
				proInDiv.src = "images/pleasewait.gif";
}

function hideProgressIndicator () {
				var proInDiv = document.getElementById('loader');
				proInDiv.src = "images/a_pixel.gif";
}

 
		
