var point_markers = [];
var panoramioLayer = null;
var wikipediaLayer = null;

function voteUpById( _mapId ) {
	AjaxService.voteUp(_mapId, {async: false, callback: postVoteUp});
}

function voteUp() {
	AjaxService.voteUp(mapId, postVoteUp);
}

function postVoteUp(data) {
	document.id('votesUp').set('html', data );
	Sexy.info(rutaminaLabels["vote.thanks"]);
}

function voteDown() {
	AjaxService.voteDown(mapId, postVoteDown);
}

function postVoteDown(data) {
	document.id('votesDown').set('html','('+data+')');
}

function send() {
	SexyLightbox.show(rutaminaLabels["detail.pop.send"],'/send?mapId=' + mapId + '&TB_iframe=true&amp;height=400&amp;width=750', 'sexylightbox');
}

function goPrintOptions(url) {
	SexyLightbox.show(rutaminaLabels["detail.pop.print"], url + '/print?TB_iframe=true&amp;height=350&amp;width=550', 'sexylightbox');
}

function goPdfOptions(url) {
	SexyLightbox.show(rutaminaLabels["detail.pop.pdf"], url + '/pdf?TB_iframe=true&amp;height=300&amp;width=550', 'sexylightbox');
}

function integration() {	
	SexyLightbox.show(rutaminaLabels["detail.pop.integration"],'/integrate?r=' + mapId + '&TB_iframe=true&amp;height=250&amp;width=500', 'sexylightbox');
}

function goPrintOptionsDetail(url) {
	sexyLB.show(rutaminaLabels["detail.pop.print"], url + '/print?TB_iframe=true&amp;height=350&amp;width=550', 'sexylightbox');
}

function goPdfOptionsDetail(url) {
	sexyLB.show(rutaminaLabels["detail.pop.pdf"], url + '/pdf?TB_iframe=true&amp;height=300&amp;width=550', 'sexylightbox');
}

function integrationDetail() {
	sexyLB.show(rutaminaLabels["detail.pop.integration"],'/integrate?r=' + mapId + '&TB_iframe=true&amp;height=250&amp;width=500', 'sexylightbox');
}

function downloadDetail(url) {
	sexyLB.show(rutaminaLabels["detail.pop.download"], url + '/download?TB_iframe=true&amp;height=300&amp;width=750', 'sexylightbox');
}

function download(url) {
	SexyLightbox.show(rutaminaLabels["detail.pop.download"], url + '/download?TB_iframe=true&amp;height=300&amp;width=750', 'sexylightbox');
}

function showMap() {
	if (!GBrowserIsCompatible()) {
		  Sexy.error('Your browser is not compatible with the Google Maps API');
	    return;
	  }

	  document.map = new GMap2(document.getElementById("map_canvas"));
	  //document.map.setCenter(new GLatLng(37.4419, -122.1419), 13);
	  document.map.addControl(new GSmallMapControl());
	  document.map.addControl(new GMapTypeControl());
	  
	  document.overlay = GPolyline.fromEncoded({color: "#0000FF",
	        weight: 5,
	        points: mapEncodedLine,
	        zoomFactor: 32,
	        levels: mapEncodedLevel,
	        numLevels: 4
	       });

	  setTimeout("centerMap()", 100);
		
}

function centerMap() {
	document.map.setCenter(new GLatLng(mapLatitude, mapLongitude), 14, getMapType());
		
	GEvent.addListener(document.map, "maptypechanged", function() {
			setMapType(document.map.getCurrentMapType().getName(true));
	});
	setTimeout("addLine()", 100);
}

function addLine() {
	document.map.addOverlay(document.overlay);

	
	setPoints();
}

var points = null;

function setPoints() {
	if (points == null) {
		AjaxService.getPoints(mapId, postGetPoints);
	} else {

		var position = 1;
		var bounds = new GLatLngBounds();
		var centrar = false;
		for (var i in points) {
			objeto = points[i];
			if (objeto["type"] && objeto["type"] == 1 && objeto["description"] && objeto["description"].length>0) {
				centrar = true;
				
			    var icon = new GIcon(G_DEFAULT_ICON); 
			    icon.image = "http://rutamina.com/images/markers/marker" + position + ".png";

			    var point = new GLatLng(objeto["latitude"], objeto["longitude"]);
			    bounds.extend(point);
				var marker = createMarker(point, objeto, icon);
				document.map.addOverlay(marker);
				position++;
			}
		}
		if (centrar) {
			document.map.setZoom(document.map.getBoundsZoomLevel(bounds));
			document.map.setCenter(bounds.getCenter());
		}
		createTabs();
	}
}
	


function createMarker(point, objeto, icon) {
	var options = { 
			draggable: false,
			icon: icon
			};

	
	var marker = new GMarker(point, options);
	
	if (objeto["title"] != "" && objeto["title"] != null && objeto["title"] != "null") {
	
	    GEvent.addListener(marker, "click", function() {
	    	marker.openInfoWindowHtml(getDetail(objeto));
	     	});
    
	}
	return marker;
}

function getDetail(objeto) {
	var textoHtml ='<div style="width:450px;height:300px;">';
	textoHtml +=   '    <div style="overflow:auto;width:450px;height:300px;">';
	textoHtml +=   '        <div style="width: 415px;padding-bottom:15px">';
	textoHtml +=   '            <img style="width:200px;height:49px;" src="/images/rutamina-rosa.gif"/>';
	textoHtml +=   '        </div>';
	textoHtml +=   '        <p><strong>' + objeto["title"] + '</strong></p>';
	textoHtml +=   '        <div style="width: 415px;">';
	if (objeto["resource"]) {
	   textoHtml += '           <img align="right" style="width:180px;height:133px; padding-left:10px;padding-bottom:10px" src="/resources/maps/' + objeto['mapPointId'] + '/' + '250px-' + objeto['resource']['resource'] + '"/>';
	}
	textoHtml +=   '            <p style="text-align:justify;">' + objeto["description"] + '</p>';
	textoHtml +=   '        </div>';
	
	textoHtml +=   '   </div>';
	textoHtml +=   '</div>';
	return textoHtml;
}
	
function postGetPoints(data) {
	points = data;
	setPoints();
}

function notLoggedUserAlert(){
	 	Sexy.alert(rutaminaLabels["login.required"]);
}

function setFavorite(){
	 if(userId==null){
	 	notLoggedUserAlert();
	 }else {
		AjaxService.setFavorite(userId, mapId, postSetFavorite);
	 }
}

function postSetFavorite(data){
	if(data==0){
		Sexy.alert(rutaminaLabels["detail.fav.ko"]);
	} else {
		Sexy.alert(rutaminaLabels["detail.fav.ok"]);
	}
	return false;
}

function facebookSharer(){
	if(fb_share_url!=null){
		var share="http://www.facebook.com/sharer.php?u="+fb_share_url+"&title="+window.title;
		window.open(share, "ventana1" , "width=600,height=400,scrollbars=NO");
	}
}

function checkElevationGraph() {
	var existe = false;
	document.id('elevationGraph').getChildren().each(function(el){
		el.addEvent('click',function(e){
			SexyLightbox.show('Elevaciin', el.src.replace(/w=252/, "w=650") + "&filetype=.png" , 'sexylightbox');
	    });
		existe = true;
	});
	if (!existe) {
		setTimeout("checkElevationGraph()", 1000);
	}
}

function handlePanomError(errorCode) {
	document.id('zonaPanom').setStyle('display', 'none');
}  

function createAccordion() {
	//create our Accordion instance
	var myAccordion = new Accordion(document.id('accordion'), 'h3.toggler', 'div.element', {
		opacity: false,
		onActive: function(toggler, element){
			toggler.setStyle('color', '#41464D');
		},
		onBackground: function(toggler, element){
			toggler.setStyle('color', '#528CE0');
		}
	});

}

var tab1Show = false;
var movimientoTabs = 222;

var mapX = null;
var mapY = null;
var mapWidth = null;
var mapHeight = null;
var tabWidth = null;

function createTabs() {
	if (document.all) {
		mapX = document.id('map_canvas').getPosition()['x']-3;
		mapY = document.id('map_canvas').getPosition()['y'];
		mapWidth = document.id('map_canvas').getSize()['x'];
		mapHeight = document.id('map_canvas').getSize()['y'];
		tabWidth = 222;
		movimientoTabs = 200;
		
	} else {
		mapX = document.id('map_canvas').getPosition()['x'];
		mapY = document.id('map_canvas').getPosition()['y'];
		mapWidth = document.id('map_canvas').getSize()['x'];
		mapHeight = document.id('map_canvas').getSize()['y'];
		tabWidth = 244;
		movimientoTabs = 222;
	}
	
	var tab1 = new Element( 'div' , { 'id': 'tab1', 'style' : 'z-index:9990;width:' + tabWidth + 'px;position:absolute; top:' + (mapY + 80) + 'px; left:' + (mapX + mapWidth - 30 ) + 'px;' }).injectTop(document.body);
	
	var tab1Text = '<div id="tabMenu1" class="tabMenu">';
	tab1Text += '<a href="javascript:void(0)" id="toggle1"><img src="/images/es/tab1.gif"/></a></div>';
	tab1Text += '<div id="v-menu1" class="v-menu">';
	tab1Text += rutaminaLabels["tab1.select"] + '...<br/><br/>';
	tab1Text += '<input type="checkbox" id="panoramioSelected"/>Panoramio<br/>';
	tab1Text += '<input type="checkbox" id="wikipediaSelected"/>Wikipedia<br/>';
	tab1Text += '<br/><br/>';
	tab1Text += '<input type="checkbox" id="servicios" value="puntos de interes"/>' + rutaminaLabels["tab1.poi"] + '<br/>';
	tab1Text += '<input type="checkbox" id="servicios" value="museos"/>' + rutaminaLabels["tab1.museum"] + '<br/>';
	tab1Text += '<input type="checkbox" id="servicios" value="hoteles"/>' + rutaminaLabels["tab1.hotel"] + '<br/>';
	tab1Text += '<input type="checkbox" id="servicios" value="bares,cafeterias"/>' + rutaminaLabels["tab1.bar"] + '<br/>';
	tab1Text += '<input type="checkbox" id="servicios" value="restaurantes"/>' + rutaminaLabels["tab1.restaurant"] + '<br/>';
	tab1Text += '<input type="checkbox" id="servicios" value="discotecas,pubs,bares de copas"/>' + rutaminaLabels["tab1.pubs"] + '<br/>';
	tab1Text += '<br/><br/>';
	//tab1Text += '<a href="javascript:loadRoutes(); hideTab1();"><img src="/images/es/bot_cerrar.gif"/></a>';
	tab1Text += '<input id="closeButtonId" type="button" onclick="loadRoutes(); hideTab1();" value="' + rutaminaLabels["tab1.close"] + '" alt="' + rutaminaLabels["tab1.close"] + '" title="' + rutaminaLabels["tab1.close"] + '"/>';
	tab1Text += '</div>';
	tab1.set('html',tab1Text);
	document.id('toggle1').addEvent('click', function(e){
		if (tab1Show) {
			hideTab1();
		} else {
			showTab1();
		}
	});
}

function showTab1() {
	if (!tab1Show) {
		document.id('v-menu1').setStyles({
			display:'block'
		});
		document.id('tab1').position({x:mapX + mapWidth - 30 - movimientoTabs, y: document.id('tab1').getPosition()['y']});
		tab1Show=true;
		$$('#closeButtonId').DoSexy();

	}
}

function hideTab1() {
	if (tab1Show) {
		document.id('v-menu1').setStyles({
			display:'none'
		});
		document.id('tab1').position({x: mapX + mapWidth - 30, y: document.id('tab1').getPosition()['y']});
		tab1Show=false;
	}
}

function loadAjaxServices(neLatitude, neLongitude, soLatitude, soLongitude, services) {
	AjaxService.getNearestServices(neLatitude, neLongitude, soLatitude, soLongitude, services, postLoadAjaxServices);
}

function loadRoutes() {
	deleteAllMarkers();

	var bounds = document.map.getBounds();
	var ne = bounds.getNorthEast();
	var so = bounds.getSouthWest();

	if (document.id('panoramioSelected') && document.id('panoramioSelected').checked && panoramioLayer == null) {
		panoramioLayer = new GLayer("com.panoramio.all");
	    document.map.addOverlay(panoramioLayer);
	} else {
		if (panoramioLayer != null) {
			document.map.removeOverlay(panoramioLayer);
			panoramioLayer = null;
		}
	}

	if (document.id('wikipediaSelected') && document.id('wikipediaSelected').checked && wikipediaLayer == null) {
		wikipediaLayer = new GLayer("org.wikipedia.es");
	    document.map.addOverlay(wikipediaLayer);
	} else {
		if (wikipediaLayer != null) {
			document.map.removeOverlay(wikipediaLayer);
			wikipediaLayer = null;
		}
	}
	
	var lsInputs = document.getElementsByTagName("input");
	
	var servicios = "";
	if (lsInputs) {
		for (var i in lsInputs) {
			if (lsInputs[i].id == 'servicios' && lsInputs[i].checked) {
				servicios+=lsInputs[i].value+",";
			}
		}
	}
	
	if (servicios.length > 0) {
		loadAjaxServices(ne.lat(), ne.lng(), so.lat(), so.lng(), servicios);
	}
	
}

function postLoadAjaxServices(data) {
	for (var i in data) {
		objeto = data[i];
				
		var point = new GLatLng(objeto["latitude"], objeto["longitude"]);

		if (objeto["type"]) {
		
		    var icon = new GIcon(G_DEFAULT_ICON); 
		    icon.image = "http://rutamina.com/images/markers/poi/" + objeto["icon"];
			icon.iconSize = new GSize(32, 37);
			
			var marker = createServiceMarker(point, objeto, icon);
			document.map.addOverlay(marker);
			point_markers[point_markers.length] = marker;
	
		}
	}
}

function deleteAllMarkers() {

	if (panoramioLayer != null) {
		document.map.removeOverlay(panoramioLayer);
		panoramioLayer = null;
	}
	if (wikipediaLayer != null) {
		document.map.removeOverlay(wikipediaLayer);
		wikipediaLayer = null;
	}
	for(var i = 0; i < point_markers.length; ++i) {
		document.map.removeOverlay(point_markers[i]);
	}

	point_markers = [];
}

function createServiceMarker(point, objeto, icon) {
	var options = { 
			draggable: false,
			icon: icon
			};

	
	var marker = new GMarker(point, options);
    GEvent.addListener(marker, "click", function() {
    	marker.openInfoWindowHtml(getServiceDetail(objeto));
     	}); 
	return marker;
}

function getServiceDetail(objeto) {
	var textoHtml ='<div style="width:450px;height:300px;">';
	textoHtml +=   '    <div style="overflow:auto;width:450px;height:300px;">';
	textoHtml +=   '        <div style="width: 415px;padding-bottom:15px">';
	textoHtml +=   '            <img style="width:200px;height:49px;" src="/images/rutamina-rosa.gif"/>';
	textoHtml +=   '        </div>';
	textoHtml +=   '        <p><strong>' + objeto["title"] + '</strong></p>';
	textoHtml +=   '        <div style="width: 415px;">';
	if (objeto["image"]) {
	   textoHtml += '           <img align="right" style="width:180px;height:133px; padding-left:10px;padding-bottom:10px" src="' + objeto['image'] + '"/>';
	}
	textoHtml +=   '            <p style="text-align:justify;">' + objeto["summary"] + '</p>';
	textoHtml +=   '        </div>';
	textoHtml +=   '        <div style="float:right; width: 350px; text-align: right;">';
	textoHtml +=   '             <a href="' + objeto['url'] + '" target="_blank" class="gris12">';
	textoHtml +=   '                  <img src="/images/logo_11870.gif"/>';
	textoHtml +=   '             </a>';
	textoHtml +=   '        </div>';
	
	textoHtml +=   '   </div>';
	textoHtml +=   '</div>';

	return textoHtml;
}

	
