/*funciones utiles*/
Function.prototype.bindAsEventListener=function(object){var __method=this,args=$A(arguments),object=args.shift();return function(event){return __method.apply(object,[(event||window.event)].concat(args).concat($A(arguments)));}}
var $A=Array.from=function(iterable){if(!iterable)return [];if(iterable.toArray){return iterable.toArray();}else{var results=[];for(var i=0,length=iterable.length;i<length;i++)results.push(iterable[i]);return results;}}
function stopevent(event){ if(event.preventDefault){event.preventDefault();event.stopPropagation();}else{event.returnValue=false;event.cancelBubble=true;}}
function	_addlistener(obj,evt,func){try{if(obj.attachEvent){obj.attachEvent('on'+evt,func);}else{if(obj.addEventListener){obj.addEventListener(evt,func,false);}else{if(obj.eval){obj["on"+evt]=func;}else{}}}}catch(e){alert("js:"+e.message);}}
function ajaxget(url, func){if(window.XMLHttpRequest){ajax=new XMLHttpRequest();}else if(window.ActiveXObject){try{ajax=new ActiveXObject("Msxml2.XMLHTTP");}catch(e){try{ajax=new ActiveXObject("Microsoft.XMLHTTP");}catch(e){}}};ajax.open("get",url,true);ajax.onreadystatechange = function(){if(ajax.readyState==4){if(ajax.status==200){var contenttype=ajax.getResponseHeader('Content-Type');if(contenttype.indexOf('xml')>-1){func(ajax.responseXML);}else{func(ajax.responseText);}}else{func('Error: '+httpObj.status);}}};ajax.send(null);}


//http://www.google.com/apis/maps/documentation/reference.html

var googlemaps= {
	key:undefined,
	version:"2.x",
	mode:'normal',
	datafile:undefined,
	layer:undefined,
	wheelscroll:true,
	controlstyle:"large",
	scale:false,
	lang:"es",
	minimap:[100,60],
	maptype:1,
	maptypecontrol:false,


/*---------------------------------------------*/
	currentplace:undefined,	placedb:new Array(),	googlemapobj:undefined,

	init:function()
	{	try
		{	if(!this.key) { throw new Error("googlemaps key not found"); }
			if(!this.layer) { this.layer=document.getElementById('map'); if(!this.layer) throw new Error("layer googlemaps not found"); }
			if(this.mode=='normal' || this.mode=='streetview')
			{	document.write('<script type="text/javascript" src="http://maps.google.com/maps?file=api&amp;hl='+this.lang+'&amp;oe=utf-8&amp;v='+this.version+'&amp;key='+this.key+'"></script>');
			}
			else throw("mode not found");
			_addlistener(window,"load",this.onload.bindAsEventListener(this));
			_addlistener(window,"unload",this.onunload.bindAsEventListener(this));
		} catch(e){alert("init js:"+e.message);}
	},

	onunload:function() { GUnload(); },
	onload:function()
	{  try
		{	if(this.mode=='normal')
			{	if(!GBrowserIsCompatible()) throw new Error("browser not compatible with googlemaps api");
				if(!(this.googlemapobj=new GMap2(this.layer))) throw new Error("cannot create googlemap");
				if(this.datafile){ ajaxget(this.datafile,this.processdatafile.bindAsEventListener(this)); }
				else this.draw();
			}
         else if(this.mode=='streetview')
			{	if(!GBrowserIsCompatible()) throw new Error("browser not compatible with googlemaps api");
				this.layer.innerHTML='';
				this.googlemapobj= new GStreetviewPanorama(this.layer);
				GEvent.addListener(this.googlemapobj, "error", this.handleNoFlash.bindAsEventListener(this));
				if(this.datafile){ ajaxget(this.datafile,this.processdatafile.bindAsEventListener(this)); }
				//this.googlemapobj.setLocationAndPOV( new GLatLng(40.056747,-0.178996), {yaw:345.1,pitch:-3.12,zoom:1} );
			}

		} catch(e){alert("onload js:"+e.message);}
	},

	handleNoFlash:function(errorCode){	if (errorCode == 603) { alert("Error: Flash doesn't appear to be supported by your browser");  return; } },

	processdatafile:function(xml)
	{	try
		{	places=xml.documentElement.getElementsByTagName("place");
			for(var i=0;i<places.length;i++)
			{	id=places[i].getAttribute("id");
				lat=parseFloat(places[i].getAttribute("lat"));
				lon=parseFloat(places[i].getAttribute("lon"));
				if(places[i].getAttribute("yaw")) yaw=parseFloat(places[i].getAttribute("yaw")); 	else yaw=null;
				if(places[i].getAttribute("pitch")) pitch=parseFloat(places[i].getAttribute("pitch")); 	else pitch=null;
				if(places[i].getAttribute("zoom")) zoom=parseFloat(places[i].getAttribute("zoom"));	else zoom=null;
				if(places[i].getAttribute("ico")) ico=places[i].getAttribute("ico");	else ico=null;
				if(places[i].firstChild)  msg=places[i].firstChild.data; else msg=null;
				this.addplace(id,lat,lon,zoom,msg,ico,yaw,pitch);
			}
		} catch(e){alert("processdatafile js:"+e.message);}

		this.draw();
	},


	draw:function()
	{ 	try
		{	if(this.placedb.length<=0) throw new Error("sin datos para representar.");

			if(this.mode=='streetview')
			{  for(i=0;i<this.placedb.length;i++) //el primero con datos pitch
				{	if(this.placedb[i][6]!=null) { this.googlemapobj.setLocationAndPOV( new GLatLng(this.placedb[i][1],	this.placedb[i][2]), {yaw:this.placedb[i][6],pitch:this.placedb[i][7],zoom:0} ); break; }
				}
			}
			else
			{	if(this.scale) this.googlemapobj.addControl(new GScaleControl());
				if(this.controlstyle=="small") this.googlemapobj.addControl(new GSmallMapControl()); else this.googlemapobj.addControl(new GLargeMapControl());
				if(this.maptypecontrol) this.googlemapobj.addControl(new GMapTypeControl());
				if(this.minimap) this.googlemapobj.addControl(new GOverviewMapControl(new GSize(this.minimap[0],this.minimap[1])));
				this.googlemapobj.enableContinuousZoom();
				if(this.wheelscroll) this.googlemapobj.enableScrollWheelZoom();
				this.moveto(0);

				for(i=0;i<this.placedb.length;i++) if(this.placedb[i][4]!=null) this.addmarker(this.placedb[i]); /*this.googlemapobj.addOverlay(new GMarker(new GLatLng(this.placedb[i][1],this.placedb[i][2])));*/

				switch(this.maptype)
				{	case 1:this.googlemapobj.setMapType(G_NORMAL_MAP);break;
					case 2:this.googlemapobj.setMapType(G_SATELLITE_MAP);break;
					case 3:this.googlemapobj.setMapType(G_HYBRID_MAP);break;
				}
			}
			//svOverlay = new GStreetviewOverlay();     this.googlemapobj.addOverlay(svOverlay);
		} catch(e){alert("js:"+e.message);}
	},



	addplace:function(id,lat,lon,zoom,msg,ico,yaw,pitch) { this.placedb.push(new Array(id,lat,lon,zoom,msg,ico,yaw,pitch)); if(!this.currentplace) this.currentplace=0; },
	movetoid:function(id){index=-1;for(i=0;i<this.placedb.length;i++)if(this.placedb[i][0]==id) {index=i;break;}else {/*alert(this.placedb[i][0]+" "+id);*/} /*alert(index);*/if(index<0) return; this.moveto(index); },
	moveto:function(index)
	{	this.currentplace=index;
		if(this.mode=='streetview')
		{	this.googlemapobj.setLocationAndPOV( new GLatLng(this.placedb[index][1],	this.placedb[index][2]), {yaw:this.placedb[index][6],pitch:this.placedb[index][7],zoom:0} );
		}
		else
      {	this.googlemapobj.setCenter(new GLatLng(this.placedb[index][1],	this.placedb[index][2]), this.placedb[index][3]);
		}

	},
	addmarker:function(item)
	{	var point=new GLatLng(item[1],item[2]);	msg=item[4];
		if(item[5])
		{	var icon = new GIcon();
			if(item[5].indexOf(';')!=-1) //viene con tamaño
			{	var part=new Array(); part=item[5].split(";");	icon.image=part[1];
				if(part[0].indexOf('x')) { var size=new Array(); size=part[0].split("x");
				icon.iconSize = new GSize(parseFloat(size[0]), parseFloat(size[1]));
				icon.iconAnchor = new GPoint(parseFloat(size[0])/2, parseFloat(size[1])  );
				icon.infoWindowAnchor = new GPoint(parseFloat(size[0])/2,parseFloat(size[1])/2 ); }
			}
			else icon.image=item[5];
			var marker=new GMarker(point,icon);
		}
		else var marker=new GMarker(point);

		if(item[4])
		{	GEvent.addListener(marker,"load",function(){marker.openInfoWindowHtml(""+item[4]+"");});
			GEvent.addListener(marker,"click",function(){marker.openInfoWindowHtml(""+item[4]+"");});
		}

		this.googlemapobj.addOverlay(marker);
	}
};

//googlemaps.init();
