/*
	Copyright MAPIDIRECTORIO.COM 2009
	Author: Sergio Armando Vasquez Colorado
	Email: servas@pgmail.com
	
	Triangulo Inmobiliario - Sistema publico Version 1
*/

/*
	Inicio Clase Punto
*/
	
	function Punto(lat,lng,inmuebleID,htmlCode,title) {
	    this.lat = lat;
		this.lng = lng;
		this.negocioID = inmuebleID;
		this.htmlCode = htmlCode;
		this.title = title;
	}

	Punto.prototype.lat;
	Punto.prototype.lng;
	Punto.prototype.inmuebleID;
	Punto.prototype.htmlCode;
	Punto.prototype.title;
	
/*
	Fin Clase Punto
*/

var puntoInicial = "(6.249797783371488, -75.568106174469)";
var Puntos;
var minMapScale = 8;
var maxMapScale = 18;
var homeHTML = "punto de prueba";
var map;
var Markers;
var mapaOculto = false;
var actualPage = 1;
var orderby = "precio asc";
var actualQuery = "";
var filtros = [];
var filtrosText = [];
var maphidden = false;
var paginaInmueble_Global = false;

function initialize() {
	if (GBrowserIsCompatible() && document.getElementById("mapapropiedades")) {	  
		map = new GMap2(document.getElementById("mapapropiedades"));

		//var cookie = getCookieLatLng();
		eval("var center = new GLatLng"+puntoInicial+"");
		/*if(cookie != null && cookie != ""){
			eval("center = new GLatLng" + cookie +"");
		}*/
		
		map.setCenter(center, 13);
		map.enableScrollWheelZoom();
		map.enableContinuousZoom();
		map.setMapType(G_HYBRID_MAP);
		
		//map.openInfoWindowHtml(center,"<strong style='color:#239DCB'>Triangulo Inmobiliario 2009</strong><br><strong>Cargando Datos. Por favor espere...</strong>");

		blankIcon = new GIcon(G_DEFAULT_ICON);
        blankIcon.image = "img/marker.gif";
		
        /*homemarker = new GMarker(center, {icon: blankIcon, title: "Mi ubicacion fisica (Punto arrastrable)" ,draggable: true});
		
        GEvent.addListener(homemarker, "dragstart", function() {
          map.closeInfoWindow();
        });
        GEvent.addListener(homemarker, "dragend", function() {
		  /*setCookieLatLng(homemarker.getPoint());
		  if(getCookieAyuda() != "yes"){
			  setCookieAyuda("no");
		  }*/
        /*  homemarker.openInfoWindowHtml(homeHTML);
        });
		GEvent.addListener(homemarker, "click", function() {
          homemarker.openInfoWindowHtml(homeHTML);
        });
		*/
		
		//map.addOverlay(homemarker);
		setTimeout("loadDataAndMarkers()",5);
		
		setTimeout("loadMapAddOns()",1000);
		
		loadToolTips();
		
  GMarker.prototype.hide = function (){
    if (this.getPoint().lat() < 90)
      try {
        this.savePoint = this.getPoint();
        this.setPoint(new GLatLng(90, 0));
      } catch(e) {}
  }
  GMarker.prototype.show = function (){
    if (this.getPoint().lat() == 90)
    if (this.savePoint)
      try {
        this.setPoint(this.savePoint);
        this.savePoint = null;
      } catch(e) {}
  } 
  
	/*var tooltip = document.getElementById("tooltip");
	ox=10;
	oy=10;
	lockX=0;
	lockY=0;
	tooltip.style.padding="0px 0px 0px 0px";*/
  
      }
    }
	
function loadMapAddOns(){
	// get array of map types
	var mapTypes = map.getMapTypes();
	// overwrite the getMinimumResolution() and getMaximumResolution() methods for each map type
	for (var i=0; i<mapTypes.length; i++) {
		mapTypes[i].getMinimumResolution = function() {return minMapScale;}
		mapTypes[i].getMaximumResolution = function() {return maxMapScale;}
	} 
	
	var fisico = G_PHYSICAL_MAP;
	fisico.getMinimumResolution = function() {return minMapScale;};
	map.addMapType(fisico);	
	map.addControl(new GScaleControl());
	map.addControl(new GLargeMapControl());
	
	var mapControl = new GMapTypeControl();
	map.addControl(mapControl);
	
	new GKeyboardHandler(map);
}

function loadDataAndMarkers(){
	new Ajax.Request("load_inmuebles_markers.php", {
	  method: 'get',
	  onSuccess: function(transport) {
		//alert(transport.responseText);
		eval(transport.responseText);
		//alert("cargado");
		loadMarkers();
		
	  }
	});
}

function loadMarkers(){
	//map.clearOverlays();
	mm = new GMarkerManager(map); 
	Markers = new Array();
	for (var i = 0; i < Puntos.length; i++) {
		
		var latlng = new GLatLng(Puntos[i].lat,Puntos[i].lng);
		Markers[i] = new GMarker(latlng,{icon: blankIcon, title: Puntos[i].title});
		
		eval("GEvent.addListener(Markers["+i+"], 'click', function() {Markers["+i+"].openInfoWindowHtml(Puntos["+i+"].htmlCode); });");
		
		//mm.addMarker(Markers[i],13); 
	}
	mm.addMarkers(Markers, 12)
	mm.refresh();
	
	//TooltipManager.init("tooltip", {url: "load_inmuebles_markers.php", options: {method: 'get'}}, {showEffect: Element.show, hideEffect: Element.hide});
	//TooltipManager.addAjax("opfiltro", {url: "load_inmuebles_markers.php", options: {method: 'get'}});
	

		
	/*var evento = GEvent.addListener(mm, "changed", function(bounds,markerCount) {
		map.addOverlay(homemarker);
		if(!paginaNegocio_Global)setTimeout("homemarker.openInfoWindowHtml(homeHTML)",500)
		GEvent.removeListener(evento);
		loadPuntosInteres();
	});*/
}

function openInmu(cod,titulo){
	
	var url = "info_inmueble.php?id="+cod;
	if (document.body && (document.body.clientWidth !=0)) {
	  clientWidth=document.body.clientWidth;
	  clientHeight=document.body.clientHeight;
   }
   if (document.documentElement && (document.documentElement.clientWidth!=0) && (document.body.clientWidth + 20 >= document.documentElement.clientWidth)) {
		clientWidth=document.documentElement.clientWidth;   
		clientHeight=document.documentElement.clientHeight;   
	}   

	var win;
	if(clientHeight > 540){
		win = new Window({className: "alphacube", title: titulo+" - Triangulo Inmobiliario", width:850, height:510, url: url,resizable:false,minimizable:false,maximizable:false, recenterAuto:false, showEffectOptions: {duration:1.5}});
	}else{
		win = new Window({className: "alphacube", title: titulo+" - Triangulo Inmobiliario", width:850, height:(clientHeight-40), url: url,resizable:false,minimizable:false,maximizable:false, recenterAuto:false, showEffectOptions: {duration:1.5}});
	}

	win.setZIndex(5);
	
	win.showCenter(true); 
	win.setDestroyOnClose();
	//win.updateWidth();
	//setTimeout("win.updateWidth()",1500);
	
}

function showInmueble(id,titulo){
	if(maphidden || !findOnMap(id)){
		openInmu(id,titulo);
	}
}

function findOnMap(id){
	var found = false;
	var breakvar = false;
	var i =0;
	if(!Puntos)return found;
	while(i < Puntos.length && !breakvar){
		if(Puntos[i].negocioID == id){
			map.setCenter(Markers[i].getLatLng());
			breakvar = true;
			
			setTimeout("Markers["+i+"].openInfoWindowHtml(Puntos["+i+"].htmlCode)",800);
			found = true;
		}
		i++;
	}
	return found;
}


function getResults(pagen){
	actualPage = pagen;
	document.getElementById('resultspage').innerHTML = "<br><br><br><br><div align=\"center\"><img src=\"img/ajax_loader.gif\" /></div>";
	new Ajax.Request("load_results.php?page="+pagen+"&orderby="+orderby+"&q="+actualQuery+"&f="+getFiltro(), {
	  method: 'get',
	  onSuccess: function(transport) {
		//alert(transport.responseText);
		document.getElementById('resultspage').innerHTML = transport.responseText;
		//alert("cargado");
		
	  }
	});
	
}

function helpSearch(text){
	document.getElementById("q").value = text;
	buscar();
}

function buscar(){
	actualQuery = document.getElementById("q").value;
	getResults(1);
}

function buscarEnter(e){
	var keynum;
	
	if(window.event) // IE
	{
		keynum = e.keyCode
	}
	else if(e.which) // Netscape/Firefox/Opera
	{
		keynum = e.which
	}
	if(keynum == 13)
		buscar();
}

function orderBy(orderbyvar){
	orderby = orderbyvar;
	getResults(actualPage);
}

function loadToolTips(){
	
	TooltipManager.addHTML("opfiltro", "filterparams",{delayOut: 800, shiftX: 10, shiftY: 0});
	
	TooltipManager.addHTML("order", "orderparams",{delayOver:100, delayOut: 800, shiftX: 10, shiftY: 0, width:285});
}

function hideMap(){
	document.getElementById("mapapropiedades").style.display = "none";
	document.getElementById("resultssmall").style.width = "938px";
	//document.getElementById("resultssmall").style.textAlign = "center";
	document.getElementById("resultspage").style.width = "938px";
	document.getElementById("resultspage").style.textAlign = "center";
	document.getElementById("hideshowmap").onclick = reshowMap;
	maphidden = true;
}

function reshowMap(){
	document.getElementById("mapapropiedades").style.display = "block";
	document.getElementById("resultssmall").style.width = "285px";
	//document.getElementById("resultssmall").style.textAlign = "center";
	document.getElementById("resultspage").style.width = "285px";
	document.getElementById("resultspage").style.textAlign = "center";
	document.getElementById("hideshowmap").onclick = hideMap;
	maphidden = false;
}

function getElementsByClassName(className, tag, elm){
	var testClass = new RegExp("(^|\\s)" + className + "(\\s|$)");
	var tag = tag || "*";
	var elm = elm || document;
	var elements = (tag == "*" && elm.all)? elm.all : elm.getElementsByTagName(tag);
	var returnElements = [];
	var current;
	var length = elements.length;
	for(var i=0; i<length; i++){
		current = elements[i];
		if(testClass.test(current.className)){
			returnElements.push(current);
		}
	}
	return returnElements;
}

function addFiltro(sentenciaSQL,texto){
	filtros.push(sentenciaSQL);
	filtrosText.push(texto);
	updateGraphicFiltros()
}

function removeFiltro(indice){
	filtros.splice(indice,1);
	filtrosText.splice(indice,1);
	updateGraphicFiltros()
}

function updateGraphicFiltros(){
	var htmlcode = "";
	
	for(i=0; i<filtros.length;i++){
		//if(i>0)temp+=",";
		htmlcode += "<div class=\"filterItem\" > " + filtrosText[i] + " <img style=\"cursor:pointer;\" onclick=\"removeFiltro("+i+")\" align=\"absmiddle\" src=\"img/closefilter.gif\" /></div>"
	}
	document.getElementById("filtros").innerHTML = htmlcode;
	
	getResults(1);
}

function getFiltro(){
	var temp = "";
	for(i=0; i<filtros.length;i++){
		if(i>0)temp+=",";
		temp+=filtros[i];
	}
	return temp;
}

function showThisFilter(obj){
	//alert((obj.parentNode).getElementsByTagName('div')[0]);
	
	var divs = (obj.parentNode.parentNode).getElementsByTagName('div');
	
	for(i=0; i < divs.length; i++){
		if(divs[i].getElementsByTagName('div').length > 0)
		divs[i].getElementsByTagName('div')[0].style.display = "none";
		
	}
	
	(obj.parentNode).getElementsByTagName('div')[0].style.display = "block";
	
	
}


window.onload = function(){
	//resize();
	initialize();
	
	if(paginaInmueble_Global)inmInicio();
	//loadMapAddOns();
	
	/*if(paginaNegocio_Global)negInicio();
	if(resultadoBusquedas_Global)query();
	ventanaAyuda();
	loadNegocios();*/
}