﻿var messageAddressNotFound='';
var messageGenericError='';

var nPois=0;
var mapBounds=null;
var markers=[];
var mgr=null;
var markerClusterer=null;
var map=null;
var gdir=null;

var clusterZoomLevel = 11;
var clusterSize = 10;
var useCluster=true;        
var defIcon=null;
var defGIcon=null;

var mapBehaviour='user';
var adSenseId='';
var dirWidth=300;

var txtSearchId=null;
var txtDestinationId=null;
var currMarker=null;



function SetFieldFromAddress(theAddress,flLat,flLng,mapVisible) 
{
       var geocoder = new GClientGeocoder();
    geocoder.getLocations(theAddress, function(response){
      if (!response || response.Status.code != 200) {
        alert("Sorry, we were unable to geocode that address");
      } else {
        place = response.Placemark[0];
       document.getElementById(flLat).value=place.Point.coordinates[1];
       document.getElementById(flLng).value=place.Point.coordinates[0];
       if(mapVisible)
       {
       document.getElementById('map').style.display='block';
       CenterSmallMap('map',place.Point.coordinates[1],place.Point.coordinates[0],13,'');
       }
       else{
       document.getElementById('map').style.display='none';
       }
      }  
    });
}

function CenterSmallMap(mapId,x,y,zoomLevel,descr,bounds,EventBoundsChanged)
{
	  
	  var mapDiv=document.getElementById(mapId);
	  if(mapDiv==null)return;
	  var map = new GMap2(document.getElementById(mapId));
	  map.addControl(new GSmallMapControl());
      map.addControl(new GMapTypeControl());
      if(zoomLevel>0){
       map.setCenter(new GLatLng(x,y), zoomLevel);
       }
       else{
      map.setCenter(new GLatLng(x,y), map.getBoundsZoomLevel(bounds));}
      map.addOverlay(new GMarker(new GLatLng(x,y)));

}

function CenterMainMapByAddress(mapId,address,zoomLevel,descr,EventBoundsChanged,setmarker)
{   var theAddress=address;
    if(address==-1)
    {
        var addr=document.getElementById(address);
        theAddress=addr.value;
    }   
    if(address=='*')
    {
        CenterMainMap(mapId,0,0,1,descr,null,EventBoundsChanged);
        return;
    }
    var geocoder = new GClientGeocoder();
    geocoder.getLocations(theAddress, function(response){
    
    if (!response || response.Status.code != 200) {
        alert(messageAddressNotFound);
      } else {
        place = response.Placemark[0];
        point = new GLatLng(place.Point.coordinates[1],
                            place.Point.coordinates[0]);
        bounds=new GLatLngBounds(new GLatLng(place.ExtendedData.LatLonBox.south,place.ExtendedData.LatLonBox.west),new GLatLng(place.ExtendedData.LatLonBox.north,place.ExtendedData.LatLonBox.east));
        CenterMainMap(mapId,point.lat(),point.lng(),zoomLevel,descr,bounds,EventBoundsChanged);
        //alert(setmarker);
        if(setmarker==true){
        marker=new GMarker(point);
        map.addOverlay(marker);
        marker.openInfoWindow(descr);
        }
      }

    
    
    
    });
          
}

function CenterMainMap(mapId,x,y,zoomLevel,descr,bounds,EventBoundsChanged)
{
	  
	  mapDiv=document.getElementById(mapId);
	  if(mapDiv==null)return;
	  map = new GMap2(document.getElementById(mapId));
	  map.addControl(new GLargeMapControl());
      map.addControl(new GMapTypeControl());
      if(zoomLevel>0){
       map.setCenter(new GLatLng(x,y), zoomLevel);
       }
       else{
      map.setCenter(new GLatLng(x,y), map.getBoundsZoomLevel(bounds));}
       //mgr = new GMarkerManager(map);

	  //map.addOverlay(new GMarker(new GLatLng(x,y)));
     
     //GEvent.addListener(map, 'bounds_changed', function(){refreshMap()});
     //GEvent.addListener(map, 'zoom_changed', function(){refreshMap()});
       markers=[];
       markerClusterer=null;
       EventBoundsChanged();
        
        //;
        //alert(map.getZoom());
        //if(confirm('points:'+mgr.getMarkerCount(13))){
        //if(mgr.getMarkerCount(map.getZoom())>100)
        //{
        //alert('cluster');
       
        //} 
        //else
        //{
        //alert('no cluster');
        //
        //}
        //}
        //alert(markers);
        
        if(!useCluster){
        mgr = new GMarkerManager(map);
        mgr.addMarkers(markers,0)
        mgr.refresh();
        }
        //cluster
        //clusterZoomLevel=map.getZoom()-1;
        else{
        refreshMap();
        }
        //alert(mapBehaviour);
        if(mapBehaviour=='extend' && zoomLevel<=0)map.setCenter(new GLatLng(x,y), map.getBoundsZoomLevel(bounds));
        
        if(adSenseId!='')EnableAdSense();
        	
}


function setPoi(lat,lng,name,description,htmlAddress,textAddress,icon,width,height,infoWindowEvent)
  {
  nPois++;
  if(defIcon!=icon){
        defIcon=icon;
        //alert(width);
        defGIcon=new GIcon(G_DEFAULT_ICON,icon);
        defGIcon.shadow="";
        defGIcon.iconSize=new GSize(width,height);
        defGIcon.iconAnchor=new GPoint(width/2,height);
        defGIcon.infoWindowAnchor=new GPoint(width/2,height/2);
         
      
  }
  return pushPoint();
  
              function pushPoint()
              {
              
              var descr='<div class="mapTitle">'+name+'</div><br/>'+'<div class="mapDescription">'+description+'</div><br/>'+'<div class="mapAddress">'+htmlAddress+'</div><br/>';   
              
              mPoint=new GLatLng(lat,lng);
              if(mapBehaviour=='extend')bounds.extend(mPoint);
              var marker=new GMarker(mPoint,
                    {icon:defGIcon}
                    )
              if(infoWindowEvent!='never'){      
              GEvent.addListener(marker, infoWindowEvent, function() {
                        marker.openInfoWindowHtml(descr);
                      });
              GEvent.addListener(marker, 'click', function() {
                        if(document.getElementById(txtDestinationId)!=null){
                        //alert(textAddress!=null && textAddress!='');
                        document.getElementById(txtDestinationId).value=(textAddress!=null && textAddress!=''?textAddress:lat.toString()+','+lng.toString());
                        }
                      });
                      }
              // alert(mgr);
              //mgr.addMarker(marker,1);
              markers.push(marker);
             // if(nPois==2)alert(defGIcon);
             return marker;
             }
             
  }
  
  function refreshMap() {
        //alert(map);
        if (markerClusterer != null) {
          markerClusterer.clearMarkers();
          return;
        }
        //markerClusterer=null;
        //var clusterStyle = "";
        clusterZoomLevel = clusterZoomLevel == -1 ? null : clusterZoomLevel;
        clusterSize = clusterSize == -1 ? null : clusterSize;
        //style = style == "-1" ? null: parseInt(style, 10);
        markerClusterer = new MarkerClusterer(map, markers, {maxZoom: clusterZoomLevel, gridSize: clusterSize});
      }
  
  function setDir(toPoint,textAddress,showText,messageText)
  {
  
    var fromAddress=document.getElementById(txtSearchId).value;
    //alert(fromAddress+'   '+toPoint);
    if(fromAddress=='' || toPoint=='') {
        alert(messageText);
        return;
    }
    
    if(document.getElementById(txtDestinationId)!=null){
                        //alert(textAddress!=null && textAddress!='');
                        document.getElementById(txtDestinationId).value=(textAddress!=null && textAddress!=''?textAddress:toPoint);
                        }
    
    if(gdir!=null)gdir.clear();
    if(!showText)
    {
        gdir = new GDirections(map);
    }
    else
    {
     
     map.getContainer().style.width=(map.getSize().width-dirWidth)+'px';
     map.checkResize(); 
     var dirDiv = document.createElement('div');
     dirDiv.id='gmappoisdir';
     dirDiv.className="mapDirections";
     dirDiv.style.marginLeft=map.getSize().width+'px';
     dirDiv.style.width=dirWidth+'px';
     
     map.getContainer().appendChild(dirDiv); 
     
     gdir = new GDirections(map,dirDiv);
    }
    GEvent.addListener(gdir, "load", onGDirectionsLoad);
    GEvent.addListener(gdir, "error", handleErrors);

    gdir.load("from: " + fromAddress + " to: " + toPoint);
    

  }
  
  
  
  
  function handleErrors(){
	   if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
	    {alert(messageAddressNotFound);}
	   else alert(messageGenericError+'\ncode:'+gdir.getStatus().code);
	   
	}

	function onGDirectionsLoad(){ 
      // Use this function to access information about the latest load()
      // results.

      // e.g.
      // document.getElementById("getStatus").innerHTML = gdir.getStatus().code;
	  // and yada yada yada...
	}

function EnableAdSense(){
    var publisher_id = adSenseId;

    var adsManagerOptions = {
      maxAdsOnMap : 3,
      style: 'adunit',
      // The channel field is optional - replace this field with a channel number 
      // for Google AdSense tracking
      channel: '999'  
    };

    adsManager = new GAdsManager(map, publisher_id, adsManagerOptions);
    adsManager.enable();
}
