'use strict';

function MyZoomControl(map) {
  var g = google.maps;
  g.event.addDomListener($('#map-control .top').get(0), 'click', function() {
    map.panBy(0, -200);
    new locationSearch('ps').toggleLocationSearchType('map');
  });
  g.event.addDomListener($('#map-control .left').get(0), 'click', function() {
    map.panBy(-200, 0);
    new locationSearch('ps').toggleLocationSearchType('map');
  });
  g.event.addDomListener($('#map-control .right').get(0), 'click', function() {
    map.panBy(200, 0);
    new locationSearch('ps').toggleLocationSearchType('map');
  });
  g.event.addDomListener($('#map-control .bottom').get(0), 'click', function() {
    map.panBy(0, 200);
    new locationSearch('ps').toggleLocationSearchType('map');
  });
  g.event.addDomListener($('#map-zoom .up').get(0), 'click', function() {
    clusterInfoWindow.close();
    map.setZoom(map.getZoom()+1);
    new locationSearch('ps').toggleLocationSearchType('map');
  });
  g.event.addDomListener($('#map-zoom .down').get(0), 'click', function() {
    clusterInfoWindow.close();
    map.setZoom(map.getZoom()-1);
    new locationSearch('ps').toggleLocationSearchType('map');
  });
  
  var slide_target = $('#map-zoom .zoom-slider');

  slide_target.slider({
    orientation:  'vertical',
    value:      map.getZoom(),
    min:      GMap_1.minZoom,
    max:      GMap_1.maxZoom,
    step:       1,
    animate:    false,
    stop: function() {
      map.setZoom(parseInt(slide_target.slider('option','value')));
    }
  });
  
  g.event.addDomListener(map, 'zoom_changed', function() {
    slide_target.slider('option','value', map.getZoom());
  });
  
  return;
}

var clusteringMarkerStyles = [{
  url: '/images/map-marker-cluster-medium.png',
  width: 28,
  height: 31,
  anchor: [0, 0],
  textColor: '#fff',
  textSize: 10
},
{
  url: '/images/map-marker-cluster-big.png',
  width: 35,
  height: 39,
  anchor: [0, -4],
  textColor: '#fff',
  textSize: 10
}];

var GMap_1 = null;
var markerClusterer = null;
var markers = [];
var infoWindow;
var clusterInfoWindow;
var clusterClicked;
var mapData;
var markerImage;

function refreshMapClustering() {
  markers = [];
  $.ajax({
    type: 'POST',
    url: google_map_search_results_coordinates_url,
    data: $('#ps').serialize(),
    success: function(data){
      mapData = data.properties;
      if (markerClusterer != null) {
        markerClusterer.clearMarkers();
      }

      $.each(data.properties, function(key, prp) {
        var latLng = new google.maps.LatLng(prp.mlat, prp.mlon);
        var marker = new google.maps.Marker({
          position: latLng,
          draggable: false,
          icon: markerImage
        });
        var options = {
          position: new google.maps.LatLng(prp.mlat, prp.mlon),
          content: '<div class="infoWindow'+(prp.img?' withPhoto':'')+'">Oferta nr: <span class="bold">'+prp.ref+'</span><br/>'
            +(prp.img?'<img src="'+prp.img+'" alt="" align="left" style="margin:5px;" />':'')+'<br/>'
            +prp.loc+'<br/>'
            +'cena: '+prp.prc+'<br/>'
            +(prp.ara?'powierzchnia: '+prp.ara:'')+'<br/>'
            +'&nbsp;<br/><a href="/of,'+prp.id+'">zobacz szczegóły</a></div>'
        };
        marker.setOptions(options);

        google.maps.event.addListener(marker, 'click', function() {
          infoWindow.setOptions(options);
          infoWindow.open(GMap_1, marker);
        });
        markers.push(marker);
      });

      markerClusterer = new MarkerClusterer(GMap_1, markers, {gridSize: 40, styles: clusteringMarkerStyles});
      clusterInfoWindow = new google.maps.InfoWindow();

      google.maps.event.addListener(markerClusterer, "clusterclick", function (cluster) {
        
        clusterClicked = true;
        
        if (cluster.getMap().getZoom() == cluster.getMap().maxZoom && cluster.getSize() > 1) {

          var content = '<div class="infoWindow">Liczba ofert: '+cluster.getSize()+'<br /><br />'
            +'<a href="javascript:searchFromCluster()"><span class="bold">Pokaż te oferty na liście</span></a>';
       
          var info = new google.maps.MVCObject;

          info.set('position', cluster.getCenter());
          clusterInfoWindow.setContent(content); 
          clusterInfoWindow.open(GMap_1, info);
          
        }
      });
    }
  });
}

/**
 * locationSearch
 * 
 * class for handling location search  
 * 
 * @param form, id form of search engine 
 * @return object
 */
function locationSearch(form) 
{
  this.form_name = form;
  this.form = $('form[name='+form+']');
  this.type = 1;
  this.maps_loaded = {};
  this.type_text = 1;
  this.type_map = 2;
  this.geocode_region = 'pl';
  this.geocode_center = null;
  this.geocode_bounds = null;

  this.toggleLocationSearchType = function(type)
  {
  	if ('text' == type)
  	{
        $('#gmap-wrapper').css('border', '2px solid #e2e2e2');
        $('#'+this.form.attr('name')+'_location_text').addClass('orange');
        $('#'+this.form.attr('name')+'_location_type').val(this.type_text);
  	}
  	else if ('map' == type)
  	{
        $('#gmap-wrapper').css('border', '2px solid #f5670d');
        $('#'+this.form.attr('name')+'_location_type').val(this.type_map);
        $('#'+this.form.attr('name')+'_location_text').removeClass('orange');
  
  	  this.maps_loaded.map_layer_id = true;
        this.initializeMapListeners(false, false);
  	}
  };

  /**
   * Bind listeners for map text location field
   */
  this.initializeMapListeners = function(refresh_map_clustering, show_map_locations)
  {
    var change_coords = false;
    if (GMap_1 != null) {
      change_coords = {
        center: GMap_1.getCenter(),
        zoom: GMap_1.getZoom()
      };
    }
    if (refresh_map_clustering)
    {
      this.GMap_initialize_1(show_map_locations);
    }
    google.maps.event.trigger(GMap_1, 'resize');
    if (change_coords != false) {
      GMap_1.setCenter(change_coords.center);
      GMap_1.setZoom(change_coords.zoom);
    }
    
    var location_input = $('#'+this.form.attr('name')+'_location_map_help');
    location_input.bind('keypress', this, function(e){ e.data.centerMapOnLocation(e, location_input, 'pl'); });
    $('#'+this.form.attr('name')+'_location_map_help_update').bind('click', this, function(e){ e.data.centerMapOnLocation(e, location_input, 'pl'); });
  };

  /**
   * Center the map based on user input (Google Map geocoding)
   */
  this.centerMapOnLocation = function(event, location_input, language)
  {
    if ($(event.target).attr('id') != location_input.attr('id') || (event.keyCode ? event.keyCode : event.which) == 13) {
      var location = location_input.val();
      if (location != '') {
        var geocoder = new google.maps.Geocoder();
        if (geocoder) {
          geocoder.geocode({
            address: location,
            language: language,
            bounds: GMap_1.getBounds()
          }, function(results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
              GMap_1.setCenter(results[0].geometry.location);
              GMap_1.fitBounds(results[0].geometry.viewport);
            }
          });
        }
      }
      event.preventDefault();
    }
  };

  /**
   * Prepare for searching
   */
  this.searchPrepare = function()
  {
    this.setLocationType();
    var coordinates = GMap_1.getBounds().toUrlValue() + ',' + GMap_1.getCenter().toUrlValue() + ',' + GMap_1.getZoom();
    $('[name="'+this.form.attr('name')+'[location_map]"]').val(coordinates);
  };

  /**
   * Submit event called from popup map.
   */
  this.searchMapSubmit = function()
  {
    this.searchPrepare();
  };

  this.setLocationType = function()
  {
    this.type = $('#'+this.form.attr('id')+' [name="'+this.form.attr('id')+'[location_type]"]').val();
  };

  this.onLoad = function(show_map_locations) 
  {
    this.setLocationType();

    var self = this;
    $('#'+this.form.attr('name')+'_location_text').click(function(){
      self.toggleLocationSearchType('text');
    });
    $('#'+this.form.attr('name')+'_location_text').focus(function(){
      self.toggleLocationSearchType('text');
    });

    this.maps_loaded.map_layer_id = true;
    
    if (google_geocode)
    {
      var this_is_me = this;
      
      new google.maps.Geocoder().geocode({
        address: google_geocode,
        region: this.geocode_region
      }, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK)
        {
          this_is_me.geocode_center = results[0].geometry.location;
          this_is_me.geocode_bounds = results[0].geometry.viewport;
        }
        this_is_me.initializeMapListeners(true, show_map_locations);
      });
    }
    else
    {
      this.initializeMapListeners(true, show_map_locations);
    }
  };
  
  this.GMap_initialize_1 = function(show_map_locations)
  {
    if (!this.geocode_center)
    {
      this.geocode_center = new google.maps.LatLng(google_map_latitude, google_map_longitude);
    }
    
    markerImage = new google.maps.MarkerImage('/images/map-marker-icon.png', new google.maps.Size(17, 25));
    var mapOptions = {
      scrollwheel: 0,
      center: this.geocode_center,
      zoom: google_map_zoom,
      minZoom: 5,
      maxZoom: 17,
      mapTypeId: google.maps.MapTypeId.ROADMAP,
      disableDefaultUI: true,
      mapTypeControl: false,
      navigationControl: false
    };
    GMap_1 = new google.maps.Map(document.getElementById('GMap_map_1'), mapOptions);
    
    if (this.geocode_bounds)
    {
      GMap_1.fitBounds(this.geocode_bounds);
    }
    
    if (show_map_locations) {
      refreshMapClustering();
    }
    infoWindow = new google.maps.InfoWindow();
    google.maps.event.addListener(GMap_1, 'click', function(event){
      if (clusterClicked)
      {
        clusterClicked = false;
      }
      else
      {
        clusterInfoWindow.close();
        infoWindow.close();
        new locationSearch('ps').toggleLocationSearchType('map');
      }
    });
    google.maps.event.addListener(GMap_1, 'dragstart', function(){
      new locationSearch('ps').toggleLocationSearchType('map');
    });

    new MyZoomControl(GMap_1); 
  };
}

/**
 * Search from Cluster on map
 */
function searchFromCluster() {
  new locationSearch('ps').toggleLocationSearchType('map');
  new locationSearch('ps').searchMapSubmit();
  document.forms['ps'].submit()
}
