// Settings
var defaultLat = 41.871940000000002;
var defaultLng = 12.56738;
var defaultZoom = 5;

// globals
var map;
var geocoder;
var address;
var bounds;
var map_message;
var searchUrl = 'poslocator';
var queryUrl;

// Icons
var here_icon;
var pos_icon;
var pos_important_icon;


// onLoad function
function initPosMap() {
    var map_container = document.getElementById('map-pos')
    map_container.style.display = 'block'
    map = new GMap2(map_container);
    map.addControl(new GSmallMapControl());
    map.addControl(new GMapTypeControl());
    map.setCenter(new GLatLng(defaultLat, defaultLng), defaultZoom);

    here_icon = new GIcon();
    here_icon.image = portal_url + "/map_here_icon.png";
    here_icon.shadow = portal_url + "/map_here_shadow.png";
    here_icon.iconSize = new GSize(32.0, 32.0);
    here_icon.shadowSize = new GSize(49.0, 32.0);
    here_icon.iconAnchor = new GPoint(16.0, 16.0);
    here_icon.infoWindowAnchor = new GPoint(16.0, 16.0);

    pos_icon = new GIcon();
    pos_icon.image = portal_url + "/map_pos_icon.png";
    pos_icon.shadow = portal_url + "/map_pos_shadow.png";
    pos_icon.iconSize = new GSize(22.0, 22.0);
    pos_icon.shadowSize = new GSize(34.0, 22.0);
    pos_icon.iconAnchor = new GPoint(11.0, 11.0);
    pos_icon.infoWindowAnchor = new GPoint(11.0, 11.0);

    pos_important_icon = new GIcon();
    pos_important_icon.image = portal_url + "/map_pos_important_icon.png";
    pos_important_icon.shadow = portal_url + "/map_pos_important_shadow.png";
    pos_important_icon.iconSize = new GSize(32.0, 32.0);
    pos_important_icon.shadowSize = new GSize(49.0, 32.0);
    pos_important_icon.iconAnchor = new GPoint(16.0, 16.0);
    pos_important_icon.infoWindowAnchor = new GPoint(16.0, 16.0);
}

// onClick function
function searchLocations() {
  if (GBrowserIsCompatible()) {
    geocoder = new GClientGeocoder();
    address = document.getElementById('addressInput').value;
    map_message = document.getElementById('map-message');
    jq("#map-results-items").html('')
    geocoder.getLatLng(address, showUserPoint)
  }
}

// -------------------
// Call back functions
// -------------------

// 1) Recuperioamo lat e lng del punto cercato
function showUserPoint(point) {
    if (!point) {
      map_message.innerHTML = 'Indirizzo non trovato';
      jq('#map-results').css('display', 'none');
      jq('#map-pos').css('display', 'none');
    } else {
      initPosMap()
      // Abbiamo trovato l'indirizzo, mostriamolo
      queryUrl = searchUrl + '?lat=' + point.lat() + '&lng=' + point.lng();
      bounds = new GLatLngBounds();
      map.clearOverlays();
      geocoder.getLocations(address, addAddressToMap);
    }
}


// 2) Mostriamo il punto cercato dall'utente
function addAddressToMap(response) {
  if (!response || response.Status.code != 200) {
    map_message.innerHTML = 'Indirizzo non trovato';
    jq('#map-results').css('display', 'none');
    jq('#map-pos').css('display', 'none');
  } else {
    place = response.Placemark[0];
    point = new GLatLng(place.Point.coordinates[1],
    place.Point.coordinates[0]);
    marker = createMarker(point, 'Tu sei qui', place.address, here_icon)
    map.addOverlay(marker);
    bounds.extend(point);

    // Ora cerchiamo i punti vendita
    GDownloadUrl(queryUrl, showLocationsNear)
  }

}


// 3) Mostriamo i punti vendita
function showLocationsNear(data) {
    xml = GXml.parse(data);
    markers = xml.documentElement.getElementsByTagName('marker');

    // Non abbiamo trovato punti vendita
    if (markers.length == 0) {
      map_message.innerHTML = 'Nessun punto vendita trovato';
      map.setCenter(new GLatLng(defaultLat, defaultLng), defaultZoom);
      return;
    }

    jq('#map-results').css('display', 'block')
    gmarkers_list = []
    gmarkers_html = []
    
    for (var i = 0; i < markers.length; i++) {
      m_name = markers[i].getAttribute('name');
      m_address = markers[i].getAttribute('address');
      m_distance = parseFloat(markers[i].getAttribute('distance'));
      m_point = new GLatLng(parseFloat(markers[i].getAttribute('lat')), parseFloat(markers[i].getAttribute('lng')));
      m_level = markers[i].getAttribute('level');
      m_phone = markers[i].getAttribute('phone');

      html = '<b>' + m_name + '</b> <br/>' + m_address;

      marker = createPosMarker(m_point, html, m_level);
      
      gmarkers_list[i] = marker
      gmarkers_html[i] = html
      
      if (m_phone != ''){
        phone_tag = ['<div class="pos-phone">Tel: ', m_phone,  '</div>'].join('')
      } else {
        phone_tag = ''
      }
      
      list_item = ['<div class="pos-level', m_level, '"><a href="#" id="pos-', i,
                   '">', m_name,
                   '</a>', phone_tag, '<div class="pos-address">', m_address,
                   '</div>',].join(''); 



      if (m_level == 0) {
        jq("#map-results-items").append(list_item);
      } else {
        jq("#map-results-items").prepend(list_item);
      }
      
      jq('#pos-' + i).bind("click", function(){
          p = jq(this).attr('id').substring(4)
          gmarkers_list[p].openInfoWindowHtml(gmarkers_html[p]);
          return false;
      });
      
      map.addOverlay(marker);
      bounds.extend(m_point);
      
    }
    
    map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
}

function createPosMarker(point, html, level) {
  // Questa parte andrebbe resa più generica
  if (level != 0){
    icon = pos_important_icon
  } else {
    icon = pos_icon
  }
  return createMarker(point, html, icon)
}

function createMarker(point, html, icon) {
  var marker = new GMarker(point, icon);
  GEvent.addListener(marker, 'click', function() {
    marker.openInfoWindowHtml(html);
  });
  return marker;
}

// jq(initPosMap)
