/*global google, MarkerClusterer, InfoBox, this_url, $HAR, submit_obstacle*/
//------------------------------------------------------------------------------
function dealersController()
{
  this.data = {markers           : {},
               dealers           : {},
               clustered_markers : []
              };

  this.geocoder = new google.maps.Geocoder();
}
//------------------------------------------------------------------------------

//------------------------------------------------------------------------------
dealersController.prototype.map_init = function(map_placeholder, markers, dealers, lat, lng, zoom)
{
  var self = this;

  this.data.markers = markers;
  this.data.dealers = dealers;

  var latlng = new google.maps.LatLng((lat == undefined || lat == '') ? 55.755786 : lat, (lng == undefined || lng == '') ? 37.617633 : lng);
  var mapOptions = {zoom: (zoom == undefined || zoom == '') ? 10 : zoom,
                    center: latlng,
                    scrollwheel: false,
                    mapTypeId: google.maps.MapTypeId.ROADMAP
                   };

  this.map = new google.maps.Map(document.getElementById(map_placeholder), mapOptions);
  /*google.maps.event.addListener(this.map, 'click', function()
  {
    self.ib.hide();
  });*/

  this.init_markers(true);

  this.infobox_options = {closeBoxMargin   : '5px',
                          pixelOffset      : new google.maps.Size(-150, -80),
                          boxStyle         : {width: "300px", height: "100px"},
                          closeBoxURL      : "i/gmap_popup/close.png",
                          alignBottom      : true,
                          infoBoxClearance : new google.maps.Size(30, 30)
                         };
  this.ib = null;
};
//------------------------------------------------------------------------------

//------------------------------------------------------------------------------
dealersController.prototype.init_markers = function(clasterisation)
{
  for(var i in this.data.markers)
  {
    if( this.data.markers[i].coordinates )
    {
      var marker = this.build_marker(this.data.markers[i].coordinates);
      marker.dealer = this.data.markers[i].dealer;
      marker.filial = this.data.markers[i].filial;
      this.data.clustered_markers.push(marker);
    }
    else
    {
      //this.update_address('г. ' + this.data.markers[i].city + ' ' + this.data.markers[i].address);
      this.update_address(this.data.markers[i].address);
    }
  }

  if( clasterisation )
  {
    var self   = this;
    var styles = [];
    for(i = 0; i < 5; i++ )
    {
      styles[i] = {url: '/i/marker_icon.png', height: 34, width: 21, textColor: '#fa7402'};
    }

    var mcOptions = {gridSize: 50,
                     maxZoom: 15,
                     styles : styles,
                     zoomOnClick: false
                     };
    this.mc       = new MarkerClusterer(this.map, this.data.clustered_markers, mcOptions);
    google.maps.event.addListener(this.mc, 'clusterclick', function(cluster)
    {
      self.show_clustered_marker(cluster);
    });
  }
};
//------------------------------------------------------------------------------

//------------------------------------------------------------------------------
dealersController.prototype.build_marker = function(coords)
{
  var latlng;
  var self = this;

  if( typeof(coords) === 'string' )
  {
    coords = coords.split(',');
    latlng = new google.maps.LatLng(coords[0], coords[1]);
  }
  else
  {
    latlng = coords;
  }

  var marker = new google.maps.Marker({position : latlng,
                                      map       : this.map,
                                      icon      : '/i/marker_icon.png'
                                     });

  var create_description = function(marker)
  {
    google.maps.event.addListener(marker, 'click', function()
    {
      self.show_marker(this);
    });
  }(marker);

  return marker;
};
//------------------------------------------------------------------------------

//------------------------------------------------------------------------------
dealersController.prototype.show_marker = function(marker)
{
  if( marker.dealer && this.data.dealers[marker.dealer] )
  {
    var container = ['<div class="dealer_list">'];
    this.build_dealer_html(this.data.dealers[marker.dealer], marker.filial, container);
    container.push('</div>');
    container = container.join('');
    this.infobox_options.content = this.createPopupWindow(container);
    var ib = new InfoBox(this.infobox_options);
    ib.open(this.map, marker);
  }
};
//------------------------------------------------------------------------------

//------------------------------------------------------------------------------
dealersController.prototype.show_clustered_marker = function(cluster)
{
  var items   = [],
      markers = cluster.getMarkers(),
      content = ['<div class="dealer_list">'];

  for( var i = 0; i < markers.length; i++ )
  {
    if( markers[i].dealer && this.data.dealers[markers[i].dealer] )
    {
      this.build_dealer_html(this.data.dealers[markers[i].dealer], markers[i].filial, items);
    }
  }

  //items.sort(sort_items);
  for(i = 0; i < items.length; i++ )
  {
    content.push(items[i]);
  }

  content.push('</div>');
  content = content.join('');

  this.infobox_options.content = this.createPopupWindow(content);
  var anchor = {position: cluster.center_, getPosition: function(){
    return this.position;
  }};
  this.ib = new InfoBox(this.infobox_options);
  this.ib.open(this.map, anchor);
};
//------------------------------------------------------------------------------

//------------------------------------------------------------------------------
dealersController.prototype.createPopupWindow = function(content)
{
  var c =  '<div class="gmap_popup">';
      c +=   '<div class="wrapper">';
      c +=     '<div class="crn"></div>';
      c +=     '<div class="crn rt"></div>';
      c +=     '<div class="cnt">';
      c +=       content;
      c +=     '</div>';
      c +=   '</div>';
      c +=   '<div class="crn bt rt"></div>';
      c +=   '<div class="crn bt"></div>';
      c +=   '<div class="beak"></div>';
      c += '</div>';

  return c;
};
//------------------------------------------------------------------------------

//------------------------------------------------------------------------------
dealersController.prototype.build_dealer_html = function(dealer, filial, container)
{
  var d  = '<div class="text_container">';
  /*d += '<a href="/dealers/' + dealer.id + '/">';

  if( dealer.logo )
  {
    d += '<img width="100" alt="" class="left" src="/f/users/' + dealer.logo + '"></a>';
  }

  d += '<div class="nofloat"><div class="s14 bb m10 grey"><a href="/dealers/?town='+dealer.city_url+'#item_'+dealer.id+'">'+dealer.name+'</a></div>';

  d += '<div class="s11 grey"><span class="bb">URL-адрес:</span>&nbsp;<a href="'+dealer.url+'">'+dealer.url+'</a></div>';
  */
  d += '<div class="s11 grey">'+dealer.title+'</div>';
  d += '<div class="s11 grey">'+dealer.adress+'</div>';
  d += '<div class="s11 grey">'+dealer.notice+'</div>';
  /*if( dealer.adress )
  {
    d += '<div class="s11 grey"><span class="bb">Адрес:</span>&nbsp;'+dealer.filials[filial].adress+'</div>';
  } */
  if( dealer.phone_0 ) d += '<div class="s11 grey"><span class="bb">Тел:</span>&nbsp;'+dealer.phone_0+(dealer.phone_0_descr ? ' - ' + dealer.phone_0_descr : '')+'</div>';
  if( dealer.phone_1 ) d += '<div class="s11 grey"><span class="bb">Тел:</span>&nbsp;'+dealer.phone_1+(dealer.phone_1_descr ? ' - ' + dealer.phone_1_descr : '')+'</div>';
  if( dealer.phone_2 ) d += '<div class="s11 grey"><span class="bb">Тел:</span>&nbsp;'+dealer.phone_2+(dealer.phone_2_descr ? ' - ' + dealer.phone_2_descr : '')+'</div>';
  if( dealer.phone_3 ) d += '<div class="s11 grey"><span class="bb">Тел:</span>&nbsp;'+dealer.phone_3+(dealer.phone_3_descr ? ' - ' + dealer.phone_3_descr : '')+'</div>';

  if( dealer.email_0 ) d += '<div class="s11 grey"><span class="bb">E-mail:</span>&nbsp;'+dealer.email_0+(dealer.email_0_descr ? ' - ' + dealer.email_0_descr : '')+'</div>';
  if( dealer.email_1 ) d += '<div class="s11 grey"><span class="bb">E-mail:</span>&nbsp;'+dealer.email_1+(dealer.email_1_descr ? ' - ' + dealer.email_1_descr : '')+'</div>';
  if( dealer.email_2 ) d += '<div class="s11 grey"><span class="bb">E-mail:</span>&nbsp;'+dealer.email_2+(dealer.email_2_descr ? ' - ' + dealer.email_2_descr : '')+'</div>';
  if( dealer.email_3 ) d += '<div class="s11 grey"><span class="bb">E-mail:</span>&nbsp;'+dealer.email_3+(dealer.email_3_descr ? ' - ' + dealer.email_3_descr : '')+'</div>';

  if( dealer.icq_0 ) d += '<div class="s11 grey"><span class="bb">ICQ:</span>&nbsp;'+dealer.email_0+(dealer.icq_0_descr ? ' - ' + dealer.icq_0_descr : '')+'</div>';
  if( dealer.icq_1 ) d += '<div class="s11 grey"><span class="bb">ICQ:</span>&nbsp;'+dealer.email_1+(dealer.icq_1_descr ? ' - ' + dealer.icq_1_descr : '')+'</div>';
  if( dealer.icq_2 ) d += '<div class="s11 grey"><span class="bb">ICQ:</span>&nbsp;'+dealer.email_2+(dealer.icq_2_descr ? ' - ' + dealer.icq_2_descr : '')+'</div>';
  if( dealer.icq_3 ) d += '<div class="s11 grey"><span class="bb">ICQ:</span>&nbsp;'+dealer.email_3+(dealer.icq_3_descr ? ' - ' + dealer.icq_3_descr : '')+'</div>';

  d += '<br></div>';

  container.push(d);
};
//------------------------------------------------------------------------------

//------------------------------------------------------------------------------
dealersController.prototype.update_address = function(address)
{
  var self = this;

  if( !this.update_address.runs )
  {
    this.update_address.runs = 1;
  }
  else
  {
    this.update_address.runs++;
  }
  if( this.update_address.runs > 10 )
  {
    return;
  }

  // get address coordinates
  this.geocoder.geocode({'address': address}, function(results, status)
  {
    if( status === google.maps.GeocoderStatus.OK )
    {
      var location      = results[0].geometry.location;
      var addr_tmp_hash = {'name': address, 'coordinates': location.toUrlValue()};

      var finish = function(resp)
      {
        if( $HAR(resp) )
        {
          // добавить дилера в массив с дилерами
        }
      };

      $.post(this_url, 'action=address_update&compiled=1&data='+encodeURIComponent($.obj.parse(addr_tmp_hash)), finish);
      self.build_marker(location);
    }
    else
    {
      console.log("Geocode was not successful for the following reason: " + status);
    }
  });
};
//------------------------------------------------------------------------------

//------------------------------------------------------------------------------
dealersController.prototype.cities_init = function(class_name)
{
  var self = this;
  $('.'+class_name).click(function(){
    var city = $(this).attr('id').match(/\w+-([\-А-я]+)/)[1];
    self.cities_show_popup(city);
  });
};
//------------------------------------------------------------------------------

//------------------------------------------------------------------------------
dealersController.prototype.cities_show_popup = function(city)
{
  var container = ['<div class="dealer_list">'];
  var marker;

  for(var i in this.data.dealers)
  {
    if( this.data.dealers[i].filials && this.data.dealers[i].filials.length )
    {
      for(var j = 0; j < this.data.dealers[i].filials.length; j++)
      {
        if( this.data.dealers[i].filials[j].city.find(city) )
        {
          this.build_dealer_html(this.data.dealers[i], j, container);
          if( !marker )
          {
            for(var k in this.data.markers)
            {
              if( this.data.clustered_markers[k].dealer == i && this.data.clustered_markers[k].filial == j )
              {
                marker = this.data.clustered_markers[k];
                break;
              }
            }
          }
        }
      }
    }
  }

  if( marker )
  {
    window.scrollBy(0, -9999);

    container.push('</div>');
    container = container.join('');
    this.infobox_options.content = this.createPopupWindow(container);
    var ib = new InfoBox(this.infobox_options);
    ib.open(this.map, marker);
  }
};
//------------------------------------------------------------------------------

//------------------------------------------------------------------------------
dealersController.prototype.registration_init = function(form, add_group_action)
{
  var self = this;
  this.form = form;
  this.registration_coords_data = {};
  this.registration_maps        = {};
  this.registration_markers     = {};

  $('.form-filials-city, .form-filials-address').live('blur', function()
  {
    if( $(this).val().length )
    {
      var id = $(this).attr('id');
      id = id.match(/form-filials-\w+-?(\d)*/)[1] || 0;

      self.registration_show_address($(this), id);

      var next_id = Number(id) + 1;
      if( $('#form-filials-city-'+next_id).length === 0 )
      {
        add_group_action('form-filials');
        $($('.form-filials-map')[next_id]).hide();
      }
    }
  });
};
//------------------------------------------------------------------------------

//------------------------------------------------------------------------------
dealersController.prototype.registration_show_address = function(e, id)
{
  var self      = this;
  var type      = $(e).attr('id').match(/form-filials-(\w+)/)[1];
  var loc_name  = $(e).val();

  $.mouseLoader(true);

  if( type.match(/address/) && this.form.filials[id] && loc_name.indexOf(this.form.filials[id].city) === -1 )
  {
    loc_name = this.form.filials[id].address = 'г. '+this.form.filials[id].city +', '+loc_name;
    $($('.form-filials-address')[id]).attr('value', loc_name);
  }

  this.geocoder.geocode({'address': loc_name}, function(results, status)
  {
    if( status === google.maps.GeocoderStatus.OK )
    {
      var location = results[0].geometry.location;

      self.registration_show_marker(location, type === 'address' ? 15 : null, id);
      self.registration_coords_data[id] = {'name' : loc_name, 'coordinates' : location.toUrlValue()};

      e.removeClass('input_error');
      if( id === 0 )
      {
        submit_obstacle.town = false;
      }
      $($('.form-filials-city-wrong')[id]).hide();
    }
    else
    {
      e.addClass('input_error');
      if( id === 0 )
      {
        submit_obstacle.town = "укажите город";
      }
      $($('.form-filials-city-wrong')[id]).show();
    }
    $.mouseLoader(false);
  });
};
//------------------------------------------------------------------------------

//------------------------------------------------------------------------------
dealersController.prototype.registration_show_marker = function(location, zoom, num)
{
  var self = this;

  if( $('.form-filials-map')[num].style.display === 'none' )
  {
    $($('.form-filials-map')[num]).show();
    var mapOptions = {zoom: zoom || 4,
                      center: location,
                      scrollwheel: false,
                      mapTypeId: google.maps.MapTypeId.ROADMAP
                     };
    this.registration_maps[num] = new google.maps.Map($('.form-filials-map')[num], mapOptions);
  }
  this.registration_maps[num].setZoom(zoom || 7);
  this.registration_maps[num].setCenter(location);

  if( this.registration_markers[num] )
  {
    this.registration_markers[num].setMap(null);
    delete this.registration_markers[num];
  }
  this.registration_markers[num] = new google.maps.Marker({'position'  : location,
                                                           'map'       : this.registration_maps[num],
                                                           'draggable' : true
                                                           });

  google.maps.event.addListener(this.registration_markers[num], 'dragend', function()
  {
    self.registration_coords_data[num].coordinates = this.getPosition().toUrlValue();
  });
};
//------------------------------------------------------------------------------

//------------------------------------------------------------------------------
dealersController.prototype.registration_add_coords = function()
{
  var coords = $.obj.parse(this.registration_coords_data);
  $.post(this_url, 'action=add_coords&compiled=1&coordinates=' + encodeURIComponent(coords), null, 'json');
};
//------------------------------------------------------------------------------

