//
if(window.GMap){//ONLY IF GMap is defined
//

//var agmap; // Instance holder
var AGMap = Class.create();
AGMap.getInstance = function(){ return AGMap.INSTANCE; }; // Singleton Pattern
AGMap.getMap = function(){ return AGMap.MAP; }; // Singleton Pattern

Object.extend(AGMap.prototype, {
  initialize: function(){    
    var options = Object.extend({
      zoom: 16,
      center: new GLatLng(43.4516727225261,-8.13194274902344),
      locked: false,
      mapOptions: {draggableCursror:'default'},
      interactive: false,
      interactiveOptions: {},
      viewScale: false,
      restorable: true,
      containerId: 'agmap',
      satellite: true
    }, arguments[0] || {});
    
    this.container = $(options.containerId);
    this.container.setStyle({background: 'none'});
    this.map = new GMap2(this.container, options.mapOptions);
    if(!options.satellite){ this.map.addControl(new GMapTypeControl()); }
    
    AGMap.MAP = this.map;
    AGMap.INSTANCE = this;
    
    this.map.setCenter(options.center, options.zoom);
    this.map.disableDoubleClickZoom();
    this.restore = false;
    
    if(options.locked){ this.map.disableDragging(); }
    else { this.map.addControl(new GSmallZoomControl()); }
    if(options.viewScale){ this.map.addControl(new GScaleControl()); }
    if(options.restorable && !options.viewScale){
      this.restore = new AGMap.RestoreMap();
      this.map.addControl(this.restore);
    }
    if(options.satellite){ this.map.setMapType(G_SATELLITE_MAP); }
    
    
    // TOOLTIP
    this.tooltip = new AGMap.Tooltip();
    this.map.addControl(this.tooltip);
    GEvent.bind(this.map,'dragstart', this.tooltip, this.tooltip.disable);
    GEvent.bind(this.map,'dragend', this.tooltip, this.tooltip.enable);
    
    // LOADER
    // this.loader = new AGMap.LoaderControl();
    // this.map.addControl(this.loader);
    // GEvent.bind(this.map,'movestart',this.loader,this.loader.show);
    // GEvent.bind(this.map,'moveend',this.loader,this.loader.hide);
    
    // ICONS
    this.icons = [];
    this.icons['default'] = new AGMap.Icon('default');
    this.icons['blue'] = new AGMap.Icon('blue');
    this.icons['green'] = new AGMap.Icon('green');
    this.icons['red'] = new AGMap.Icon('red');
    this.icons['yellow'] = new AGMap.Icon('yellow');
    
    // INTERACTIVE
    if(options.interactive){
      GEvent.bind(this.map, 'click',this, function(overlay, latlng){
        if(latlng){
          if(options.interactiveOptions.unique && this.unique){
            this.unique.setLatLng(latlng);
            if(options.interactiveOptions.updateFields){ this.unique.updateFields(); }
          } else {
            this.addOverlay(new AGMap.Marker(latlng, { 
              draggable: options.interactiveOptions.draggable,
              unique: options.interactiveOptions.unique,
              updateFields: options.interactiveOptions.updateFields,
              restoreMarker: options.restorable
            }));
          }
          this.unique.centerRestoreControl(latlng);
        }
      });
    }
  },
  addOverlay: function(overlay){
    overlay.map = this;
    if(overlay.unique){ this.unique = overlay; }
    this.map.addOverlay(overlay);
    return overlay;
  },
  getIcon: function(name){ return this.icons[name]; },
  getRestoreControl: function(){ return this.restore; }
});

Object.extend(GMarker.prototype, {
  tooltipDisabled: false,
  openTooltip: function(){
    if(!this.tooltipDisabled) this.map.tooltip.show(this);
  },
  closeTooltip: function(){ this.map.tooltip.hide(); },
  updatePrefix: '',
  updateFields: function(){
    if(this.updatePrefix){
      if($(this.updatePrefix + '_latitude')){ $(this.updatePrefix + '_latitude').value = this.getLatLng().lat(); }
      if($(this.updatePrefix + '_lonxitude')){ $(this.updatePrefix + '_lonxitude').value = this.getLatLng().lng(); }
    }
  },
  bindTo: function(bind){
    this.bind = bind;
    GEvent.addListener(this,'dragend',function(){ this.bind.redraw(true); });
  },
  centerRestoreControl:function(){
    this.map.getRestoreControl().setOCenter(this.getLatLng());
  }
});

AGMap.Marker = function(latlng){
  var options = Object.extend({
    iconName: false,
    tooltip: false,
    windowContent: false,
    removable: false,
    draggable: false,
    updateFields: false,
    unique: false,
    bind: false,
    title: false,
    restoreMarker: false
  }, arguments[1] || {});
  var markerOptions = new Object();
  
  if(options.iconName){ markerOptions.icon = AGMap.getInstance().getIcon(options.iconName); }
  else{ markerOptions.icon = AGMap.getInstance().getIcon('default'); }
  if(options.draggable){ Object.extend(markerOptions,{draggable: true, dragCrossMove: true, bouncy: true, bounceGravity: 4}); }
  if(options.tooltip){ markerOptions.title = options.tooltip; }
  if(options.title){ markerOptions.title = options.title; }
  marker = new GMarker(latlng, markerOptions);
  
  // Provoca un fallo en IE cuando se llama a openInfoWindowHTML
  //if(options.tooltip){
    //marker.tooltip = options.tooltip;
    //GEvent.addListener(marker, 'mouseover', marker.openTooltip);
    //GEvent.addListener(marker, 'mouseout', marker.closeTooltip);
    //GEvent.addListener(marker, 'click', marker.closeTooltip);
    //if(options.draggable){ GEvent.addListener(marker, 'dragstart', marker.closeTooltip); }
    //GEvent.addListener(marker, 'infowindowopen', function(){this.tooltipDisabled = true;});
    //GEvent.addListener(marker, 'infowindowclose', function(){this.tooltipDisabled = false;});
  //}
  if(options.windowContent){
    marker.windowContent = options.windowContent;
    GEvent.addListener(marker, 'click', function(){
      this.openInfoWindowHtml(this.windowContent);
    });
  }
  if(options.removable){ 
    GEvent.addListener(marker, 'dblclick', function(){ 
      this.map.removeOverlay(this);
    });
  }
  if(options.draggable && options.updateFields) GEvent.addListener(marker, 'dragend', marker.updateFields);
  if(options.updateFields){
    marker.updatePrefix = options.updateFields;
    marker.updateFields();
  }
  if(options.restoreMarker){
    marker.restoreMarker = true;
    GEvent.addListener(marker, 'dragend', function(){
      this.centerRestoreControl();
    });
  }
  marker.unique = options.unique;
  if(options.bind){ marker.bindTo(options.bind); }
  return marker;
};

AGMap.Icon = Class.create();
Object.extend(Object.extend(AGMap.Icon.prototype, GIcon.prototype),{
  initialize: function(name){
    this.image = '/images/icon_'+name+'.png';
    this.shadow = "/images/icon_shadow.png";
    this.iconSize = new GSize(19, 45);
    this.shadowSize = new GSize(32, 45);
    this.iconAnchor = new GPoint(9, 42);
    this.infoWindowAnchor = new GPoint(9, 8);
    this.infoShadowAnchor = new GPoint(36, 34);
  }
});

AGMap.Tooltip = function(){};
Object.extend(Object.extend(AGMap.Tooltip.prototype, GControl.prototype), {
  initialize: function(map){
    this.container = $(document.createElement('div'));
    this.message = $(document.createElement('div'));
    //this.shadowBottom = $(document.createElement('div'));
    //this.shadowRight = $(document.createElement('div'));
    this.message.addClassName('msg');
    //this.shadowBottom.addClassName('shadow');
    //this.shadowRight.addClassName('shadow');
    //this.shadowBottom.setStyle({height: '3px', position: 'absolute', left: '6px', bottom: 0, opacity: 0.5});
    //this.shadowRight.setStyle({width: '3px', position: 'absolute', right: 0, top: '6px', opacity: 0.5});
    this.container.addClassName('tooltip');
    //this.container.appendChild(this.shadowBottom);
    //this.container.appendChild(this.shadowRight);
    this.container.appendChild(this.message);
    map.getContainer().appendChild(this.container);
    //this.container.setStyle({padding: '3px'});
    this.container.hide();
    this.map = map;
    this.disabled = false;
    return this.container;
  },
  show: function(marker){
    if(this.disabled) return false;
    this.message.update(marker.tooltip);
    point = this.map.getCurrentMapType().getProjection().fromLatLngToPixel(this.map.getBounds().getSouthWest(),this.map.getZoom());
    offset = this.map.getCurrentMapType().getProjection().fromLatLngToPixel(marker.getPoint(),this.map.getZoom());
    anchor = marker.getIcon().iconAnchor;
    width = marker.getIcon().iconSize.width;
    pos = new GControlPosition(G_ANCHOR_BOTTOM_LEFT, new GSize(offset.x - point.x - anchor.x + width,- offset.y + point.y +anchor.y)); 
    pos.apply(this.container);
    //dimensions = this.container.getDimensions();
    //this.shadowBottom.setStyle({width: (dimensions.width-6)+'px'});
    //this.shadowRight.setStyle({height: (dimensions.height-9)+'px'});
    this.container.show();
  },
  hide: function(){
    this.container.hide();
  },
  disable: function(){
    this.disabled = true;
  },
  enable: function(){
    this.disabled = false;
  },
  getDefaultPosition: function(){
    return new GControlPosition(G_ANCHOR_BOTTOM_LEFT, new GSize(1,1));
  }
});

AGMap.Drawer = function(points){
  points.pop();
  this.points = points;
};

Object.extend(Object.extend(AGMap.Drawer.prototype, GOverlay.prototype),{
  initialize: function(map){
    this.markers = [];
    this.markerCount = 0;
    
    var bind = this;
    var markerCount = this.markerCount;
    
    this.points.each(function(p){
      bind.addMarker(new AGMap.Marker(p,{draggable: true, bind: bind, removable: true, title: bind.size()+1}) );
    });
    
    this.polyline = new GPolyline(this.computePoints());
    
    map.drawer = this;
    this.map = map;
    
    GEvent.addListener(map,'click',function(overlay,latlng){ if(latlng) this.drawer.addPoint(latlng);});
  },
  copy: function(){},
  remove: function(){},
  redraw: function(force){
    if(!force) return;
    this.map.removeOverlay(this.polyline);
    this.polyline = new GPolyline(this.computePoints());
    this.map.addOverlay(this.polyline);
    if($('point_collector')){
      markers = this.computePoints();
      markers.pop();
      $('point_collector').value = '[' + markers.join(',').gsub(/\(/,'[').gsub(/\)/,']') + ']';
    }
  },
  computePoints: function(){
    markers = this.markers.collect(function(m){ return m.getLatLng(); });
    markers.push(this.markers[0].getLatLng());
    return markers;
  },
  addPoint: function(point){
    var limit = this.markerCount + 1;
    var pos = prompt('Posición del nuevo marcador',limit);
    if(pos != 0 && !pos) return;
    if(pos > limit) pos = limit;
    if(pos < 1) pos = 1;
    
    marker = new AGMap.Marker(point,{draggable: true, bind: this, title: pos});
    this.map.addOverlay(marker);
    this.markerCount++;
    
    parts = this.markers.partition(function(m){
      return pos > Number(m.getTitle());
    });
    var markers = [].concat(parts[0]).compact();
    var bind = this;
    markers.push(marker);
    subs = parts[1].collect(function(m){
      newPos = Number(m.getTitle()) + 1;
      bind.map.removeOverlay(m);
      marker = new AGMap.Marker(m.getLatLng(),{draggable: true, bind: bind, removable: true, title: newPos});
      bind.map.addOverlay(marker);
      return marker;
    });
    markers = markers.concat(subs).compact();
    this.markers = markers;
    this.redraw(true);
  },
  addMarker: function(marker){
    this.markers.push(marker);
    this.markerCount++;
    this.map.addOverlay(marker);
  },
  size: function(){
    return this.markerCount;
  }
});

AGMap.RestoreMap = function(){};
Object.extend(Object.extend(AGMap.RestoreMap.prototype, GControl.prototype), {
  initialize: function(map){
    this.container = $(document.createElement('div'));
    this.container.update('<img src="/images/center.gif" alt="Restaurar mapa" title="Restaurar mapa"/>');
    this.container.down().setStyle({padding:0, border:0, cursor: 'pointer'});
    this.map = map;
    this.ocenter = map.getCenter();
    this.ozoom = map.getZoom();
    map.getContainer().appendChild(this.container);
    GEvent.bindDom(this.container, 'click', this, function(){
      this.map.setCenter(this.ocenter,this.ozoom);
    });
    return this.container;
  },
  getDefaultPosition: function(){
    return new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(7, 42));
  },
  setOCenter: function(center){
    this.ocenter = center;
    this.ozoom = this.map.getZoom();
  }
});


//
}// END block of if(window.GMap)
//

Event.behold({
  '.imgre:click': function(ev){
    $('imxprev').down().down().writeAttribute('src', this.readAttribute('rel'));
    $('imxprev').down().writeAttribute('href', this.readAttribute('href'));
    ev.stop();
  }
});