/**
 * Google Maps
 *
 * @package    oferia
 * @subpackage google
 * @author     Bartosz "Inc!" Kielczewski
 * @version    SVN: $Id: actions.class.php 9301 2008-05-27 01:08:46Z dwhittle $
 */

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

  map: function(elementId, lat, lng, options) 
  {
    this.instance[this.instanceCount++] = new GoogleMap(elementId, lat, lng, options); 
  },
  correctAddress : function(c){
     var mapParent      =  jQuery('#google_map').parent("div"),
         inputMap =  jQuery('#google_map_query'),
         statusMap = jQuery('#google_map_status');
         
         
     if (inputMap.val() !== '' && c == false) {
      mapParent.addClass('rowError');
      inputMap.addClass('query');
      statusMap.addClass('statusMapError')
     } 
     else {
        mapParent.removeClass('rowError');
        statusMap.removeClass('statusMapError');
        

     }
  },
  hideError: function(){
    // usuwanie komunikatow z walidacji
    var cityError = jQuery('#city_id_error');
    
    if (cityError.length >0 ){
        cityError.removeClass('formError');
        cityError.find('.formErrorInfo').hide();
    }      
  }
}

function GoogleMap(elementId, lat, lng, options) 
{
  this.lat                = lat;
  this.lng                = lng;
  this.elementId          = elementId;
  this.latId              = elementId + '_lat';  
  this.lngId              = elementId + '_lng';
  this.canvasId           = elementId + '_canvas';  
  this.queryId            = elementId + '_query';  
  this.statusId           = elementId + '_status';
  this.querySubmitId      = elementId + '_query_submit';
  this.directionsId       = elementId + '_directions';
  this.directionsSubmitId = elementId + '_directions_submit';
  this.options            = options;

  if ($(elementId) == null)
  {
    alert('Exception: You try to bind the map to non-existant element id=' + elementId);
  }
  
  if (!this.getOption('customUI', false))
  {
    this.renderUI();
  }
  else
  {
    this.canvasId = this.elementId;
  } 
  
  if ($$('form #' + this.elementId) != '')
  {
    this.interceptFormSubmit();
  }

  google.load('maps', '2', {'language' : 'pl'});
  google.setOnLoadCallback(this.init.bind(this));    
}

GoogleMap.prototype.init = function()
{
  if (GBrowserIsCompatible()) 
  {
    this.map = new GMap2(document.getElementById(this.canvasId));
    this.map.addControl(new GLargeMapControl());
    //this.map.enableScrollWheelZoom();
    
    this.map.disableDoubleClickZoom(); // pauluZ
    
    this.map.enableContinuousZoom();    
    this.geocoder = new GClientGeocoder();
 
    if (!this.getOption('readonly', false))
    {
	    this.lat = parseFloat($(this.latId).value);
	    this.lng = parseFloat($(this.lngId).value);
    } 
    
    if(this.getOption('address', false))
    {
    	$(this.queryId).value = this.getOption('address','');
    }
    
    if (isNaN(this.lat) || isNaN(this.lng) || this.lat == '' || this.lng == '')
    {
      this.lat = this.getOption('defaultLat', '50.0616227606934');
      this.lng = this.getOption('defaultLng', '19.937363862991333');
      
      point = new GLatLng(this.lat, this.lng);
      this.map.setCenter(point, this.getOption('defaultZoom', 16));
      
      if(this.getOption('address', false))
      {
  	    this.submitQuery();
      } 
      else
      {
    	  if($(this.queryId) != null && this.lat == '50.0616227606934' && this.lng == '19.937363862991333')
          {
        	  $(this.queryId).value = 'Rynek główny, Kraków';
          }
    	  
          this.update(point);
          this.updateMarker(point, null);  
      }
    }
    else
    {
      point = new GLatLng(this.lat, this.lng);
      this.map.setCenter(point, this.getOption('defaultZoom', 16));
      this.updateMarker(point, null);
    }
    
    if ($(this.querySubmitId) != null)
    {
      $(this.querySubmitId).observe('click', this.onSubmitQuery.bind(this));
    }
    if ($(this.directionsSubmitId) != null)
    {
      $(this.directionsSubmitId).observe('click', this.onSubmitDirections.bind(this));
    }
    if ($(this.queryId) != null)
    {
      $(this.queryId).observe('change', this.onSubmitQuery.bind(this));
      $(this.queryId).observe('keypress', this.onSubmitQueryOnEnter.bind(this));
    }
    if ($(this.directionsId) != null)
    {
      $(this.directionsId).observe('change', this.onSubmitDirections.bind(this));
    }

    GEvent.addListener(this.map, "click", this.onClick.bind(this));
  }
  else
  {
    if (typeof this.options.onBrowserUnsupported == 'function')
    {
      this.options.onBrowserUnsupported(this);
    }
  }  
}

GoogleMap.prototype.showAddress = function(response)
{  
  if (!response || response.Status.code != 200) 
  {
    if ($(this.statusId) != null)
    {
      if ($('order_address')) {
        if ($('order_address').value !== '') {
          $(this.statusId).update(this.getOption('message_address_not_found', 'Address not found'));
        }
      }
      if ($('service_address')) {
        if ($('service_address').value !== '') {
          $(this.statusId).update(this.getOption('message_address_not_found', 'Address not found'));
        }
      }
      Google.correctAddress(false);
    }
	  if (typeof this.options.onAddressNotFound == 'function')
	  {
	    this.options.onAddressNotFound(this);
            Google.correctAddress(false);
	  }
  } 
  else 
  {
    place = response.Placemark[0];
    point = new GLatLng(place.Point.coordinates[1], place.Point.coordinates[0]);
    if ($(this.statusId) != null)
    {
      $(this.statusId).update(this.getOption('message_address_found', 'Now you can refine your selection by dragging the marker around'));
      //$(this.queryId).value = place.address;
      if ($('order_address'))
      {
        $('order_address').value = $(this.queryId).value;
        $('order_region').value = place.AddressDetails.Country.AdministrativeArea.AdministrativeAreaName;
      }
      if ($('service_address'))
      {
        $('service_address').value = $(this.queryId).value;
        $('service_region').value = place.AddressDetails.Country.AdministrativeArea.AdministrativeAreaName;
      }
      Google.correctAddress(true);
      Google.hideError();
    }
    this.map.setZoom(16);
    this.update(point);
    this.updateMarker(point, place.address);
  }

}

GoogleMap.prototype.showAddressOnDragEnd = function(response)
{
  if (!response || response.Status.code != 200)
  {
    if (typeof this.options.onAddressNotFound == 'function')
    {
      this.options.onAddressNotFound(this);
      Google.correctAddress(false);
    
    }
  }
  else
  {
    place = response.Placemark[0];
    point = new GLatLng(place.Point.coordinates[1], place.Point.coordinates[0]);
    if ($(this.statusId) != null)
    {
      $(this.statusId).update(this.getOption('message_address_found', 'Now you can refine your selection by dragging the marker around'));
      if (place.AddressDetails.Accuracy > 7)
      {
        $(this.queryId).value = place.address;
        if ($('order_address'))
        {
          $('order_address').value = $(this.queryId).value;
          $('order_region').value = place.AddressDetails.Country.AdministrativeArea.AdministrativeAreaName;
        }
        if ($('service_address'))
        {
          $('service_address').value = $(this.queryId).value;
          $('service_region').value = place.AddressDetails.Country.AdministrativeArea.AdministrativeAreaName;
        }
      }
      Google.correctAddress(true);
      Google.hideError(); 
    }

    if (place.AddressDetails.Accuracy > 7)
    {
      this.map.setZoom(16);
      this.update(point);
      this.updateMarker(point, place.address);
    }
  }
}

GoogleMap.prototype.update = function(point)
{
  try {
    $(this.latId).value = point.lat();
  } catch (e) {}
  try {
    $(this.lngId).value = point.lng();
  } catch (e) {}
  
  this.lat = point.lat();
  this.lng = point.lng();

  if (typeof this.options.onUpdate == 'function')
  {
    this.options.onUpdate(this);
  }
}

GoogleMap.prototype.updateMarker = function(point, info)
{
  this.map.clearOverlays();
  this.map.panTo(point);
  var marker = new GMarker(point, {draggable: true});
  this.marker = marker;
 
  if (this.getOption('readonly', false) || document.getElementById('google_map_query').value !== '') {
    this.map.addOverlay(marker);
  }

  this.directions = new GDirections(this.map);
  GEvent.addListener(this.directions, "error", this.onDirectionsError.bind(this));
  GEvent.addListener(this.directions, "load", this.onDirectionsLoad.bind(this));

  if (info != null)
  {
    marker.openInfoWindowHtml(info);
  }    
  
  if (!this.getOption('readonly', false))
  {
    GEvent.addListener(marker, "dragstart", this.onMarkerDragStart.bind(this));  
    GEvent.addListener(marker, "dragend", this.onMarkerDragEnd.bind(this));
  } 
  else
  {
    marker.disableDragging()
  }
}

GoogleMap.prototype.renderUI = function()
{
  if (!this.getOption('readonly', false) && !this.getOption('hideForm', false)) 
  {  
		$(this.elementId).insert(
		  '<span><input id="' + this.latId + '" name="' + this.getOption('elementNameLat', this.latId) + '" type="hidden" value="' + this.lat + '" /></span>' +
		  '<span><input id="' + this.lngId + '" name="' + this.getOption('elementNameLng', this.lngId) + '" type="hidden" value="' + this.lng + '" /></span>' +
		  '<label for="searchInput">' + this.getOption('inputLabel', 'Szukaj adresu:') + '</label>' +
		  '<div class="searchForm">' +
		  '<div class="left"><input id="' + this.queryId + '" name="searchInput" type="text" class="query" value="'+this.getOption('search_input_text', '')+'" /></div>' +
		  '<div class="left">' +
		  '<a id="' + this.querySubmitId + '" class="buttonV1"><span>' + this.getOption('message_search', 'Search') + '</span></a></div>' +
	      '<small class="clear" id="' + this.statusId + '">' + this.getOption('message_address_help', 'Please type the address find it on map') + '</small>' +
	      '</div>' + '<div class="clear"></div>' + 
	      '<div id="' + this.canvasId + '" class="canvas"></div>' +
		  ''
		);
  }
  else if (!this.getOption('readonly', false)) 
  {
    $(this.elementId).insert(
      '<input id="' + this.latId + '" name="' + this.getOption('elementNameLat', this.latId) + '" type="hidden" value="' + this.lat + '" />' +
      '<input id="' + this.lngId + '" name="' + this.getOption('elementNameLng', this.lngId) + '" type="hidden" value="' + this.lng + '" />' +
      '<input id="' + this.queryId + '" type="text" class="query" style="visibility: hidden" value="" />' +
      '<input id="' + this.querySubmitId + '" type="button" class="query_submit" style="visibility: hidden" value="' + this.getOption('message_search', 'Search') + '" /><br />' +
      '<small id="' + this.statusId + '">' + this.getOption('message_address_help', 'Please type the address find it on map') + '</small>' +
      '<div id="' + this.canvasId + '" class="canvas"></div>' +
	  ''
    );
  }
  else
  {
    $(this.elementId).insert(      
      '<div id="' + this.directionsId + '_changer" >' +
      '<a class="' + this.getOption('changer_class', "green") + '" href="javascript:fixVisibility(\'' + this.directionsId + '\');"> '+
      this.getOption('changer_text', "Szukaj") + 
      '</a></div>' + 
      '<div id="' + this.directionsId + '_div" style = "display:none; height:135px; width:550px; overflow-x:hidden; zoom:1;">' +
        '<div>' + this.getOption('message_search', 'Search') + '</div>' +
        '<label for="searchInput" style="line-height:25px;height:25px;padding-left:10px">Skąd: </label>' +
        '<div class="searchForm">' +
          '<div class="left"><input id="' + this.directionsId + '" name="searchInput" type="text" class="query" style="width:390px"/></div>' +
          '<div class="left butWG">' + '<a id="' + this.directionsSubmitId + '"><span>' + 'Wyznacz trasę' + '</span></a></div>' +
          '<div class="clear"><small class="clear" id="' + this.statusId + '" style="padding-bottom:10px;margin-left:0px">' + this.getOption('message_address_help', 'Please type the address find it on map') + '</small></div>' +
        '</div> <div class="clear" style="font-size:0px; height: 0px; line-height: 0px;"></div> <div>' +
        '<b> odległość: <span id="distanceCounter" style="color:#239198"> nieznana </b></span>' +
        '<span style="margin-left:50px"> <img src="/images/gdstart.gif"> - punkt startowy</span>' +
        '<span style="margin-left:10px"> <img src="/images/gdend.gif"> - cel trasy</span>' +
        '</div>' +
      '</div>' +
      '<div class="clear"></div>' +
      '<div id="' + this.canvasId + '" class="canvas" style="margin-right:0px; margin-top:3px"></div>'
    );
  }
  
}

function resize(what, what2,  to) {
	to = to + 10;
	var start = parent.document.getElementById(what).style.height;
	var start2 = parent.document.getElementById(what2).style.top;
	
	start = start.substring(0, start.length-2);	
	start2 = start2.substring(0, start2.length-2);
	
	start = Number(start);
	var diff = (to - start)/2;
	start2 = Number(start2) - diff;
	
	
	document.body.style.height = "100%";
	
	parent.document.getElementById(what).style.height = to  + 'px';	
	parent.document.getElementById(what2).style.height = (to+10)  + 'px';
	parent.document.getElementById(what2).style.top   = start2 + 'px';		
	
}

function fixVisibility(name){
	if($(name+'_canvas')){(name+'_canvas').hide();}
	$(name+'_div').show();
	$(name+'_changer').hide();
	if($(name+'_canvas')){$(name+'_canvas').show();}
	
	if (window.parent.document.getElementById('lightwindow'))
	{
		// lightwindow used
		fixVisibilityLightWindow();
	}
	else
	{
		// fancybox used
		fixVisibilityFancyBox();
                document.getElementById('google_map_directions_div').style.overflowY = 'hidden';
	}	
}

function fixVisibilityLightWindow()
{
	window.parent.document.getElementById('lightwindow').style.marginTop = '50px';
	
	if(navigator.appName.substring(0,2) == "Mi"){
		try {
			resize('lightwindow_contents', 'lightwindow_container', 663 );
			resize('extralightwindow_contents', 'extralightwindow_container', 663 );
		} catch (e) {}
	}
	else
	{
		try {
			resize('lightwindow_contents', 'lightwindow_container', 658 );
			resize('extralightwindow_contents', 'extralightwindow_container', 658 );
			
		} catch (e) {}
	}
}

function fixVisibilityFancyBox()
{

	try {
		height = parent.document.getElementById("fancy_outer").style.height;
		height = height.substring(0, height.length-2);
		height = Number(height) + 110;
		parent.document.getElementById("fancy_outer").style.height = height + 'px';		
		height = parent.document.getElementById("fancy_inner").style.height;
		height = height.substring(0, height.length-2);
		height = Number(height) + 110;
		parent.document.getElementById("fancy_inner").style.height = height + 'px';	
		height = parent.document.getElementById("fancy_content").style.height;
		height = height.substring(0, height.length-2);
		height = Number(height) + 110;
		parent.document.getElementById("fancy_content").style.height = height + 'px';
	} catch (e) {}
	try {
		height = parent.document.getElementById("fancybox-wrap").style.height;
		height = height.substring(0, height.length-2);
		height = Number(height) + 110;
		parent.document.getElementById("fancybox-wrap").style.height = height + 'px';
		height = parent.document.getElementById("fancybox-inner").style.height;
		height = height.substring(0, height.length-2);
		height = Number(height) + 110;
		parent.document.getElementById("fancybox-inner").style.height = height + 'px';
		height = parent.document.getElementById("fancybox-wrap").style.top;
		height = height.substring(0, height.length-2);
		height = Number(height) - 55;
		parent.document.getElementById("fancybox-wrap").style.top = height + 'px';
                
	} catch (e) {}
	try {
		height = parent.document.getElementById("fancybox-content").style.height;
		height = height.substring(0, height.length-2);
		height = Number(height) + 110;
		parent.document.getElementById("fancybox-content").style.height = height + 'px';
          } catch (e) {}
}

GoogleMap.prototype.interceptFormSubmit = function()
{
  var handler = function(event) 
  { 
    Event.stop(event); 
  }

  if ($(this.queryId) != null)
  {
		$(this.queryId).observe('focus', 
		  function(event) 
		  {
		    form = Event.element(event).form;
		    Event.observe(form, 'submit', handler);
		  }
		);
		$(this.queryId).observe('blur', 
		  function(event) 
		  {
		    form = Event.element(event).form;
		    Event.stopObserving(form, 'submit', handler);
		  }
		);
  }

  if ($(this.directionsId) != null)
  {
    $(this.directionsId).observe('focus', 
      function(event) 
      {
        form = Event.element(event).form;
        Event.observe(form, 'submit', handler);
      }
    );
    $(this.directionsId).observe('blur', 
      function(event) 
      {
        form = Event.element(event).form;
        Event.stopObserving(form, 'submit', handler);
      }
    );
  }
}

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

GoogleMap.prototype.onSubmitQuery = function(event)
{
  if (this.geocoder != null) {
    this.geocoder.getLocations($(this.queryId).value, this.showAddress.bind(this));
  }
  var point = new GLatLng(this.lat, this.lng);
  this.update(point);
  this.updateMarker(point, null);
  if ($('service_address')) {
    $('service_address').value = $(this.queryId).value;  
  } else if ($('order_address')) {
    $('order_address').value = $(this.queryId).value;  
  }
}

GoogleMap.prototype.onSubmitQueryOnEnter = function(event)
{
  var code = event.keyCode || event.which;
  if (code == 13)
  {
    var point = new GLatLng(this.lat, this.lng);
    this.geocoder.getLocations($(this.queryId).value, this.showAddress.bind(this));
    this.update(point);
    this.updateMarker(point, null);
  }
} 

GoogleMap.prototype.submitQuery = function()
{
  if (this.geocoder != null) {
    this.geocoder.getLocations($(this.queryId).value, this.showAddress.bind(this));
  }
  var point = new GLatLng(this.lat, this.lng);
  this.update(point);
  this.updateMarker(point, null);
}

GoogleMap.prototype.onSubmitDirections = function(event)
{
  if ($(this.directionsId).value != '')
  {
    this.geocoder.getLocations($(this.directionsId).value + ', poland', this.onSubmitDirectionsTested.bind(this));
  }
}

GoogleMap.prototype.onSubmitDirectionsTested = function(response)
{
  if (!response || response.Status.code != 200) 
  {
    if ($(this.statusId) != null)
    {
      $(this.statusId).update(this.getOption('message_address_not_found', 'Address not found'));
    }
    if (typeof this.options.onAddressNotFound == 'function')
	{
	  this.options.onAddressNotFound(this);
	}
  } 
  else 
  {
    place = response.Placemark[0];
    point = new GLatLng(place.Point.coordinates[1], place.Point.coordinates[0]);
    var zmienna = new Array();
    zmienna[0] = place.Point.coordinates[1] + ',' + place.Point.coordinates[0]; 
    zmienna[1] = this.lat + ',' + this.lng;
    this.directions.loadFromWaypoints(zmienna,{getPolyline:true,getSteps:true});
  }
}

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

GoogleMap.prototype.onDirectionsLoad = function()
{
  this.map.removeOverlay(this.marker);
	
	
  $('distanceCounter').update(this.directions.getDistance().html);

  setTimeout("var poly=Google.instance[0].directions.getPolyline(); Google.instance[0].map.addOverlay(new GMarker(poly.getVertex(0),G_START_ICON));", 500);
  setTimeout("var poly=Google.instance[0].directions.getPolyline(); Google.instance[0].map.addOverlay(new GMarker(poly.getVertex(poly.getVertexCount()-1),G_END_ICON));",500);  
}

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

GoogleMap.prototype.onMarkerDragEnd = function(point)
{
  this.update(point);
  this.updateMarker(point, null);
//  this.geocoder.getLocations(point, this.showAddressOnDragEnd.bind(this));
}

GoogleMap.prototype.onClick = function(overlay, latlng)
{
  if (latlng == null)
  {
	return true;
  }

  this.update(latlng);
//  this.updateMarker(latlng);
//  this.geocoder.getLocations(latlng, this.showAddressOnDragEnd.bind(this));
}

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

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