﻿var Gmap, tipo, iC, aff = true, ven = true, minp = 0, maxp = 0, tuttip = true, tip = 131071, cl, city, cprev, istat, fb=false, mrkrs = [];

function setTB(a)
{
   var b = 1;
   for(var c = 1; c < 12; c ++ )
   {
      $("#T" + c).attr("checked", (a & b)!=0);
      b += b
   }
   $("#T15").attr("checked", (a & 65536)!=0);
   tip = a
}
function setT(d)
{
   setTB(d ? 131071 : 0);
   GetMappa()
}
function prezzo_onclick(a)
{
   tuttip = a;
   GetMappa()
}
function ven_onclick(a)
{
   ven = a;
   if( ! (aff || ven))
   {
      $("#Aff").attr("checked", aff = true)
   }
   GetMappa()
}
function aff_onclick(a)
{
   aff = a;
   if( ! (aff || ven))
   {
      $("#Ven").attr("checked", ven = true)
   }
   GetMappa()
}
function tip_onclick(g, a)
{
   tip |= a;
   if( ! g)
   {
      tip ^= a
   }
   GetMappa()
}
function maxp_onchange(a)
{
   maxp = a;
   GetMappa()
}
function minp_onchange(a)
{
   minp = a;
   GetMappa()
}
function loadS()
{
	tipo=getP('t');
	if(tipo!="") setTB(tipo);
	if(getP('c')=='A') $("#Ven").attr("checked", ven=false);
	if(getP('c')=='V') $("#Aff").attr("checked", aff=false);
	istat=getP('istat');
	
	dropShadow("base");
	roundedCorner("cerca", "v");
	
	iS = new google.maps.Size(20, 20);
	iP = new google.maps.Point(0,0);
	iA = new google.maps.Point(10, 10);
	iC = new Array();
	
	for(i=0;i<4;i++){iC[i] = new google.maps.MarkerImage("/icons/casa"+i+".png",iS,iP,iA);}
	
	setLatLon();
	// GetMappa()
	initInput()
}
function GetMappa()
{
	city = true;
	Zoom = Gmap.getZoom();	
	cl = true;
	if(Zoom){GetAnnunci();}
}
function getLL(lat,lon)
{
	alert("Ancora da implementare");
}
function GetAnnunci()
{
	
	point = Gmap.getCenter();
   if(point)
   {
	$("#annuncio").hide();
      var bounds = Gmap.getBounds();
      var j = "MaxLat=" + bounds.getNorthEast().lat() + "&MaxLon=" + bounds.getNorthEast().lng() + "&MinLat=" + bounds.getSouthWest().lat() + "&MinLon=" + bounds.getSouthWest().lng();
      if(aff != ven)
      {
         j += setPar("Contratto", ven?"V":"A")
      }
      if(minp > 0)
      {
         j += setPar("MinP", minp)
      }
      if(maxp > 0)
      {
         j += setPar("MaxP", maxp)
      }
      if( ! tuttip)
      {
         j += setPar("SenzaP", "N")
      }
      if(tip != 16383)
      {
         j += setPar("Tipo", tip)
      }
	  $.ajax(
      {
         type : "GET", contentType : "application/json; charset=utf-8", dataType : "json", url : "/vc/an2", data : j, processData : false, success : function(d)
         {
			if(cl)
            {
			cl = false;
			if(mrkrs){for (i in mrkrs)mrkrs[i].setMap(null);mrkrs.length = 0;}
			var f, k;
			if(d.com)
			{
				for(k = 0; k < d.com.length; k ++ )
				{
					f = d.com[k];
					var l="<a target=_blank href='/cerca.html?istat="+f.Istat+"'>";
					var g = "<div class=mrkcom>" + f.Com + "</div>";
					g += "<div class=mrktip><br />Presenti " + f.Num + " annunci</div>";
					g += "<div class=mrkinfo>"+l+"Per zoomare clicca sull'icona</a></div>";
					createMarker(f.Lat, f.Lon, g, 2, "TODO:inserire il link allo zoom");
				}
			}
			if(d.ann)
			{
				for(k = 0; k < d.ann.length; k ++ )
				{
					f = d.ann[k];
					var l="<a target=_blank href='/vc/red?id="+f.Id+"'>", g = "<div class=mrkcom>" + f.Com + "</div>";
					if(f.Img!="") g = "<div class=mrkimg>"+l+"<img border=0 src='"+f.Img+"' /></a></div>"+g;
					g += "<div class=mrktip>" + getTipo(f.Tipo)+" in "+((f.Con=="A")?"affitto":"vendita")+"</div>";
					if(f.Prezzo) g += "<div class=mrkprz>" + formatta(f.Prezzo) + " euro</div>";
					g += "<div class=mrkinfo>Classe energetica"+(f.Classe!='0'?": " + f.Classe:" non definita") + "<br/>"+l+"Per i dettagli clicca sull'icona</a></div>";

					createMarker(f.Lat, f.Lon, g, 3, "id=" + f.Id);
				}
			}
			if(mrkrs){for(i in mrkrs) mrkrs[i].setMap(Gmap);}
         }
		 }
         , error : function(f, d, g)
         {
         }
      }
      );
   }
}
function createMarker(m, d, n, f, a)
{
	m = new google.maps.Marker({position: new google.maps.LatLng(m,d), map: Gmap, icon: iC[f]});
	google.maps.event.addListener(m, "mouseover", function(){ShowAnn(n)});
	if(a){google.maps.event.addListener(m, "click", function(){apri("/vc/red?" + a)})}
	mrkrs.push(m);
	return m;
}
function getZoom(m, n, a, o, d)
{
   var f = new google.maps.LatLngBounds();
   f.extend(new google.maps.LatLng(n, a));
   f.extend(new google.maps.LatLng(o, d));
   return m.getBoundsZoomLevel(f)
}
function setLatLon()
{
	var a;
	if(istat) a=setPar("Istat",istat);
	
	if(aff!=ven){a+=setPar("c", aff?"A":"V");}
	if(tip!=131071) a+=setPar("Tipo",tip);
	if(minp>0) a+=setPar("MinP",minp);
	if(maxp>0) a+=setPar("MaxP",maxp);
	if(!tuttip) a+=setPar("SenzaP","N");

	$.ajax(	{type : "GET", contentType : "application/json; charset=utf-8", dataType : "json", url : "/vc/ll100", data : a, processData : false, success : function(d)
				{
					if(!Gmap) SetMap();
					if(d.Com)fadeImmoPub("P1="+d.Com);
					if(d.Zoom)
					{
						Gmap.setCenter(new google.maps.LatLng(d.Lat, d.Lon));
						Gmap.setZoom(parseInt(d.Zoom));
					} else if(d.MaxLat)
					{
						var sw = new google.maps.LatLng(d.MinLat, d.MinLon);
						var ne = new google.maps.LatLng(d.MaxLat, d.MaxLon);
						var b = new google.maps.LatLngBounds(sw,ne);
						fb=true;
						Gmap.fitBounds(b);
						// Gmap.fitBounds(new google.maps.LatLngBounds(new google.maps.LatLng(d.MinLat, d.MinLon),new google.maps.LatLng(d.MaxLat, d.MaxLon)));
					}
				}, error : function(d, j, h){}
			}
		 )
}
function clickcomune(a)
{
   window.document.location = "cerca.html?istat=" + a.id
}
function vaia(a)
{
	istat=a.id;
	setLatLon();
}
function apri(a)
{
   window.open(a, "_blank")
}
function getTipo(a)
{
   if(a == 1)
   {
      return"Monolocale"
   }
   if(a == 2)
   {
      return"Bilocale"
   }
   if(a == 4)
   {
      return"Trilocale"
   }
   if(a == 8)
   {
      return"Appartamento"
   }
   if(a == 16)
   {
      return"Box o posto auto"
   }
   if(a == 32)
   {
      return"Villa"
   }
   if(a == 64)
   {
      return"Loft o open space"
   }
   if(a == 128)
   {
      return"Multiproprietà"
   }
   if(a == 256)
   {
      return"Rustico o casale"
   }
   if(a == 512)
   {
      return"Terreno"
   }
   if(a == 1024)
   {
      return"Commerciale"
   }
   if(a == 65536)
   {
      return"Altro"
   }
}
function formatta(g)
{
   x = g + "";
   var a = /(\d+)(\d{3})/;
   while(a.test(x))
   {
      x = x.replace(a, "$1.$2")
   }
   return x
}
function addAdsense()
{
   var a =
   {
      maxAdsOnMap : 3, style : "adunit"
   }
   ;
   adsManager = new GAdsManager(Gmap, "pub-0160037778132923", a);
   adsManager.enable()
}
function minigeogo()
{
   setGeoImg(true);
   switch(existGeo())
   {
      case 0 :
      $.getJSON("/vc/ip2pos", function(d)
      {
         Gmap.setCenter(new google.maps.LatLng(d.Latitude, d.Longitude), 11);
         setGeoImg(false)
      }
      );
      break;
      case 1 :
      navigator.geolocation.getCurrentPosition(showPositionS, handleError);
      break;
      case 2 :
      var a = google.gears.factory.create("beta.geolocation");
      a.getCurrentPosition(showPositionGS);
      break
   }
}
function geogo()
{
   setGeoImg(true);
   switch(existGeo())
   {
      case 0 :
      $.getJSON("/vc/ip2pos", function(d){geoMap(d.Latitude, d.Longitude, 11)});
      break;
      case 1 :
      navigator.geolocation.getCurrentPosition(showPosition, handleError);
      break;
      case 2 :
      var a = google.gears.factory.create("beta.geolocation");
      a.getCurrentPosition(showPositionG);
      break
   }
}
function geoMap(a, k, d)
{
   var j = "cerca.html?lat=" + a + "&lon=" + k;
   if(d)
   {
      j += "&zoom=" + d
   }
   document.location = j
}
function existGeo()
{
   if(navigator.geolocation)
   {
      return 1
   }
   else
   {
      try
      {
         if(google.gears)
         {
            return 2
         }
      }
      catch(a)
      {
         return 0
      }
   }
   return 0
}
function showPosition(a)
{
   geoMap(a.coords.latitude, a.coords.longitude)
}
function showPositionG(a)
{
   geoMap(a.latitude, a.longitude)
}
function showPositionS(a)
{
   Gmap.setCenter(new google.maps.LatLng(a.coords.latitude, a.coords.longitude), 11);
   setGeoImg(false)
}
function showPositionGS(a)
{
   Gmap.setCenter(new google.maps.LatLng(a.latitude, a.longitude), 11);
   setGeoImg(false)
}
function handleError(a)
{
   alert("impossibile determinare la posizione")
}
function dropShadow(a)
{
   e = document.getElementById(a);
   addIMG(e, "/images/tls.png", "top", "left");
   addIMG(e, "/images/trs.png", "top", "right");
   addIMG(e, "/images/bls.png", "bottom", "left");
   addIMG(e, "/images/brs.png", "bottom", "right");
   addDIV(e, "border-left:solid 1px #EBECED;background-color:#D8D9DA;top:7px;bottom:7px;left:0px;width:1px");
   addDIV(e, "border-right:solid 1px #EBECED;background-color:#D8D9DA;top:7px;bottom:7px;right:0px;width:1px");
   addDIV(e, "border-top:solid 1px #EBECED;border-bottom:solid 1px #BCBDBE;background-color:#D8D9DA;top:0px;left:6px;right:6px;height:1px");
   addDIV(e, "border-bottom:solid 1px #EBECED;border-top:solid 1px #BCBDBE;background-color:#D8D9DA;bottom:0px;left:6px;right:6px;height:1px")
}
function roundedCorner(a, g)
{
   if( ! g)
   {
      g = "b"
   }
   b = document.getElementById(a);
   addIMG(b, "/images/tl" + g + ".png", "top", "left");
   addIMG(b, "/images/tr" + g + ".png", "top", "right");
   addIMG(b, "/images/blb.png", "bottom", "left");
   addIMG(b, "/images/brb.png", "bottom", "right");
   addDIV(b, "background-color:#000080;top:11px;bottom:11px;left:0px;width:1px");
   addDIV(b, "background-color:#000080;top:11px;bottom:11px;right:0px;width:1px");
   addDIV(b, "background-color:#000080;top:0px;left:11px;right:11px;height:1px");
   addDIV(b, "background-color:#000080;bottom:0px;left:11px;right:11px;height:1px")
}
function addDIV(j,h)
{
   var a = document.createElement("div");
   a.style.cssText = "position:absolute;" + h;
   a.setAttribute("z-index", "99");
   j.appendChild(a)
}
function addIMG(d, a, l, m)
{
   var k = document.createElement("img");
   k.style.cssText = "position:absolute;" + l + ":0px;" + m + ":0px;";
   k.setAttribute("src", a);
   k.setAttribute("z-index", "99");
   d.appendChild(k)
}
function fadeImmoPub(d)
{
   if(d != cprev)
   {
      $("#immopub").attr("src", "/vc/immo?com=" + ((p = (cprev = d).indexOf(" (")) > 0 ? d.substr(0, p) : d));
   }
}
function initInput()
{
   var h =
   {
      script : "/vc/comuni?", varname : "input", cache : false, noresults : "Nessuna località trovata", maxentries : 10, timeout : 10000, callback : vaia, json : true
   };
   var j = new bsn.AutoSuggest("testinput", h);
   var g = $("#testinput");
   g.attr("value", "Inserisci la località");
   g.css("color", "grey");
   g.css("font-style", "italic");
   g.focus(function()
   {
      if(g.css("color") == "grey")
      {
         g.attr("value", "");
         g.css("color", "black");
         g.css("font-style", "normal")
      }
   }
   );
   g.blur(function()
   {
      if(g.attr("value") == "")
      {
         g.attr("value", "Inserisci la località");
         g.css("color", "grey");
         g.css("font-style", "italic")
      }
   }
   )
}
function loadI()
{
   dropShadow("base");
   roundedCorner("menu1");
   roundedCorner("menu2");
   roundedCorner("menu3");
   var h =
   {
      script : "/vc/comuni?", varname : "input", cache : false, noresults : "Nessuna località trovata", maxentries : 10, timeout : 10000, callback : clickcomune, json : true
   }
   ;
   var j = new bsn.AutoSuggest("testinput", h);
   var g = $("#divmappa");
   g.click(function(a)
   {
      cx = a.pageX - g.offset().left;
      cy = a.pageY - g.offset().top;
      geoMap(46.76114 - 0.04832 * cy, 6.709942 + 0.06564 * cx, 9)
   }
   )
}
function setGeoImg(d)
{
   if(d)
   {
      $("#geoimg").hide();
      $("#waitimg").show()
   }
   else
   {
      $("#waitimg").hide();
      $("#geoimg").show()
   }
}

function setPar(g,f)
{
   return "&" + g + "=" + f;
}

function getP(n)
{
	n=n.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");  
	var rS = "[\\?&]"+n+"=([^&#]*)";
	var rx = new RegExp(rS);
	var r = rx.exec( window.location.href );
	if(r==null) return ""; else return r[1];
}

function SetMap()
{
	var opt = {
		mapTypeId:google.maps.MapTypeId.ROADMAP,
		zoomControl:true, 
		zoomControlOptions:{ style:google.maps.ZoomControlStyle.LARGE,position: google.maps.ControlPosition.TOP_LEFT},
		scaleControl:true,
		scaleControlOptions:{position:google.maps.ControlPosition.BOTTOM_LEFT},
		streetViewControl:true,
		streetViewControlOptions:{position:google.maps.ControlPosition.TOP_LEFT},
		mapTypeControl:false,
		panControl:false
		};
		Gmap = new google.maps.Map(document.getElementById("mappa"),opt);
		google.maps.event.addListener(Gmap, "bounds_changed", function(){if(fb){fb=false;GetMappa()}});
		google.maps.event.addListener(Gmap, "zoom_changed", function(){if(!fb){GetMappa()}});
		google.maps.event.addListener(Gmap, "dragend", function(){if(!fb){GetMappa()}});
}

function ShowAnn(n)
{
	$("#annuncio").html(n); 
	$("#annuncio").show();
}
