//      3index_B.js
//      
//      Copyright 2007 jesus <jesus@JMF>
//      
//      This program is free software; you can redistribute it and/or modify
//      it under the terms of the GNU General Public License as published by
//      the Free Software Foundation; either version 2 of the License, or
//      (at your option) any later version.
//      
//      This program is distributed in the hope that it will be useful,
//      but WITHOUT ANY WARRANTY; without even the implied warranty of
//      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//      GNU General Public License for more details.
//      
//      You should have received a copy of the GNU General Public License
//      along with this program; if not, write to the Free Software
//      Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
//      MA 02110-1301, USA.



//<%
//nombre=request.servervariables("HTTP_REFERER")
//if nombre <> "http://localhost/web/peralvillo/peralvillo2/2index.php" then
//response.end
//end if
//%>

//var lastzIndex=1;
/*window.addEvent('unload',function(){
						//if($type(GUnload)=='function') {GUnload();alert('no')}
						GUnload();
						})
*/
//local=ABQIAAAAVnbPoY9qiYjJwgG-iJel3xT2yXp_ZAY8_ufC3CFXhHIE1NvwkxQARNc8ElxXz5lGlir80AvkLbVQPg
//alajo=ABQIAAAAVnbPoY9qiYjJwgG-iJel3xQVro2hakJFaphMoa8E3IMv_q_CAxTVhtJ_qHZg8UYbtu6613CSlHqHpg
var Util={
 	mapa: function(opcs){ //google Maps
 		//var pueblo= opcs.pueblo || 'leon';
 		var pueblo= elPueblo.texto || 'leon';
 		pueblo= (pueblo == 'Buenos Aires') ? pueblo+',Argentina' : pueblo+','+elPueblo.municipio+',Spain';
 		var zoom= 15;
		var tipo= G_SATELLITE_MAP // G_HYBRID_MAP;
		//Util.ver(opcs.elEvent)
		if (GBrowserIsCompatible()) {
			$('centro').empty();
			new Element('div',{id:'googleM'})
				.setStyles('border:2px solid green;border-style:inset;height:500px;margin:15px 0 15px 0;background-image:url(gif/spinner.gif);background-repeat:no-repeat;background-position:center')
				.inject('centro');
		
			var map = new GMap2($("googleM"));
			/*map.setCenter(new GLatLng(latitud, longitud), zoom);
			map.addControl(new GSmallMapControl());
			map.addControl(new GMapTypeControl());*/
			var geocoder = new GClientGeocoder();
        						
			var addAddressToMap= function(response) {
				//map.clearOverlays();
				if (response && response.Status.code != 200) {
				  //alert("No se localiza " + decodeURIComponent(response.name));
					//map= null; geocoder= null;
					zoom= 10; tipo= G_HYBRID_MAP
					geocoder.getLocations('leon,Spain', addAddressToMap);
				} else {
				  var place = response.Placemark[0];
				  //Util.ver(place.AddressDetails)
				  var point = new GLatLng(place.Point.coordinates[1],
										  place.Point.coordinates[0]);
				  map.setCenter(point, zoom);
				  map.setMapType( tipo );//G_HYBRID_MAP 
				  map.addControl(new GSmallMapControl());
				  map.addControl(new GMapTypeControl());
				  map.openInfoWindowHtml(point, /*"<b>Pueblo:</b> " +*/ place.address
				  /* + "<br><b>Población:</b> " + place.population*/);
				}
		  	}
										
			geocoder.getLocations(pueblo, addAddressToMap);
																	
		 	 /*  GEvent.addListener(map, "click", function(marcador, punto) {
		  			var nuevoMarcador = new GMarker(punto);
		  			GEvent.addListener(nuevoMarcador, "click", function() {
							this.openInfoWindowHtml("Lat: " + this.getPoint().lat() + "<br/>Lon: " + this.getPoint().lng());
			  		});
		  			map.addOverlay(nuevoMarcador);
				});*/
        													
		} //GBrowserIsCompatible()
	//onunload="GUnload()"
 	},//mapa
    mapaV3: function(opcs){
        var options={id:47, pueblo:'León', municipio:'León, calle ordoño II, 20', imagen:'fotos/115.jpg'};
        options= $merge(options, opcs);
        //console.log(options);
        /*var imagen= new Image(20,20);
        imagen.src= options.imagen*/
        
        var point=[], mapa, geocoder, marker;
        //var icono= new google.maps.MarkerImage(options.imagen,null,null,null,new google.maps.Size(50, 50)/*, size?:Size, origin?:Point, anchor?:Point, scaledSize?:Size*/);
        mapa = new google.maps.Map(document.getElementById("satelite"), {zoom:16, mapTypeId: google.maps.MapTypeId.ROADMAP});
		if (options.id ==3) { //3:fdez.olite (no lo ubica bien)
            point[0] = new google.maps.LatLng(42.59647071827869, -5.606675148010254)
            mapa.setCenter(point[0]);
            marker = new google.maps.Marker({map: mapa, position: point[0]});
		}else if (options.id ==34){//34: vicente joyeros (2 direcciones)
			point[0] = new google.maps.LatLng(42.59498589308012,-5.573458671569824);
			point[1] = new google.maps.LatLng(42.593627404993605,-5.572385787963867);
            mapa.setCenter(point[0]);
            marker = new google.maps.Marker({map: mapa, position: point[0]});
            var marker2 = new google.maps.Marker({map: mapa, position: point[1]});
		}else{//
            geocoder = new google.maps.Geocoder();
            geocoder.geocode( { 'address': options.municipio}, function(results, status) {
                if (status == google.maps.GeocoderStatus.OK) {
                    point[0]= results[0].geometry.location;
                    mapa.setCenter(point[0]);
                    
                    marker = new google.maps.Marker({map: mapa, position: point[0],title:options.pueblo/*, icon:icono*/});
                    //console.log(google.maps)
                } else {
                    point[0] = new google.maps.LatLng(42.5905137,-5.5609498);//fejorcale
                    mapa.setZoom(10);
                    mapa.setCenter(point[0]);
                    marker = new google.maps.Marker({map: mapa, position: point[0]/*,icon:icono*/});
                }
            });
		}
        
           /* geocoder = new google.maps.Geocoder();
	        if (google.loader.ClientLocation)
	        {
	            //Averiguamos latitud/longitud del visitante
	            var latt = google.loader.ClientLocation.latitude;
	            var longg = google.loader.ClientLocation.longitude;
	 
	            //Centramos el mapa en sus coordenadas
	            var latlng = new google.maps.LatLng(latt,longg);
	        }*/
	        
	       //console.log(geocoder) 

    }
};//Util

//console.log('a')

function mapas(opcs){
        Util.mapaV3(opcs)
        //initialize()
 		//return false;

}
/*
var initialLocation;
var siberia = new google.maps.LatLng(60, 105);
var newyork = new google.maps.LatLng(40.69847032728747, -73.9514422416687);
var browserSupportFlag =  new Boolean();

function initialize() {
  var myOptions = {
    zoom: 16,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  };
  var map = new google.maps.Map(document.getElementById("satelite"), myOptions);
  
  // Try W3C Geolocation (Preferred)
  if(navigator.geolocation) {
    browserSupportFlag = true;
    navigator.geolocation.getCurrentPosition(function(position) {
      initialLocation = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
      map.setCenter(initialLocation);
    }, function() {
      handleNoGeolocation(browserSupportFlag);
    });
  // Try Google Gears Geolocation
  } else if (google.gears) {
    browserSupportFlag = true;
    var geo = google.gears.factory.create('beta.geolocation');
    geo.getCurrentPosition(function(position) {
      initialLocation = new google.maps.LatLng(position.latitude,position.longitude);
      map.setCenter(initialLocation);
    }, function() {
      handleNoGeoLocation(browserSupportFlag);
    });
  // Browser doesn't support Geolocation
  } else {
    browserSupportFlag = false;
    handleNoGeolocation(browserSupportFlag);
  }
  
  function handleNoGeolocation(errorFlag) {
    if (errorFlag == true) {
      alert("Geolocation service failed.");
      initialLocation = newyork;
    } else {
      alert("Your browser doesn't support geolocation. We've placed you in Siberia.");
      initialLocation = siberia;
    }
    map.setCenter(initialLocation);
  }
}
*/
//---------------------------------
var mapa = { 
	options:{
		pueblo:'Leon',
		municipio: 'Leon',
		zoom: 16,
		tipo: ''//G_SATELLITE_MAP, // G_HYBRID_MAP;
	},
	map: {},
	cargando: null,
	initialize: function(options){
		mapa.options= $merge(mapa.options, options);
		//console.log(mapa)
		var point=[];
		if (GBrowserIsCompatible()) {
			this.map = new GMap2(document.getElementById("satelite"));
            
            //var latlng = new google.maps.LatLng(42.59647071827869, -5.606675148010254);
            //this.map = new google.maps.Map(document.getElementById("satelite"),{zoom: 16, center: latlng, mapTypeId: google.maps.MapTypeId.ROADMAP});
			this.options.tipo= G_NORMAL_MAP; //G_SATELLITE_MAP;
			if (this.options.id ==3) { //fdez.olite (no lo ubica bien)
				point[0] = new GLatLng(42.59647071827869, -5.606675148010254)
				this.visualiza(point);
			}else if (this.options.id ==34){//vicente joyeros (2 direcciones)
				point[0] = new GLatLng(42.59498589308012,-5.573458671569824);
				point[1] = new GLatLng(42.593627404993605,-5.572385787963867);
				this.visualiza(point);
			}else{//
				this.buscaText();
			}
		}
		//window.addEvent('unload',function(){GUnload();});
	},
	buscaText: function(){
		var geocoder = new GClientGeocoder();
		var point=[];
		var addAddressToMap= function(response){
			if (! response || response.Status.code != 200) {
				mapa.options.zoom= 10; mapa.options.tipo= G_HYBRID_MAP;
				geocoder.getLocations('leon,leon, Spain', addAddressToMap);
			} else {
				var place = response.Placemark[0];
				point[0] = new GLatLng(place.Point.coordinates[1],
									place.Point.coordinates[0]);
				mapa.visualiza(point);
				//mapa.map.openInfoWindowHtml(point, /*"<b>Pueblo:</b> " +*/ place.address.replace(', Spain','')
				//	  /* + "<br><b>Población:</b> " + place.population*/);
				//	var centro= new GLatLng((place.Point.coordinates[1] + point2.y)/2, (place.Point.coordinates[0] + point2.x)/2);
				//	mapa.map.setCenter(centro, mapa.options.zoom);
			}
		};
		geocoder.getLocations(this.options.municipio, addAddressToMap);
		//console.log(this.options.municipio)
	},//buscaText
	visualiza: function(points){
		this.map.setCenter(points[0], this.options.zoom);
		for (var point in points){
			var marcador=new GMarker(points[point],{draggable:true});
			this.map.addOverlay(marcador);
			this.getCoord(marcador);
		}
		this.map.setMapType( this.options.tipo );//G_HYBRID_MAP 
		this.map.addControl(new GSmallMapControl());
		this.map.addControl(new GMapTypeControl());
		//console.log(this.map.getCenter())
	},
	getCoord: function(marcador){
		/*GEvent.addListener(marcador, "click", function() {
		})*/
		GEvent.addListener(marcador, "dragend", function() {
                var position = marcador.getPoint(); 
                //mapa.map.panTo(new GLatLng(position.lat(), position.lng())); //CENTRA EL MAPA
				marcador.openInfoWindow(position.lat()+"|"+position.lng());
        }) 
	}
};
//---------------------------------------

//----------------------------------------------------------------------------
var Event1 = {
	add: function(obj,type,fn,args) {
		obj.addEvent(type, fn); //mootools
	},
	remove: function(obj,type,fn) {
		obj.removeEvent(type, fn); //mootools
	},
	fix: function(e,dat) {
       e = e || window.event
       if (! e.target) {e.target= e.srcElement};
       if (! e.currentTarget) {e.currentTarget=e.target.parentNode;} //estaba bien
       if(e.fromElement){ e.relatedTarget = e.fromElement; }
       if(e.toElement){ e.relatedTarget = e.toElement; }
       if (typeof e.layerX == 'undefined') e.layerX = e.offsetX;
       if (typeof e.layerY == 'undefined') e.layerY = e.offsetY;
       if (typeof e.clientX == 'undefined') e.clientX = e.pageX;
       if (typeof e.clientY == 'undefined') e.clientY = e.pageY;
       if (! e.stopPropagation) {e.stopPropagation=function(){this.cancelBubble = true}}
       if (! e.preventDefault) {e.preventDefault=function(){this.returnValue = false}}
   
       e.otra='nada'//dat;
       e.fixEvent=true;
       return e
	},
	cancel: function(e) {
		e= new Event(e).stop(); //mootools
		/*if (! e.fixEvent) this.fix(e);
        e.stopPropagation();
        e.preventDefault();*/
	}
}//Event


//==================================================================0
function $defined(obj){
	return (obj != undefined);
};

/*
Function: $type
	Returns the type of object that matches the element passed in.

Arguments:
	obj - the object to inspect.

Example:
	>var myString = 'hello';
	>$type(myString); //returns "string"

Returns:
	'element' - if obj is a DOM element node
	'textnode' - if obj is a DOM text node
	'whitespace' - if obj is a DOM whitespace node
	'arguments' - if obj is an arguments object
	'object' - if obj is an object
	'string' - if obj is a string
	'number' - if obj is a number
	'boolean' - if obj is a boolean
	'function' - if obj is a function
	'regexp' - if obj is a regular expression
	'class' - if obj is a Class. (created with new Class, or the extend of another class).
	'collection' - if obj is a native htmlelements collection, such as childNodes, getElementsByTagName .. etc.
	false - (boolean) if the object is not defined or none of the above.
*/

function $type(obj){
	if (!$defined(obj)) return false;
	if (obj.htmlElement) return 'element';
	var type = typeof obj;
	if (type == 'object' && obj.nodeName){
		switch(obj.nodeType){
			case 1: return 'element';
			case 3: return (/\S/).test(obj.nodeValue) ? 'textnode' : 'whitespace';
		}
	}
	if (type == 'object' || type == 'function'){
		switch(obj.constructor){
			case Array: return 'array';
			case RegExp: return 'regexp';
			case Class: return 'class';
		}
		if (typeof obj.length == 'number'){
			if (obj.item) return 'collection';
			if (obj.callee) return 'arguments';
		}
	}
	return type;
};

/*
Function: $merge
	merges a number of objects recursively without referencing them or their sub-objects.

Arguments:
	any number of objects.

Example:
	>var mergedObj = $merge(obj1, obj2, obj3);
	>//obj1, obj2, and obj3 are unaltered
*/

function $merge(){
	var mix = {};
	for (var i = 0; i < arguments.length; i++){
		for (var property in arguments[i]){
			var ap = arguments[i][property];
			var mp = mix[property];
			if (mp && $type(ap) == 'object' && $type(mp) == 'object') mix[property] = $merge(mp, ap);
			else mix[property] = ap;
		}
	}
	return mix;
};

//==========================================================
