Location: PHPKode > projects > injooosm > components/com_injooosm/helpers/gpsClass.php
<?php
/**
 * Joomla! 1.5 component injooosm
 *
 * @version $Id: gpsClass.php 2010-02-16 13:40:00$
 * @author Christian Knorr
 * @package injooosm
 * @subpackage frontend
 * @license GNU/GPL
 * @filesource
 *
 */
 
// no direct access
defined('_JEXEC') or die('Restricted access');

/**
 * Mainclass to write the map
 */
class gpsClass {

	var $gpsFile= NULL;

public function parseCatIcon($catid,$istrack=0,$iswp=0,$isroute=0) {
	$catimage = false;
	$cats = $this->getCats();
	foreach ( $cats AS $cat ) {
		if ( $cat->id == $catid ) {
			if ( $cat->image ) {
				$catimage = $cat->image;
				break;
			}
		}
	}
	$marker = "";

	if ( $catimage !== false ) {
		$catimage = "components".DS."com_injooosm".DS."assets".DS."images".DS.$catimage;
		if ( is_file($catimage) ) {
			$simagesize = getimagesize($catimage);
			$sizex = $simagesize[0];
			$sizey = $simagesize[1];
			$maximagesize = 26;
			if ( ( $sizex > $maximagesize ) OR ( $sizey > $maximagesize) ) {
				$oldsizex = $sizex;
				$oldsizey = $sizey;
				$ratio = $sizex / $sizey;
				if ( $ratio > 1 ) {
// Bild ist Breit
					$sizex = $maximagesize;
					$sizey = $sizex / $ratio;
				} else {
// Bild ist Hochkant
					$sizey = $maximagesize;
					$sizex = $sizey * $ratio;
				}
				
			}
			$offsetx = round(-($sizex/2));
			$offsety = round(-($sizey/2));
			$marker .= "var size = new OpenLayers.Size(".$sizex.", ".$sizey."); ";
			$marker .= "var offset = new OpenLayers.Pixel(".$offsetx.", ".$offsety."); ";
			$marker .= "var file = '".JURI::base().$catimage."'; ";
			$marker .= "var icon = new OpenLayers.Icon(file,size,offset);";
			$marker .= "addMarker(ll, popupClass, popupContentHTML, true, true, icon);\n";
			return $marker;
		}
	}
	if ( $istrack == "1" )
		$marker .= "addMarker(ll, popupClass, popupContentHTML, true, true );\n";
	else {
// ToDo: Typeigenes Icon (Track, WP, Route)
		$wpcoords = simplexml_load_file('components'.DS.'com_injooosm'.DS.'assets'.DS.'images'.DS.'symbols'.DS.'wp.xml');
		$marker .= "var size = new OpenLayers.Size(".$wpcoords->sizex.", ".$wpcoords->sizey."); ";
		$marker .= "var offset = new OpenLayers.Pixel(".$wpcoords->offsetx.", ".$wpcoords->offsety."); ";
		$marker .= "var file = '".JURI::base()."components".DS."com_injooosm".DS."assets".DS."images".DS."symbols".DS."wp.png'; ";
		$marker .= "var icon = new OpenLayers.Icon(file,size,offset);";
// var_dump($wpcoords);
// die();
		$marker .= "addMarker(ll, popupClass, popupContentHTML, true, true, icon);\n";
// 		$marker .= "addMarker(ll, popupClass, popupContentHTML, true, true, ";
// 		$marker .= "'components/com_injooosm/assets/images/symbols/Pin Green.png');\n";
	}
	return $marker;
}

	/**
	 * Checkt auf WPs
	 * @return (int) Anzahl
	 */
public function parseOwnIcon($ownicon=false) {
		$jpath = JPATH_SITE.DS."components".DS."com_injooosm".DS."assets".DS."images".DS."symbols".DS;
		$jbase = JURI::root()."components".DS."com_injooosm".DS."assets".DS."images".DS."symbols".DS;

		$filename = JFile::makeSafe($ownicon);
			$pngfile = $jbase.$filename.".png";
			$xmlfile = $jpath.$filename.".xml";
		if ( ( $ownicon == false ) OR (!is_file($jpath.$filename.".png")) ) {
			if ((!JFile::exists($xmlfile)) AND (is_writable($jpath))) {
// Vorlage zur Erstellung unbekannter Icons
				$xmlcontent = "<xml>\n	<sizex></sizex>\n	<sizey></sizey>\n	<offsetx></offsetx>\n	<offsety></offsety>\n</xml>\n<!--\nUm dieses Icon verfügbar zu machen, erstelle dieses Bild: \"".$filename.".png\",\nund vervollständige obige 4 Parameter.\n\"offsetx\" beschreibt die Anzahl der Pixel von links bis zum Punkt (negativ) und\n\"offsety\" beschreibt die Anzahl der Pixel von oben bis zum Punkt (ebenfalls negativ).\nMit \"Punkt\" ist der Punkt gemeint, der auf der Koordinate sitzt.\n-->\n";
				JFile::write($xmlfile,$xmlcontent);
				JPath::setPermissions($xmlfile,"0666");
			}
// Standardicon
			$pngfile = $jbase."unknown.png";
			$xmlfile = $jpath."unknown.xml";
		}
			$icon = $pngfile;
			$this->gpsFile = $xmlfile;
			$xml = $this->loadFile();
			$sizex = $xml->sizex;
			$sizey = $xml->sizey;
			$offsetx = $xml->offsetx;
			$offsety = $xml->offsety;
		return "		var icon = new OpenLayers.Icon('".$icon."',\n			new OpenLayers.Size(".$sizex.", ".$sizey."),\n			new OpenLayers.Pixel(".$offsetx.", ".$offsety."));\n";

}
	/**
	 * Checkt auf WPs
	 * @return (int) Anzahl
	 */
public function parseWPs($wps) {
	if( $wps == false) return false;
	$wp = "// <!-- parseWPs BEGIN -->\n";
	$wp .= "wps = new OpenLayers.Layer.Markers(\"".JText::_('OSM_WAYPOINTS')."\");";
	$wp .= "map.addLayer(wps);";
	$wp .= "addWPs();";
	$wp .= "function addWPs() {\n";
	foreach($wps as $key => $value){
// var_dump($value);
// die();
		$lonlat = $value->attributes();
		$lon = $lonlat['lon'];
		$lat = $lonlat['lat'];
		$name = trim(str_replace("
","<br />",$value->name));		// Name
		$cmt = trim(str_replace("
","<br />",$value->cmt));		// ?
		$desc = trim(str_replace("
","<br />",$value->desc));		// Beschreibung
		$ele = (float)$value->ele;	// Höhe
		$sym = $value->sym;		// Symbol

		$wp .= "llwp = new OpenLayers.LonLat(".$lon.",".$lat.").transform(new OpenLayers.";
		$wp .= "Projection(\"EPSG:4326\"), map.getProjectionObject());\n";
		$wp .= "popupClasswp = AutoSizeAnchored;\n";
		$wp .= "popupContentHTMLwp = '<b>".JText::_('OSM_NAME').":</b> ".$name."<br /><small>";
		if ($desc) $wp .= "<b>".JText::_('OSM_DESCRIPTION').":</b> ".$desc;
		if ( ($cmt) AND ($desc != $cmt) ) $wp .= "<br /><b>cmt:</b> ".$cmt;
		if ($ele) $wp .= "<br /><b>".JText::_('OSM_ELE')." :</b> ca. ".round($ele,1)."m<small>";
		$wp .= "';\n";
		$wp .= $this->parseOwnIcon($sym);
		$wp .= "addWP(llwp, popupClasswp, popupContentHTMLwp, true, true, icon);\n";
	}
	$wp .= "	}\n";
//	$wp .= "	//
//	* Function: addWP
//	* Add a new marker to the markers layer given the following lonlat, 
//	*	 popupClass, and popup contents HTML. Also allow specifying 
//	*	 whether or not to give the popup a close box.
//	* 
//	* Parameters:
//	* ll - {<OpenLayers.LonLat>} Where to place the marker
//	* popupClass - {<OpenLayers.Class>} Which class of popup to bring up 
//	*	 when the marker is clicked.
//	* popupContentHTML - {String} What to put in the popup
//	* closeBox - {Boolean} Should popup have a close box?
//	* overflow - {Boolean} Let the popup overflow scrollbars?
//	*/

	$wp .= "	function addWP(ll, popupClass, popupContentHTML, closeBox, overflow, icon) {
		var feature = new OpenLayers.Feature(wps, ll);
		feature.closeBox = closeBox;
		feature.popupClass = popupClass;
		feature.data.popupContentHTML = popupContentHTML;
		feature.data.overflow = (overflow) ? \"auto\" : \"hidden\";
		var wp = new OpenLayers.Marker(ll,icon);
		wp.feature = feature;
		var markerClick = function (evt) {
			if (this.popup == null) {
				this.popup = this.createPopup(this.closeBox);
				map.addPopup(this.popup);
				this.popup.show();
			} else {
				this.popup.toggle();
			}
		currentPopup = this.popup;
		OpenLayers.Event.stop(evt);
		};
		wp.events.register(\"mousedown\", feature, markerClick);
		wps.addMarker(wp);
	}\n";
	$wp .= "// <!-- parseWPs END -->\n";
	return $wp;
}

	/**
	 * Checkt auf WPs
	 * @return (int) Anzahl
	 */
public function extractWPs($file) {
// 	$file = JPATH_SITE.DS."components".DS."com_injooosm".DS."uploads".DS.$file;
// var_dump($file);die();
	$this->gpsFile = $file;
	$xml = $this->loadFile();
// var_dump($xml);die();
	if($xml->wpt) {
		$i = 0;
		$wp = array();
		while (true) {
			if($xml->wpt[$i])
				$wp[] = $xml->wpt[$i];
			else
				break;
		$i++;
		}
	return $wp;
	} else return false;
}
	/**
	 * Formatiert die Beschreibung und kürzt bei Bedarf
	 * @return string
	 */
	public function showDesc($desc) {
	$stringlength = 200;
	$maxslperrow = 50;

// Trennung nach <p>Katitel</p> BEGIN
	$desc = str_replace('</p>',"",$desc);
	$desc = explode('<p>',$desc);
	$newdesc = "";
	$count_letters = 0;
	$return = "";
	foreach ( $desc AS $chapter ) {
		if ( $chapter != "" ) {
			$chapter = trim($chapter);
// 	Trennung nach Wörter BEGIN
			$words = explode(' ',$chapter);
			$return .= "<p>";
			$rowlen = 0;
			foreach($words AS $word) {
				$count_letters = ( $count_letters + strlen($word) +1 ); // "1" wegen der Leerstelle
// 		Einfügung von Zeilensprung BEGIN
				$rowlen = ( $rowlen + strlen($word) );
				if ( $rowlen > $maxslperrow ) {
					$return = trim($return)."<br />";
					$rowlen = 0;
				}
				if ( ( $count_letters + strlen($word) ) > $stringlength )
					return $return."[...]</p>";
// 		Einfügung von Zeilensprung END
				$return .= $word." ";
			}
			$return = trim($return)."</p>";
// 	Trennung nach Wörter END
			$newdesc[] = $chapter;
		}
	}
// Trennung nach <p>Katitel</p> END

	if ( $count_letters == 0 )
		return "<p>".JText::_('OSM_NO_DESC')."</p>";
	return $return;
}

	/**
	 *
	 * @return array()
	 */
	public function maySee($rows) {
	$user = JFactory::getUser();
	$return = array();
	foreach ( $rows AS $row ) {
		if ( ( $row->published ) AND ( ( !$row->access ) OR ( ( $row->access ) AND ( $user->userid ) ) ) ) {
			$return[] = $row;
		}
	}
	return $return;
}

	/**
	 * Löscht den aktuellen Track aus der
	 * Gesamtansicht
	 *
	 * @return array()
	 */
	public function deleteTrack($rows,$track) {
	foreach ( $track AS $key => $value ) {
		$trackid = $value;	// Track-ID herausfinden und Schleife verlassen
		break;
	}
	$return = array();
	foreach ( $rows AS $key => $value ) {
		foreach ( $value AS $key_b => $value_b ) {
			if ( $value_b != $trackid )
				$store = true;
			else
				$store = false;
			break;
		}
		if ( $store == true ) $return[] = $value;
	}
	return $return;
}

	/**
	 *
	 */
	public function transformTtRGB($t) {
	if ($t <= 60) {
		$r = dechex(255);
		$g = dechex(round($t*4.25));
		$b = dechex(0);
	}elseif ($t <= 120) {
		$r = dechex(round(255-(($t-60)*4.25)));
		$g = dechex(255);
		$b = dechex(0);
	}elseif ($t <= 180) {
		$r = dechex(0);
		$g = dechex(255);
		$b = dechex(round((($t-120)*4.25)));
	}elseif ($t <= 240) {
		$r = dechex(0);
		$g = dechex(round(255-(($t-180)*4.25)));
		$b = dechex(255);
	}elseif ($t <= 300) {
		$r = dechex(round((($t-240)*4.25)));
		$g = dechex(0);
		$b = dechex(255);
	}elseif ($t < 360) {
		$r = dechex(255);
		$g = dechex(0);
		$b = dechex(round(255-(($t-300)*4.25)));
	}elseif ($t >= 360)
		return false;
	if (strlen($r)==1) $r = (string)"0".$r;
	if (strlen($g)==1) $g = (string)"0".$g;
	if (strlen($b)==1) $b = (string)"0".$b;
	return $r.$g.$b;
	}

	/**
	 *
	 */
	public function calculateAllColors($count) {
	$color = array();
	for($i=1;$i<=$count;$i++){
		$color[($i-1)] = $this->transformTtRGB(round(300/$count*$i));
	}
	return $color;
	}

	/**
	 *
	 * @return color (#000000 - #ffffff) or own wish
	 */
	public function getHexColor($wish=false) {
	if ($wish !== false) return $whish;
	$color = "";
	for($i=0;$i<3;$i++) {
		$dec = (int)rand(16,128);
		$color .= dechex($dec);
	}
	return ("#".$color);
	}

	/**
	 *
	 * @return object
	 */
	public function loadFile() {

if (file_exists($this->gpsFile)) {
	$xml = simplexml_load_file($this->gpsFile);

	return $xml;
} else {
	return false;
}
	}

	/**
	 *
	 * @return array
	 */
	public function getStartCoordinates() {
jimport('joomla.filesystem.file');

if(JFile::getExt($this->gpsFile) == 'kml'):
	$start = $this->getStartKML($this->gpsFile);
endif;

if(JFile::getExt($this->gpsFile) == 'gpx'):
	$start = $this->getStartGPX();
endif;

if(JFile::getExt($this->gpsFile) == 'tcx'):
	$start = $this->getStartTCX();
endif;

return $start;

	}

	/**
	 *
	 * @return array
	 */
	private function getStartKML($file) {

$coords = $this->getCoords($file);

$start = $coords[0];

return $start;

	}

	/**
	 *
	 * @return array
	 */
public function isTrack($file = false) {
	if ($file == false)
		$file = $this->loadFile();
	$xml = $file;
// var_dump($xml);
// die();
	for($i=0;$i<10;$i++) { // Unternehme 10 Versuche LonLat zu finden
		$trackpoint = $xml->trk[$i]->trkseg->trkpt;
// die(var_dump($xml));
		if (!empty($trackpoint))
			return (int)$i;
	}
	return false;
}

	/**
	 *
	 * @return array
	 */
public function isWaypoint($file = false) {
	if ($file == false)
		$file = $this->loadFile();
	$xml = $file;
// var_dump($file);
// die();
	for($i=0;$i<10;$i++) { // Unternehme 10 Versuche LonLat zu finden
		$trackpoint = $xml->wpt[$i];
		if (!empty($trackpoint))
			return (int)$i;
	}
	return false;
}

	/**
	 *
	 * @return array
	 */
	private function getStartGPX() {
	$isTrack = $this->isTrack();
// var_dump($isTrack);
// die();
	$xml = $this->loadFile();
	if ($isTrack !== false) {
		$trackpoint = $xml->trk[$isTrack]->trkseg->trkpt;
		$startpoint = $trackpoint->attributes();
		$start = array((string)$startpoint['lon'],(string)$startpoint['lat']);
		return $start;
	}
	$isWaypoint = $this->isWaypoint();
// var_dump($xml);
// die();
	if ($isWaypoint !== false) {
		$trackpoint = $xml->wpt;
		$startpoint = $trackpoint->attributes();
		$start = array((string)$startpoint['lon'],(string)$startpoint['lat']);
		return $start;
	}
	return false;
	}

	private function getStartTCX() {
$xml = $this->loadFile();

if(isset($xml->Activities->Activity->Lap->Track)) {
	$startpoint = $xml->Activities->Activity->Lap->Track[0]->Trackpoint;
} elseif (isset($xml->Courses->Course->Track)) {
	$startpoint = $xml->Courses->Course->Track[0]->Trackpoint;
}

$lat = $startpoint->Position->LatitudeDegrees;
$lon = $startpoint->Position->LongitudeDegrees;

$start = array((string)$lon,(string)$lat);

return $start;
	}

	/**
	 *
	 * @global object $mainframe
	 * @return array
	 */
	function getMapNates() {
global $mainframe;

$db =& JFactory::getDBO();

$query = "SELECT start_n FROM #__osm_files"
. "\n ORDER BY start_n ASC"
. "\n LIMIT 1";

$db->setQuery($query);
$north = $db->loadResult();

$query = "SELECT start_e FROM #__osm_files"
. "\n ORDER BY start_e DESC"
. "\n LIMIT 1";

$db->setQuery($query);
$east = $db->loadResult();

$cnates = array();
$cnates[] = $north;
$cnates[] = $east;

return $cnates;

	}

	/**
	 *
	 * @global object $mainframe
	 * @return array
	 */
	function getTracks() {
global $mainframe;

$db = JFactory::getDBO();

$query = "SELECT a.*, b.title AS cat FROM #__osm_files AS a"
. "\n LEFT JOIN #__osm_cats AS b"
. "\n ON a.catid=b.id"
;

$db->setQuery($query);
$rows = $db->loadObjectList();

return $rows;
	}

	/**
	 *
	 * @global object $mainframe
	 * @return array
	 */
	function getCats() {
global $mainframe;

$db = JFactory::getDBO();

$query = "SELECT * FROM #__osm_cats"
;

$db->setQuery($query);
$rows = $db->loadObjectList();

return $rows;
	}

	/**
	 *
	 * @param string $url
	 * @return string
	 */
	private function parseKml($url)
	{
if ($url)
{
	$string = "var geoXml = new GGeoXml(\"$url\");\n
		map.addOverlay(geoXml);\n";
	return $string;
}
else
{
	return true;
}
	}

	/**
	 * counts the distance of a track
	 * $koords look like this: $array($point1(array(lat,lon)),$point2(array(lat,lon)))...
	 * 
	 * @param array $koord
	 * @return int kilometers
	 */
	public function getDistance($koord) {
// var_dump($koord);die();
if (!is_array($koord))
{
	return false;
} else {

$ent = 0;
$welt = 6378.137; // Erdradius, ca. Angabe
$last = array_pop($koord);
foreach($koord as $key => $fetch)
{
	if (isset($koord[$key + 1]))
	{
$erste_breite = $koord[$key][1]; // lat
$erste_laenge = $koord[$key][0]; // lon
$erste_breite_rad = deg2rad($erste_breite);
$erste_laenge_rad = deg2rad($erste_laenge);

$zweite_breite = $koord[$key + 1][1]; // lat
$zweite_laenge = $koord[$key + 1][0]; // lon
$zweite_breite_rad = deg2rad($zweite_breite);
$zweite_laenge_rad = deg2rad($zweite_laenge);

$dis = acos(
	(sin($erste_breite_rad) * sin($zweite_breite_rad)) +
	(cos($erste_breite_rad) * cos($zweite_breite_rad) *
cos($zweite_laenge_rad - $erste_laenge_rad))) * $welt;

if(is_nan($dis)) {
	$ent = $ent;
} else {
	$ent = $ent + $dis;
}
	}
}
$entfernung = $ent;
$entfernung = round($entfernung, 2);
// var_dump($entfernung);die();
return $entfernung;
}
	}

	/**
	 *
	 * @param array $coords
	 * @return array
	 */
	public function getElevation($coords) {

$asc = 0;
$desc = 0;
for($i=0, $n=count($coords); $i<$n; $i++) {
if($coords[$i][2] < $coords[$i+1][2]):
$asc = $asc + ($coords[$i+1][2] - $coords[$i][2]);
endif;
}

for($i=0, $n=count($coords); $i<$n-1; $i++) {
if($coords[$i][2] > $coords[$i+1][2]):
$desc = $desc + ($coords[$i][2] - $coords[$i+1][2]);
endif;
}

$ele = array(round($asc,0),round($desc,0));

return $ele;

	}

	/**
	 *
	 * @param array $coords
	 * @return string
	 */
	public function createChartsData($coords) {
$cht = "";

$n = count($coords);
if($n > 600) {
	$c = $n / 600;
	$c = round($c,0);
} else {
	$c = 1;
}
$ele = array();
for($i=0; $i<$n; $i = $i+$c) {
	$coord = $coords[$i];
	$cht .= round($coord[2],0).",";
	array_push($ele,round($coord[2],0));
}
$chtn = substr($cht, 0, -1);

return $chtn;
	}

	/**
	 *
	 * @param string $date
	 * @return (int) timestamp
	 */
public function giveTimestamp($date) {
	// ToDo: unterschiedliche Zeittypen können hier eingefügt werden
	if ( $date == 0 ) return false;
	$date = explode('T',$date);
		$time_tmp_date = explode('-',$date[0]);
			$time_tmp_date_year = $time_tmp_date[0];
			$time_tmp_date_month = $time_tmp_date[1];
			$time_tmp_date_day = $time_tmp_date[2];
		$time_tmp_time = explode(':',str_replace("Z","",$date[1]));
			$time_tmp_time_hour = $time_tmp_time[0];
			$time_tmp_time_minute = $time_tmp_time[1];
			$time_tmp_time_sec = $time_tmp_time[2];
	return mktime(	$time_tmp_time_hour,$time_tmp_time_minute,$time_tmp_time_sec,
				$time_tmp_date_month,$time_tmp_date_day,$time_tmp_date_year);
}

	/**
	 *
	 * @return (int) speed
	 */
public function giveSpeed($lonA,$latA,$timeA,$lonB,$latB,$timeB,$unit,$digits=0) {

	$Erdradius=6378.137;

	if ((($latB-$latA)==0) AND (($lonB-$lonA)==0))
		$e = 0;
// var_dump($latB);
	else {
	// Haversine
		$lonA = $lonA / 180 * pi() ;
		$latA = $latA / 180 * pi() ;
		$lonB = $lonB / 180 * pi() ;
		$latB = $latB / 180 * pi() ;
		$e = acos( sin($latA)*sin($latB) + cos($latA)*cos($latB)*cos($lonB-$lonA) );
	}

	$entfernung = (($e * $Erdradius)*1000);		// Meter
	$time_distance = ( $timeA - $timeB );		// Sekunden
	if ($time_distance == 0) return false;
	$speed = ($entfernung/$time_distance);		// Meter pro Sekunde
// var_dump($speed);
	if ( $speed > (1000*1000/3600) ) $speed = 0;	// wenn mehr als 1000 km/h
	if ( $unit == "Kilometer" )
		return round(($speed/1000*3600),$digits);
	if ( $unit == "Miles" )
		return round(($speed/1609.344*3600),$digits);
/* Formel für Umrechnung Meter -> Meilen:
http://www.din-formate.de/kalkulator-berechnung-laenge-masse-groesse-umrechnung-meter.html
*/
	return false; // wenn Einheit unbekannt
}

	/**
	 *
	 * @param array $coords
	 * @return string
	 */
	public function createSpeedData($coords,$unit) {
	$cht = "";
	$n = count($coords);
	if($n > 600) {
		$count = $n / 600;
		$count = round($count,0);
	} else {
		$count = 1;
	}
	$time = array();
	$lon = array();
	$lat = array();
	$j = 0;
	for($i=0; $i<$n; $i = $i+$count) {
		$lon[$j] = ($coords[$j][0]);
		$lat[$j] = ($coords[$j][1]);
		$time[$j] = $this->giveTimestamp($coords[$j][3]);
		if ($time[$j] === false) return false;
		if ( $j > 0 ) {
			$speed = $this->giveSpeed($lon[$j],$lat[$j],$time[$j],$lon[($j-1)],$lat[($j-1)],$time[($j-1)],$unit);
			$cht .= $speed.",";
		}
		$j++;
	}
	$chtn = substr($cht, 0, -1);
	return $chtn;
	}

public function createBeatsData($coords) {
$cht = "";

$n = count($coords);
if($n > 600) {
	$c = $n / 600;
	$c = round($c,0);
} else {
	$c = 1;
}
$beats = array();
for($i=0; $i<$n; $i = $i+$c) {
	$coord = $coords[$i];
	$cht .= $coord[4].",";
	array_push($beats,$coord[4]);
}
$chtn = substr($cht, 0, -1);

return $chtn;
	}

	/**
	 *
	 * @param string $distance
	 * @return string
	 */
	public function distance2chart($distance) {
$end = round($distance,1);
$first = round($distance/4,1);
$mid = round($distance/2,1);
$third = round($first * 3,1);
$dis = "0|".$first."|".$mid."|".$third."|".$end;

return $dis;
	}

// Osm BEGIN
	public function writeOSMMap() {
$cfg =& injooosmHelper::getConfig();

// 	$cnates = $this->getMapNates();
	$rows = $this->getTracks();
// 	$user = JFactory::getUser();
// 	$userid = $user->id;
	$rows = $this->maySee($rows);
	$map .= $this->parseScriptOSMHead();
	$map .= $this->parseOSMMapControl();
	$map .= $this->parseOSMLayer($cfg->osm_allow_map);
// 	$map .= $this->parseOSMPOIs(); // currently not active
// 	$map .= $this->parseOSMTracks($rows); // Schlecht bei vielen verfügbaren Tracks
// 	$map .= $this->parseXMLlinesOSM($rows,"/".$file);
	$map .= $this->parseOSMMarker($rows);
	$map .= $this->parseOSMMapCenter($rows);
	$map .= $this->parseOSMMapFunctions();
	$map .= $this->parseScriptOSMFooter();
// return $this->buildColorBalken();
// die();
return $map;
	}

	public function writePersonelMap() {
	$map = "
<script type=\"text/javascript\" src=\"http://localhost:81/custom/.GPS-Joomla/components/com_injooosm/assets/js/homeposition.js\"></script>
";
	$cfg =& injooosmHelper::getConfig();
	$cnates = $this->getMapNates();
	$rows = $this->getTracks();
// 	$user = JFactory::getUser();
// 	$userid = $user->id;
	$rows = $this->maySee($rows);

	$map .= $this->parseScriptOSMHead();
	$map .= $this->parseOSMMapControl();
	$map .= $this->parseOSMLayer($cfg->osm_allow_map);
//	$map .= $this->parseOSMPOIs();
// 	$map .= $this->parseOSMTracks($rows); // Schlecht bei vielen verfügbaren Tracks
// 	$map .= $this->parseXMLlinesOSM($rows,"/".$file);
//	$map .= $this->parseOSMMarker($rows);
//	$map .= $this->parseOSMMapCenter($rows);
	$map .= "// <!-- parseOSMMapCenter BEGIN -->
	\n";
	$map .= "	layerMarker_options= {styleMap: new OpenLayers.StyleMap({
		externalGraphic: \"components/com_injooosm/assets/images/home.png\",
		backgroundGraphic: \"components/com_injooosm/assets/images/home_shdw.png\",
		graphicXOffset:-15,
		graphicYOffset:-20,
		backgroundXOffset:-15,
		backgroundYOffset:-20,
		// Set the z-indexes of both graphics to make sure the background
		// graphics stay in the background (shadows on top of markers looks
		// odd; let's not do that).
		graphicZIndex: 11,
		backgroundGraphicZIndex: 10,
		pointRadius: 20
	}),
	displayInLayerSwitcher: false,
	isBaseLayer:false,
//	isBaseLayer:true,
	rendererOptions: {yOrdering: true},
	eventListeners:{'featureadded': function(){map.getControlsByClass('OpenLayers.Control.Permalink')[0].updateLink()},
		'featuresremoved': function(){map.getControlsByClass('OpenLayers.Control.Permalink')[0].updateLink()}
		}
	};
	//Layer to draw a personalized marker within
	layerMarker = new OpenLayers.Layer.Vector(\"Marker\", layerMarker_options);
	// Add a drag feature control to move features around.
	var dragFeature = new OpenLayers.Control.DragFeature(layerMarker,
	{onComplete:function(){map.getControlsByClass('OpenLayers.Control.Permalink')[0].updateLink()}});
	map.addControl(dragFeature);
	dragFeature.activate();
	map.addLayers([layerMarker]);


function handleMapClick(evt) {
//set Marker on click
	layerMarker.removeFeatures(layerMarker.features);
	var pixel = new OpenLayers.Pixel( evt.xy.x, evt.xy.y);
	var lonLat = map.getLonLatFromViewPortPx(pixel);
	var marker = [];
	marker.push(new OpenLayers.Feature.Vector(new OpenLayers.Geometry.Point(lonLat.lon, lonLat.lat)));
	layerMarker.addFeatures(marker);
	OpenLayers.Event.stop(evt);
};
map.events.register('click', map, handleMapClick);

\n";

	$map .= "var min = lonLatToMercator(new OpenLayers.LonLat";
	$bbox_lon_min = -180;
	$bbox_lat_min = 83;
	$bbox_lon_max = 180;
	$bbox_lat_max = -55;
	$map .= "(".$bbox_lon_min.",".$bbox_lat_min."));\nvar max = lonLatToMercator";
	$map .= "(new OpenLayers.LonLat(".$bbox_lon_max.",".$bbox_lat_max."));\n";
	$map .= "map.zoomToExtent(new OpenLayers.Bounds(min.lon, min.lat, max.lon, max.lat));\n";
	$map .= "// <!-- parseOSMMapCenter END -->\n";

	$map .= $this->parseOSMMapFunctions();
	$map .= $this->parseScriptOSMFooter();
	return $map;
	}

	/**
	 * counts the MapCenter and ZoomLevel of Boundingbox
	 * 
	 * @param flow $lon_min,$lon_max,$lat_min,$lat_max
	 * @return array('lon'=>lon,'lat'=>lat)
	 */
	public function calcMapCenter($lon_min,$lon_max,$lat_min,$lat_max) {
		$lat = 47;	// Weltansicht ohne Südpol
		$lon = 0;
		$zoom_min = 2;
		$zoom_max = 14;
		$return = array();
		if ( ( $lon_min == $lon_max ) AND ( $lat_min == $lat_max ) ) {
// 			Nur eine Koordinate wurde übergeben
			$return['lon'] = $lon_min;
			$return['lat'] = $lat_min;
// 			$return['zoom'] = $zoom_max;
		} else {
			$return['lon'] = ( ( $lon_max + $lon_min ) / 2 );
			$return['lat'] = ( ( $lat_max + $lat_min ) / 2 );
		}
// 		return $return;
	}

	/**
	 *
	 * @return string
	 */
	private function parseOSMMapCenter($rows) {

	$count = count($rows);
	$bbox_lat_max = 0;
	$bbox_lat_min = 90;
	$bbox_lon_max = 0;
	$bbox_lon_min = 90;
	foreach ( $rows AS $row ) {
		if ( ( $row->start_n ) AND ( $row->start_n > $bbox_lat_max ) )
			$bbox_lat_max = $row->start_n;
		if ( ( $row->start_n ) AND ( $row->start_n < $bbox_lat_min ) )
			$bbox_lat_min = $row->start_n;
		if ( ( $row->start_e ) AND ( $row->start_e > $bbox_lon_max ) )
			$bbox_lon_max = $row->start_e;
		if ( ( $row->start_e ) AND ( $row->start_e < $bbox_lon_min ) )
			$bbox_lon_min = $row->start_e;
	}
// die(var_dump($bbox_lon_min));
// 	echo ("\n<!--\n\$bbox_lat_max = ".$bbox_lat_max."\n\$bbox_lat_min = ".$bbox_lat_min."\n-->");
	$center = "// <!-- parseOSMMapCenter BEGIN -->\n";
	$center .= "var min = lonLatToMercator(new OpenLayers.LonLat";
	$center .= "(".$bbox_lon_min.",".$bbox_lat_min."));\nvar max = lonLatToMercator";
	$center .= "(new OpenLayers.LonLat(".$bbox_lon_max.",".$bbox_lat_max."));\n";
	$center .= "map.zoomToExtent(new OpenLayers.Bounds(min.lon, min.lat, max.lon, max.lat));\n";
	$center .= "// <!-- parseOSMMapCenter END -->\n";
	return $center;
}

	/**
	 *
	 * @return string
	 */
	private function parseOSMMapCenterSingleTrack($file) {
	if (!is_file($file)) return false;
	$xml = simplexml_load_file($file);
	$bbox_lat_max = -90;
	$bbox_lat_min = 90;
	$bbox_lon_max = -180;
	$bbox_lon_min = 180;
	$this->gpsFile = $file;
	$isWaypoint = $this->isWaypoint();
	if ( $isWaypoint !== false ) {
		$i = $isWaypoint;
		$found = 0;
		while(true) {
			if (isset($xml->wpt[$i])) {
				$wp = $xml->wpt[$i];
				if ( $wp != null ) {
					$wp = $wp->attributes();
					$lon = (float)$wp->lon;
					$lat = (float)$wp->lat;
					if ( $lat > $bbox_lat_max ) $bbox_lat_max = $lat;
					if ( $lat < $bbox_lat_min ) $bbox_lat_min = $lat;
					if ( $lon > $bbox_lon_max ) $bbox_lon_max = $lon;
					if ( $lon < $bbox_lon_min ) $bbox_lon_min = $lon;
					$found = 0;
				}
				$i++;
			}
			$found++;
			if ( $found > 10 ) break;
		}
	}
	$isTrack = $this->isTrack();
	if ( $isTrack !== false ) {
		$i = $isTrack;
		$found = 0;
		$foundj = 0;
		while(true) {
			if (isset($xml->trk[$i]->trkseg->trkpt)) {
				$found = 0;
				$j = 0;
				while(true) {
					if (isset($xml->trk[$i]->trkseg->trkpt[$j])) {
						$trk = $xml->trk[$i]->trkseg->trkpt[$j]->attributes();
						if ( $trk != null ) {
							$lon = (float)$trk->lon;
							$lat = (float)$trk->lat;
							if ( $lat > $bbox_lat_max ) $bbox_lat_max = $lat;
							if ( $lat < $bbox_lat_min ) $bbox_lat_min = $lat;
							if ( $lon > $bbox_lon_max ) $bbox_lon_max = $lon;
							if ( $lon < $bbox_lon_min ) $bbox_lon_min = $lon;
							$foundj = 0;
						}
						$j++;
					}
					$foundj++;
					if ( $foundj > 10 ) break;
				}
			}
			$found++;
			if ( $found > 10 ) break;
			$i++;
		}
	}
	$center = "// <!-- parseOSMMapCenterSingleTrack BEGIN -->\n";
	$center .= "var min = lonLatToMercator(new OpenLayers.LonLat";
	$center .= "(".$bbox_lon_min.",".$bbox_lat_min."));\n";
	$center .= "var max = lonLatToMercator(new OpenLayers.LonLat";
	$center .= "(".$bbox_lon_max.",".$bbox_lat_max."));\n";
	$center .= "map.zoomToExtent(new OpenLayers.Bounds(min.lon, min.lat, max.lon, max.lat));\n";
	$center .= "// <!-- parseOSMMapCenterSingleTrack END -->\n";
	return $center;
}

	/**
	 *
	 * @return string
	 */
	private function parseOSMMapFunctions() {
	$marker = "// <!-- parseOSMMapFunctions BEGIN -->\n";
/*
	$marker .= "	/**
	* Function: lonLatToMercator
	* OpenLayers-Karte mit OSM-Daten aufbauen
	* Version 2009-09-07 
	* \"EPSG:41001\" -> 4326
	* http://www.fotodrachen.de/javascripts/map.js
	* Parameters:
	* ll - {<OpenLayers.LonLat>}
	*/

$marker .= "	function lonLatToMercator(ll) {
		var lon = ll.lon * 20037508.34 / 180;
		var lat = Math.log(Math.tan((90 + ll.lat) * Math.PI / 360)) / (Math.PI / 180);
		lat = lat * 20037508.34 / 180;
		return new OpenLayers.LonLat(lon, lat);
	}\n";

	$marker .= "// <!-- parseOSMMapFunctions END -->\n";
return $marker;
}

	/**
	 *
	 * @return string
	 */
//	 private function parseOSMStartZiel() {
// 	$startziel = "// <!-- parseOSMStartZiel BEGIN -->\n";
// 	$startziel .= "// <!-- parseOSMStartZiel END -->\n";
// 	return $startziel;
// }

	/**
	 *
	 * @return string
	 */
	private function parseOSMMarker($track_array,$visiblitiy=true) {
	$marker = "// <!-- parseOSMMarker BEGIN -->\n";
	if ( $visiblitiy != true )
		$marker .= "	markers = new OpenLayers.Layer.Markers(\"".JText::_('OSM_OTHER_STARTPOINTS')."\");\n";
	else
		$marker .= "	markers = new OpenLayers.Layer.Markers(\"".JText::_('OSM_STARTPOINTS')."\");\n";
	$marker .= "	map.addLayer(markers);\n";
	$marker .= "	addMarkers();\n";
	if ( $visiblitiy != true )
		$marker .= "	markers.setVisibility(false);\n";
	$marker .= "	function addMarkers() {\n";

foreach ( $track_array AS $row ) {
	$link = JROUTE::_("index.php?option=com_injooosm&view=files&layout=file&id=".$row->id);
// var_dump($row->file);
// die();

	$lon = $row->start_e;
	$lat = $row->start_n;
	if ( ( $row->published == 1 ) AND ( ( $lon ) OR ( $lon ) ) ){
		$marker .= "ll = new OpenLayers.LonLat(".$lon.",".$lat.").";
		$marker .= "transform(new OpenLayers.Projection(\"EPSG:4326\"), map.getProjectionObject()); ";
		$marker .= "popupClass = AutoSizeFramedCloud; ";
		$marker .= "popupContentHTML = '<b>".JText::_('OSM_TITLE').": <a href=\"".$link."\">";
		if ($row->title)
			$marker .= $row->title;
		else
			$marker .= "<i>".JText::_('OSM_NO_TITLE')."</i>";
// 		if ( $row->access == 1 ) // wird eh ausgeblendet
// 			$marker .= "&nbsp;<img src=\\\"components/com_injooosm/assets/images/registred_only.png\\\" />";
		$marker .= "</a></b>";
		if ( $row->cat != "" ) {
			$marker .= "<br />".JText::_('OSM_CAT').": ";
			$marker .= "<a href=\"index.php?option=com_injooosm&view=files&layout=list&search=";
			$marker .= $row->cat."\">".$row->cat."</a><br />";
		} else
			$marker .= "<br /><i>".JText::_('OSM_CAT_NONE')."</i>";
		$marker .= $this->showDesc($row->description);
		$marker .= "'; ";

// start icon
		$marker .= $this->parseCatIcon($row->catid,$row->istrack,$row->iswp,$row->isroute);
// end icon
	}
}
	$marker .= "	}\n";
//	$marker .= "	//
//	* Function: addMarker
//	* Add a new marker to the markers layer given the following lonlat, 
//	*	 popupClass, and popup contents HTML. Also allow specifying 
//	*	 whether or not to give the popup a close box.
//	* 
//	* Parameters:
//	* ll - {<OpenLayers.LonLat>} Where to place the marker
//	* popupClass - {<OpenLayers.Class>} Which class of popup to bring up 
//	*	 when the marker is clicked.
//	* popupContentHTML - {String} What to put in the popup
//	* closeBox - {Boolean} Should popup have a close box?
//	* overflow - {Boolean} Let the popup overflow scrollbars?
//	*/

	$marker .= "function addMarker(ll, popupClass, popupContentHTML, closeBox, overflow, icon) {
		var feature = new OpenLayers.Feature(markers, ll);
		feature.closeBox = closeBox;
		feature.popupClass = popupClass;
		feature.data.popupContentHTML = popupContentHTML;
		feature.data.overflow = (overflow) ? \"auto\" : \"hidden\";
		var marker = new OpenLayers.Marker(ll,icon);
		marker.feature = feature;
";

$marker .= "
		var markerClick = function (evt) {
			if (this.popup == null) {
				this.popup = this.createPopup(this.closeBox);
				map.addPopup(this.popup);
				this.popup.show();
			} else {
				this.popup.toggle();
			}
		currentPopup = this.popup;
		OpenLayers.Event.stop(evt);
		};
";
/*
$marker .= "		var markerHover = function (evt) {
			if (this.popup == null) {
				this.popup = this.createPopup(this.closeBox);
				map.addPopup(this.popup);
				this.popup.show();
			} else {
				this.popup.toggle();
			}
		currentPopup = this.popup;
		OpenLayers.Event.stop(evt);
		};

		var markerDestroy = function (evt) {
			if (this.popup != null) {
				this.popup.dest();
			}
		currentPopup = this.popup;
		OpenLayers.Event.stop(evt);
		};
";
*/

// MouseDown
$marker .= "		marker.events.register(\"mousedown\", feature, markerClick);\n";

// MouseHover
//$marker .= "		marker.events.register(\"mouseover\", feature, markerHover);\n";
//$marker .= "		marker.events.register(\"mouseout\", feature, markerHover);\n";

	$marker .= "		markers.addMarker(marker);}\n";
	$marker .= "// <!-- parseOSMMarker END -->\n";
	return $marker;
}
	/**
	 *
	 * @return string
	 */
	private function parseOSMTracks($rows) {

	$string = "// <!-- parseOSMTracks BEGIN -->\n";
	$string .= "layer_vectors = new OpenLayers.Layer.Vector(\"".JText::_('osm_files')."\", { displayInLayerSwitcher: true } );\n";
	$string .= "map.addLayer(layer_vectors);\n";
	foreach($rows AS $row) {
		$file = ("./components/com_injooosm/uploads/".$row->file);
		$coords = $this->getCoords($file);
		$string .= "geometries = new Array();geometries.push(drawLine([\n";
		if ($coords){
			foreach($coords as $key => $fetch) {
				$string .= "[".$coords[$key][0].",".$coords[$key][1]."],\n";
			}
		}
		$string .= "],\n{strokeColor:\"".$this->getHexColor()."\",\nstrokeWidth: 2,\nfillColor: \"".$this->getHexColor()."\",\nfillOpacity: 0.4}));\n";
	}
	$string .= "// <!-- parseOSMTracks END -->\n";
	return $string;
}

	/**
	 *
	 * @return string
	 */
	private function parseOSMPOIs() {
	$pois = "// <!-- parseOSMPOIs BEGIN -->\n";
	$pois .= "// <!-- parseOSMPOIs END -->\n";
	return $pois;
}

	/**
	 *
	 * @return string
	 */
	private function parseOSMLayer($osm_allow_map="1000000001") {
	$osm_allow_map_default = ($osm_allow_map[9]-1);

	for($i=0;$i<9;$i++) {
		${"osm_allow_map_".$i} = $osm_allow_map[$i];
	}

	$layer = "// <!-- parseOSMLayer BEGIN -->\n";

	$layertoshow = array();

	$layertoshow[0] = "		layerMapnik = new OpenLayers.Layer.OSM.Mapnik(\"Mapnik\");\n			map.addLayer(layerMapnik);\n";
	$layertoshow[1] = "		layerTilesAtHome = new OpenLayers.Layer.OSM.Osmarender(\"Osmarender\");\n			map.addLayer(layerTilesAtHome);\n";
	$layertoshow[2] = "		layerCycleMap = new OpenLayers.Layer.OSM.CycleMap(\"CycleMap\");\n			map.addLayer(layerCycleMap);\n";
/*	$layertoshow[3] = "
		layerol_wms = new OpenLayers.Layer.WMS( \"OpenLayers WMS (metacarta)\",
			\"http://labs.metacarta.com/wms/vmap0?\", {layers: \"basic\"} );
			map.addLayer(layerol_wms);\n
";
 	$layertoshow[3] .= "		layerOpenLayers = new OpenLayers.Layer.WMS( \"OpenLayers WMS (cubewerx)\",
			\"http://demo.cubewerx.com/demo/cubeserv/cubeserv.cgi?\",
			{layers: 'Foundation.GTOPO30', version: '1.3.0'},
			{singleTile: true});
			map.addLayer(layerOpenLayers);\n
";*/
/*
for google you need:
<script src='http://maps.google.com/maps?file=api&amp;v=2&amp;key='></script>
*/

/* 	$layertoshow[3] .= "
// create Google Mercator layers
		var gmap = new OpenLayers.Layer.Google(
			\"Google Streets\",
			{'sphericalMercator': true});
			map.addLayer(gmap);\n
";
 	$layertoshow[3] .= "		var gsat = new OpenLayers.Layer.Google(\"Google Satellite\",
			{type: G_SATELLITE_MAP, 'sphericalMercator': true, numZoomLevels: 22});
			map.addLayer(gsat);\n
";
 	$layertoshow[3] .= "		var ghyb = new OpenLayers.Layer.Google(\"Google Hybrid\",
			{type: G_HYBRID_MAP, 'sphericalMercator': true});
			map.addLayer(ghyb);\n
";


// for VE you need:
// <script src='http://dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=6.1'></script>

 	$layertoshow[3] .= "// create Virtual Earth layers
		var veroad = new OpenLayers.Layer.VirtualEarth(\"Virtual Earth Roads\",
			{'type': VEMapStyle.Road, 'sphericalMercator': true});
			map.addLayer(veroad);\n
";
 	$layertoshow[3] .= "		var veaer = new OpenLayers.Layer.VirtualEarth(\"Virtual Earth Aerial\",
			{'type': VEMapStyle.Aerial, 'sphericalMercator': true});
			map.addLayer(veaer);\n
";
 	$layertoshow[3] .= "		var vehyb = new OpenLayers.Layer.VirtualEarth(\"Virtual Earth Hybrid\",
			{'type': VEMapStyle.Hybrid, 'sphericalMercator': true});
			map.addLayer(vehyb);\n
";
 	$layertoshow[3] .= "// create Yahoo layer
		var yahoo = new OpenLayers.Layer.Yahoo(\"Yahoo Street\",
			{'sphericalMercator': true});
			map.addLayer(yahoo);\n
";
 	$layertoshow[3] .= "		var yahoosat = new OpenLayers.Layer.Yahoo(
				\"Yahoo Satellite\",
				{'type': YAHOO_MAP_SAT, 'sphericalMercator': true});
			map.addLayer(yahoosat);\n
";
 	$layertoshow[3] .= "			var yahoohyb = new OpenLayers.Layer.Yahoo(
				\"Yahoo Hybrid\",
				{'type': YAHOO_MAP_HYB, 'sphericalMercator': true});
			map.addLayer(yahoohyb);\n
";
 	$layertoshow[3] .= "var layerWoE = new OpenLayers.Layer.WMS(
		\"WMS of Europe\",
		\"http://openls.giub.uni-bonn.de/ors-tilecache/tilecache.py?\",
		{layers: 'ors-osm',srs: 'EPSG:900913', format: 'image/png',numZoomLevels: 19},
		{'buffer':2});
			map.addLayer(layerWoE);\n";*/
/*	tot?
 	$layertoshow[3] .= "			var oam = new OpenLayers.Layer.XYZ(
				\"OpenAerialMap\",
				\"http://tile.openaerialmap.org/tiles/1.0.0/openaerialmap-900913/${z}/${x}/${y}.png\",
				{sphericalMercator: true});
			map.addLayer(oam);\n
";
*/
/* 	$layertoshow[3] .= "
			var osmarender = new OpenLayers.Layer.OSM(
				\"OpenStreetMap (hide@address.com)\",
				\"http://tah.openstreetmap.org/Tiles/tile/${z}/${x}/${y}.png\");
			map.addLayer(osmarender);\n
";
*/
/*	tot?
 	$layertoshow[3] .= "			// create WMS layer
			var wms = new OpenLayers.Layer.WMS(
				\"World Map\",
				\"http://world.freemap.in/tiles/\",
				{'layers': 'factbook-overlay', 'format':'png'},
				{
					'opacity': 0.4, visibility: false,
					'isBaseLayer': false,'wrapDateLine': true
				}
			);
			map.addLayer(wms);\n
";
*/

/*	$layertoshow[3] .= "// Hillshading layer provided by University of Bonn
			// based on CIAT-CSI SRTM data, available for
			// non-commercial use only
			var hs_name = \"Hillshade (Uni Bonn)\";
			var hs_url = \"http://services.giub.uni-bonn.de/hillshade?\";
			var hs_options = {layers: 'europe_wms:hs_srtm_europa',srs: 'EPSG:900913', format: 'image/JPEG'};
			var hs = new OpenLayers.Layer.WMS(hs_name , hs_url , hs_options, {'buffer':2});
		map.addLayer(hs);\n";*/
/*
	$layertoshow[3] .= "// Hillshading layer provided by University of Bonn
			// based on CIAT-CSI SRTM data, available for
			// non-commercial use only
			var hs_name = \"Hillshade (Uni Bonn)\";
			var hs_url = \"http://services.giub.uni-bonn.de/hillshade?\";
			var hs_options = {layers: 'europe_wms:hs_srtm_europa',srs: 'EPSG:900913', format: 'image/JPEG', transparent: 'true', isBaseLayer: true};
			var hs = new OpenLayers.Layer.WMS(hs_name , hs_url , hs_options, {'buffer':2});
			hs.setOpacity(0.15);
			hs.visibility = false;
		map.addLayer(hs);\n";
*/
// 	$layertoshow[3] = "		layerOffline = new OpenLayers.Layer.OSM(\"-keine-\",\"\");\n			map.addLayer(layerOffline);\n";
	$layertoshow[3] = "		NASAGlobalMosaic = new OpenLayers.Layer.WMS(\n			\"NASA Global Mosaic\",\n			\"http://t1.hypercube.telascience.org/cgi-bin/landsat7/\",\n			{layers: \"landsat7\"});\n			map.addLayer(NASAGlobalMosaic);\n";
// 	$layertoshow[5] = "		layerKosmos = new OpenLayers.Layer.OSM.Kosmos(\"Kosmos\");\n		layerKosmos = new OpenLayers.Layer.OSM(\"Kosmos\",\"http://home.vrweb.de/~thomas.buedel/Tiles/\", \"basic\", { 'format':'image/png',maxResolution: 180/256 } );\n			map.addLayer(layerKosmos);\n";

	$defaultmapisset = false;							// Gültiger Default-Layer nicht gefunden
	$baselayer = false;
	for($i=-1;$i<9;$i++) {
		if ( ( $i == -1 ) AND							// erster Durchlauf nur für Def.-Layer
		( isset($osm_allow_map[$osm_allow_map_default])) AND			// existiert der Eintrag auf den der Def.-Layer verweist?
		( $osm_allow_map[$osm_allow_map_default] != 0) ) {			// ... und ist dieser zugelassen?
			$layer .= $layertoshow[$osm_allow_map_default];			// Def.-Layer an erste Stelle
			$defaultmapisset = $osm_allow_map_default;			// Das wird der Def.-Layer (für die Schleife)
			$baselayer = explode('=',$layertoshow[$osm_allow_map_default]);	// Baselayer ebenfalls benannt
			$baselayer = trim($baselayer[0]);
		} elseif ( ( $osm_allow_map[$i] == 1 ) AND ( $defaultmapisset != $i ) )	// Füge Layer nur hinzu, wenn zugelassen ...
			$layer .= $layertoshow[$i];					// ... und es kein Def.-Layer ist
	}
// echo("<br>\nHallo Welt \"".$layer."\"");

	$layer .= "// <!-- parseOSMLayer END -->\n";

	if ( $baselayer != false ) {
		$layer .= "		map.setBaseLayer(".$baselayer.");\n";
		return $layer;
	} else return $layertoshow[0];	// Gib nur Mapnik aus, für den Fall der Fehlkonfiguration
}

public function writeTrackOSM($track) {
	$cfg =& injooosmHelper::getConfig();
//	global $mainframe;
	jimport('joomla.filesystem.file');
	$rows = $this->getTracks();
	$file = "components".DS."com_injooosm".DS."uploads".DS.$track->file;
	$this->gpsFile = $file;
	$map = "\n<!-- writeTrackOSM BEGIN -->\n";
	$rows = $this->maySee($rows);		// Berechtigung Okay?
// ToDo: Berechtigungen vorher schon checken?
	$rows = $this->deleteTrack($rows,$track);	// Aktuelle Stecke löschen
// var_dump($links);die();
	$map .= $this->parseScriptOSMHead();
	$map .= $this->parseOSMMap();
	$map .= $this->parseOSMMapControl();
	$map .= $this->parseOSMLayer($cfg->osm_allow_map);
	$coords = $this->parseXMLlinesOSM("./".$file);
// die(var_dump($coords));
// var_dump($coords);die();
	$map .= $coords;
	$map .= $this->parseOSMMarker($rows,false); // Andere Tracks standardmäßig ausblenden
// 	$map .= $this->parseStartPointOSM($coords); // ist jetzt für jede einzelne Spur definiert
	$file_tmp = $file;
	$wp = $this->extractWPs($file);
	if ($wp !== false);
		$map .= $this->parseWPs($wp);
// var_dump($wp);die();
// 	$map .= $this->parseOSMStartZiel();
	$file = $file_tmp;
	$map .= $this->parseOSMMapCenterSingleTrack($file);
// var_dump($wp);die();
	$map .= $this->parseOSMMapFunctions();

	$map .= $this->parseScriptOSMFooter();
	return $map;
	}

	public function writeSingleTrackOSM($file) {
// für kleine Map in der Administration
	$cfg =& injooosmHelper::getConfig();
	global $mainframe;
	jimport('joomla.filesystem.file');
	$file = JPATH_SITE.DS."components".DS."com_injooosm".DS."uploads".DS.$file;
	$this->gpsFile = $file;
	$map = "\n<!-- writeSingleTrackOSM BEGIN -->\n";
	$map .= $this->parseScriptOSMHead();
	$map .= $this->parseOSMMap();
	$map .= $this->parseOSMMapControl(true);
	$map .= $this->parseOSMLayer($cfg->osm_allow_map);
// 	$coords = $this->parseXMLlinesOSM($file);
// var_dump($coords);die();
	$map .= $this->parseXMLlinesOSM($file);
// 	$map .= $this->parseOSMMarker($rows,false); // Andere Tracks standardmäßig ausblenden
// 	$map .= $this->parseStartPointOSM($coords); // ist jetzt für jede einzelne Spur definiert
// 	$file_tmp = $file;
	$wp = $this->extractWPs($file);
// var_dump($wp);die();
	if ($wp !== false);
		$map .= $this->parseWPs($wp);
// var_dump($wp);die();
// 	$map .= $this->parseOSMStartZiel();
// 	$file = $file_tmp;
	$map .= $this->parseOSMMapCenterSingleTrack($file);
// var_dump($wp);die();
	$map .= $this->parseOSMMapFunctions();

	$map .= $this->parseScriptOSMFooter();
	$map .= "<!-- writeSingleTrackOSM END -->\n";
	return $map;
	}

	/**
	 *
	 * @return string
	 */
	private function parseScriptOSMHead() {

	$map = "\n<!-- parseScriptOSMHead BEGIN -->\n";
	$map .= "<script type=\"text/javascript\">\n";
	$map .= "	OpenLayers.Popup.FramedCloud.prototype.autoSize = false;\n";
	$map .= "	var AutoSizeFramedCloud = OpenLayers.Class(OpenLayers.Popup.FramedCloud, {\n	'autoSize': true\n	});\n";
	$map .= "	var AutoSizeAnchored = OpenLayers.Class(OpenLayers.Popup.Anchored, {\n	'autoSize': true\n		});\n";
	$map .= "	function slippymap_init(divName) {\n";
	$map .= "		var map = new OpenLayers.Map (divName, {\n";
	$map .= "// <!-- parseScriptOSMHead END -->\n";

return $map;
	}

	/**
	 *
	 * @return string
	 */
	private function parseScriptOSMFooter() {

$map = "// <!-- parseScriptOSMFooter BEGIN -->\n";
$map .= "}\n";
$map .= "</script>\n";
$map .= "<!-- parseScriptOSMFooter END -->\n";
// $map .= "<center><div id=\"map\" style=\"width: 600px; height: 400px;\" ><script type=\"text/javascript\">slippymap_init();</script></div></center>\"";

return $map;
	}

	/**
	 *
	 * @return string
	 */
	private function parseOSMMapControl($adminonly = false) {
/*

*/
	$control = "// <!-- parseOSMMapControl BEGIN -->\n";
	$control .= "		controls:[\n";
	$control .= "//		Don't forget to remove comma in last line.\n//		Otherwise it doesn't work with IE.\n";
// 	$control .= "				new OpenLayers.Control.ArgParser(),	// ?\n";
// 	$control .= "				new OpenLayers.Control.KeyboardDefaults(),	// Tastatur: hoch, runter, links, rechts, +, -\n";
	$control .= "				new OpenLayers.Control.MousePosition(),		// Koordinate des Mauszeigers (lat, lon)\n";
	$control .= "				new OpenLayers.Control.Navigation(),		// mit Maus verschieb- und zoombar\n";
	$control .= "				new OpenLayers.Control.LayerSwitcher(),		// Menue zum ein/aus-Schalten der Layer\n";
if ( $adminonly === false){
	$control .= "				new OpenLayers.Control.PanZoomBar(),		// Zoombalken\n";
	$control .= "				new OpenLayers.Control.Attribution(),		// ?\n";
//	$control .= "				new OpenLayers.Control.ScaleLine(),		// Maszstab (nur am Aequator genau?)\n";

//	$control .= "				new OpenLayers.Control.ScaleLine({\n		opOutUnits: 'm',\n					topInUnits: 'km',\n					bottomOutUnits: 'km',\n					bottomInUnits: 'm'}),					// Massstab (nur an Äquator genau?)\n";
//	$control .= "				new OpenLayers.Control.Permalink(null,'t', permalinkOptions),\n";
//	$control .= "				new OpenLayers.Control.Permalink(),		// Permalink\n";
}
	$control .= "				new OpenLayers.Control.MouseDefaults()		// ?\n";
	$control .= "			],\n";
	$control .= "				maxExtent: new OpenLayers.Bounds(-20037508.34,-20037508.34,20037508.34,20037508.34),\n";
	$control .= "				maxResolution: 156543.0399,\n";
	$control .= "				numZoomLevels: 19,\n";
	$control .= "				units: \"m\",\n";
	$control .= "				projection: new OpenLayers.Projection(\"EPSG:900913\"),\n";
	$control .= "				displayProjection: new OpenLayers.Projection(\"EPSG:4326\")\n";
	$control .= "			} );\n";

if ( $adminonly === false) {
//	$control .= "				var layer_overviewmap = new OpenLayers.Layer.OSM.Mapnik(\"Mapnik\");\n";
//	$control .= "				map.addControl(new OpenLayers.Control.OverviewMap({layers: [layer_overviewmap]}));\n";
//	$control .= "			// Uebersicht\n";
}
	$control .= "// <!-- parseOSMMapControl END -->\n";
return $control;
	}

	/**
	 *
	 * @return string
	 */
	private function markerFunctionOSM() {
$map = "// <!-- markerFunctionOSM BEGIN -->\n";
// $map .= "function createMarker(point,html) {\n";
// $map .= "var marker = new GMarker(point);\n";
// $map .= "GEvent.addListener(marker, 'click', function() {\n";
// $map .= "marker.openInfoWindowHtml(html);\n";
// $map .= "});\n";
// $map .= "return marker;\n";
// $map .= "}\n";
$map .= "// <!-- markerFunctionOSM END -->\n";

return $map;
	}

	/**
	 *
	 * @return string
	 */
	private function parseOSMMap() {
$string = "// <!-- parseOSMMap BEGIN -->\n";
/*
$cfg =& injooosmHelper::getConfig();
switch($cfg->map_type) {
	case "0":
$type = "G_NORMAL_MAP";
break;

	case "1":
$type = "G_SATELLITE_MAP";
break;

	case "2":
$type = "G_HYBRID_MAP";
break;

	case "3":
$type = "G_PHYSICAL_MAP";
break;

	default:
$type = "G_NORMAL_MAP";
break;
}
*/
// $string .= "map = new GMap2(document.getElementById('map'));\n";
// $string .= "map.addMapType(G_PHYSICAL_MAP);\n";
// $string .= "map.setMapType(".$type.");\n";

$string .= "// <!-- parseOSMMap END -->\n";
return $string;
	}

	/**
	 *
	 * @param object $track
	 * @return string
	 */
	private function parseStartPointOSM($coords) {
	$map = "// <!-- parseStartPointOSM BEGIN -->\n";
	$rows = explode("\n",$coords);
	$fetch = false;
	foreach ( $rows AS $row ) {
		if ( trim($row) == "// fetchCoordsEnd" ) $fetch = false;
		if ( $fetch == true ) {
			$row = preg_replace(array('/\[/','/\]/'),'',trim($row));
			$row = explode(',',$row);
			$lon = $row[0];
			$lat = $row[1];
			if (!isset($start))
				$start = $lon.", ".$lat;
			$stop = $lon.", ".$lat;
		}
		if ( trim($row) == "// fetchCoordsBegin" ) $fetch = true;
	}
$map .= "		layerStartZiel = new OpenLayers.Layer.Markers(\"Start/Ziel\");
			map.addLayer(layerStartZiel);
			layerStartZiel.setVisibility(true);

		var lonLatStart = new OpenLayers.LonLat(".$start.").transform(new OpenLayers.Projection(\"EPSG:4326\"), map.getProjectionObject());
		var lonLatZiel = new OpenLayers.LonLat(".$stop.").transform(new OpenLayers.Projection(\"EPSG:4326\"), map.getProjectionObject());
		var sizeStart = new OpenLayers.Size(24,24);
		var sizeZiel = new OpenLayers.Size(24,24);
		var offsetStart = new OpenLayers.Pixel(-3,-22);
		var offsetZiel = new OpenLayers.Pixel(-11,-21);
		var iconStart = new OpenLayers.Icon(\"".JURI::root()."components".DS."com_injooosm".DS."assets".DS."images".DS."start.png\",sizeStart,offsetStart);
		var iconZiel = new OpenLayers.Icon(\"".JURI::root()."components".DS."com_injooosm".DS."assets".DS."images".DS."ziel.png\",sizeZiel,offsetZiel);
		layerStartZiel.addMarker(new OpenLayers.Marker(lonLatStart,iconStart));
		layerStartZiel.addMarker(new OpenLayers.Marker(lonLatZiel,iconZiel));
// <!-- parseStartPointOSM END -->\n";
	return $map;
	}

	/**
	 *
	 * @param string $file
	 * @return array
	 */
	private function parseXMLlinesOSM($file) {
	$i = 0;
	$foundtracks = 0;
	$link = JFactory::getURI();
	$link = $link->_uri;
	$this->gpsFile = $file;
	$xml = ($this->loadFile());
	$string_se = "";
	$string = "// <!-- parseXMLlinesOSM BEGIN -->\n";
	$counttracks=0;
	while (true) {
		$coords = $this->getCoords($file,$i);
		if ( $coords != false ) {
			$foundtracks = 0;
			$counttracks++;
		} elseif ( $foundtracks > 10 ) {
			break;
		}
		$foundtracks++;
		$i++;
	}
$counttracks = $this->calculateAllColors($counttracks);
	$foundtracks = 0;
	$i = 0;
	while (true) {
		$coords = $this->getCoords($file,$i);
		if ( $coords != false ) {
			$track = $xml->trk[$i];
			$subid = $link."&amp;subid=".$i;
			$string .= "layer_vectors = new OpenLayers.Layer.Vector(";
			$string .= "\"".JText::_('OSM_TRACK').$i.": ".$track->name."\"";
			$string .= ", { displayInLayerSwitcher: true }";
			$string .= ")";
			$string .= ";map.addLayer(layer_vectors)";
// 			$string .= ";map.addLayer(layerMapnik)";
			$string .= ";\n";
// 		if ( $i != 0 ) // nur erste Spur standardmäßig anzeigen
// 			$string .= "layer_vectors.setVisibility(false);\n";
			$string .= "var geometries = new Array();geometries.push(drawLine([\n";
			//$string .= "// fetchCoordsBegin\n";
			if ($coords) {
				$j = 0;
				$coordscount = (count($coords)-1);
				$n=0;
				foreach($coords as $key => $fetch) {
					if ($j == 0)
						$start = ($coords[$key][0].",".$coords[$key][1]);
					elseif ($j == $coordscount)
						$stop = ($coords[$key][0].",".$coords[$key][1]);
					$string .= "[".$coords[$key][0].",".$coords[$key][1]."]";
					if($n != $coordscount)
						$string .= ",\n";
					else
						$string .= "\n";
					$j++;
					$n++;
				}
			}
//			$string .= "// fetchCoordsEnd\n";
			$string .= "],\n{";
			$color = "#".$counttracks[$i];
			$string .= "strokeColor:\"".$color."\",\n";
			$string .= "strokeWidth: 3,\n";
// 			$string .= "fillColor: \"".$this->getHexColor()."\",\n";
// 			$string .= "fillOpacity: 0.4";
			$string .= "strokeOpacity: 0.7";
			$string .= "}));\n";

			$string_se .= "var lonLatStart".$i." = new OpenLayers.LonLat(".$start.").";
			$string_se .= "transform(new OpenLayers.Projection(\"EPSG:4326\"), map.getProjectionObject());\n";
			$string_se .= "var lonLatZiel".$i." = new OpenLayers.LonLat(".$stop.").";
			$string_se .= "transform(new OpenLayers.Projection(\"EPSG:4326\"), map.getProjectionObject());\n";
			$string_se .= "var sizeStart".$i." = new OpenLayers.Size(24,24);\n";
			$string_se .= "var sizeZiel".$i." = new OpenLayers.Size(24,24);\n";
			$string_se .= "var offsetStart".$i." = new OpenLayers.Pixel(-3,-22);\n";
			$string_se .= "var offsetZiel".$i." = new OpenLayers.Pixel(-11,-21);\n";
			$string_se .= "var iconStart".$i." = ";
			$string_se .= "new OpenLayers.Icon(\"".JURI::root()."components".DS."com_injooosm".DS."assets".DS."images".DS."start.png\",";
			$string_se .= "sizeStart".$i.",offsetStart".$i.");\n";
			$string_se .= "var iconZiel".$i." = new OpenLayers.Icon(\"".JURI::root()."components".DS."com_injooosm".DS."assets".DS."images".DS."ziel.png\",";
			$string_se .= "sizeZiel".$i.",offsetZiel".$i.");\n";
// 			$string_se .= "layer_startziel.addMarker(new OpenLayers.Marker(lonLatStart".$i.",iconStart".$i."));\n";
			$string_se .= "layer_startziel.addMarker(new OpenLayers.Marker(lonLatZiel".$i.",iconZiel".$i."));\n";
			$string_se .= "popupClassStart = AutoSizeAnchored;\n";
// 			$name[$i] = $track->name;
// 			$string_se .= "popupContentHTMLStart = '<span style=\"background-color:#000\"<a href=\"".$subid."\"><b>";
			$string_se .= "popupContentHTMLStart = '<b>";
			$string_se .= "<font color=\"".$color."\">".JText::_('OSM_TRACK').$i.": ".$track->name;
// 			$string_se .= "</font></b></a></span>';\n";
			$string_se .= "</font></b>';\n";
			$string_se .= "addlayer_startziel(lonLatStart".$i.", popupClassStart, popupContentHTMLStart, true, false, iconStart".$i.", map);\n";

			$foundtracks = 0;
		} elseif ( $foundtracks > 10 ) break;
// 			Überspringe 10 Spuren ohne Punkte
		$foundtracks++;
		$i++;
	}
	$string .= "layer_startziel = new OpenLayers.Layer.Markers(";
	$string .= "\"".$i.": ".$track->name."\"";
	$string .= ", { displayInLayerSwitcher: false }";
	$string .= ");";
	$string .= "map.addLayer(layer_startziel);";
	$string .= "layer_startziel.setVisibility(true);";
	$string .= $string_se;
	$string .= "// <!-- parseXMLlinesOSM END -->\n";
	return $string;
	}

	/**
	 *
	 * @param string $file
	 * @return array
	 */
	public function giveClickLinks($file) {
	$i = 0;
	$links = array();
	$this->gpsFile = $file;
// var_dump($file);die();
	while (true) {
		$coords = $this->getCoords($file,$i);
		if ( $coords == false ) break;
		$xml = $this->loadFile();
		$xml = $xml->trk[$i];
		$link = JFactory::getURI();
		$link = $link->_uri;
		$link = $link."&amp;subid=".$i;
		$name = (string)$xml->name;
		$links[$i]['link'] = $link;
		$links[$i]['name'] = $name;
		$i++;
	}
	return $links;
	}

	/**
	 * checks if the given file is a GPX or KML file and call the function for it
	 * 
	 * @param string $file
	 * @return array
	 */
	public function getCoords($file,$trackid=0) {
jimport('joomla.filesystem.file');

$ext = JFile::getExt($file);
// var_dump($ext);die();

if($ext == 'kml') {
	$coords =$this->getCoordsKML($file,$trackid);
	return $coords;
} else if($ext == 'gpx') {
	$coords = $this->getCoordsGPX($file,$trackid);
	if ( $coords == false ) return false;
	return $coords;
} else if ($ext == 'tcx') {
	$coords = $this->getCoordsTCX($file,$trackid);
	return $coords;
} else {
	return JText::_('OSM_FILE_ERROR');
}

	}

	/**
	 *
	 * @param string $file
	 * @return array
	 */
	private function getCoordsKML($file,$trackid=0) {

if (file_exists($file)) {
	$xml = simplexml_load_file($file);
	$namespaces = $xml->getNamespaces();

	$newns = array();
	foreach($namespaces as $key => $ns) {
	array_push($newns, $ns);
	}

	$doc = new DOMDocument;
	$doc->load($file);

	$xpath = new DOMXPath($doc);
	$xpath->registerNamespace('kml', $newns[0]);

	$query = $xpath->query('//kml:LineString/kml:coordinates/text()');

	$coords = $query->item(0)->nodeValue;
	// catch different types coordinates are written in kml files
	$coords = str_replace("\n", '/',$coords);
	$coords = str_replace(" ", '/',$coords);
	
	$coords = explode('/', $coords);
	$newco = array();
	for($i=0, $n=count($coords); $i<$n; $i++) {
if($coords[$i] != NULL) {
	$file = explode(',', $coords[$i]);
	$a = array($file[0],$file[1],$file[2],0,0);
	array_push($newco, $a);
}
	}
	$start = array_pop($newco);
	
	return $newco;

	} else {
return false;
	}

	}

/**
 *
 * @param string $file
 * @return array
 */
private function getCoordsGPX($file,$trackid=0) {
	if (!file_exists($file)) return false;
	$xml = simplexml_load_file($file);
	$start = array();
	for($j=0; $j < count($xml->trk[$trackid]->trkseg); $j++) {
		for($i=0; $i < count($xml->trk[$trackid]->trkseg[$j]->trkpt); $i++) {
			$trkpt = $xml->trk[$trackid]->trkseg[$j]->trkpt[$i];
			if(isset($trkpt->attributes()->lat) && isset($trkpt->attributes()->lon)) {
				$lat = $trkpt->attributes()->lat;
				$lon = $trkpt->attributes()->lon;
				if(isset($trkpt->ele)) {
					$ele = $trkpt->ele;
				} else {
					$ele = "0";
				}
				if(isset($trkpt->time)) {
					$time = $trkpt->time;
				} else {
					$time = "0";
				}
				$start[] = array((string)$lon, (string)$lat,(string)$ele,(string)$time,0);
			}
		}
	}
	return $start;
}

	/**
	 *
	 * @param string $file
	 * @return array
	 */
	private function getCoordsTCX($file,$trackid=0) {
		if (file_exists($file)) {
			$xml = simplexml_load_file($file);
// die(var_dump($xml->Courses->Course->Track[1]));
			if(isset($xml->Activities->Activity->Lap->Track)) {
				$startpoint = $xml->Activities->Activity->Lap->Track[$trackid];
			} elseif (isset($xml->Courses->Course->Track)) {
				$startpoint = $xml->Courses->Course->Track[$trackid];
			}

			$coords = array();
if (!$startpoint[0]) return false;
			foreach($startpoint[0] as $start) {
// 				die(var_dump($start));
				if(isset($start->Position->LatitudeDegrees) && isset($start->Position->LongitudeDegrees)) {
					$lat = $start->Position->LatitudeDegrees;
					$lon = $start->Position->LongitudeDegrees;
					$ele = $start->AltitudeMeters;
					$time = $start->Time;
					if(isset($start->HeartRateBpm->Value)) {
						$heart = $start->HeartRateBpm->Value;
					} else {
						$heart = "0";
					}

					$bak = array((string)$lon,(string)$lat,(string)$ele,(string)$time,(string)$heart);
					array_push($coords,$bak);
				}
			}
			return $coords;
		} else {
			return false;
		}
	}

// Osm END

// Google BEGIN

	/**
	 *
	 * this writes the Javascript code for the overview map
	 * the map is shown in a div container with <strong>id="map"</strong>
	 * <code>
	 * $gps = new gpsClass();
	 * $track = loadObject($query);
	 * $gps->writeMap($track);
	 * </code>
	 * 
	 * @return string Javascriptcode
	 */
	public function writeGoogleMap() {

$cnates = $this->getMapNates();
$rows = $this->getTracks();

$map = "\n";
$map .= "<script type=\"text/javascript\">//<![CDATA[\n";
$map .= "	google.load(\"maps\", \"2\");\n";
$map .= "	google.load(\"search\", \"1\");\n";
$map .= "	var map;\n";
$map .= $this->markerFunctionGoogle();
$map .= "	function initialize() {\n";
$map .= $this->parseGoogleMap();
$map .= "		var bounds = new GLatLngBounds();\n";

$map .= $this->parseGoogleMapControl();
$map .= "		map.addControl(new google.maps.LocalSearch(),\n";
$map .= "			new GControlPosition(G_ANCHOR_BOTTOM_LEFT, new GSize(10,20)));\n";
$map .= $this->parseMarkersGoogle();
$map .= "		map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));\n";
$map .= $this->parseScriptGoogleFooter();

return $map;
	}

	/**
	 * this function shows the map for a single track
	 * the map is shown in a div container with id="map"
	 * $track is the database object of the track
	 * <code>
	 * $gps = new gpsClass();
	 * $track = loadObject($query);
	 * $gps->writeTrack($track);
	 * </code>
	 *
	 * @global object $mainframe
	 * @param object $track
	 * @return string Javascriptcode
	 */
	public function writeTrackGoogle($track) {
global $mainframe;
jimport('joomla.filesystem.file');

$file = "components".DS."com_injooosm".DS."uploads".DS.$track->file;
$map = "";

	$map .= $this->parseScriptGoogleHead();
	$map .= $this->parseGoogleMap();
	$map .= 'var bounds = new GLatLngBounds();';
	$map .= $this->parseGoogleMapControl();
	$map .= $this->parseStartPointGoogle($track);
	$map .= $this->parseXMLlinesGoogle("./".$file);
	$map .= "map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));\n";
	$map .= $this->parseScriptGoogleFooter();

return $map;
	}

	/**
	 *
	 * @return string
	 */
	private function parseScriptGoogleHead() {

$map = "";
$map .= "\n<script type='text/javascript'>//<![CDATA[\n";
$map .= "google.load('maps', '2');\n";
$map .= "var map\n";
$map .= "function initialize() {\n";

return $map;
	}

	/**
	 *
	 * @return string
	 */
	private function parseScriptGoogleFooter() {

$map = "";
$map .= "	}\n";
$map .= "	google.setOnLoadCallback(initialize);\n";
$map .= "//]]>\n";
$map .= "</script>\n";

return $map;
	}

	/**
	 *
	 * @return string
	 */
	private function parseGoogleMapControl() {

$control = "";
$control .= "		var mapControl = new GMapTypeControl();\n";
$control .= "		map.addControl(mapControl);\n";
$control .= "		map.addControl(new GLargeMapControl());\n";
$control .= "		map.addControl(new GOverviewMapControl());\n";

return $control;
	}

	/**
	 *
	 * @return string
	 */
	private function markerFunctionGoogle() {
$map = "";
$map .= "	function createMarker(point,html) {\n";
$map .= "		var marker = new GMarker(point);\n";
$map .= "		GEvent.addListener(marker, 'click', function() {\n";
$map .= "			marker.openInfoWindowHtml(html);\n";
$map .= "		});\n";
$map .= "		return marker;\n";
$map .= "	}\n";

return $map;
	}

	/**
	 *
	 * @return string
	 */
	private function parseMarkersGoogle() {
$rows = $this->getTracks();
$map = "";
foreach($rows as $row) {
	$link = JROUTE::_("index.php?option=com_injooosm&view=files&layout=file&id=".$row->id);
	$map .= "		var point = new GLatLng(".$row->start_n.", ".$row->start_e.");";
	$map .= "bounds.extend(point);";
	$map .= "var marker = createMarker( point,\"";
	$map .= "<a href=\\\"".$link."\\\">";
	$map .= "<b>".$row->title."</b>";		// ToDo: Link für Nicht-Registrierte nur als Text anzeigen
	$map .= "</a>";
	if ( $row->access == 1 )
	$map .= "&nbsp;<img src=\\\"components/com_injooosm/assets/images/registred_only.png\\\" />";
	$map .= "<br />".JText::_('OSM_CAT').": ".$row->cat."\"); map.addOverlay(marker);\n";
}

return $map;
	}
	
	/**
	 *
	 * @return string
	 */
	private function parseGoogleMap() {
$cfg =& injooosmHelper::getConfig();
switch($cfg->map_type) {
	case "0":
$type = "G_NORMAL_MAP";
break;

	case "1":
$type = "G_SATELLITE_MAP";
break;

	case "2":
$type = "G_HYBRID_MAP";
break;

	case "3":
$type = "G_PHYSICAL_MAP";
break;

	default:
$type = "G_NORMAL_MAP";
break;
}

$string = "";
$string .= "		map = new GMap2(document.getElementById('map'));\n";
$string .= "		map.addMapType(G_PHYSICAL_MAP);\n";
$string .= "		map.setMapType(".$type.");\n";

return $string;
	}

	/**
	 *
	 * @param object $track
	 * @return string
	 */
	private function parseStartPointGoogle($track) {
$map = "";
	$map .= "var blueIcon = new GIcon(G_DEFAULT_ICON);\n";
	$map .= "blueIcon.image = '".JURI::base()."components".DS."com_injooosm".DS."assets".DS."images".DS."gruen.png';\n";
	$map .= "markerOptions = { icon:blueIcon };\n";
	$map .= "var point = new GLatLng(".$track->start_n.",".$track->start_e.")\n";
	$map .= "map.addOverlay(new GMarker(point, markerOptions));\n";

	return $map;
	}

	/**
	 *
	 * @param string $file
	 * @return array
	 */
	private function parseXMLlinesGoogle($file) {

$coords = $this->getCoords($file);

$string = "";
$string .= "var polyline = new GPolyline([\n";
foreach($coords as $key => $fetch) {
	$string .= "new GLatLng(".$coords[$key][1].",".$coords[$key][0]."),\n";
}	 
$string .= "], '#ff0000', 4);\n";
$string .= "map.addOverlay(polyline);\n";
foreach($coords as $key => $fetch) {
	$string .= "bounds.extend(new GLatLng(".$coords[$key][1].",".$coords[$key][0]."));";
}

return $string;
// print_r($coords);
	}

// Google END

}
Return current item: injooosm