//      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();
						})
*/
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
};//Util



function mapas(opcs){
		//console.log(opcs)
 		var algo=mapa.initialize(opcs);
 		return false;

}

//---------------------------------
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"));
			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;
};

//==========================================================
