/* GOOGLE MAP functionalities 
   Author: joban john <j06anj0hn@gmail.com> 
   Generates a map of tours by geographical location using Google Maps 
*/
var side_bar_html = "";
var gmarkers = new Array();
var htmls = [];
var i = 0;
var map;
var selectedServices = new Array();
var tooltip = document.createElement("div");
var tryagain = true;
var tourId = 1;
var MarkerIDs;
var abcount=0;
var directionsPanel;
var directionsP;
var directionsN;
var directionsAll;
var directionsPreNext;
var geocoder;
var polyN;
var polyP;
var polyAll = new Array();
var xmlDoc = new Array();
var markers = new Array(); 
var markersLatLong =new Array();
var locFlagP = new Array();
var locFlagN = new Array();
var polylinesN = new Array();
var polylinesP = new Array();
var polylinesAll = new Array();
var polylinesPN = new Array();
gicons = new GIcon(G_DEFAULT_ICON, "/tourmap/icons/icon.png");
gicons.shadow = "/map/imagens/shadow-seta1.png";
gicons.iconSize = new GSize(32, 32);
gicons.shadowSize = new GSize(32, 34);
gicons.iconAnchor = new GPoint(20, 25);
gicons.infoWindowAnchor = new GPoint(9, 2);

function gera(tourId) 
{ 
	  loading();
      selectedServices = new Array();
      //yalert(tourId);
      document.getElementById("TourID").value = tourId;
      document.getElementById("IconID").value = tourId;
      var teste2;      
      teste2 = SGL_JS_WEBROOT+"/tourmap/" + tourId + ".xml"+RandomURLEnding();
      $.get(SGL_JS_WEBROOT + "/usermap/action/generateTours/tourId/"+tourId+"/"+RandomURLEnding(),function(str){
      	 $("#teste").html(str);
      	 startLocationDetails();      	 
 		 readMap();
	  });
}

function voted() {
    //alert("Already voted");
}
function thanks() {	
    //alert("Thanks for voting!");
    //markers[i].setAttribute("rating","5");
}


// A function to create the marker and set up the event window
function createMarker(point,name,html,lng,lat,i) 
{	
	if (!html) 
 	{
  	// Some markers have no data, so ignore them
  		return;
 	}
 	//alert(icontype);
 	var IconId = document.getElementById("IconID").value;
 	var cIcon = new GIcon(gicons); 	
    cIcon.image = SGL_JS_WEBROOT+"/tourmap/icons/icon" + IconId + ".png"; 
	markerOptions = { icon:cIcon,title:name };
	var marker = new GMarker(point, markerOptions);
	//alert(marker);
	gmarkers.push(marker); 
	
	GEvent.addListener(marker, "click", function() {
  		//marker.openInfoWindowHtml(html);
  		/*var sizee = new GSize(0,5000);*/
  		marker.openInfoWindowHtml('<div class="nome">'+html+'</div>', {maxWidth:300});
  		addNextPrevious(i);  		
  		infoBarShow(i);
  		//maplistHide();	
  		addLocationDetails(i);
  		var locationId = markers[i].getAttribute("locationId");
  		var tourIds="";
  		$("input[@name='ServiceFilters[]']").each(function() {		
	         if ($(this).attr('checked')) 
			 {
	            tourIds = tourIds+","+$(this).val();
	         }       
	    });
	    if(tourIds==""){
	    	tourIds = '"-"';
	    }
	    var clicks = false;
	    if(tourIds == '"-"'){ 
	    	clicks = false;
	    }else{
	    	clicks = true;
	    }
	    var rating =  SGL_JS_WEBROOT+'/usermap/action/rate/lId/'+locationId+'/tourId/'+tourIds+'/';	
	    var ratingVal = markers[i].getAttribute("rating");	  		
        $('#star'+i).starRating({
            clickable:clicks,
            rating:ratingVal,
            showNumber:true,
            sucess:thanks,
            showNumber:false, 
            failure:voted,
            ratingUrl : rating,
            basicImage   : SGL_JS_WEBROOT+'/js/star.gif',	
			ratedImage   : SGL_JS_WEBROOT+'/js/star_hover.gif',	
			hoverImage   : SGL_JS_WEBROOT+'/js/star_blue.gif'                       
    	});
	});
	
	GEvent.addListener(marker, "infowindowclose", function() { 
		//map.returnToSavedPosition();
		infoBarHide(); 
	}); 
	
	//  ======  The new marker "mouseover" and "mouseout" listeners  ======
	
	GEvent.addListener(marker,"mouseover", function() {
  	showTooltip(marker);
	});
	
	GEvent.addListener(marker,"mouseout", function() {
      tooltip.style.display="none"
	});
		
	htmls[i] = html;
	marker.tooltip = '<div class="tooltip">'+name+'</div>';
	return marker;
}

function mymouseout() 
{
     tooltip.style.visibility="hidden";
}
// ====== This function displays the tooltip ======
// it can be called from an icon mousover or a side_bar mouseover
function showTooltip(marker) 
{
	tooltip.innerHTML = marker.tooltip;
  	var point=map.getCurrentMapType().getProjection().fromLatLngToPixel(map.getBounds().getSouthWest(),map.getZoom());
  	var offset=map.getCurrentMapType().getProjection().fromLatLngToPixel(marker.getPoint(),map.getZoom());
  	var anchor=marker.getIcon().iconAnchor;
  	var width=marker.getIcon().iconSize.width;
  	var pos = new GControlPosition(G_ANCHOR_BOTTOM_LEFT, new GSize(offset.x - point.x - anchor.x + width,- offset.y + point.y +anchor.y));
  	//var pos = new GControlPosition(G_ANCHOR_BOTTOM_LEFT, new GSize(10,10));
	pos.apply(tooltip);
  	tooltip.style.visibility="visible"; 
}

// ===== This function is invoked when the mouse goes over an entry in the side_bar =====
// It launches the tooltip on the icon
function mymouseover(i) 
{
	showTooltip(gmarkers[i]);
}

function criaLocal() 
{
   var tourId = $('#TourID').val();
   $.get(SGL_JS_WEBROOT + "/usermap/action/getCenter/tourId/"+ tourId +"/"+RandomURLEnding(),function(str){
		if(str){
			var lonlat = str.split(',');
			map.setCenter(new GLatLng(lonlat[0],lonlat[1]), 14); 
		}else{
			map.setCenter(new GLatLng(44.237,-76.5), 14); // set experimentally for Kingston FH 080914	
		}
  }); 
  
  map.savePosition(); 
   
}

function setnewCenter(tourid){	
	var latLng = map.getCenter();
	var conf = confirm ("You are going to set this position as the default center position for this tour. Do you want to continue?");
	if(conf){ 
		$.get(SGL_JS_WEBROOT + "/usermap/action/setNewCenter/latLng/"+ latLng +"/tourId/"+ tourid +"/"+RandomURLEnding(),function(str){
			alert('The map centered into a new position');
		});
	}
}

function  openLocationWindow(point,src,overlay){ 
	$.get(SGL_JS_WEBROOT + "/usermap/action/checkUserPermission/"+RandomURLEnding(),function(str){ 		
		if(str==1){                                              
    		mypoint = map.fromContainerPixelToLatLng(point);//alert(mypoint);
   			geocoder.getLocations(mypoint,showinfoBox);
		}else{
			alert($('#map_noPermission').val());
		}
    });
}

function showinfoBox(response)
{
	if (!response || response.Status.code != 200) {
        alert("Status Code:" + response.Status.code);
    }else{	  		
		var place = response.Placemark[0];
		marker1 = new GMarker(mypoint);	    
	    if(place.address){
	    	var placeVal = place.address;	   
		    var placeValues = placeVal.split(",");		    
		    //if(placeVal.match('Kingston, ON, Canada')){		    	
			    if(placeValues.length==4){
			    	map.addOverlay(marker1);
			    	var confirmVal = confirm("Would you like to add " + placeValues[0] + " to your Tours");
			    	if(confirmVal){			    			    				
			    		window.location= SGL_JS_WEBROOT + "/usermap/action/addLocations/addr/"+ placeVal +"/";
			    	}else{
			    		map.removeOverlay(marker1);
			    	}
			    }
			    else{			    	
			    	alert($('#map_noLocationDefined').val());
			    }			    
		  /* }else{
		    	alert($('#map_theLocationNotInKingstonONCanada').val());
		    }*/
	    }
	    else{
	    	alert($('#map_noLocationDefined').val());
	    }
	}
}

/* Use this to append a random string to a URL so that it is never cached */
function RandomURLEnding() 
{
	return '?a=' + Math.random(); 
}


function stateChanged() 
{	
	if (request.readyState == 4)
	{
    	if(request.responseXML){
			
			xmlDoc = request.responseXML;	
			
	    	// obtain the array of markers and loop through it    	
	    	markers = xmlDoc.getElementsByTagName("marker");  		
			// hide the info window, otherwise it still stays open where the removed marker used to be
	    	map.getInfoWindow().hide();	
	    	gmarkers = [];		
	    	var bounds = map.getBounds();
	    	var southWest = bounds.getSouthWest();
	    	var northEast = bounds.getNorthEast();
	    	var lngSpan = northEast.lng() - southWest.lng();
	    	var latSpan = northEast.lat() - southWest.lat();
	    	map.clearOverlays();
	    	var markerCount = 0;
	    	var n = markers.length;	    	
	    	//alert(n);
			for (var i = 0; i < markers.length; i++) 
			{
				// obtain the attribues of each marker
	      		var lat = parseFloat(markers[i].getAttribute("lat"));
	      		var lng = parseFloat(markers[i].getAttribute("lng"));
				//alert(lat+"-"+lng);
	      		point = new GLatLng(lat,lng);   			
				//alert(point);
	          	var label = markers[i].getAttribute("city");
	          	var count = markers[i].getAttribute("count");
	          	var region = markers[i].getAttribute("region");
	          	var country = markers[i].getAttribute("country");
				if (count > 1) 
				{
	              	plural = 's';
	          	} 
				else 
				{
	              	plural = '';
	          	}
	          	var html = '<div style="max-width:400px; font-size:10px; font-family: Verdana; position:relative;">';
	         	var showMarker = true;
	          	/* Code for service provider information!!!! */	          	
	          	var heading       = str_replace('-and-','&',markers[i].getAttribute("heading"));         	
	          	var tours         = str_replace('-and-','&',markers[i].getAttribute("tours"));
	          	var location	  = str_replace('-and-','&',markers[i].getAttribute("location"));
	          	var image		  = markers[i].getAttribute("image");          	
	          	var orgimage	  = markers[i].getAttribute("orgimage");          	
	          	var description   = str_replace('-and-','&',markers[i].getAttribute("description"));
	          	var period        = markers[i].getAttribute("period");
	          	var video         = markers[i].getAttribute("video");
	          	var locationId    = markers[i].getAttribute("locationId");
	          	var address       = str_replace('-and-','&',markers[i].getAttribute("address"));				
	            if(tours != null && tours != "") 
				{
	            	var toursArray = tours.split('+');
	                info += '|' + tours;
	            }
	            var info ="";
	          	if(heading != null && heading != "") 
				{
	              	html +='';
	              	info += '|' + heading +'<br>'; 
	              	var orgArray = heading.split('|');
	              	if(description != null && description != "") 
					{
	                 	var descriptionArray = description.split('|');
	                 	info += '|' + description;  
	               	}
	
	               	if(location != null && location != "") 
					{
	                 	var locationArray = location.split('|');
	                 	info += '|' + location;  
	               	}
	               	
	               	if(image != null && image != "") 
					{
	                 	var imageArray = image.split('|');
	                 	info += '|' + image;  
	               	}
	               	if(orgimage != null && orgimage != "") 
					{
	                 	var orgimageArray = orgimage.split('|');
	                 	info += '|' + orgimage;  
	               	}
	               	if(period != null && period != "") 
					{
	                 	var periodArray = period.split('|');
	                 	info += '|' + period;  
	               	}
	               	if(video != null && video != "") 
					{
	                 	var videoArray = video.split('|');
	                 	info += '|' + video;  
	               	}
	               	if(locationId != null && locationId != "") 
					{
	                 	var locationIdArray = locationId.split('|');
	                 	info += '|' + locationId;  
	               	}
	               	if(address != null && address != "") 
					{
	                 	var addressArray = address.split('|');
	                 	info += '|' + address;  
	               	}               	
	               	               
	              	var separator = '';
	              	var videoFlag = "";
	              	for (org in orgArray) 
					{
	                  	if(orgArray[org] != "") 
						{
	                      	html += separator + '<b>' + orgArray[org]+'</b>';
	                      	separator = '<br>'; 
	                      	
	                      	if(location && locationArray[org] && locationArray[org] != "")
							{
	                       		html += separator + '<br><i>'+ $("#map_location").val() +':</i> ' + locationArray[org];
	                      	}
	                      	
	                      	if(description && descriptionArray[org] && descriptionArray[org] != "")
							{
	                       		html += separator + '<br><i>'+ $("#map_shortSummary").val() +':</i> ' + descriptionArray[org];
	                      	}
	                      	
	                      	if(period && periodArray[org] && periodArray[org] != "")
							{
	                       		html += separator + '<br><i>'+ $("#map_period").val() +':</i> ' + periodArray[org];
	                      	}
	                      	
	                      	if(video && videoArray[org] && videoArray[org] != "")
							{
								html += separator + '<br><object width="300" title="loading.." standby="loading.." height="250"><param name="movie" value="http://www.youtube.com/v/'+ videoArray[org] +'&rel=1"></param><param name="wmode" value="transparent"></param><embed wmode="transparent" src="http://www.youtube.com/v/'+ videoArray[org] +'&rel=1" type="application/x-shockwave-flash" width="300" height="250"></embed></object>';
	                      		
						   	   
						   	    //html += separator + getvideo(video);					
								//$("#vidrenderor").render(getvideo(video),'html');
								videoFlag = "set";
							}
	                      	
	                      	if(videoFlag !="set" &&   image && imageArray[org] && imageArray[org] != "")
							{
								html += separator + '<br><a target="_blank" href="'+ orgimageArray[org] +'"<img width="200" alt="loading.." height="200" title="mappic" src="' + imageArray[org] + '" width="200" heigh="200" border="0" /></a>';
	                      	} 
	                      	                     	
	                      	html += separator + '<i>'+ $("#map_tour").val() +':</i> ';
	                      	
	                      	var orgTours = tours.split('+');
	                     	var sComma = '';
							for (entry in orgTours) 
							{
	                      	  		//generateService(orgServices[entry]);
								  	html += sComma + orgTours[entry];
								  	sComma = ', ';                              
	                      	}
	                      	
							
							var pathLocations="";
							
							
							if(pathLocations!== ""){
								html += separator + '<span style="width:200px;">'+pathLocations+'</span>';
							}
							
							var links="";
	                      	//var val = parseInt(i+1);
							if(i !== 0){		
	                      		links += '<a href="javascript:myPrevClick(\''+ i +'\');">'+ $("#map_prev").val() +'</a>&nbsp;';
							}
							if(i!== (n-1)){		
	                      		links += '&nbsp;<a href="javascript:myNextClick(\''+ i +'\');">'+ $("#map_next").val() +'</a>';
							}
							if(links!== ""){
								html += separator + '<span style="width:200px;">'+links+'</span>';
							}											
	                      	var url = SGL_JS_WEBROOT + "/usermap/action/moreLocationInfo/lId/"+locationIdArray[org];
	                      	var addfavurl = SGL_JS_WEBROOT + "/usermap/action/addToFavorites/lId/"+locationIdArray[org];
	                      	html += '&nbsp;&nbsp;&nbsp;<span style="text-align:left;"><a target="_blank" href="'+addfavurl+'">'+ $("#map_addtoFavorites").val() +'</a></span>&nbsp;&nbsp;&nbsp;<span style="text-align:right;"><a target="_blank" href="'+url+'">'+ $("#map_moreinfo").val() +'</a></span>';
	                      	html +='<div id="star'+i+'" class="star"></div>';
	                      	html += '</div>';
	                   	}
	              	}
	          	}    	          
	            
	          	html += '</div>';          	
				if (showMarker) 
				{
					//markerCount = markerCount + parseInt(count);
					//alert("adderss1:"+address+"-Location-"+location);
	             	var marker = createMarker(point,heading,html,lng,lat,i);
					//alert('\npoint>'+point+"\n heading>"+heading+"\n html>"+html+"\n lng>"+lng+"\n lat>"+lat+"\n i>"+i);
	             	// create the marker
	             	map.addOverlay(marker);   
	          	}
	    	}
	    	if($('#checkAllRoutes').attr('checked')){
	    		getDirectionsAll();
	    	}
	    }
	}
    //criaLocal();
    //criaLocal();
}

function getDirections()
{
	var start;	       
    var end;    
	if (!markersLatLong.length) {
		return;
	}
	//alert(markersLatLong.length);
	var from = markersLatLong[0];
	var to = markersLatLong[1];	
	markersLatLong.shift();
	var loadStr = 'from: ' + from + ' to: ' + to;
	directionsAll.load(loadStr,{getPolyline:true,getSteps:true});
}

function onDirectionsLoad()
{
	/*var status = dirObj.getStatus();
	var bounds = dirObj.getBounds();
	var distance = parseInt(dirObj.getDistance().meters / 1609);
	var duration = parseFloat(dirObj.getDuration().seconds / 3600).toFixed(2);*/
	var polyline = directionsAll.getPolyline();
	polyline.color = "#ff0000"; 
	polyline.opacity = 1;
	polyline.weight = 2;
	polyAll.push(polyline);	
	map.addOverlay(polyline);
	getDirections();
}

function getDirectionsAll()
{ 
   //alert(polylinesP.length); 	
	
   if($('#checkAllRoutes').attr('checked')){
   	
   	    $('#prevOnMarker').attr('checked', false);
   	    $('#nextOnMarker').attr('checked', false); 
   	    
   	    if(polylinesP.length>0){	
	        for (var i = 0; i < polylinesP.length; i++){ 
				map.removeOverlay(polylinesP[i]);
			}	
	    }
	    if(polylinesN.length>0){	
	        for (var i = 0; i < polylinesN.length; i++){ 
				map.removeOverlay(polylinesN[i]);
			}	
	    }
   		if(markers.length>0)
		{					
	        for (var i = 0; i < markers.length; i++) 
			{
				// obtain the attribues of each marker
	      		var lat = parseFloat(markers[i].getAttribute("lat"));
	      		var lng = parseFloat(markers[i].getAttribute("lng"));
	      		markersLatLong[i] = lat+','+lng;
			}		
			getDirections();
		}else{		
			//alert('No data found');
		}
	}else
	{
		if (!polyAll.length) {
			return;
		}		
		for (var i = 0; i < polyAll.length; i++){ 
			map.removeOverlay(polyAll[i]);
		}
	}
}

function addNextPrevious(i){
	if(polylinesP.length>0){	
        for (var it = 0; it < polylinesP.length; it++){ 
			map.removeOverlay(polylinesP[it]);
		}	
    }
    if(polylinesN.length>0){	
        for (var it = 0; it < polylinesN.length; it++){ 
			map.removeOverlay(polylinesN[it]);
    	}	
	}	
	if(markers.length>0)
	{					
        // obtain the attribues of each marker
        if($('#prevOnMarker').attr('checked')){
	        var lessI = parseInt(i)-1;
	        if(lessI>=0){
		        var latL = parseFloat(markers[lessI].getAttribute("lat"));
	      		var lngL = parseFloat(markers[lessI].getAttribute("lng")); 
	      		var start = latL+','+lngL;	      		
	   			var latI = parseFloat(markers[i].getAttribute("lat"));
	      		var lngI = parseFloat(markers[i].getAttribute("lng"));      		
	   			var end = latI+','+lngI;   			
	   			GEvent.addListener(directionsP,"load",function(){	  	
			    polyP=directionsP.getPolyline(true);	   
			    polyP.color = "#ff0000"; 
			    polyP.opacity = 1;
			    polyP.weight = 2;	   
			    map.addOverlay(polyP);
			    polylinesP.push(polyP);
			 	}); 	
				GDirectionsOptions  = { 
					preserveViewport:true,
					locale:"en_CA",
					getPolyline:true
				};   			
	   			var loadStr = 'from: ' + start + ' to: ' + end;   			
	   			directionsP.load(loadStr,GDirectionsOptions);
	        }
        }
		if($('#nextOnMarker').attr('checked')){			
			var bigI = parseInt(i)+1;
			if(bigI <= markers.length-1){
	   			var latI = parseFloat(markers[i].getAttribute("lat"));
	      		var lngI = parseFloat(markers[i].getAttribute("lng"));      		
	   			var start = latI+','+lngI;
	   			var latG = parseFloat(markers[bigI].getAttribute("lat"));
	      		var lngG = parseFloat(markers[bigI].getAttribute("lng"));      		
	   			var end = latG+','+lngG;
	   			GEvent.addListener(directionsN,"load",function(){	  	
			    polyN=directionsN.getPolyline(true);	   
			    polyN.color = "#ff0000"; 
			    polyN.opacity = 1;
			    polyN.weight = 2;	   
			    map.addOverlay(polyN);
			    polylinesN.push(polyN);
			 	}); 	
				GDirectionsOptions  = { 
					preserveViewport:true,
					locale:"en_CA",
					getPolyline:true
				};   			
	   			var loadStr = 'from: ' + start + ' to: ' + end;
	   			directionsN.load(loadStr,GDirectionsOptions); 
			} 
		} 			
	}
}

function nextPrev(){
	var start;	       
    var end;    
	if (!markersLatLong.length) {
		return;
	}
	//alert(markersLatLong.length);
	var from = markersLatLong[0];
	var to = markersLatLong[1];	
	markersLatLong.shift();
	var loadStr = 'from: ' + from + ' to: ' + to;
	directionsPreNext.load(loadStr,{getPolyline:true,getSteps:true});
}

function loadPrevNext(){
	polyPN=directionsPreNext.getPolyline(true);	   
    polyPN.color = "#ff0000"; 
    polyPN.opacity = 1;
    polyPN.weight = 2;	   
    map.addOverlay(polyPN);
    polylinesPN.push(polyPN);
    nextPrev();
}

function clearRoutes(){
	$('#checkAllRoutes').attr('checked', false);
	if(!$('#prevOnMarker').attr('checked')){ 
		if(polylinesP.length>0){	
	       for (var i = 0; i < polylinesP.length; i++){ 
				map.removeOverlay(polylinesP[i]);
			}	
	    }
	}
	if(!$('#nextOnMarker').attr('checked')){ 
		if(polylinesN.length>0){	
	       for (var i = 0; i < polylinesN.length; i++){ 
				map.removeOverlay(polylinesN[i]);
			}	
	    }
	}
	if(polyAll.length>0){
		for (var it = 0; it < polyAll.length; it++){ 
			map.removeOverlay(polyAll[it]);
		}
	}
}

function addLocationDetails(i){	
	if(markers.length>0){
		var add = markers[i].getAttribute("address");
		var html ="";	
		html += '<span class="prev">';
		if(i == 0){		
			html += '<a href="javascript:void(0);" onclick="myStartClick(0)">'+ $("#map_start").val() +'</a>';
		}else{
			prevAdd = markers[i-1].getAttribute("address"); //added by Rasa
			html += 'Return to<a href="javascript:void(0);" onclick="myPrevClick('+ i +')">'+prevAdd+'</a>';
			//html += '<a href="javascript:void(0);" onclick="myPrevClick('+ i +')">'+ $("#map_prev").val() +'</a>'; //orignal line			
		}
		html += '</span>';
		html += '<span class="address">You are at <b>'+ add +'</b></span>';
		//html += '<span class="address"><a href="javascript:void(0);" onclick="myStartClick('+ i +');">'+ add +'</a></span>';
		html += '<span class="next">';
		if(i == markers.length-1){
			html += '<a href="javascript:void(0);" onclick="myStartClick(0)">'+ $("#map_start").val() +'</a>';
		}else{
			nextAdd = markers[i+1].getAttribute("address"); //added by Rasa
			html += 'Go to<a href="javascript:void(0);" onclick="myNextClick('+i+')">'+nextAdd+'</a>'; //edited by rasa		
			//html += '<a href="javascript:void(0);" onclick="myNextClick('+i+')">'+ $("#map_next").val() +'</a>';//orignal line		
		}
		html += '</span>';
		$('#locationdetails').html(html);
	}	
}


function startLocationDetails(){
	var html = '<span class="prev"><a onclick="myStartClick(0)" href="javascript:void(0);">'+ $("#map_start").val() +'</a></span>';
	html += '<span class="address">&nbsp;</span>';
	html += '<span class="next"><a onclick="myStartClick(0)" href="javascript:void(0);">'+ $("#map_start").val() +'</a></span>';
	$('#locationdetails').html(html);
}

// This function picks up the click and opens the corresponding info window

function myStartClick(i)
{
	if(gmarkers.length>0){
		GEvent.trigger(gmarkers[i], "click");
	}	
}

function myNextClick(i) 
{	
	i++;
	GEvent.trigger(gmarkers[i], "click");	
}

function myPrevClick(i) 
{	
	i--;
	GEvent.trigger(gmarkers[i], "click");	
}

function createRequestObject() 
{
    var ro;
    var browser = navigator.appName;
    if(browser == "Microsoft Internet Explorer")
	{
		try 
		{
			ro = new ActiveXObject("MSXML2.XMLHTTP.3.0");
			//ro = null; // to free up memory
		} 
		catch(e) 
		{
			window.location='error.php';
		}
	}
	else
	{
        ro = new XMLHttpRequest();	
    }
    return ro;
}


var request = createRequestObject();

function readMap() 
{
	tourId = document.getElementById("TourID").value;
	//alert(tourId);
	var url=SGL_JS_WEBROOT+"/tourmap/" + tourId + ".xml"+RandomURLEnding();
	//$("#markerinfo").load("/tourmap/" + catid + ".html", "", HandleLoadedMarkers);
	//alert(url);
	request.open('GET', url);
    request.onreadystatechange = stateChanged;
    request.send(null);	
}

function loadmap() 
{
 window.onunload = GUnload;
 loading(); 
 if (GBrowserIsCompatible()) 
 {
    map = new GMap2(document.getElementById("map"));
    
    G_NORMAL_MAP.getMaximumResolution = function () { return 20 };
    G_NORMAL_MAP.getMinimumResolution = function () { return 10 };
    map.addControl(new GSmallMapControl());
    /*map.addControl(new GMapTypeControl());*/
    directionsN       = new GDirections();
    directionsP       = new GDirections(); 
    directionsAll     = new GDirections();
    directionsPreNext = new GDirections();
    criaLocal();
    
    GEvent.addListener(map,"singlerightclick",openLocationWindow);
    GEvent.addListener(directionsAll, "load", onDirectionsLoad);
    GEvent.addListener(directionsPreNext, "load", loadPrevNext);
    GEvent.addListener(map, "move", checkBounds);
      
    geocoder = new GClientGeocoder();
    
    // ====== set up marker mouseover tooltip div ======
    document.getElementById("map").appendChild(tooltip);
    tooltip.style.visibility="hidden";
 }
 else 
 {
  alert($('#map_sorryTheGoogle').val());
 }
}

// The allowed region which the whole map must be within
var allowedBounds = new GLatLngBounds(new GLatLng(43.984910, -77.030640), new GLatLng(44.476911, -75.932007));

// If the map position is out of range, move it back
function checkBounds() {
	// Perform the check and return if OK
	if (allowedBounds.contains(map.getCenter())) {
	  return;
	}
	// It`s not OK, so find the nearest allowed point and move there
	var C = map.getCenter();
	var X = C.lng();
	var Y = C.lat();
	
	var AmaxX = allowedBounds.getNorthEast().lng();
	var AmaxY = allowedBounds.getNorthEast().lat();
	var AminX = allowedBounds.getSouthWest().lng();
	var AminY = allowedBounds.getSouthWest().lat();
	
	if (X < AminX) {X = AminX;}
	if (X > AmaxX) {X = AmaxX;}
	if (Y < AminY) {Y = AminY;}
	if (Y > AmaxY) {Y = AmaxY;}
	//alert ("Restricting "+Y+" "+X);
	//map.setCenter(new GLatLng(Y,X));
	criaLocal();
}





function trimSpaces(sString) 
{
 while (sString.substring(0,1) == ' ') 
 {
     sString = sString.substring(1, sString.length);
 } 
 while (sString.substring(sString.length-1, sString.length) == ' ') 
 {
     sString = sString.substring(0,sString.length-1);
 }
 return sString;
}



function drowlines()
{  
	// ========= Now process the polylines ===========	

	//var lines = xmlDoc.documentElement.getElementsByTagName("line");
	// read each line
	//for (var a = 0; a < lines.length; a++) {
	// get any line attributes
	/*var colour = lines[a].getAttribute("colour");
	var width  = parseFloat(lines[a].getAttribute("width"));
	// read each point on that line
	var points = lines[a].getElementsByTagName("point");
	var pts = [];
	for (var i = 0; i < points.length; i++) {
	   pts[i] = new GLatLng(parseFloat(points[i].getAttribute("lat")),
	   parseFloat(points[i].getAttribute("lng")));
	}
	map.addOverlay(new GPolyline(pts,colour,width));
	}*/
}   

function searchTours()
{
	var search = $("#txtSearch").val();
	if(search!=""){
		searchgera(search);
	}	
}

function searchgera(search) 
	{ 
	loading();      
	document.getElementById("IconID").value = '0';
	var teste2;      
	var filename = Math.ceil(Math.random(10000)*15000);
	document.getElementById("TourID").value = filename;
	$.get(SGL_JS_WEBROOT + "/usermap/action/searchTours/search/"+search+"/filename/"+filename+"/"+RandomURLEnding(),function(str){
		 $("#teste").html(str);
		 if(str == "There is no tour location to display"){
		 	$('#locationdetails').html('');
		 }else{
		 	startLocationDetails();
		 }
		 readMap();
	});	  
}

function filterTours()
{
	var tourIds = "";
	var tourtypes = "";
	var driving ="";
	var walking = "";
	var highlights = "";
	var periods = "";
	var fullTours  = "";
	var cycling  = "";
	loading(); 
	// filters based on tours
	$("input[@name='ServiceFilters[]']").each(function() {		
         if ($(this).attr('checked')) 
		 {
            tourIds = tourIds+","+$(this).val();
         }       
    });
    if(tourIds==""){
    	tourIds = '"-"';
    }
	
    // based on tour types
    if($("input[@name='tourTypeDriving']").attr('checked')){
		driving = 1;
	}
	if($("input[@name='tourTypeWalking']").attr('checked')){
		walking = 1;
	}
	if($("input[@name='tourTypeHighlights']").attr('checked')){
		highlights = 1;
	}
	if($("input[@name='tourTypeCycling']").attr('checked')){
		cycling = 1;
	}
	if($("input[@name='tourTypeFullTour']").attr('checked')){
		fullTours = 1;
	}
    if(driving==1){
    	tourtypes = '"Driving","Walking","Highlights"'
    }
    else if(highlights==1){
    	tourtypes = '"Highlights"';
    }
    else if(walking==1 && driving!=1){
    	tourtypes = '"Highlights","Walking"';
    }
    else if(cycling==1){
    	tourtypes = '"cycling"';
    }
    else if(fullTours==1){
    	tourtypes = '"Full Tour"';
    }
    
    
    if(tourtypes==""){
    	tourtypes = '"-"'
    }
    
    //period filters
    
    $("input[@name='periodFil[]']").each(function() {		
         if ($(this).attr('checked')) 
		 {
            periods = periods+',"'+$(this).val()+'"';
         }       
    });
    
    if(periods==""){
    	periods = '"-"'
    }
    
    var filename = Math.ceil(Math.random(10000)*15000);
    document.getElementById("TourID").value = filename;
    document.getElementById("IconID").value = '0';    
    $.get(SGL_JS_WEBROOT + "/usermap/action/filterTours/filterVals/"+tourIds+"/tourtypes/"+tourtypes+"/periods/"+periods+"/filename/"+filename+"/"+RandomURLEnding(),function(str){
    	$("#teste").html(str);
      	if(str == "There is no tour location to display"){  
      		 $('#locationdetails').html('');   	 	
      	}else{
      		startLocationDetails();
      	}
 		readMap(); 		
	});
}

function loading()
{
	$("#teste").html($('#map_checking').val()+ "...");
	$('#locationdetails').html($('#map_refreshing').val()+ "...");		
}
function ShowAllTours()
{
	var tourIds = "";
	loading();
    $("input[@name='ServiceFilters[]']").each(function() {
      this.checked = true;
    });
    filterTours();    
}

function tourLocationList(){
	var tourIds = "";
	var tourtypes = "";
	var driving ="";
	var walking = "";
	var highlights = "";
	var fullTours  = "";
	var cycling  = "";
	var periods = "";
	// filters based on tours
	$("input[@name='ServiceFilters[]']").each(function() {		
         if ($(this).attr('checked')) 
		 {
            tourIds = tourIds+","+$(this).val();
         }       
    });
    if(tourIds==""){
    	tourIds = '"-"';
    }
	
    // based on tour types
    if($("input[@name='tourTypeDriving']").attr('checked')){
		driving = 1;
	}
	if($("input[@name='tourTypeWalking']").attr('checked')){
		walking = 1;
	}
	if($("input[@name='tourTypeHighlights']").attr('checked')){
		highlights = 1;
	}
	if($("input[@name='tourTypeCycling']").attr('checked')){
		cycling = 1;
	}
	if($("input[@name='tourTypeFullTour']").attr('checked')){
		fullTours = 1;
	}


	
    if(driving==1){
    	tourtypes = '"Driving","Walking","Highlights"'
    }
    else if(highlights==1){
    	tourtypes = '"Highlights"';
    }
    else if(walking==1 && driving!=1){
    	tourtypes = '"Highlights","Walking"';
    }
    else if(cycling==1){
    	tourtypes = '"Cycling"';
    }
    else if(fullTours==1){
    	tourtypes = '"Full Tour"';
    }
    
    if(tourtypes==""){
    	tourtypes = '"-"'
    }
    
    //period filters
    
    $("input[@name='periodFil[]']").each(function() {		
         if ($(this).attr('checked')) 
		 {
            periods = periods+',"'+$(this).val()+'"';
         }       
    });
    
    if(periods==""){
    	periods = '"-"'
    }        
    window.open(SGL_JS_WEBROOT + "/usermap/action/tourLocationList/filterVals/"+tourIds+"/tourtypes/"+tourtypes+"/periods/"+periods+"/","StonesKingston");
}

function userFavorites(){
	var tourIds = "";
	var userTours ="";
	$("input[@name='ServiceFilters[]']").each(function() {		
         if ($(this).attr('checked')) 
		 {
            tourIds = tourIds+","+$(this).val();
         }       
    });
    if(tourIds==""){
    	tourIds = '"-"';
    }    
    
    userTours = $("#userTours").val();
    if(userTours!="" && tourIds!='"-"'){    
	    var filename = Math.ceil(Math.random(10000)*15000);
	    document.getElementById("TourID").value = filename;
	    document.getElementById("IconID").value = '0';
	    $.get(SGL_JS_WEBROOT + "/usermap/action/filterUserTours/filterVals/"+tourIds+"/userTourId/"+userTours+"/filename/"+filename+"/"+RandomURLEnding(),function(str){
	    	$("#teste").html(str);
	      	if(str == "There is no tour location to display"){  
	      		 $('#locationdetails').html('');   	 	
	      	}else{
	      		startLocationDetails();
	      	}
	 		readMap(); 		
		});
    }  
}

function maplistShow(){
	$('#mapList').show("slow");
	if($("#infoListVal").val()=="yes"){
		$("#map").css("width","470px");	
		$("#map").css("left","180px");
		$("#map").css("float","left");		
	}
	else
	{		
		$("#map").css("width","650px");	
		$("#map").css("float","left");
	}
}

function maplistHide(){
	$('#mapList').hide("slow");
	if($("#infoListVal").val()=="yes"){
		$("#map").css("width","620px");		
		$("#map").css("float","left");
	}
	else{	
		$("#map").css("width","800px");
		$("#map").css("left","0px");
	}
	map.checkResize();
}

function toggleSideBar(){
	if($('#chkToggle').attr('checked')){
		maplistShow();
		map.checkResize();		 
	}
	else{
		maplistHide();
		map.checkResize();
	}
	
}

function infoBarShow(i){
	if($('#chkToggle').attr('checked')){
		$("#map").css("width","470px");
		$("#map").css("left","180px");
		$("#map").css("float","left");
		$("#infoListVal").val("yes");
	}	
	else{
		$("#map").css("width","620px");
		$("#map").css("float","right");
		$("#infoListVal").val("yes");		
	}
	if(markers.length>0){		
		var heading       = str_replace('-and-','&',markers[i].getAttribute("heading"));         	
      	var location	  = str_replace('-and-','&',markers[i].getAttribute("location"));          	
      	var image		  = markers[i].getAttribute("image");          	
      	var description   = str_replace('-and-','&',markers[i].getAttribute("description"));
      	var video         = markers[i].getAttribute("video");
      	var image         = markers[i].getAttribute("image");
      	var orgimage      = markers[i].getAttribute("orgimage");
      	var allImage      = markers[i].getAttribute("allimage");  
      	var address       = str_replace('-and-','&',markers[i].getAttribute("address"));	
      	var locationId    = markers[i].getAttribute("locationId");
      	      	
      	var html= "";
      	
      	html += '<div id="infoListContent">';
      	if(heading && heading!=""){	
      		html += '<br><b>'+ heading +'</b></br>';
      	}
      	if(location && location!=""){	
      		html += '<br><b> '+ $("#map_location").val() +' </b>: '+ location +'</br>';
      	}
      	
      	if(description && description!=""){	
      		html += '<br><p style="">';
      		/*if(image && image!=""){
      			html +='<a href="'+ orgimage +'" target="_blank"><img  style="padding-right:3px;padding-bottom:3px;" align="left" width="75" alt="loading.." border="0" height="75" title="mappic" src="' + image + '" width="75" height="75"/></a>';
      		}*/
      		html +=''+ description +'</p></br>';
      	}
      	if(allImage && allImage!=""){
	      	var imageVal      = allImage.split('~|~');     	
			for (entry in imageVal) 
			{      	  		
			  	if(imageVal[entry] && imageVal[entry]!=""){
					var imageSplit = imageVal[entry].split('|~|');
					if(imageSplit[0] && imageSplit[1]){
						html +='<a href="'+ imageSplit[1] +'" target="_blank"><img  style="" align="left" width="75" alt="loading.." border="0" height="75" title="mappic" src="' + imageSplit[0] + '" width="75" height="75"/></a>';
					}
			  	}			  	                            
	      	}
      	}
      	
      	var url = SGL_JS_WEBROOT + "/usermap/action/moreLocationInfo/lId/"+locationId;
      	html += '<br><p class="clear"><a target="_blank" href="'+url+'">'+ $("#map_moreinfo").val() +'</a></span></p>';
      	
      	
      	/*if(image && image!=""){	
      		html += '<br></br>';
      	}*/      	
      	
      	/*if(period && period!=""){	
      		html += '<br><b> Period </b> : '+ period +'</br>';
      	}*/
      	
      	/*if(tours && tours!=""){	
      		var orgTours = tours.split('+');
         	var sComma = '';
         	var tourHtml ="";
			for (entry in orgTours) 
			{
          	  		//generateService(orgServices[entry]);
				  	tourHtml += sComma + orgTours[entry];
				  	sComma = ', ';                              
          	}
      		
      		html += '<br><b> Tours : </b>'+ tourHtml +'</br>';
      	}*/
      	
      	html +='</div>';
		
	}else{		
		html = '';
	}
	$('#infoList').show("slow");
	$('#infoList').html(html);	
	map.checkResize();		
}

function infoBarHide(){
	if($('#chkToggle').attr('checked')){
		$("#map").css("width","650px");
		$("#map").css("left","0px");
		$("#map").css("right","0px");
		$("#map").css("float","left");			
	}else{		
		$("#map").css("width","800px");
		$("#map").css("left","0px");
		$("#map").css("float","left");			
	}
	$("#infoListVal").val("no");		
	$('#infoList').hide("slow");		
	map.checkResize();
}

function str_replace(search, replace, subject, count) {
    // Replaces all occurrences of search in haystack with replace  
    // 
    // version: 905.3122
    // discuss at: http://phpjs.org/functions/str_replace
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Gabriel Paderni
    // +   improved by: Philip Peterson
    // +   improved by: Simon Willison (http://simonwillison.net)
    // +    revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +   bugfixed by: Anton Ongson
    // +      input by: Onno Marsman
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +    tweaked by: Onno Marsman
    // +      input by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   input by: Oleg Eremeev
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Oleg Eremeev
    // %          note 1: The count parameter must be passed as a string in order
    // %          note 1:  to find a global variable in which the result will be given
    // *     example 1: str_replace(' ', '.', 'Kevin van Zonneveld');
    // *     returns 1: 'Kevin.van.Zonneveld'
    // *     example 2: str_replace(['{name}', 'l'], ['hello', 'm'], '{name}, lars');
    // *     returns 2: 'hemmo, mars'
    
    var i = 0, j = 0, temp = '', repl = '', sl = 0, fl = 0,
            f = [].concat(search),
            r = [].concat(replace),
            s = subject,
            ra = r instanceof Array, sa = s instanceof Array;
    s = [].concat(s);
    if (count) {
        this.window[count] = 0;
    }

    for (i=0, sl=s.length; i < sl; i++) {
        if (s[i] === '') {
            continue;
        }
        for (j=0, fl=f.length; j < fl; j++) {
            temp = s[i]+'';
            repl = ra ? (r[j] !== undefined ? r[j] : '') : r[0];
            s[i] = (temp).split(f[j]).join(repl);
            if (count && s[i] !== temp) {
                this.window[count] += (temp.length-s[i].length)/f[j].length;}
        }
    }
    return sa ? s : s[0];
}


