/*** Maplib*/

var geocoder;
var markeridx = 0;
var markers = [];

var bounds = new GLatLngBounds();
var centerDefined = false;
var zomval = 14;
var maps = [];
var themap;
var originalZoom;
var originalCenter;
var originalPoint;

// inicializa el invento. llama a loadcoordinates. ha de ser implementada.

function resetMap(mapid) {
	// alert ("resetMap:"+ mapid);
	var mymap;
	if (mapid == null)
		mapid = 'map';

	if (mapid != null) {
		mymap = maps[mapid];
	}

	if (mymap != null) {
		mymap.clearOverlays();
		markeridx = 0;
		markers = [];

		bounds = new GLatLngBounds();
		centerDefined = false;
		zomval = 14;

		// alert ("mapa limpio");
	} else {
		// alert ("el mapa no estaba inicializado");
	}
}

function initBirujiMap(f, mapid) {
	var mymap;

	if (mapid == null)
		mapid = 'map';

	if (!GBrowserIsCompatible())
		alert("browser not compatible")
	else {
		mymap = new GMap2(document.getElementById(mapid));
		maps[mapid] = mymap;
		mymap.setCenter(new GLatLng(0, 0), 0);

		themap = mymap;

		geocoder = new GClientGeocoder();
		//

		if (f == null) {
			// alert("cargando load coordinates");
			loadCoordinates();
		} else {
			// alert("cargando ajax coordinates");
			f();
		}

		originalZoom = mymap.getBoundsZoomLevel(bounds);

		if (originalZoom > 13)
			originalZoom = 13;

		// mymap.setMapType(G_NORMAL_MAP);

		/*
		 * if (zomval >= 9) mymap.setMapType(G_SATELLITE_MAP); else
		 * mymap.setMapType(G_NORMAL_MAP)
		 * 
		 */
	

		mymap.setZoom(originalZoom);

		if (!centerDefined) {
			var clat = (bounds.getNorthEast().lat() + bounds.getSouthWest()
					.lat()) / 2;
			var clng = (bounds.getNorthEast().lng() + bounds.getSouthWest()
					.lng()) / 2;

			originalCenter = new GLatLng(clat, clng);

			mymap.setCenter(originalCenter);
		}

		if (!editorMode) {

			GEvent.addListener(mymap, "click", function(marker, point) {
				themap.setCenter(point);
				// map.setZoom(map.getZoom()+1);
			});
		}
		/*
		 * mymap.addControl(new GSmallZoomControl());
		 * mymap.removeMapType(G_HYBRID_MAP); mymap.addControl(new
		 * GMapTypeControl());
		 */
		mymap.setUIToDefault();
	}
}

function undoMap(mapid) {
	if (mapid == null)
		mapid = 'map';
	var mymap = maps[mapid];

	if (originalPoint==null)  originalPoint=originalCenter;

	setEditMarker(originalPoint, mymap);
	themap.setCenter(originalPoint, originalZoom);
}

function setDefaultCenter(lat,lng)
{	
	originalCenter=new GLatLng(lat, lng)
}

function setcenter(lat, lng, mapid) {
	if (mapid == null)
		mapid = 'map';
	var mymap = maps[mapid];

	if (lat == 0 || lng == 0)
		return;
	if (isNaN(lat) || isNaN(lng))
		return;

	centerDefined = true;
	mymap.setCenter(new GLatLng(lat, lng));
}

function addLayerBox(min_lat, min_lng, max_lat, max_lng, mindist, mapid) {
	if (mapid == null)
		mapid = 'map';
	var mymap = maps[mapid];
	// alert('addlayer');
	if (min_lat == 0.0 || min_lng == 0.0 || max_lat == 0.0 || max_lng == 0.0)
		return;

	var point = new GLatLng(min_lat, min_lng);
	bounds.extend(point);

	point = new GLatLng(max_lat, max_lng);
	bounds.extend(point);

	if (max_lat - min_lat < mindist) {

		max_lat += mindist;
		min_lat -= mindist;

	}

	if (max_lng - min_lng < mindist) {
		max_lng += mindist;
		min_lng -= mindist;
	}

	pintando_cuadrados = true;

	var polygon = new GPolygon( [ new GLatLng(min_lat, min_lng),
			new GLatLng(min_lat, max_lng), new GLatLng(max_lat, max_lng),
			new GLatLng(max_lat, min_lng), new GLatLng(min_lat, min_lng) ],
			"#f33f00", 1, 11, "#ff0000", 0.2);

	// map = new GMap2(document.getElementById("map"));
	mymap.addOverlay(polygon);

}

// creaq un marker y le vincula la ventana.

function createMarker(point, html, icon_url, mapid) {
	if (mapid == null)
		mapid = 'map';
	var mymap = maps[mapid];
	// var marker= new GMarker(point);

	icon = new GIcon(G_DEFAULT_ICON, icon_url)
	icon.iconSize = new GSize(20, 12);
	var marker = new GMarker(point, icon);
	GEvent.addListener(marker, "click", function() {
		marker.openInfoWindowHtml(html);
	});
	return marker;
}

function addCoordinate(lng, lat, purl, titulo, subtitulo, mapid) 
{
	if (mapid == null)
		mapid = 'map';
	var mymap = maps[mapid];
	if (lat == 0.0 || lng == 0.0) return;

	var point = new GLatLng(lng, lat);
	var marker = createMarker(point, writePictureBallon(titulo, " ", subtitulo), purl);
	markers[markeridx++] = marker;
	mymap.addOverlay(marker);
	bounds.extend(point);
}

// callback para que la API llame cuando busca algo con el geodecoder.
// actualiza el formulario de coordenadas.

function showAddressOLD(address, mapid) {
	if (mapid == null)
		mapid = 'map';
	var mymap = maps[mapid];

	if (geocoder) {
		geocoder.getLocations(address, function(point, mapid) {
			var mymap = maps[mapid];
			if (!point) {
				alert(address + " no encontrada");
			} else {
				themap.setCenter(point, 13);

				setEditMarker(point);
				editMarker.openInfoWindowHtml(address);

			}
		});
	}
}

function showAddress(address, mapid) {

	if (address == null || address.length < 3)
		return false;

	if (mapid == null)
		mapid = 'map';
	var mymap = maps[mapid];

	if (geocoder) {
		geocoder.getLocations(address, function(result, mapid) {

			var mymap = maps[mapid];
			// TODO - traducir msg error
			if (result.Status.code != G_GEO_SUCCESS) {
				alert("[" + result.Status.code + "] " + address
						+ " no encontrada");
			} else {
				place = result.Placemark[0];
				point = new GLatLng(place.Point.coordinates[1],
						place.Point.coordinates[0]);

				themap.setCenter(point, 13);

				str = place.address + '<br>' + '('
						+ place.AddressDetails.Country.CountryNameCode + ')';

				setEditMarker(point);
				editMarker.openInfoWindowHtml(str);

			}
		});
	}
}

// ====== Create a Client Geocoder ======
var mygeo = new GClientGeocoder();

// ====== Array for decoding the failure codes ======
var reasons = [];
reasons[G_GEO_SUCCESS] = "Success";
reasons[G_GEO_MISSING_ADDRESS] = "Missing Address: The address was either missing or had no value.";
reasons[G_GEO_UNKNOWN_ADDRESS] = "Unknown Address:  No corresponding geographic location could be found for the specified address.";
reasons[G_GEO_UNAVAILABLE_ADDRESS] = "Unavailable Address:  The geocode for the given address cannot be returned due to legal or contractual reasons.";
reasons[G_GEO_BAD_KEY] = "Bad Key: The API key is either invalid or does not match the domain for which it was given";
reasons[G_GEO_TOO_MANY_QUERIES] = "Too Many Queries: The daily geocoding quota for this site has been exceeded.";
reasons[G_GEO_SERVER_ERROR] = "Server error: The geocoding request could not be successfully processed.";
reasons[403] = "Error 403: Probably an incorrect error caused by a bug in the handling of invalid JSON.";

// ====== Geocoding ======
function getAddress(search) {
	mygeo.getLocations(search, function(result) {
		// If that was successful
		if (result.Status.code == G_GEO_SUCCESS) {
			// Lets assume that the first marker is the one we want
			alert(result.Placemark.length);
			var p = result.Placemark[0].Point.coordinates;
			var lat = p[1];
			var lng = p[0];
			// Display the results in XML format
			var xml = '&nbsp;&nbsp;&lt;marker address="' + search + '" lat="'
					+ lat + '" lng="' + lng + '"&gt;<br>';
			// document.getElementById("message").innerHTML += xml;
			alert(xml);
		}
		// ====== Decode the error status ======
		else {
			// === if we were sending the requests to fast, try this one again
			// and increase the delay
			if (result.Status.code == G_GEO_TOO_MANY_QUERIES) {
				nextAddress--;
				delay++;
			} else {
				var reason = "Code " + result.Status.code;
				if (reasons[result.Status.code]) {
					reason = reasons[result.Status.code]
				}
				var xml = '&nbsp;&nbsp;&lt;marker address="' + search
						+ '" error="' + reason + '"&gt;<br>';
				document.getElementById("message").innerHTML += xml;
			}
		}

	});
}

var editMarker; // temporal para guardar el marker de posicionamiento en
// edicion
var editorMode = false;

// establece el marker de edicion, acutaliza las coordenadas del formulario
function setEdit(lat, lng, mapid) {
	if (mapid == null)
		mapid = 'map';
	var mymap = maps[mapid];

	var point = new GLatLng(lat, lng)
	
		
	if (lat == 0 || lng == 0)
		return;
	if (isNaN(lat) || isNaN(lng))
		return;

	originalPoint = point;
	setEditMarker(point, mymap);
}

function setEditMarker(point) {

	var mymap = themap;

	if (editMarker != null)
		mymap.removeOverlay(editMarker);

	if (edit_icon != null)
		editMarker = new GMarker(point, edit_icon);
	else
		editMarker = new GMarker(point);
	mymap.addOverlay(editMarker);
	c = editMarker.getPoint();
	document.getElementById('DivesiteLat').value = c.lat();
	;
	document.getElementById('DivesiteLng').value = c.lng();
	// mymap.setCenter(point);
	// map.setZoom(14);
	centerDefined = true;
	updateDegCoordinates(true); // true to avoid recursive call
}

function updateEditMarker() {
	// lat=document.getElementById('DivesiteLat').value;
	mymap = themap;

	if (mymap == null)
		alert("es null");
	lat = document.getElementById('DivesiteLat').value;
	lng = document.getElementById('DivesiteLng').value;
	if (editMarker != null)
		mymap.removeOverlay(editMarker);
	point = new GLatLng(lat, lng);

	if (edit_icon != null)
		editMarker = new GMarker(point, edit_icon);
	else
		editMarker = new GMarker(point);
	mymap.addOverlay(editMarker);

	mymap.setCenter(point);

	centerDefined = true;
}
// establece modo de trabajo "en edicion"
function setEditorMode(mapid) {
	var mymap = maps[mapid];
	editorMode = true;

	GEvent.addListener(mymap, "click", function(marker, point) {
		setEditMarker(point);
	});
}

var edit_icon = null;

function setEditIcon(icon_url, mapid) {
	if (mapid == null)
		mapid = 'map';
	var mymap = maps[mapid];
	edit_icon = new GIcon(G_DEFAULT_ICON, icon_url)
	edit_icon.iconSize = new GSize(20, 12);
}

// va a un marker y abre el baloon
function gotoMarker(id, mapid) {
	if (mapid == null)
		mapid = 'map';
	var mymap = maps[mapid];
	// map.setZoom(2); //TODO poner el zoom adecuado para ver una nuve
	// decente.

	GEvent.trigger(markers[id], 'click');
	return false;
}

// escribe el contendido del baloon. TODO que alguien lo ponga bonito.
function writePictureBallon(url, titulo, subtitulo)
{	
	return '<div style="width:240px">' + titulo + '<br><a href='+url+'>'  + subtitulo + '</a></div>';
}

function updateDegCoordinates2(mapid) {
	if (mapid == null)
		mapid = 'map';
	var mymap = maps[mapid];

	lat = document.getElementById('DivesiteLat').value;
	lng = document.getElementById('DivesiteLng').value;
	signlat = 1;
	signlng = 1;

	if (lat < 0) {
		signlat = -1;
	}
	latAbs = Math.abs(Math.round(lat * 1000000.));

	// Error checks
	// if(latAbs > (90 * 1000000)) { alert(' Degrees Latitude must be in the
	// range of -90. to 90. '); return; }

	// if(lng < 0) { signlng = -1; }
	lngAbs = Math.abs(Math.round(lng * 1000000.));

	// Error checks
	// if(lngAbs > (90 * 1000000)) { alert(' Degrees Latitude must be in the
	// range of -90. to 90. '); return; }

	deg = Math.floor(lngAbs / 1000000) * signlng;
	min = Math.floor(((lngAbs / 1000000) - Math.floor(lngAbs / 1000000)) * 60);
	seg = Math
			.floor(((((lngAbs / 1000000) - Math.floor(lngAbs / 1000000)) * 60) - Math
					.floor(((lngAbs / 1000000) - Math.floor(lngAbs / 1000000)) * 60)) * 100000) * 60 / 100000;

	document.getElementById('hourE').value = deg + 1;
	document.getElementById('minE').value = min;
	document.getElementById('segE').value = seg;

	deg = Math.floor(latAbs / 1000000) * signlat;
	min = Math.floor(((latAbs / 1000000) - Math.floor(latAbs / 1000000)) * 60);
	seg = Math
			.floor(((((latAbs / 1000000) - Math.floor(latAbs / 1000000)) * 60) - Math
					.floor(((latAbs / 1000000) - Math.floor(latAbs / 1000000)) * 60)) * 100000) * 60 / 100000;

	document.getElementById('hourN').value = deg;
	document.getElementById('minN').value = min;
	document.getElementById('segN').value = seg;
	// document.getElementById('DivesiteLat').value=lat;
	// document.getElementById('DivesiteLng').value=lng;
}

function updateDecimalCoordinates() {
	lat = (document.getElementById('hourN').value * 1.0)
			+ document.getElementById('minN').value / 60
			+ document.getElementById('segN').value / 3600;
	lng = (document.getElementById('hourE').value * 1.0)
			+ document.getElementById('minE').value / 60
			+ document.getElementById('segE').value / 3600;

	if (lat == 0 || lng == 0)
		return;
	if (lat == "" || lng == "")
		return;
	if (lat == NaN || lng == NaN)
		return;

	document.getElementById('DivesiteLat').value = lat;
	document.getElementById('DivesiteLng').value = lng;
	updateEditMarker();
	return false;

}

/**
 * Lo saca del formulario campo escondido
 */
function updateDegCoordinates() {
	updateDegCoordinates(false);
}

function updateDegCoordinates(isRecursive) {

	lat = parseFloat(document.getElementById('DivesiteLat').value);
	lng = parseFloat(document.getElementById('DivesiteLng').value);

	if (lat == 0 || lng == 0)
		return;
	if (isNaN(lat) || isNaN(lng))
		return;

	hourN = Math.floor(lat);
	minN = Math.floor((lat - hourN) * 60);
	segN = ((lat - hourN) * 60 - minN) * 60;

	// TODO que hacer si hay menos decimales? cntrolar lognitud string;

	document.getElementById('hourN').value = hourN;
	document.getElementById('minN').value = minN;
	document.getElementById('segN').value = ("" + segN).substring(0, 5);

	hourE = Math.floor(lng);
	minE = Math.floor((lng - hourE) * 60);
	segE = ((lng - hourE) * 60 - minE) * 60;

	// TODO que hacer si hay menos decimales? cntrolar lognitud string;

	document.getElementById('hourE').value = hourE;
	document.getElementById('minE').value = minE;
	document.getElementById('segE').value = ("" + segE).substring(0, 5);
	if (!isRecursive)
		updateEditMarker();

	return false;
}


//** Smooth Navigational Menu- By Dynamic Drive DHTML code library: http://www.dynamicdrive.com
//** Script Download/ instructions page: http://www.dynamicdrive.com/dynamicindex1/ddlevelsmenu/
//** Menu created: Nov 12, 2008

//** Dec 12th, 08" (v1.01): Fixed Shadow issue when multiple LIs within the same UL (level) contain sub menus: http://www.dynamicdrive.com/forums/showthread.php?t=39177&highlight=smooth

//** Feb 11th, 09" (v1.02): The currently active main menu item (LI A) now gets a CSS class of ".selected", including sub menu items.

//** May 1st, 09" (v1.3):
//** 1) Now supports vertical (side bar) menu mode- set "orientation" to 'v'
//** 2) In IE6, shadows are now always disabled

//** July 27th, 09" (v1.31): Fixed bug so shadows can be disabled if desired.
//** Feb 2nd, 10" (v1.4): Adds ability to specify delay before sub menus appear and disappear, respectively. See showhidedelay variable below

var ddsmoothmenu={

//Specify full URL to down and right arrow images (23 is padding-right added to top level LIs with drop downs):
arrowimages: {down:['downarrowclass', '/static/images/icons/blank.gif', 23], right:['rightarrowclass', '/static/images/icons/blank.gif']},
transition: {overtime:300, outtime:300}, //duration of slide in/ out animation, in milliseconds
shadow: {enable:false, offsetx:5, offsety:5}, //enable shadow?
showhidedelay: {showdelay: 100, hidedelay: 200}, //set delay in milliseconds before sub menus appear and disappear, respectively

///////Stop configuring beyond here///////////////////////////

detectwebkit: navigator.userAgent.toLowerCase().indexOf("applewebkit")!=-1, //detect WebKit browsers (Safari, Chrome etc)
detectie6: document.all && !window.XMLHttpRequest,

getajaxmenu:function($, setting){ //function to fetch external page containing the panel DIVs
	var $menucontainer=$('#'+setting.contentsource[0]); //reference empty div on page that will hold menu
	$menucontainer.html("Loading Menu...")
	$.ajax({
		url: setting.contentsource[1], //path to external menu file
		async: true,
		error:function(ajaxrequest){
			$menucontainer.html('Error fetching content. Server Response: '+ajaxrequest.responseText)
		},
		success:function(content){
			$menucontainer.html(content)
			ddsmoothmenu.buildmenu($, setting)
		}
	})
},


buildmenu:function($, setting){
	var smoothmenu=ddsmoothmenu
	var $mainmenu=$("#"+setting.mainmenuid+">ul") //reference main menu UL
	$mainmenu.parent().get(0).className=setting.classname || "ddsmoothmenu"
	var $headers=$mainmenu.find("ul").parent()
	$headers.hover(
		function(e){
			$(this).children('a:eq(0)').addClass('selected')
		},
		function(e){
			$(this).children('a:eq(0)').removeClass('selected')
		}
	)
	$headers.each(function(i){ //loop through each LI header
		var $curobj=$(this).css({zIndex: 100-i}) //reference current LI header
		var $subul=$(this).find('ul:eq(0)').css({display:'block'})
		$subul.data('timers', {})
		this._dimensions={w:this.offsetWidth, h:this.offsetHeight, subulw:$subul.outerWidth(), subulh:$subul.outerHeight()}
		this.istopheader=$curobj.parents("ul").length==1? true : false //is top level header?
		$subul.css({top:this.istopheader && setting.orientation!='v'? this._dimensions.h+"px" : 0})
		$curobj.children("a:eq(0)").css(this.istopheader? {paddingRight: smoothmenu.arrowimages.down[2]} : {}).append( //add arrow images
			'<img src="'+ (this.istopheader && setting.orientation!='v'? smoothmenu.arrowimages.down[1] : smoothmenu.arrowimages.right[1])
			+'" class="' + (this.istopheader && setting.orientation!='v'? smoothmenu.arrowimages.down[0] : smoothmenu.arrowimages.right[0])
			+ '" style="border:0;" />'
		)
		if (smoothmenu.shadow.enable){
			this._shadowoffset={x:(this.istopheader?$subul.offset().left+smoothmenu.shadow.offsetx : this._dimensions.w), y:(this.istopheader? $subul.offset().top+smoothmenu.shadow.offsety : $curobj.position().top)} //store this shadow's offsets
			if (this.istopheader)
				$parentshadow=$(document.body)
			else{
				var $parentLi=$curobj.parents("li:eq(0)")
				$parentshadow=$parentLi.get(0).$shadow
			}
			this.$shadow=$('<div class="ddshadow'+(this.istopheader? ' toplevelshadow' : '')+'"></div>').prependTo($parentshadow).css({left:this._shadowoffset.x+'px', top:this._shadowoffset.y+'px'})  //insert shadow DIV and set it to parent node for the next shadow div
		}
		$curobj.hover(
			function(e){
				var $targetul=$subul //reference UL to reveal
				var header=$curobj.get(0) //reference header LI as DOM object
				clearTimeout($targetul.data('timers').hidetimer)
				$targetul.data('timers').showtimer=setTimeout(function(){
					header._offsets={left:$curobj.offset().left, top:$curobj.offset().top}
					var menuleft=header.istopheader && setting.orientation!='v'? 0 : header._dimensions.w
					menuleft=(header._offsets.left+menuleft+header._dimensions.subulw>$(window).width())? (header.istopheader && setting.orientation!='v'? -header._dimensions.subulw+header._dimensions.w : -header._dimensions.w) : menuleft //calculate this sub menu's offsets from its parent
					if ($targetul.queue().length<=1){ //if 1 or less queued animations
						$targetul.css({left:menuleft+"px", width:header._dimensions.subulw+'px'}).animate({height:'show',opacity:'show'}, ddsmoothmenu.transition.overtime)
						if (smoothmenu.shadow.enable){
							var shadowleft=header.istopheader? $targetul.offset().left+ddsmoothmenu.shadow.offsetx : menuleft
							var shadowtop=header.istopheader?$targetul.offset().top+smoothmenu.shadow.offsety : header._shadowoffset.y
							if (!header.istopheader && ddsmoothmenu.detectwebkit){ //in WebKit browsers, restore shadow's opacity to full
								header.$shadow.css({opacity:1})
							}
							header.$shadow.css({overflow:'', width:header._dimensions.subulw+'px', left:shadowleft+'px', top:shadowtop+'px'}).animate({height:header._dimensions.subulh+'px'}, ddsmoothmenu.transition.overtime)
						}
					}
				}, ddsmoothmenu.showhidedelay.showdelay)
			},
			function(e){
				var $targetul=$subul
				var header=$curobj.get(0)
				clearTimeout($targetul.data('timers').showtimer)
				$targetul.data('timers').hidetimer=setTimeout(function(){
					$targetul.animate({height:'hide', opacity:'hide'}, ddsmoothmenu.transition.outtime)
					if (smoothmenu.shadow.enable){
						if (ddsmoothmenu.detectwebkit){ //in WebKit browsers, set first child shadow's opacity to 0, as "overflow:hidden" doesn't work in them
							header.$shadow.children('div:eq(0)').css({opacity:0})
						}
						header.$shadow.css({overflow:'hidden'}).animate({height:0}, ddsmoothmenu.transition.outtime)
					}
				}, ddsmoothmenu.showhidedelay.hidedelay)
			}
		) //end hover
	}) //end $headers.each()
	$mainmenu.find("ul").css({display:'none', visibility:'visible'})
},

init:function(setting){
	if (typeof setting.customtheme=="object" && setting.customtheme.length==2){ //override default menu colors (default/hover) with custom set?
		var mainmenuid='#'+setting.mainmenuid
		var mainselector=(setting.orientation=="v")? mainmenuid : mainmenuid+', '+mainmenuid
		document.write('<style type="text/css">\n'
			+mainselector+' ul li a {background:'+setting.customtheme[0]+';}\n'
			+mainmenuid+' ul li a:hover {background:'+setting.customtheme[1]+';}\n'
		+'</style>')
	}
	this.shadow.enable=(document.all && !window.XMLHttpRequest)? false : this.shadow.enable //in IE6, always disable shadow
	jQuery(document).ready(function($){ //ajax menu?
		if (typeof setting.contentsource=="object"){ //if external ajax menu
			ddsmoothmenu.getajaxmenu($, setting)
		}
		else{ //else if markup menu
			ddsmoothmenu.buildmenu($, setting)
		}
	})
}

} //end ddsmoothmenu variable
