/**
 * Google Maps. Code copied from google.js and modified to fulfil geolocalizer needs
 *
 * @package    oferia
 * @subpackage google
 * @author     Bartosz "Inc!" Kielczewski
 * @modifiedby Paweł Leszczynski
 * @version    SVN: $Id: actions.class.php 9301 2008-05-27 01:08:46Z dwhittle $
 */

var Google =  
{
  instanceCount: 0,
  instance: [],

  map: function(elementId, starterLat, starterLng, markers, options) 
  {
    this.instance[this.instanceCount++] = new GoogleMap(elementId, starterLat, starterLng, markers, options); 
  }
}

function GoogleMap(elementId, starterLat, starterLng, markers ,options) 
{
  this.starterLat         = starterLat;
  this.starterLng         = starterLng;
  this.starterMarker;
  this.elementId          = elementId;
  this.markers 			  = markers;  
  this.latId              = elementId + '_lat';  
  this.lngId              = elementId + '_lng';
  this.canvasId           = elementId + '_canvas';  
  this.directions;
  this.options            = options;

  if ($(elementId) == null)
  {
    alert('Exception: You try to bind the map to non-existant element id=' + elementId);
  }
  
  this.canvasId = this.elementId;
  
  google.load('maps', '2');
  
  google.setOnLoadCallback(this.init.bind(this));    
}

GoogleMap.prototype.init = function()
{
  if (GBrowserIsCompatible()) 
  {
	this.map = new GMap2(document.getElementById(this.canvasId));
    this.map.addControl(new GSmallMapControl());
    this.map.addControl(new GMapTypeControl());

    
    //this.map.enableScrollWheelZoom();
    
    //this.map.disableDoubleClickZoom(); // pauluZ
    
    this.map.enableContinuousZoom();      
    
    point = new GLatLng(this.starterLat, this.starterLng);
    this.map.setCenter(point, this.getOption('defaultZoom', 7));
    
    // putting initial marker
    this.createStarterMarker();
   
    //adding found point markers
    this.addObjectMarkers();
   
    this.renderUI();    
  }
  else
  {
    if (typeof this.options.onBrowserUnsupported == 'function')
    {
      this.options.onBrowserUnsupported(this);
    }
  }  
}

/**
 * dostosowuje mape do nowych rozmiarow kontenera
 * by sos
 */
GoogleMap.prototype.recenter = function() {

    var point;

    point = new GLatLng(this.starterLat, this.starterLng);
    this.map.checkResize();
    this.map.setCenter(point, this.getOption('defaultZoom', 7));
};

/**
 * Displays initial point
 * 
 * @author Pawel
 */
GoogleMap.prototype.createStarterMarker = function(lat, lng)
{
	if (this.getOption('no_start_point', false))
		return;
		
	
	var baseIcon = new GIcon();
    
	baseIcon.image = '/images/geolocalizer/start.gif';
    baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
    baseIcon.iconSize = new GSize(25, 34);
    baseIcon.shadowSize = new GSize(37, 34);
    baseIcon.iconAnchor = new GPoint(9, 34);
    baseIcon.infoWindowAnchor = new GPoint(9, 2);

    var letteredIcon = new GIcon(baseIcon);
	
	markerOptions = { icon:letteredIcon };
    point = new GLatLng(this.starterLat, this.starterLng);
	var marker = new GMarker(point, markerOptions);
	
	this.map.addOverlay(marker);
	
	this.starterMarker = marker;
}

GoogleMap.prototype.getObjectMarkerBaseIcon = function()
{
	var baseIcon = new GIcon(G_DEFAULT_ICON);
    baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
    baseIcon.iconSize = new GSize(20, 34);
    baseIcon.shadowSize = new GSize(20, 34);
    baseIcon.iconAnchor = new GPoint(9, 34);
    baseIcon.infoWindowAnchor = new GPoint(9, 2);
	
    return baseIcon;
}

GoogleMap.prototype.addObjectMarkers = function()
{
	baseIcon = this.getObjectMarkerBaseIcon();
	
	array = eval("(" + this.markers + ")");
	
	markers = new Array();
	
	if (array.length < 1) return;
	
	for (i=0; i< array.length; i++) 
	{
		element = array[i];
		
		lat = element['lat'];
		lng = element['lng'];
		
		point = new GLatLng(lat, lng);
		markers[i] = this.createObjectMarker(baseIcon, point, i, element['body'])
        this.map.addOverlay(markers[i]);
	}
	
	this.markers = markers;
}

GoogleMap.prototype.fireMarker = function(index)
{
	marker = this.markers[index];
	
	this.map.setCenter(marker.getPoint());
	
	this.firedIndex = index;

	GEvent.trigger(marker, "click");
}

GoogleMap.prototype.reloadObjectMarkers = function(markers)
{
	this.map.clearOverlays();
	
	this.recenter();
	
	this.createStarterMarker();
	
    this.markers = new Array();
	
	baseIcon = this.getObjectMarkerBaseIcon();
	
	array = markers;
	
	if (array.length < 1) return;
	
	for (i=0; i< array.length; ++i) 
	{
		element = array[i];
		
		lat = element['lat'];
		lng = element['lng'];
		
		point = new GLatLng(lat, lng);
        
		this.markers[i] = this.createObjectMarker(baseIcon, point, i, element['body']);
		
        this.map.addOverlay(this.markers[i]);
	}	
}

GoogleMap.prototype.createObjectMarker = function(baseIcon, point, index, body) {
    var icon = new GIcon(baseIcon);    
    index++;    
    if (body.indexOf('zlecenie') < 0)
    {
      icon.image = "/images/geolocalizer/flag" + index + ".png";
    }
    else
    {
      icon.image = "/images/geolocalizer/flag" + index + "o.png";
    }
    
    // Set up our GMarkerOptions object
    markerOptions = { icon:icon };
    var marker = new GMarker(point, markerOptions);

    marker.bindInfoWindowHtml(body);
    
    GEvent.addListener(marker, "mouseover", function() { 
    		GEvent.trigger(marker, "click");
    		Google.instance[0].showAllMarkers();
    		Google.instance[0].hideDirections();
    });
    
    return marker;
  }

GoogleMap.prototype.hideDirections = function()
{
	if (this.directions == null) return;
	
	for (i=0; i< this.markers.length; i++) 
	{
		if ($("directions_toolbar_" + i) != null) {
      $("directions_toolbar_" + i).setStyle({'display': 'none'});
    }
		// if ($("actions_" + i) != null) $("actions_" + i).show();
	}
	
	this.directions.clear();
}

GoogleMap.prototype.displayDirections = function(lat, lng, index)
{
	if (this.directions != null)
	{
		this.directions.clear();
	}
	
	this.directions = new GDirections(this.map);				
	
	var directionsArray = new Array();
	directionsArray[0] = this.starterLat + "," + this.starterLng;
	directionsArray[1] = lat + "," + lng;
	
	GEvent.addListener(this.directions, "load", this.onDirectionsLoad.bind(this, index));
	
	this.directions.loadFromWaypoints(directionsArray);

//  this.map.getInfoWindow().reset(null,null,new GSize(300,200),null,null);

  
  if (document.getElementById("orderMarkerHeight") != null){
      var elheight = $("orderMarkerHeight").getHeight();
      this.map.getInfoWindow().reset(null,null,new GSize(315,elheight+40),null,null);
  }
  
}

GoogleMap.prototype.renderUI = function()
{  
    $(this.elementId).insert(
      '<div id="' + this.canvasId + '" class="canvas"></div>'
    );  
}

GoogleMap.prototype.getOption = function(name, defaultValue)
{
  return eval('this.options.' + name) ? eval('(this.options.' + name + ')') : defaultValue;
}

GoogleMap.prototype.onDirectionsError = function()
{
  $(this.statusId).update(this.getOption('message_directions_not_found', 'No driving route found'));        
}

GoogleMap.prototype.onDirectionsLoad = function(index)
{
	startMarker = this.directions.getMarker(0);
	startMarker.getIcon().image = '/images/geolocalizer/directions_start.png'
	
	endMarker = this.directions.getMarker(1);
	endMarker.getIcon().image = '/images/geolocalizer/directions_end.png'
	
	distance = this.directions.getDistance();

	this.showAllMarkers();
	
	$("marker_distance_" + index).innerHTML = distance.html;
	$("directions_toolbar_" + index).setStyle({'display': 'block'});
//	$("actions_" + index).hide();
//this.map.getInfoWindow().reset(null,null,new GSize(200,500),null,null);

	this.starterMarker.hide();
	this.markers[index].hide();

}

GoogleMap.prototype.showAllMarkers = function()
{
	for (i=0; i< this.markers.length; ++i) 
	{
		this.markers[i].getIcon().image = "/images/geolocalizer/flag" + i + ".png";
		
		this.markers[i].show();				
	}
	
	this.starterMarker.getIcon().image = '/images/geolocalizer/start.gif';
	
	this.starterMarker.show();
}


GoogleMap.prototype.onMarkerDragStart = function()
{
  this.map.closeInfoWindow();
}

GoogleMap.prototype.onMarkerDragEnd = function(point)
{
  this.update(point);
  this.updateMarker(point, null);
}

GoogleMap.prototype.serialize = function()
{
  return '?lat=' + this.lat + '&lng=' + this.lng;
}

window.unload = function() 
{ 
  GUnload(); 
}
