var savedMarkers = [];
var savedPoints = [];
var savedHtml = [];
var savedImages = [];
var savedIcons = [];
var savedIconsWidth = [];
var savedIconsHeight = [];

var currentYoutube;
var currentPhoto=0;

var photos = [];


   function createMarker(point, html, image, iconImage, iconWidth, iconHeight, storeData, showThumb) {
       var marker=null;
       if (image && showThumb && iconImage==-1){
          var icon = new GIcon();
          icon.image = pathRoot+"tours/mapImage.php?image="+image;
          icon.iconSize = new GSize(40, 54);
          icon.iconAnchor = new GPoint(20, 54);
          icon.infoWindowAnchor = new GPoint(20, 52);
          marker=new GMarker(point,icon);
     } else {
          var icon = new GIcon();
          if (iconImage && iconImage!=-1){
             icon.image = pathRoot+"tours/image.php?type=icons&image="+iconImage;
             icon.iconSize = new GSize(iconWidth, iconHeight);
             icon.iconAnchor = new GPoint(iconWidth/2, 27);
             icon.infoWindowAnchor = new GPoint(iconWidth/2, 27);
          }else{
             icon.image = pathRoot+"templates/default/template/images/others/wp_standart_small.png";
             icon.shadow = pathRoot+"templates/default/template/images/others/wp_shadow_small.png";
             icon.shadowSize = new GSize(30, 20);
             icon.iconSize = new GSize(15, 27);
             icon.iconAnchor = new GPoint(8, 27);
             icon.infoWindowAnchor = new GPoint(8, 27);
          }   
          marker = new GMarker(point,icon);
     }
       GEvent.addListener(marker, "click", function() {
         marker.openInfoWindowHtml(html);
       });
       savedMarkers.push(marker);
       if (storeData==true){
           savedPoints.push(point);
           savedHtml.push(html);
           savedImages.push(image);
           savedIcons.push(iconImage);
           savedIconsWidth.push(iconWidth);
           savedIconsHeight.push(iconHeight);
       }
       return marker;
     }

	function addWaypoints(wp)
	{
        window.overlaysWP = [];
		for (var i=0; i<wp.length; i++) {
			var html = '<div style="width: 195px; text-align: left; font-size: 8pt;">';
			if (wp[i].Image)
				html += '<a href="#" onclick="javascript:openGallery('+wp[i].Image+');return false;">' +
						'<img align="right" width="60" height="60" src="'+pathRoot+'tours/image.php?type=thumbs&amp;image='+wp[i].Image+'" style="border: 1px solid #CE191C; margin:5px;" alt="" /></a>';
			html += '<span style="color:#B40E44"><b>'+wp[i].Name+'</b></span><br /><b>'+wp[i].Comment+'</b>';
			if (wp[i].Url)
				html += '<br /><a href="'+wp[i].Url+'">'+wp[i].Url+'</a>';
			html += '<br/>'+wp[i].Description;

			html += '<br/><br/><span style="color:#B40E44;">m '+wp[i].Elevation;
			html += '<br/>'+wp[i].LatitudeT+' &nbsp; '+wp[i].LongitudeT;
			html += '</span></div>';

  			var point = new GLatLng(wp[i].Latitude * 1, wp[i].Longitude * 1);
  			window.overlaysWP[i] = [true,createMarker(point,html,wp[i].Image,wp[i].Icon, wp[i].Width,wp[i].Height,true,true)];
      		map.addOverlay(window.overlaysWP[i][1]);
		}

		if (!window.tourWaypoints)
			window.tourWaypoints = wp;
	}

	function addTracks(tracks,data)
	{
		var colors = ['#FEA90A','#FF0000','#AE0000','#FF00CC','#00FF00','#00FFFF','#0099FF','#E67300','#FFFF00','#FFFFFF'];
		var j = 0;
		window.overlaysTrack = [];
		for (trackId in tracks) {
			addTrack(trackId,tracks[trackId],colors[j%10],data[trackId]);
            j++;
		}

		if (!window.tourTracks)
			window.tourTracks = tracks;

		var elem = document.getElementById('alltracks');
		if (elem) {
			elem.style.fontWeight = "bold";
			elem.style.color = "#000000";
		}
	}

	function addThumbs(thumbs)
	{
		for (var i=0;i<thumbs.length; i++) {
	 		photos.push(thumbs[i]);
		}
	}
	
	function showPhoto( id, alternatePath ) {
		try {
			var str = currentPhoto?currentPhoto:photos[0].id;
			var im = document.getElementById('photo' + str);
			//alert(im);
			if( im ) {
				im.style['border'] = "1px solid #FFFFFF";
			}
			
	
			im = document.getElementById('photo' + id);
			if( im ) {
				im.style['border'] = "1px solid #CE191C";
				currentPhoto=id;
			}
	
			im = document.getElementById('photo0');
			if( im ) {
				im.style.display = 'none';
				//im.src = alternatePath?(pathRoot+'tours/resize.php?MAX_WIDTH=570&path='+alternatePath):(pathRoot+'tours/resize.php?id='+id+'&MAX_WIDTH=570');
				im.src = alternatePath?(alternatePath):(pathRoot+'tours/resize.php?id='+id+'&MAX_WIDTH=370');
				im.style.display = 'block';
				im.photo = id;
				//alert(alternatePath);
			}

		} catch (e) {
			
		}
	}

	function showThumbs(offset){
		var galleryLimit=20;
		var gallerySize=photos.length;
		var galleryStart=offset;
		var galleryEnd=((offset+galleryLimit)<gallerySize?galleryLimit:gallerySize-offset)+offset;
	
		var photothumbs = document.getElementById('photothumbs');
		
		if (photothumbs){
			
			photothumbs.innerHTML='';
			//var thumb = ;
			for (var i=offset;i<galleryEnd; i++) {
				/*var newAttr = document.createAttribute("class");
				newAttr.nodeValue = "photoitem";
				var thumb = top.document.createElement('div');
				thumb.setAttributeNode(newAttr); 
				thumb.style.float = "left";
				thumb.style.position = "relative";
				thumb.style.margin = "3px";
				thumb.innerHTML = "<a href='#' onclick="+'"'+"showPhoto('"+photos[i].id+"','"+photos[i].normal+"')"+'"'+"><img id='photo"+photos[i].id+"' width='75' height='75' src='"+photos[i].thumb+"' style='border: 1px solid "+(i == 0?"#CE191C;":"#FFFFFF;")+"' alt=''/></a>";
				//alert(photos[i].thumb);
	            //photothumbs.innerHTML = "<a href='#' onclick="+'"'+"showPhoto('"+photos[i].id+"','"+photos[i].normal+"')"+'"'+"><img id='photo"+photos[i].id+"' width='75' height='75' src='"+photos[i].thumb+"' style='border: 1px solid "+(i == 0?"#CE191C;":"#FFFFFF;")+"' alt=''/></a>"; 
				photothumbs.appendChild(thumb);*/

				photothumbs.innerHTML+='<div style="float:left;position:relative;margin:3px;">';
				photothumbs.innerHTML += "<a href='#' onclick="+'"'+"showPhoto('"+photos[i].id+"','"+photos[i].normal+"')"+'"'+"><img id='photo"+photos[i].id+"' width='75' height='75' src='"+photos[i].thumb+"' style='border: 1px solid "+(i == 0?"#CE191C;":"#FFFFFF;")+"' alt=''/></a>";
				photothumbs.innerHTML+='</div>';
			}
			/*
			var br = document.createElement('br');
			photothumbs.appendChild(br);
			
			var newAttr = document.createAttribute("class");
			newAttr.nodeValue = "photoitem";
			
			var navig = document.createElement('div');
			navig.setAttributeNode(newAttr); 
			navig.style.float = "left";
			navig.style.position = "relative";
			navig.style.margin = "3px";
			*/
			if (offset>0){
				var valueOffset=(offset>offset-galleryLimit?(offset-galleryLimit):offset);
				var prevOffset=((offset-galleryLimit<0)?0:offset-galleryLimit)+"-"+offset;
				var navPrevValue="<a href='#' onclick='showThumbs("+valueOffset+")'>"+prevOffset+"</a>";
			}
			
			if (gallerySize>offset+galleryLimit){
				var valueOffset=offset+galleryLimit;
				var nextOffset=offset+galleryLimit+"-"+((offset+galleryLimit*2<gallerySize)?offset+galleryLimit*2:gallerySize);
				var navNextValue="<a href='#' onclick='showThumbs("+valueOffset+")'>"+nextOffset+"</a>";
			}
			
			//navig.innerHTML='<table width="140"><tr><td width="50%" align="center">'+(navPrevValue?navPrevValue:'&nbsp;')+'</td><td width="50%" align="center">'+(navNextValue?navNextValue:'&nbsp;')+'</td></tr></table>';
			//photothumbs.appendChild(navig);
			photothumbs.innerHTML+='<div>';
			photothumbs.innerHTML+=' <table width="140"><tr><td width="50%" align="center">'+(navPrevValue?navPrevValue:'&nbsp;')+'</td><td width="50%" align="center">'+(navNextValue?navNextValue:'&nbsp;')+'</td></tr></table>';
			photothumbs.innerHTML+='</div>';
		}
	}
	

	function addTrack(trackId,track,color,data)
	{
        var points = [];
		var gmarkers = []
		for (var i=0;i<track.length; i++) {
		    if (i==0){
                var icon = new GIcon();
                icon.image = pathRoot+"templates/default/template/images/others/track_start.png";
                icon.iconSize = new GSize(15, 15);
                icon.iconAnchor = new GPoint(8, 8);
                icon.infoWindowAnchor = new GPoint(8, 15);
                gmarkers[0]=new GMarker(new GLatLng(track[i][0], track[i][1]),icon);
			}
			if (i==track.length-1){
                var icon = new GIcon();
                icon.image = pathRoot+"templates/default/template/images/others/track_stop.png";
                icon.iconSize = new GSize(15, 15);
                icon.iconAnchor = new GPoint(8, 8);
                icon.infoWindowAnchor = new GPoint(8, 15);
                gmarkers[1]=new GMarker(new GLatLng(track[i][0], track[i][1]),icon);
			}
			points.push(new GLatLng(track[i][0], track[i][1]));
		}
		window.overlaysTrack[trackId] = [true,new GPolyline(points,color,2,1)];
		map.addOverlay(window.overlaysTrack[trackId][1]);
		if (gmarkers[0] && gmarkers[1]){
            var html = '<div style="width: 195px; text-align: left; font-size: 8pt;">';
			html += '<b>Start</b><br><span style="color:#B40E44">Track: <b>'+data[0][0]+'</b></span><br /><b>'+data[0][1]+'</b>';
			html += '<br/><br/><span style="color:#B40E44;">Distance: '+data[0][2]/1000+' km';
			html += '<br/> Ascent: '+data[0][3]+' m &nbsp; Descent: '+data[0][4]+' m</span>';
			html += '</div>';

            GEvent.addListener(gmarkers[0], "click", function() {
               gmarkers[0].openInfoWindowHtml(html);
            });
            var html2 = '<div style="width: 195px; text-align: left; font-size: 8pt;">';
			html2 += '<b>End</b><br><span style="color:#B40E44">Track: <b>'+data[0][0]+'</b></span><br /><b>'+data[0][1]+'</b>';
			html2 += '<br/><br/><span style="color:#B40E44;">Distance: '+data[0][2]/1000+' km';
			html2 += '<br/> Ascent: '+data[0][3]+' m &nbsp; Descent: '+data[0][4]+' m</span>';
			html2 += '</div>';
            GEvent.addListener(gmarkers[1], "click", function() {
               gmarkers[1].openInfoWindowHtml(html2);
            });
			map.addOverlay(gmarkers[0]);
			map.addOverlay(gmarkers[1]);
		}
	}



	function showYoutube( id, firstId ) {
		try {
			var str = currentYoutube?currentYoutube:firstId			
			var im = document.getElementById('youtube' + str);
			if( im ) {
				im.style['border'] = "1px solid #FFFFFF";
				currentYoutube=id;
			}

			im = document.getElementById('youtube' + id);
			if( im ) {
				im.style['border'] = "1px solid #CE191C";
			}
	
			im = document.getElementById('youtubemovie');
			if( im ) {
				//im.value = "http://www.youtube.com/v/"+id;
				im.innerHTML="<object width='365' height='300' classid='clsid:D27CDB6E-AE6D-11cf-96B8-444553540000' codebase='http://active.macromedia.com/flash2/cabs/swflash.cab#version=4,0,0,0'>"+
							"<param name='movie' value='http://www.youtube.com/v/"+id+"'></param>"+
							"<param name='wmode' value='transparent'></param>"+
 				            "<embed src='http://www.youtube.com/v/"+id+"'"+
							" type='application/x-shockwave-flash'"+ 
							" wmode='transparent' width='365' height='300'></embed></object>";
			}

		} catch (e) {
//		alert('error');
		}
	}


	function openGallery(photo)
	{
		var idx = 0;
		if( photo )
			idx = photo;
		else
		{
			var im = document.getElementById('photo');
			idx = im.photo;
		}

		var i = 0;
		if( idx )
		for(i = 0; i < photos.length; i++ ) {
			if( photos[i].id == idx )
				break;
		}
        var url = pathRoot+'tours/gallery.php?id='+tour+'&type=photos&pageID='+(i+1);
		window.open(url, "", "toolbar=0,status=1,resizable=0,scrollbars=1,titlebar=0,width=850,height=750");
	}

	function showAllTracks() {
		try {

		if (!window.tourTracks) { return; }
		for (trackId in window.tourTracks) {
			/*
			var s = document.getElementById('track' + trackId);
			if (s) {
				//s.class = "active";
			}
			*/
			var elem = document.getElementById('track' + trackId);
			if (elem) {
				elem.style.fontWeight = "";
				elem.style.color = "#888888";
			}
			var elem = document.getElementById('alltracks');
			if (elem) {
				elem.style.fontWeight = "bold";
				elem.style.color = "#000000";
			}

			if (!window.tourTracks[trackId][0]) {
				map.addOverlay(window.overlaysTrack[trackId][1]);
				window.tourTracks[trackId][0] = true;
			}
		}

		centerMap();

		} catch (e) {
			//alert(e.message);
		}
	}

	function showOneTrack(id) {
		try {

		if (!window.tourTracks) { return; }
		for (trackId in window.tourTracks) {

			/*
			var s = document.getElementById('track' + trackId);
			if (s) {
				s.['class'] = 'active';
			}
			*/
			var elem = document.getElementById('track' + trackId);
			if (elem) {
				elem.style.fontWeight = (trackId == id?"bold":"");
				elem.style.color = (trackId == id?"#000000":"#888888");
			}
			elem = document.getElementById('alltracks');
			if (elem) {
				elem.style.fontWeight = "";
				elem.style.color = "#888888";
			}


			if (id == trackId) {
				if (!window.tourTracks[trackId][0]) {
					map.addOverlay(window.overlaysTrack[trackId][1]);
					window.tourTracks[trackId][0] = true;
				}

				var sw = new GLatLng(trackStats[id].MinLat, trackStats[id].MinLon);
				var ne = new GLatLng(trackStats[id].MaxLat, trackStats[id].MaxLon);
				var bounds = new GLatLngBounds(sw,ne);

				var zoom = map.getBoundsZoomLevel(bounds);

				map.setCenter(new GLatLng(trackStats[id].CenLat,trackStats[id].CenLon),zoom);
			}
			else {
				if (window.tourTracks[trackId][0]) {
					map.removeOverlay(window.overlaysTrack[trackId][1]);
					window.tourTracks[trackId][0] = false;
				}
			}
		}

		} catch (e) {
			//alert(e.message);
		}
	}

	function changethumb(object){
		  var show=(object.checked?true:false);
          var marker=null;
          for (var i=0;i<savedMarkers.length;i++){
              marker=savedMarkers[i];
              map.removeOverlay(marker);
          }
          savedMarkers = new Array();
          for (var j=0;j<savedPoints.length;j++){
      		map.addOverlay(createMarker(savedPoints[j],savedHtml[j],savedImages[j],savedIcons[j],savedIconsWidth[j],savedIconsHeight[j],false,show));
          }

	}

