if (!('indexOf' in Array.prototype)) {
    Array.prototype.indexOf= function(find, i /*opt*/) 
    {
      if (i===undefined) i= 0;
      if (i<0) i+= this.length;
      if (i<0) i= 0;
      for (var n= this.length; i<n; i++)
        if (i in this && this[i]===find)
          return i;
      return -1;
    };
}
var imgBaseUrl = "/images/markers/";

function FonTile(tileSize, tilesUrl)
{
  this.tileSize = tileSize;
  this.tilesUrl = tilesUrl;
}

function issetTid(icons, router){
  return(typeof(icons[router]) ? icons[router] : 'fon_spots/01fon.png');
}

function issetBid(icons, router){
  return(typeof(icons[router]) ? icons[router] : '');
}

function infowindowContent(partner, width, margin_right)
{
  infowindow = "<div style='width:250px; height:90px; overflow-y:auto;'>" +
    "<div style='width: 160px;'>" +
    "<p style='font-size: 12px;'>%ADDRESS%%STREETNUMBER%</p>" +
    "</div>"
    if(partner != 'belga')
    {
      infowindow = infowindow + "<div style='width: 160px;'>" +
      "<p style='font-size: 12px;'>%POSTALCODE%, %LOCALITY%</p>" +
      "</div>"
    }
    infowindow = infowindow + "<div style='float: right; margin-top: 4px; margin-left: 2px;position:absolute;bottom:0;right:0;'>" +
    "<img width="+width+" style='float: right; margin-top: 5px; margin-right:"+margin_right+";' src='/images/%IMAGE%'>" +
    "</div>" +
    "</div>"
  return infowindow;
}

function infowindowContentBusiness(width, margin_right)
{
  return "<div style='width:250px; height:90px; overflow-y:auto;'>" +
    "<div style='padding-bottom: 8px; padding-top: -2px;position:absolute;top:0;right:0;'>" +
    "<img width='66px' style='float: right; margin-right: 19px;' src='/images/%IMAGETIPO%'>" +
    "</div>" +
    "<div style='float: right; margin-top: 4px; margin-left: 2px;position:absolute;bottom:0;right:0;'>" +
    "<img width="+width+" style ='float: right; margin-top: 5px; margin-right:"+margin_right+";' src='/images/%IMAGE%'>" +
    "</div>" +
    "<div style='width: 160px;'>" +
    "<p style='font-size: 12px;'>%ADDRESS%%STREETNUMBER%</p>" +
    "</div>" +
    "<div style='width: 160px;'>" +
    "<p style='font-size: 12px;'>%POSTALCODE%, %LOCALITY%</p>" +
    "</div>" +
    "<div style='width: 160px;'>" +
    "<a style='font-size: 12px; color:blue;' target='_blank' href='%URLHREF%';>%URL%</a>" +
    "</div>" +
    "</div>"
}

FonTile.prototype.maxZoom = 15;
FonTile.prototype.getTile = function(coord, zoom, ownerDocument)
{
  if (coord.x < 0 || coord.y < 0 || zoom > FonTile.prototype.maxZoom)
    return ownerDocument.createElement('span');
  
  var img = ownerDocument.createElement('img');
  if (img.addEventListener) 
  {
    img.addEventListener('error', function() {
      this.style.display = 'none'
    }, true);
  }
  else 
  {
    img.attachEvent('error', function() {
      this.style.display = 'none'
    });
  }
  img.src = this.tilesUrl + '/getTile.php?x='+coord.x+'&y='+coord.y+'&z='+zoom;

  return img;
};

(function($)
{
  if (typeof google == "undefined" || typeof google.maps == "undefined")
  {
    alert("You need to load Google Maps API v3 before using FONMaps.\nhttp://code.google.com/apis/maps/documentation/javascript/");
    return;
  }

  $.extend ({
    fonMap: new function()
    {
      this.defaults = {
        tilesUrl: '',
        centerLat: 0,
        centerLon: 0,
        mapTypeId: 0,
        safeMaxLat: 0,
        safeMinLat: 0,
        safeMinLng: 0,
        safeMaxLng: 0,
        geocodeZoom: 16,
        geocodeZoomInicio: 6,
        markers: [],
        markersIdx: [],
        activeMarker: null,
        markerActive: [],
        BtFon: 11,
        BelgaFon: 6,
        zoom: 2,
        status: 0,
        loading: "#loadingNodes",
        debug: false,
        infowindow: new google.maps.InfoWindow()
      };
      
      this.setActiveMarker = function(markerId)
      {
        var divmap = this;
        var infowindow = divmap.config.infowindow;
        var markers = divmap.config.markers;
        var markersIdx = divmap.config.markersIdx;
        
        if (this.config.activeMarker != null)
        {
          infowindow.close();
        }
        
        var idx = markersIdx[markerId];
        var marker = markers[idx];
        //var marker = markers[markerId];
        if (! marker || typeof marker == "undefined")
        {
          return;
        }
        divmap.config.activeMarker = markerId;
        marker.setIcon(imgBaseUrl + marker.activeImage);
        divmap.timer = setTimeout(function() {
          $(divmap.config.loading).show()
        }, 2000);
        geocoder = new google.maps.Geocoder();
        var latlng = new google.maps.LatLng(marker.getPosition().lat(), marker.getPosition().lng());
        
        if(marker.tid == divmap.config.BtFon)
        {
          content_bt = infowindowContent('bt', '66px', '19px')
          content_bt = content_bt.replace("%ADDRESS%", 'There are ' + marker.nob + ' hotspots in this area');
          content_bt = content_bt.replace("%STREETNUMBER%", '');
          content_bt = content_bt.replace("%POSTALCODE%", '(postal code: ' + markers[idx].id + ')');
          content_bt = content_bt.replace("%LOCALITY%", '');
          content_bt = content_bt.replace("%IMAGE%", 'logos_partners/partner_bt.png');
          infowindow.setContent(content_bt);
          
          clearTimeout(divmap.timer);
          infowindow.open(divmap.map, marker);
          $(divmap.config.loading).hide();
          hide_stuff();
        }else
        {
          geocoder.geocode( {
            'location': latlng
          },
          function(results, status)
          {
            /* TODO: Check status*/
            result = results[0];
            address = '';
            street_number = '';
            postal_code = '';
            locality = '';
            $.each(result.address_components,
              function(index, value)
              {
                if (value.types.indexOf('street_number') != -1)
                {
                  street_number = ', '+value.long_name;
                } 
                if (value.types.indexOf('route') != -1)
                {
                  address = value.long_name;
                }
                if (value.types.indexOf('locality') != -1)
                {
                  locality = value.long_name;
                }
                if (value.types.indexOf('postal_code') != -1)
                {
                  postal_code = value.long_name;
                }
              }
              );
            if (address == '')
            {
              address = result.formatted_address;
            }
            if (!street_number || street_number == null || street_number == '' )
            {
              street_number = '';
            }
            //en softbank (10) ponemos el de fon hasta que softbank nos de uno propio
            //checks the type of partner
            icons = new Array();
            icons.options = {4:"fon_spots/01fon.png", 5:"logos_partners/partner_zon.png", 6:"logos_partners/partner_belgacom.png", 7:"logos_partners/partner_netia.gif", 8:"logos_partners/partner_oi.png", 10:"fon_spots/01fon.png", 12:"logos_partners/partner_mtc.png"};
            
            logo = issetTid(icons.options, marker.tid);
            
            //added icons for bussiness partners            
            icons = new Array();
            icons.options = {2:"business/business_cafe.png", 3:"business/business_restaurant.png", 4:"business/business_hotel.png", 5:"business/business_shop.png"};
            
            icon = issetBid(icons.options, marker.bid);
            
            if(marker.bid!=1){
              var url = marker.url;
              var markerUrl = marker.url;
              
              if(!markerUrl)
              {
                markerUrl='';
                url='';
              }
              else
              {
                var result = url.substring(-2, 7);
                if (result != 'http://')
                {
                  markerUrl = "http://".concat(marker.url);
                }
                
                if (url.length > 27)
                {
                  url = url.substring(0, 25);
                  url = url.concat("...");
                }
              }
              //en softbank (10) ponemos el de fon hasta que softbank nos de uno propio
              icons = new Array();
              icons.options = {4: infowindowContentBusiness('66px', '19px'), 5:infowindowContentBusiness('66px', '19px'), 7:infowindowContentBusiness('138px', '25px'), 8:infowindowContentBusiness('66px', '19px'), 10:infowindowContentBusiness('66px', '19px'), 12:infowindowContentBusiness('120px', '9px')};

              infowindow_content = issetTid(icons.options, marker.tid);
              
              infowindow_content = infowindow_content.replace("%IMAGETIPO%", icon);
              infowindow_content = infowindow_content.replace("%ADDRESS%", address);
              infowindow_content = infowindow_content.replace("%STREETNUMBER%", street_number);
              infowindow_content = infowindow_content.replace("%POSTALCODE%", postal_code);
              infowindow_content = infowindow_content.replace("%LOCALITY%", locality);
              infowindow_content = infowindow_content.replace("%URLHREF%", markerUrl);
              infowindow_content = infowindow_content.replace("%URL%", url);
              infowindow_content = infowindow_content.replace("%IMAGE%", logo);
            }
            else
            {
              //en softbank (10) ponemos el de fon hasta que softbank nos de uno propio
              icons = new Array();
              icons.options = {4:infowindowContent('fon', '66px', '19px'), 5:infowindowContent('zon', '66px', '19px'), 6:infowindowContent('belga', '120px', '9px'), 7:infowindowContent('netia', '138px', '25px'), 8:infowindowContent('oi', '66px', '19px'), 10:infowindowContent('sofbank', '66px', '19px'), 12:infowindowContent('mtc', '120px', '9px')};

              infowindow_content = issetTid(icons.options, marker.tid);
              
              if(marker.tid != divmap.config.BelgaFon)
              {
                infowindow_content = infowindow_content.replace("%ADDRESS%", address);
                infowindow_content = infowindow_content.replace("%STREETNUMBER%", street_number);
                infowindow_content = infowindow_content.replace("%POSTALCODE%", postal_code);
                infowindow_content = infowindow_content.replace("%LOCALITY%", locality);
                infowindow_content = infowindow_content.replace("%IMAGE%", logo);
              }
              else
              {
                infowindow_content = infowindow_content.replace("%ADDRESS%", 'Belgacom Fon Hotspots in the area of ' + postal_code + ' ' + locality);
                infowindow_content = infowindow_content.replace("%STREETNUMBER%", '');
                infowindow_content = infowindow_content.replace("%IMAGE%", logo);
              }
            }
            
            infowindow.setContent(infowindow_content);
            
            clearTimeout(divmap.timer);
            infowindow.open(divmap.map, marker);
            $(divmap.config.loading).hide();
            hide_stuff();
          });
        }
      }
      
      this.addMarker = function(marker)
      {
        var divmap = this;
        markers = this.config.markers;
        var infowindow = divmap.config.infowindow;
        /*if (markers.length >= 200)
        {
          return;
        }*/
        
        $.extend(marker,
          new google.maps.Marker(
          {
            position: new google.maps.LatLng(marker.lat, marker.lon),
            flat: true
          }),
          {
            activeImage: marker.image,
            circle: null,
            fonid: "id"+marker.id.toString()
          }
        );
        
        google.maps.event.addListener(
          marker,
          "click",
          function()
          {
            divmap.setActiveMarker(this.fonid);
          }
        );
        
        google.maps.event.addListener(
          this.config.infowindow,
          "closeclick",
          function()
          {
            infowindow.close();
            divmap.config.activeMarker = null;
          }
        );
          
        marker.setIcon(imgBaseUrl + marker.image);
        marker.setMap(this.map);
        
        //this.config.markers[marker.fonid] = marker;
        this.config.markersIdx[marker.fonid] = this.config.markers.length;
        this.config.markers.push(marker);
      };
      
      this.removeMarker = function(markerId)
      {
        if (markerId == null)
        {
          return;
        }
        
        markers = this.config.markers;
        if (this.config.activeMarker == markerId)
        {
          infowindow.close();
        }
        
        if (markers[markerId] && typeof markers[markerId] != "undefined")
        {
          markers[markerId].setMap(null);
          markers[markerId] = null;
        }
      };
      
      this.cleanMarkers = function ()
      {
        var divmap = this;
        active = divmap.config.activeMarker;
        markers = this.config.markers;
//        this.config.infowindow.close();
//        this.config.activeMarker = null;
        
        for (var i=0; i<markers.length; i++) {
          markers[i].setMap(null);
        }
        
        this.config.markers = Array();
        this.config.markersIdx = Array();
      };
      
      this.refreshMarkers = function(forceRefresh)
      {
        hide_stuff();
        return this.each(function()
        {
          var zoom = this.map.getZoom();
          if (zoom < 16)
          {
            this.cleanMarkers();
            $(this.config.loading).hide();
            $("#not_found_marker").hide();
            return;
          }
          
          var bounds = this.map.getBounds();
          if (bounds.isEmpty())
          {
            return;
          }
          
          var swLat= bounds.getSouthWest().lat();
          var swLng = bounds.getSouthWest().lng();
          var neLat = bounds.getNorthEast().lat();
          var neLng = bounds.getNorthEast().lng();
          var filters = 4095;//FONMaps.filters;
          var status = 1;//this.status;
          var center = this.map.getCenter();
          var centerLat = center.lat();
          var centerLng = center.lng();
          
          if (forceRefresh || centerLat > this.safeMaxLat || centerLat < this.safeMinLat || centerLng > this.safeMaxLng || centerLng < this.safeMinLng) {
            var divmap = this;
            divmap.timer = setTimeout(function() {
              $(divmap.config.loading).show()
            }, 2000);
            $.getJSON("/ajax/getNodes",
            {
              swLat: swLat,
              swLng: swLng,
              neLat: neLat,
              neLng: neLng,
              zoom: zoom,
              forceRefresh: forceRefresh ? 1 : 0,
              filters: filters,
              status: status
            },
            function (actions)
            {
              if (actions.add[0])
              {
                $("#not_found_marker").hide();
                clearTimeout(divmap.timer);

                divmap.safeMinLat = actions.safe[0];
                divmap.safeMaxLat = actions.safe[1];
                divmap.safeMinLng = actions.safe[2];
                divmap.safeMaxLng = actions.safe[3];
                if (actions.clean)
                {
                  divmap.cleanMarkers();
                }

                $(actions.rem).each(function()
                {
                  divmap.removeMarker("id"+this)
                });
                $(actions.add).each(function()
                {
                  divmap.addMarker(this)
                });
                if (divmap.config.activeMarker)
                {
                  divmap.setActiveMarker(divmap.config.activeMarker);
                }
                $(divmap.config.loading).hide();
              }
              else
              {
                $("#not_found_marker").show();
                clearTimeout(divmap.timer);
              }
            }
            );
          }
        });
      };
      
      this.getMap = function()
      {
        var maps = Array()
        this.each(function()
        {
          maps.push(this.map);
        });
        
        return maps;
      };
      
      this.getMarkers = function()
      {
        var markers = Array()
        this.each(function()
        {
          markers.push(this.config.markers);
        });
        markers.push(this.config.markerActive);
        return markers;
      };
      
      this.moveMap = function(directions)
      {
        return this.each(function()
        {
          var center = this.map.getCenter();
          directions = $.extend(
          {
            zoom : this.map.getZoom(),
            lat  : center.lat(),
            lng  : center.lng()
          },
          directions);
          
          this.map.setZoom(directions.zoom);
          var newcenter = new google.maps.LatLng(directions.lat, directions.lng);
          this.map.setCenter(newcenter);
        });
      };
      
      this.geocode = function(address, callback, callback_data)
      {
        return this.each(function()
        {
          if (address == "")
          {
            return;
          }
          var geocoder = new google.maps.Geocoder();
          
          var divmap = this;
          geocoder.geocode(
          {
            address: address
          },
          function(results, status)
          {
            if (results.length == 0)
            {
              $("#error").show();
              $("#not_found_marker").hide();
              divmap.cleanMarkers();
              return;
            }
            $("#error").hide();
            if (callback)
            {
              callback(divmap, results, callback_data);
            }
            else
            {
              if(divmap.config.status == 0){
                divmap.map.setZoom(divmap.config.geocodeZoomInicio);
                divmap.config.status = 1;
              }
              else{
                divmap.map.setZoom(divmap.config.geocodeZoom);
              }
              divmap.map.panTo(results[0].geometry.location);
              setTimeout(function(){
                $(divmap).refreshMarkers(false)
              }, 1000);
            }
          }
          );
        });
      };
      
      this.construct = function (settings)
      {
        return this.each (function()
        {
          if (! google.maps)
          {
            alert("You need to load Google Maps API v3 before using FONMaps.\nhttp://code.google.com/apis/maps/documentation/javascript/");
            return;
          }
          
          this.config = $.extend({},
            $.fonMap.defaults,
            settings);
          
          this.refreshMarkers = $.fonMap.refreshMarkers;
          this.cleanMarkers = $.fonMap.cleanMarkers;
          this.addMarker = $.fonMap.addMarker;
          this.removeMarker =  $.fonMap.removeMarker;
          this.setActiveMarker = $.fonMap.setActiveMarker;
          this.getMap = $.fonMap.getMap;
          
          this.map = new google.maps.Map(this,
          {
            zoom      : this.config.zoom,
            center    : new google.maps.LatLng(this.config.centerLat, this.config.centerLon),
            minZoom   : 2,
            mapTypeId : google.maps.MapTypeId.ROADMAP,
            mapTypeControlOptions:
            {
              mapTypeIds: [google.maps.MapTypeId.ROADMAP, google.maps.MapTypeId.SATELLITE, google.maps.MapTypeId.TERRAIN],
              style: google.maps.DROPDOWN_MENU
            },
            streetViewControl: false,
            disableDoubleClickZoom: this.config.debug ? true : false
          });
          
          google.maps.event.addListener(
            this.map,
            "tilesloaded",
            function()
            {
              $(this.getDiv()).refreshMarkers(true);
              
            }
          );
          
          var divmap = this;
          
          if (this.config.debug)
          {
            var dbginfowindow = new google.maps.InfoWindow();
            var dbgmarker = new google.maps.Marker();
            google.maps.event.addListener(
              this.map,
              "dblclick",
              function(event)
              {
                dbginfowindow.close();
                dbginfowindow.setContent("lat: "+event.latLng.xa+"<br />lon: "+event.latLng.za);
                dbgmarker.setPosition(new google.maps.LatLng(event.latLng.xa, event.latLng.za));
                dbgmarker.setMap(divmap.map);
                dbginfowindow.open(divmap.map, dbgmarker);
              }
            );
          }
           
          this.map.overlayMapTypes.insertAt(0,
            new FonTile(new google.maps.Size(256, 256), this.config.tilesUrl));
        });
      };
    }
  });
  
  $.fn.extend(
  {
    fonMap         : $.fonMap.construct,
    refreshMarkers : $.fonMap.refreshMarkers,
    getMarkers     : $.fonMap.getMarkers,
    getMap         : $.fonMap.getMap,
    geocode        : $.fonMap.geocode,
    moveMap        : $.fonMap.moveMap,
    addMarker      : $.fonMap.addMarker
  });

})(jQuery);
