var ___Map = {
  map: null,
  directions: null,
  points: [                
    {'text':'Hotel Bellevue', 'lat':'45.545793', 'lon':'12.651443'},
    {'text':'Golf Club Jesolo', 'lat':'45.511159', 'lon':'12.603722'},
    {'text':'Aqualandia', 'lat':'45.499128', 'lon':'12.604065'},
    {'text':'Pista Azzurra', 'lat':'45.5114', 'lon':'12.628784'},
    {'text':'Jesolo Tourist Port', 'lat':'45.493834', 'lon':'12.586212'},
    {'text':'Congress Centre', 'lat':'45.505384', 'lon':'12.634277'},
    {'text':'Play Village', 'lat':'45.513565', 'lon':'12.641144'},
    {'text':'Marina Club', 'lat':'45.500572', 'lon':'12.594109'},
    {'text':'Villa Giulia Beauty & Wellness', 'lat':'45.545553', 'lon':'12.638741'},
    {'text':'Cortellazzo ', 'lat':'45.543148', 'lon':'12.721825'},
    {'text':'Nautica Boat Service', 'lat':'45.537137', 'lon':'12.722511'},
    {'text':'Pineta', 'lat':'45.530884', 'lon':'12.709122'}
  ],
  markers: [],
  
  recursiveHindex: 1,
  
  goToPrintPage: function()
  {
    center = this.map.getCenter();
    zoom = this.map.getZoom();
    from = URLEncode($('#dir_from_hidden').attr('value'));
    if(!from)
    {
      from = '';
    }
    
    //to = URLEncode($('#dir_to').attr('value'));
    to = URLEncode('Box Up Self Storage @45.553840,9.260820');
    window.open('print_map.php?x=' +  center.x + '&y=' + center.y  + '&zoom=' + zoom + '&from=' + from + '&to=' + to);  
  },
  
  initMap: function() {
    // Init map object
    this.resizeMap();
    this.map = new GMap2(document.getElementById("map_contents"));
    //this.map.addControl(new ExtMapTypeControl(),new GControlPosition(G_ANCHOR_TOP_RIGHT,new GSize(8,30)))
    //this.map.removeMapType(G_NORMAL_MAP);
    
    /*var copyright = new GCopyright(1, new GLatLngBounds(new GLatLng(-90, -180), new GLatLng(90, 180)), 0, '');
    var copyrights = new GCopyrightCollection('');
    copyrights.addCopyright(copyright);
    var tilelayer = new GTileLayer(copyrights, 0, 17);
    tilelayer.getTileUrl = function() { 
      ___Map.map.setMapType(oldMapType);
    };
    this.CUSTOM_MAP = new GMapType( [tilelayer], new GMercatorProjection(20), "Print" );
    this.map.addMapType(this.CUSTOM_MAP);*/
    
    //this.map.setCenter(new google.maps.LatLng(41.909434,12.490154), 15);
    //this.map.setCenter(new google.maps.LatLng(45.426445,12.362741), 13);
    var map_print_page = false;
    if(map_print_page)
    {
      this.map.setCenter(new google.maps.LatLng(map_y,map_x), map_zoom);
    }
    else
    {
      this.map.setCenter(new google.maps.LatLng(45.553907612029064, 9.26048755645752), 15);
    }
    
    this.map.addControl(new GLargeMapControl());
    this.map.addControl(new GMapTypeControl());
    // init directions object
    this.directions = new GDirections(this.map, document.getElementById("directions"));
      GEvent.addListener(this.directions , "load", this.onGDirectionsLoad);
      GEvent.addListener(this.directions , "error", this.handleDirErrors);

    // Resize on every window resize event
    window.onresize = ___Map.resizeMap;


  },

  initMain: function() {
    var latlng = new GLatLng(45.553840,9.260820);
    var marker = new GMarker(latlng)

      this.map.addOverlay(marker);

    GEvent.addListener(marker, "click", function() {
      marker.openInfoWindowHtml("<div><h3 style='color:black'>Box Up Self Storage</h3><br />Via San Maurizio al Lambro<br />n. 1 angolo V.le Italia -<br /> 20099 Sesto San Giovanni</div>");

        });
    var map_print_page = false;
    if(map_print_page)
    {
      this.map.setCenter(new google.maps.LatLng(map_y,map_x), map_zoom);
    }
    else
    {
      marker.openInfoWindowHtml("<div><h3 style='color:black'>Box Up Self Storage</h3><br />Via San Maurizio al Lambro<br />n. 1 angolo V.le Italia -<br /> 20099 Sesto San Giovanni</div>");
    }
    
  },

  initPoints: function() {

    var e = function(marker, i) {
      return function() {
        marker.openInfoWindowHtml(___Map.points[i].text);
      }
    }




    var latlng, marker;
    for(var i = 0; i<this.points.length; i++) {
      var blueIcon = new GIcon(G_DEFAULT_ICON);
      //blueIcon.image = "http://maps.google.com/mapfiles/ms/micons/blue-dot.png";
      //blueIcon.image = "http://maps.google.com/intl/ru_ALL/mapfiles/markerTransparent.png";
      //blueIcon.image = "images/google/marker";
      //blueIcon.image = "http://babotel.com/victoriahotel/images/google/marker1.png";
      blueIcon.shadow = "http://maps.google.com/intl/en_ALL/mapfiles/ms/micons/msmarker.shadow.png";
      blueIcon.shadowSize = new GSize(59,32);
      latlng = new GLatLng(this.points[i].lat,this.points[i].lon);
      if(i<=21){
        blueIcon.image = "images/google/marker"+(i+1)+".png";
        blueIcon.iconSize = new GSize(20, 34);
      }else{
        blueIcon.image = "http://maps.google.com/mapfiles/ms/micons/blue-dot.png";
        blueIcon.iconSize = new GSize(32, 32);
      }
      marker = new GMarker(latlng, {icon: blueIcon});
      this.markers[i] = marker;
        this.map.addOverlay(marker);
      GEvent.addListener(marker, "click", e(marker, i));
    }
  },

  initSide: function() {
    var panel = $("#points");
    for (var i = 0; i < this.points.length; i++) {
      panel.append("<div class=\"markerHelper\" marker=\""+i+"\">"+(i+1)+") "+this.points[i].text+"</div>");
    }

    $('.markerHelper').bind('click', ___Map.helperClick);

  },

  handleDirErrors: function() {
    error = ___Map.directions.getStatus().code;

    if (error == G_GEO_UNKNOWN_ADDRESS) {
      alert("No corresponding geographic location could be found for one of the specified addresses. This may be due to the fact that the address is relatively new, or it may be incorrect.\nError code: " + error);
    } else if (error == G_GEO_SERVER_ERROR) {
      alert("A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known.\n Error code: " + error);
    } else if (error == G_GEO_MISSING_QUERY) {
      alert("The HTTP q parameter was either missing or had no value. For geocoder requests, this means that an empty address was specified as input. For directions requests, this means that no query was specified in the input.\n Error code: " + error);
    } else if (error == G_GEO_BAD_KEY) {
      alert("The given key is either invalid or does not match the domain for which it was given. \n Error code: " + error);
    } else if (error == G_GEO_BAD_REQUEST) {
      alert("A directions request could not be successfully parsed.\n Error code: " + error);
    } else {
      //alert("An unknown error occurred. Error code: " + error);
    }
  },

  onGDirectionsLoad : function() {

  },

  loadDir: function(from, to) {
    // As default, en_US locale is used.
    // TODO: add locale depending on site language
    //this.directions.load("from: " + from + " to: " + URLEncode("Box Up Self Storage @45.553840,9.260820"), {locale:map_lang_full_code});
   this.directions.load("from: " + from + " to: " + to, {locale:map_lang_full_code});
  },


  search: function() {
    from = $('#dir_from').attr('value');
	if ($('#dir_to').attr('value')=='BoxUp Via San Maurizio al Lambro n. 120099 Sesto San Giovanni'){
	to = 'Box Up Self Storage @45.553840,9.260820';
	}else{
   to = $('#dir_to').attr('value');
   }
    $('#dir_from_hidden').val(from);
    if(from=="" || from==null){
      alert('The field "From" should be filled.');
      return;
    }
    if(to=="" || to==null){
      alert('The field "To" should be filled.');
      return;
    }
    ___Map.loadDir(from, to);

  },

  helperClick: function() {
    // 1. getMarker
    m_id = parseInt($(this).attr('marker'));
    marker = ___Map.markers[m_id];
    point = ___Map.points[m_id];
    // 2. make directions
    //___Map.loadDir(point.lat+", "+point.lon, "Hotel Sant`Elena - Calle Buccari 10 - Sant`Elena - 30132 Venezia");
    ___Map.loadDir(point.lat+", "+point.lon, $('#dir_to').attr('value'));
    $('#dir_from_hidden').val(point.lat+", "+point.lon);
    // 3. Open marker window
    marker.openInfoWindowHtml(___Map.points[m_id].text);
     // ___Map.resetHeight();
  },
  
    resetHeight: function() {
    document.getElementById('col_2').style.height = '';
    document.getElementById('col_1').style.height = '';
    ___Map.recursiveH();
  }, 
  
  recursiveH: function() {
    while(___Map.recursiveHindex < 10)
    {
      ___Map.recursiveHindex++;
      setTimeout('h();', 3000);
      
    }
  },

  resizeMap: function() {
    var width = document.getElementById('right').offsetWidth;
    width = parseInt(width);
    //$('.mapElement').attr('width', (parseInt(width) - 220)+"px;");
    document.getElementById('map_contents').style.width = 500;//(width - 192);//(width - 240); were 130 ! change 06.08 for ie compability
    document.getElementById('mapElement').style.width = 500;//(width - 192);//(width - 240);
    //$('#map_contents').attr('width', (parseInt(width) - 220)+"px;");
  }
}


google.load("maps", "2.x", {"language" : map_lang_code});
//google.load("maps", "2.x", {"language" : "en"});
// Call this function when the page has been loaded
function init() {
  ___Map.initMap();
  ___Map.initMain();
  ___Map.initPoints();
  ___Map.initSide();

  $(document).ready(function(){
    setPrintAcrion();
  });

  //___Map.addControl(new GControl(false, true), new GControlPosition(G_ANCHOR_TOP_RIGHT , new GSize(60, 10)));
  //___Map.loadDir("41.905056, 12.480683", "Via Campania, 41, 00187 Roma (RM), Italy (Hotel Victoria Roma)");
}

/*
  directions = new GDirections(map);

    GEvent.addListener(directions , "load", onGDirectionsLoad);
    GEvent.addListener(directions , "error", handleErrors);

  // To provide result of directions, use appropriate locale
  directions.load("from: 41.905056, 12.480683 to: Via Campania, 41, 00187 Roma (RM), Italy (Hotel Victoria Roma)", {locale:"en_US"});
  //directions.load("from: 41.905056,12.480683 to: 41.909434,12.490154");
  //directions.load('from: New York, NY to: Chicago, IL');


  //map.setCenter(new google.maps.LatLng(41.909434,12.490154), 16);
}
*/


/**
 * urlencode the string
 *
 * @param {string} clearString
 * @return {string}
 */
function URLEncode(clearString) {
    if(!clearString){
         return '';
    }
     var clearString = encodeURIComponent(clearString);
     var re = /%20/g;
     return clearString.replace(re, '+');
}

function setPrintAcrion(print)
{
  if($('#print_button').is('*'))
  {
    document.getElementById('print_button').onmousedown = function () {
        oldMapType = ___Map.map.getCurrentMapType(); 
          if(map_print_page)
          {
            window.print();
          }
          else
          {
            ___Map.goToPrintPage();
          }
        };
    if(map_print_page)
    {
      //setTimeout("window.print();", 2000);
    }
  }
  else
  {
    setTimeout("setPrintAcrion()", 1000);
  }
}
oldMapType = false;
google.setOnLoadCallback(init);
