var map, manager;
//var maxZoom=18;var minZoom=10;


var i1 = new GIcon();
i1.iconSize = new GSize(ialto, iancho);
i1.iconAnchor = new GPoint(iposx, iposy);
i1.infoWindowAnchor = new GPoint(iinfox, iinfoy);
i1.image = ico1;


var i2 = new GIcon();
i2.iconSize = new GSize(ialto, iancho);
i2.iconAnchor = new GPoint(iposx, iposy);
i2.infoWindowAnchor = new GPoint(iinfox, iinfoy);
i2.image = ico2;


var i3 = new GIcon();
i3.iconSize = new GSize(ialto, iancho);
i3.iconAnchor = new GPoint(iposx, iposy);
i3.infoWindowAnchor = new GPoint(iinfox, iinfoy);
i3.image = ico3;


var i4 = new GIcon();
i4.iconSize = new GSize(ialto, iancho);
i4.iconAnchor = new GPoint(iposx, iposy);
i4.infoWindowAnchor = new GPoint(iinfox, iinfoy);
i4.image = ico4;


var i5 = new GIcon();
i5.iconSize = new GSize(ialto, iancho);
i5.iconAnchor = new GPoint(iposx, iposy);
i5.infoWindowAnchor = new GPoint(iinfox, iinfoy);
i5.image = ico5;


var i6 = new GIcon();
i6.iconSize = new GSize(ialto, iancho);
i6.iconAnchor = new GPoint(iposx, iposy);
i6.infoWindowAnchor = new GPoint(iinfox, iinfoy);
i6.image = ico6;



var customIcons = [];
customIcons["1"] = i1;
customIcons["2"] = i2;
customIcons["3"] = i3;
customIcons["4"] = i4;
customIcons["5"] = i5;
customIcons["6"] = i6;
var markerGroups = { "1": [], "2": [], "3": [], "4": [], "5": [], "6": []};


function createMarkerClickHandler(marker, nombre, dir, tel, imagen, web) {
  return function() {
    var codigo = '<div id="marca"><h4>' + nombre + '</h4></br>';     
    if (imagen) { codigo = codigo + '<img src=img/' + imagen + ' width=120 height=100>'; }
    if (dir) { codigo = codigo + '<h3>' + dir + '</h3>'; }    
    if (tel) { codigo = codigo + '<h3>' + tel + '</h3>'; }       
    if (web) { codigo = codigo + '</br><h3><a href="' + web + '" target="_blank">[web]</a></h3>'; }    
    codigo = codigo + '</div>';
    
    marker.openInfoWindowHtml(codigo);
    return false;
  };
}


function createMarker(pointData) {
  var latlng = new GLatLng(pointData.lat, pointData.lon);
  
  
  opts = {
    "title": pointData.nombre,
    "icon": customIcons[pointData.tipo],
    "draggable": true,
    "clickable": true,
    "labelText": pointData.id,
    "labelOffset": new GSize(itxtx, itxty)
  };
 
  var marker = new LabeledMarker(latlng, opts);
  markerGroups[pointData.tipo].push(marker);
  
  var handler = createMarkerClickHandler(marker, pointData.nombre, pointData.dir, pointData.tel, pointData.img, pointData.web);
	
  GEvent.addListener(marker, "click", handler);
  //GEvent.addListener(marker, "click", function(){
  //            marker.openExtInfoWindow(
  //              map, "custom_info_window_red", "<div>" + pointData.nombre + "</div>");
  //          });
  

  var listItem = document.createElement('li');
  //if(IE) listitem.setAttribute('className','"c' + pointData.tipo + '"'); else punto.setAttribute('class','"c' + pointData.tipo + '"');
  //listitem.setAttribute('class','"c' + pointData.tipo + '"')
  //listItem.innerHTML = '<div class="label">'+pointData.id+'</div><a href="' + pointData.web + '">' + pointData.nombre + '</a>';
  listItem.setAttribute('id','t'+pointData.tipo);
  //listItem.innerHTML = '<div class="c' + pointData.tipo + '">'+pointData.id+'</div><a href="' + pointData.web + '" class="c' + pointData.tipo + '">' + pointData.nombre + '</a>';
  listItem.innerHTML = '<div style="background:url(' + customIcons[pointData.tipo].image + ');">'+pointData.id+'</div><a href="' + pointData.web + '" class="c' + pointData.tipo + '">' + pointData.nombre + '</a>';
  
  //document.getElementById('debug').value = listItem.innerHTML;
  
  listItem.getElementsByTagName('a')[0].onclick = handler;

  document.getElementById('listado').appendChild(listItem);

  return marker;
}

function toggleGroup(tipo) {
   for (var i = 0; i < markerGroups[tipo].length; i++) {
       	var marker = markerGroups[tipo][i];
	if (marker.isHidden()) {
  		marker.show();
	} else {
  		marker.hide();
  		//document.getElementById('sidebar-list').removeChild(markerGroups[tipo][i]);
	}
   } 
  // document.getElementById('gr').href = 'style2.css';
}

function selGroup(tipo) {   
  
  document.getElementById('gr').href = 'css/gr' + tipo + '.css';
  //document.getElementById('debug').value = 'style' + tipo + '.css';
  
  if (tipo == '0') 
  {
	for (grupo in markerGroups) 
	{
        	for (var i = 0; i < markerGroups[grupo].length; i++) 
        	{
          		var marker = markerGroups[grupo][i];
          		marker.show();
        	}
      	}
  } 
  else 
  {
	for (grupo in markerGroups) 
	{
        	for (var i = 0; i < markerGroups[grupo].length; i++) 
        	{
          		var marker = markerGroups[grupo][i];
          		if (tipo == grupo) { marker.show(); } else { marker.hide(); }
        	}
      	}   
  } 

}



function toggleLabels() {
      var showLabels = document.getElementById("etiquetas").checked;
      for (groupName in markerGroups) {
        for (var i = 0; i < markerGroups[groupName].length; i++) {
          var marker = markerGroups[groupName][i];
          marker.setLabelVisibility(showLabels);
        }
      }
}


function windowHeight() {
  // Standard browsers (Mozilla, Safari, etc.)
  if (self.innerHeight) {
    return self.innerHeight;
  }
  // IE 6
  if (document.documentElement && document.documentElement.clientHeight) {
   return document.documentElement.clientHeight;
  }
  // IE 5
  if (document.body) {
    return document.body.clientHeight;
  }
  // Just in case. 
  return 0;
}



function handleResize() {
  var height = windowHeight() - document.getElementById('cabecera').offsetHeight - 30;
  document.getElementById('mapa').style.height = height + 'px';
  document.getElementById('datos').style.height = height + 'px';
}

function changeBodyClass(from, to) {
	document.body.className = document.body.className.replace(from, to);
	return false;
}


function CambiaZoom(a){
	//if(!midiendo){marker=null;map.clearOverlays();}
	//document.getElementById('debug').value = 'x';
	var actZoom=map.getZoom();
	selGroup( document.getElementById('seleccion').value );
	//Firefox
	if (a.detail) {
	  if (a.detail < 0 && actZoom < maxZoom ) ZoomInZoomOut('in'); 
	  else if (a.detail > 0 && actZoom > minZoom ) ZoomInZoomOut('out');
	}
	else if (a.wheelDelta) {/* IE*/if (a.wheelDelta > 0) ZoomInZoomOut('in'); else if (a.wheelDelta < 0) ZoomInZoomOut('out');}
}

function ZoomInZoomOut(a){
    var m = map.fromLatLngToDivPixel(latlngMouse); 
    var c = map.fromLatLngToDivPixel(map.getCenter()); 
    if (a == 'in') { var x = c.x - ((m.x - c.x) * -.5); var y = c.y - ((m.y - c.y) * -.5); var n = map.fromDivPixelToLatLng(new GPoint(x,y)); map.setCenter(n);map.zoomIn(); } 
    else { var x = c.x - (m.x - c.x); var y = c.y - (m.y - c.y); var n = map.fromDivPixelToLatLng(new GPoint(x,y)); map.setCenter(n);map.zoomOut(); } 
}



/******************************************************************************/

function init() {
  document.getElementById('ocultarmenu').onclick = function() 
  { 
  	if (document.body.className == 'menu-izquierda-g')
  	{ return changeBodyClass('menu-izquierda-g', 'sin-menu-g'); }
  	else
  	{ return changeBodyClass('menu-izquierda', 'sin-menu'); }
  };
  document.getElementById('vermenu').onclick = function() 
  { 
  	if (document.body.className == 'sin-menu-g')
  	{ return changeBodyClass('sin-menu-g', 'menu-izquierda-g'); }
  	else
  	{ return changeBodyClass('sin-menu', 'menu-izquierda'); }
  };

  handleResize();
	
  map = new GMap(document.getElementById("mapa"));
  //map.addControl(new GSmallMapControl());
  
  //map.addMapType(G_MAP_TYPE);
  //map.addMapType(G_PHYSICAL_MAP);
  map.removeMapType(G_SATELLITE_MAP);
  map.removeMapType(G_HYBRID_MAP);
  map.addControl(new GMapTypeControl());
  map.addControl(new CustomZoomControl());
  map.addControl(new CustomMapControl());
    
  map.setCenter(new GLatLng(centerLat, centerLon), zoom);
  
  GEvent.addListener(map, "zoomend", function(a,b) {selGroup( document.getElementById('seleccion').value );});

  //manager = new MarkerManager(map);
  markers.sort(function(a, b) { return (a.id > b.id) ? +1 : -1; }); 
	
  batch = [];
  for(id in markers) {
       //batch.push(createMarker(markers[id])); 
       map.addOverlay(createMarker(markers[id])); 
  }
  //manager.addMarkers(batch, 12);
  //manager.refresh();    
  
  var insert1 = new EInsert(new GLatLng(39.59356, -0.9732341766357422), "img/escudo.gif", new GSize(54,61), 18); 
  map.addOverlay(insert1);   
  
  for (var i=0; i<lineas.length; i++) {
       map.addOverlay(new GPolyline(lineas[i].points, lineas[i].colour, lineas[i].width)); 
  }
  //map.addOverlay(new GPolygon(lineas,"#808080", 1,.9,"#0000ff",.03)); 
  
  map.addOverlay(new GPolygon(area[0].points,"#808080", 2,.9,"#00aa00",.03)); 
  
  selGroup(document.getElementById('seleccion').value);
  
}

window.onresize = handleResize;
window.onload = init;
window.onunload = GUnload;

