/*
 * This file is part of the mgWidgets package.
 * (c) 2008 Qarmaq
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

function gourmetMap(){
  // this global attributes
  this.wuid = null;
  this.widget = null;
  this.icons = {};

  this.geocoder = null;
  this.map = null;
  this.markers = [];
  this.disable_refresh = false;
}

gourmetMap.prototype = new mgWidgetObject();

// this method is call when the object is created
gourmetMap.prototype.init = function(wuid) {
  // common code
  this.wuid = wuid;
  this.widget = jQuery('#' + wuid);

  // fake inputs
  this.inputs = {
    where: jQuery('#' + wuid + '_where_input'),
    search: jQuery('#' + wuid + '_search_input'),
    category: jQuery('#' + wuid + '_search_category'),
    category_1c: jQuery('#' + wuid + '_search_category_1c'),
    btn_submit_2c: jQuery('#' + wuid + '_btn_submit_2c'),
    btn_submit_1c: jQuery('#' + wuid + '_btn_submit_1c')
  }

  // real input
  this.settings = {
    where: jQuery('#' + wuid + '_widget_settings_where'),
    category: jQuery('#' + wuid + '_widget_settings_categories'),
    search: jQuery('#' + wuid + '_widget_settings_search'),
    lat: jQuery('#' + wuid + '_widget_settings_center_lat'),
    lng: jQuery('#' + wuid + '_widget_settings_center_lng'),
    zoom: jQuery('#' + wuid + '_widget_settings_zoom')
  }

  this.inputs.where.val(this.settings.where.val());
  this.inputs.search.val(this.settings.search.val());
  this.inputs.category.val(this.settings.category.val());
  this.inputs.category_1c.val(this.settings.category.val());

  // register action to trigger when dependency will be ready
  Dependency.add('gmap', [this, 'loadGmap']);
  Dependency.add('starrating', [this, 'loadStar']);

};


gourmetMap.prototype.refreshMap = function()
{
  log('refresh the map disabled : ', this.disable_refresh);
  
  if (this.disable_refresh)
  {
    
    return;
  }

  // step 1 : update value
  var point = this.map.getCenter();  
  this.settings.lat.val(point.lat());
  this.settings.lng.val(point.lng());
  this.settings.zoom.val(this.map.getZoom());

  // step 2 : save the settings
  this.saveStates(false);
  
  // step 3 : refresh points
  // 20090901 Cyrille: display loading indicator
  jQuery('h1.widget-header-title span.widget-loading-indicator', this.widget).addClass('widget-loading-indicator-display');

  var formSettings = jQuery('form[wuid=' + this.wuid + ']', this.widget).serializeArray();

  formSettings.push({'name':  'bounds', 'value': this.map.getBounds()});

  var link = Portal.linkToAction('gourmetMap', 'refreshMap', this.wuid, {});

  var widget = this;

  var ajax = jQuery.post(link, formSettings, function(data) {
    widget.map.clearOverlays();

    widget.data = data;
    widget.createListMappable();

    widget.disable_refresh = false;
    
    var size = null;

    for(var i in data) {
      var mappable = data[i];
      var latlng = new google.maps.LatLng(mappable.lat, mappable.lng);

      // Positionne le label selon le nombre de caractères
      if(mappable.pos < 10) {
        size = new GSize(1, -16);
      } else {
        size = new GSize(-2, -16);
      }

      var marker = new LabeledMarker(latlng, {
        icon: gourmetMap.icons[mappable.klass],
        title: mappable.main_type + " : " + mappable.name,
        labelText: "<strong style='color:white; font-size: 10px'>" + mappable.pos + "</strong>",
        labelOffset: size
      });

      marker.widget = widget;
      marker.id = i;
      google.maps.Event.bind(marker, 'click', marker, gourmetMap.handleClickMarker);

      widget.map.addOverlay(marker);
    }
  }, 'json');

  this.attachModalBox();
};

gourmetMap.prototype.createListMappable = function()
{
  // 2009-07-29 cyrillej
  var map_filters = jQuery("div.widget-map-filters", gourmetMap);
  
  var cpt = 0;
  var html = "";
  for(var i in this.data) {

    if(cpt > 2)
    {
      break;
    }

    var mappable = this.data[i];

    var photo = mappable.photos.length > 0 ? mappable.photos[0] : false;
    //2009-08-26 Cyrille (truncates name & address)
    var truncated_name = mappable.name.length > 16 ? mappable.name.substr(0,16) + '...': mappable.name;
    var compound_address = mappable.addr1 + ' - ' + mappable.postal_code + ' ' + mappable.city;
    compound_address = compound_address.length > 33 ? compound_address.substr(0,33) + '...': compound_address;
    var num_comments = mappable.num_comments <= 0 ? leave_comment_message : mappable.num_comments;
    var num_stars = mappable.note != null ? Math.round(mappable.note) : 0;

    var photo_path = '';
    var photo_alt  = '';
    
    if (photo)
    {
      photo_path = photo.path;
      photo_alt  = photo.alt;
    }
    else
    {
      photo_path = mappable.default_photo;
      photo_alt  = '';
    }

    html += ' <li class="result-' + cpt + '"> ';
    html += '     <div class="result-image"><a href="' + mappable.url + '" target="_parent"><img alt="' + photo_alt + '" src="' + photo_path + '" /></a></div>';
    html += '     <div class="result-type"><span>' + mappable.type + '</span></div>';
    html += '     <div class="result-marker marker-' + mappable.klass + '">';
    html += '       ' + mappable.pos;
    html += '     </div>'
    html += '     <div class="result-info">';
    html += '       <div class="result-name"><a href="' + mappable.url + '" target="_parent" title="' + mappable.name + '">' + truncated_name + '</a></div>';
    html += '       <div class="result-stars"><img alt="' + num_stars + '" src="/images/icons/stars_' + num_stars + '.gif" /></div>';
    html += '       <div class="result-address">' + compound_address + '</div>';
    html += '       <div class="result-comments"><a href="' + mappable.url + '#comments">' + num_comments + '</a></div>';
    html += '       <div class="clear"></div>';
    html += '     </div>';
    html += '     <div class="clear"></div>';
    html += '   </li>';

    cpt++;

  }

  jQuery('#list_' + this.wuid + '_mappables').html('<ul>' + html + '</ul>');
  
  // 20090901 Cyrille: reset loading indicator
  jQuery('#' + this.wuid + ' h1.widget-header-title span.widget-loading-indicator').removeClass('widget-loading-indicator-display');
};

/**
 * récupère le mouvement en pixels nécessaire pour que le marker cliqué soit en haut de sa fenêtre d'info
 *
 * @param google.maps.Marker marker
 * @author fabriceb
 * @since 2009-06-25
 */
gourmetMap.prototype.getDestinationPanBy = function(marker)
{
  // on récupère la position de la popup
  var dest_x = jQuery('.widget-map-popup', this.widget).css('left') + jQuery('.widget-map-popup', this.widget).css('width')/2;
  var dest_y = jQuery('.widget-map-popup', this.widget).css('top');

  // debug: comme la popup est détruite au moment du mouvement, voilà les valeurs par défaut
  dest_x = 147;
  dest_y = 62;

  var marker_pix = this.map.fromLatLngToContainerPixel(marker.getLatLng());
  var pan_x = dest_x - marker_pix.x;
  var pan_y = dest_y - marker_pix.y;
  var pan_size = new google.maps.Size(pan_x,pan_y);

  return pan_size;
}

/**
 * bouge la carte afin que le marker cliqué soit en haut de sa fenêtre d'info
 *
 * @param google.maps.Marker marker
 * @author fabriceb
 * @since 2009-06-25
 */
gourmetMap.prototype.moveMapAfterMarkerClick = function(marker)
{
  this.disable_refresh = true;
  this.map.panBy(this.getDestinationPanBy(marker));
}

// this = GMarker
gourmetMap.handleClickMarker = function(e)
{
  var widget = this.widget;
  var data = widget.data[this.id];
  var wuid = widget.wuid;

  widget.moveMapAfterMarkerClick(this);
  
  jQuery('#data_' + wuid + '_main_type', this.wuid).html('<span class="color-' + data.klass + '">' + data.main_type + '</span>');
  jQuery('#data_' + wuid + '_name', this.wuid).html('<a href="' + data.url + '" title="' + data.name + '">' + data.name + "</a>");
  jQuery('#data_' + wuid + '_address', this.wuid).html(data.address);
  jQuery('#data_' + wuid + '_telephone', this.wuid).html(data.telephone);
  jQuery('#data_' + wuid + '_note', this.wuid).html(Math.round(data.note));
  jQuery('#data_' + wuid + '_information', this.wuid).html(data.information);
  jQuery('#data_' + wuid + '_num_comments', this.wuid).html(data.num_comments);

  var comments = "";
  for(var i in data.comments) {
    var comment = data.comments[i];

    comments += "<div> Name : " + comment.name + "<br /> Message : " + comment.message + "</div>";
  }

  // show pictures
  var photo = data.photos.length > 0 ? data.photos[0] : false;
  
  // Mappable picture
  var photo_path = '';
  var photo_alt  = '';
  
  if (photo)
  {
    photo_path = photo.path;
    photo_alt  = photo.alt;
  }
  else
  {
    photo_path = data.default_photo;
    photo_alt  = '';
  }

  var html = '';
  var photos = '';
  if(photo_path)
  {
    html = "<img src='" + photo_path + "' alt='" +  photo_alt + "'/>";

    for(var i in data.photos) {
      var mappable_photo = data.photos[i];
      var mappable_photo_path = '';
      var mappable_photo_alt  = '';
      
      if (mappable_photo)
      {
        mappable_photo_path = photo.path;
        mappable_photo_alt  = photo.alt;
      }
      else
      {
        mappable_photo_path = data.default_photo;
        mappable_photo_alt  = '';
      }
      
      photos += "<img src='" + mappable_photo_path + "' alt='" +  mappable_photo_path + "' />";
    }

    jQuery('div.tab-pictures-available',  this.wuid).html(photos).show();
    jQuery('div.tab-pictures-not-available',  this.wuid).hide();
  }
  else
  {
    jQuery('div.tab-pictures-available',  this.wuid).hide().html(photos);
    jQuery('div.tab-pictures-not-available',  this.wuid).show();
  }


  /*var html = '';
  var photos = '';
  if(photo)
  {
    html = "<img src='" + photo.path + "' alt='" +  photo.alt + "'/>";

    for(var i in data.photos) {
      photos += "<img src='" + data.photos[i].path + "' alt='" +  data.photos[i].alt + "' />";
    }

    jQuery('div.tab-pictures-available',  this.wuid).html(photos).show();
    jQuery('div.tab-pictures-not-available',  this.wuid).hide();
  }
  else
  {
    jQuery('div.tab-pictures-available',  this.wuid).hide().html(photos);
    jQuery('div.tab-pictures-not-available',  this.wuid).show();
  }*/

  jQuery('#data_' + wuid + '_image', this.wuid).html(html);

  jQuery('#data_' + wuid + '_comments', this.wuid).html(comments);

  jQuery('#add_note_' + wuid + '_id', this.wuid).val(data.id);

  // stars
  jQuery('input.etoile', this.wuid).rating({
    callback: function(value, link){
      jQuery(this.form).trigger('submit');
    }
  }).rating('drain');

  // handle the note
  jQuery('div.mappable-stars', this.wuid)
    .attr('class', '')
    .attr('class', 'mappable-stars stars star-' + (Math.round(data.note) || 0))
    .html('&nbsp;' + (Math.round(data.note) || 0));

  // Position du label dans le marker de la popup selon la position
  if (data.pos < 10)
  {
    var popup_marker_class = "mappable-marker-small";
  }
  else
  {
    var popup_marker_class = "mappable-marker-large";
  }

  // handle the marker
  jQuery('div.mappable-marker', this.wuid)
    .attr('class', '')
    .attr('class', 'mappable-marker ' + popup_marker_class + ' flat-marker-' + data.klass)
    .html(data.pos);

  jQuery('label.star-label', this.wuid).hide();

  // comment
  jQuery('#add_comment_' + wuid + '_error').hide();
  jQuery('#add_comment_' + wuid + '_confirmation').hide();
  jQuery('form#add_comment_' + wuid + '_form').show();

  jQuery('textarea', 'form#add_comment_' + wuid + '_form').val('');

  jQuery('#add_comment_' + wuid + '_mappable_object_id').val(data.id);

  jQuery('div.widget-map-popup', widget.widget).show();

};

// this method is call when the DOM / window is loaded
gourmetMap.prototype.loadGmap = function()
{

  this.load();

  jQuery('div.widget-map-popup', this.widget).hide();

  if (GBrowserIsCompatible())
  {
    this.googleInitMarkers();

    this.geocoder = new GClientGeocoder();

    this.map = new google.maps.Map2(document.getElementById('map_' + this.wuid));
    this.centerMap();

    this.map.enableDoubleClickZoom();
    this.map.setUIToDefault();

//    return;
    google.maps.Event.bind(this.map, "moveend", this, this.refreshMap);
    
    this.googleInitMarkers();

    // load the data
    this.refreshMap();
  }

  this.attachModalBox();
};

gourmetMap.prototype.centerMap = function()
{
    this.map.setCenter(
      new google.maps.LatLng(this.settings.lat.val(), this.settings.lng.val()),
      parseInt(this.settings.zoom.val())
    );
}

gourmetMap.prototype.load = function()
{
  // add note action
  jQuery('form#add_note_' + this.wuid + '_form', this.widget).submit(function() {
    var form = jQuery(this);

    jQuery.ajax({
      type: 'GET',
      url: form.attr('action'),
      data: form.serialize()
    });

    return false;
  });

  // Cyrille: displays tabs
  /*jQuery("a.mappable-show-more-choices", this.widget).bind(
    'click',
    [this, 'onClickMoreChoices']
  );*/

  // display comment form
  jQuery("a.mappable-show-comment-form", this.widget).bind(
    'click',
    [this, 'onClickShowCommentForm']
  );

  // add comment action
  jQuery('form#add_comment_' + this.wuid + '_form', this.widget).submit(function() {
    var form = jQuery(this);

    jQuery.ajax({
      type: 'GET',
      dataType: 'json',
      url: form.attr('action'),
      data: form.serialize(),
      wuid:  form.mgWidgetContainer().attr('id'),
      success: function(data, textStatus) {
        if(data.hasErrors) {
          jQuery('#add_comment_' + this.wuid + '_error').show();
          jQuery('#add_comment_' + this.wuid + '_confirmation').hide();

          for(var field in data.errors)
          {
            var error = data.errors[field];
            var id = '#add_comment_' + this.wuid + '_' + field;

            jQuery(id).addClass('error');
          }
        } else {
          jQuery('#add_comment_' + this.wuid + '_confirmation').show();
          jQuery('form#add_comment_' + this.wuid + '_form').hide();
          jQuery('#add_comment_' + this.wuid + '_error').hide();
        }
      }
    });

    return false;
  });

  jQuery('div.widget-map-popup-close', this.widget)
    .click(function() {
      var wuid = jQuery(this).mgWidgetContainer().attr('id');
      jQuery('div.widget-map-popup', '#' + wuid).hide();
    })
    .mouseover(function() {
      jQuery(this).addClass('widget-map-popup-close-hover')
    })
    .mouseout(function() {
      jQuery(this).removeClass('widget-map-popup-close-hover')
    });


  this.inputs.btn_submit_2c.bind(
    'click', 
    [this, 'bindFormSubmit']
  );

  this.inputs.btn_submit_1c.bind(
    'click', 
    [this, 'bindFormSubmit']
  );

  this.inputs.where.bind(
    'keyup',
    [this, 'bindWhereChange']
  );

  this.inputs.search.bind(
    'keyup',
    [this, 'bindSearchChange']
  );

  this.inputs.category.bind(
    'change',
    [this, 'bindCategoryChange']
  );
  
  this.inputs.category_1c.bind(
    'change',
    [this, 'bindCategoryChange1c']
  );

  // create tabs
  jQuery('li.widget-map-tabs', this.widget).tabs();
};

gourmetMap.prototype.bindFormSubmit = function(event)
{
//  this.settings.where.val(this.inputs.where.val());
//  this.settings.category.val(this.inputs.category.val());
//  this.settings.search.val(this.inputs.search.val());
//
//  this.refreshMap();
  var widget = this;
  this.geocoder.getLatLng(this.settings.where.val(), function(point)
  {
    widget.map.setCenter(point, parseInt(widget.settings.zoom.val()));
    widget.refreshMap();
  });
  
  event.preventDefault();

};

gourmetMap.prototype.bindSearchChange = function(event)
{
  if(event.keyCode == 13)
  {
    
    var widget = this;
    this.geocoder.getLatLng(this.settings.where.val(), function(point)
    {
      widget.map.setCenter(point, parseInt(widget.settings.zoom.val()));
      widget.refreshMap();
    });
    
    return;
  }

  this.settings.search.val(this.inputs.search.val());
};

gourmetMap.prototype.bindCategoryChange = function(event)
{
  
  this.settings.category.val(this.inputs.category.val());
  
  this.refreshMap();
};

gourmetMap.prototype.bindCategoryChange1c = function(event)
{
  this.settings.category.val(this.inputs.category_1c.val());

  this.refreshMap();
};

gourmetMap.prototype.bindWhereChange = function(event)
{
  event.preventDefault();
  event.stopPropagation();

  if(event.keyCode == 13)
  {    
    var widget = this;
    this.geocoder.getLatLng(this.settings.where.val(), function(point)
    {
      widget.map.setCenter(point, parseInt(widget.settings.zoom.val()));
      widget.refreshMap();
    });

    return;
  }

  this.settings.where.val(this.inputs.where.val());
};

gourmetMap.prototype.loadStarRating = function()
{

};

gourmetMap.prototype.attachModalBox = function()
{
  jQuery('a.nyroModal', this.widget).nyroModal({
      modal: false,
      width: 900,
      height: 450,
      resizeable: true
  });
};

gourmetMap.prototype.googleInit = function()
{

};

gourmetMap.prototype.unload = function()
{
  // place here all code to unbind event
  // always use jQuery's namespace event
  jQuery(window).unbind('load.gourmetMap', [this, 'load']);
  this.load = function() {}; // make sure the metthod is not exececuted
  //google.Unload();
  //jQuery(window).unbind('click.gourmetMap', [this, 'onClickButton']);
  //this.onClickButton = function() {};
};

gourmetMap.prototype.onClickButton = function()
{
  // catch your on click button
};

gourmetMap.prototype.onClickMoreChoices = function()
{

  jQuery('li.choice-icon', this.widget).toggleClass("choice-icon-selected");
  jQuery("div.rounded-bottom-corners", this.widget).toggleClass("white-corners");
  jQuery("li.widget-map-tabs", this.widget).toggle();

  return false;
}

gourmetMap.prototype.onClickShowCommentForm = function()
{
  jQuery('li.comment-icon', this.widget).toggleClass("comment-icon-selected");
  jQuery('li.comment-icon a.mappable-show-comment-form', this.widget).next().toggle();

  return false;
}

gourmetMap.icons = false;

gourmetMap.prototype.googleInitMarkers = function()
{

  if(gourmetMap.icons)
  {
    return;
  }

  var icons = {
    restaurant: {
      image: WIDGET_BASE_MEDIA_URL + "/gourmet_map/images/small_marker_restaurant.png"
    },
    other: {
      image: WIDGET_BASE_MEDIA_URL + "/gourmet_map/images/small_marker_organization_school_other.png"
    },
    none: {
      image: WIDGET_BASE_MEDIA_URL + "/gourmet_map/images/small_marker_organization_school_other.png"
    },
    club: {
      image: WIDGET_BASE_MEDIA_URL + "/gourmet_map/images/small_marker_club.png"
    },
    event: {
      image: WIDGET_BASE_MEDIA_URL + "/gourmet_map/images/small_marker_event.png"
    },
    school: {
      image: WIDGET_BASE_MEDIA_URL + "/gourmet_map/images/small_marker_organization_school_other.png"
    },
    organization: {
      image: WIDGET_BASE_MEDIA_URL + "/gourmet_map/images/small_marker_organization.png"
    },
    organisation: {
      image: WIDGET_BASE_MEDIA_URL + "/gourmet_map/images/small_marker_organization_school_other.png"
    },
    market: {
      image: WIDGET_BASE_MEDIA_URL + "/gourmet_map/images/small_marker_market.png"
    },
    supplier: {
      image: WIDGET_BASE_MEDIA_URL + "/gourmet_map/images/small_marker_supplier_producer.png"
    },
    producer: {
      image: WIDGET_BASE_MEDIA_URL + "/gourmet_map/images/small_marker_supplier_producer.png"
    }
  };

  gourmetMap.icons = {};

  for(var name in icons)
  {
    gourmetMap.icons[name] = new google.maps.Icon();
    gourmetMap.icons[name].image = icons[name].image;
    gourmetMap.icons[name].iconSize = new google.maps.Size(28,32);
    //gourmetMap.icons[name].iconSize = new google.maps.Size(22,26);
    gourmetMap.icons[name].iconAnchor = new google.maps.Point(8,22);
    gourmetMap.icons[name].infoWindowAnchor = new google.maps.Point(6,3);
    gourmetMap.icons[name].shadow = "";
    gourmetMap.icons[name].shadowSize = new google.maps.Size(22,20);
  }
};

// set javascript for this widget as loaded
WIDGET_LOADED['gourmetMap'] = true;

