/*************** MAPA GOOGLE */

function hbMap() {
    this.directionService = new google.maps.DirectionsService();
    this.map = null;
    this.markers = new Array();
    this.mapOptions = {
	   center: null,
	   disableDefaultUI : false,
	   draggable : true,
	   mapTypeId: google.maps.MapTypeId.ROADMAP,
	   scrollwheel : true,
	   streetViewControl : false,
	   zoom: 14
    };

    this.createMap = function(div, lat, lng, options) {
	   this.setCenter(lat, lng);
	   this.map = new google.maps.Map(document.getElementById(div), this.mapOptions);
    }


    this.setCenter = function(lat, lng) {
	   this.mapOptions.center = new google.maps.LatLng(lat, lng);
    }


    this.setDraggable = function(value) {
	   this.mapOptions.draggable = value;
    }


    this.setMapUI = function(value) {
	   this.mapOptions.disableDefaultUI = value;
    }

    this.setDoubleClickZoom = function(value) {
	   this.mapOptions.disableDoubleClickZoom = !value;
    }

    this.setMapScrollWheel = function(value) {
	   this.mapOptions.scrollwheel = value;
    }


    this.createMarker = function(lat, lng, name, icon) {
	   this.markers.push(
		  new google.maps.Marker({
			 position: new google.maps.LatLng(lat,lng),
			 map: this.map,
			 title:name,
			 icon : icon
		  })
		  );
    }

    this.getTrasport = function() {

    }

    this.getNeighbourhoodInfo = function(lat, lng) {
	   $.ajax({
		  url: '/ajax/getpointsneighbourhood/',
		  type: "post",
		  data : {id: offer_id, id_rubryka: offer_id_rubryka, id_podrubryka: offer_id_podrubryka},
		  dataType: "json",
		  success: function(json) {
			 
		  }
	   });
	   return places;
    }


    this.createMarkersNeighbourhood = function(lat, lng) {
	   var places = this.getNeighbourhoodInfo(lat, lng);
	   var distances = new Array();
	   $(".objects").empty();
	   $(".objects").append('<table></table>');
	   for(var i=0; i< places.results.length; i++) {
		  var currentPlace = places.results[i];

		  this.createMarker( currentPlace.geometry.location.lat ,
			 currentPlace.geometry.location.lng ,
			 currentPlace.name,
			 '/hb/img/'+ currentPlace.type +'_ico.jpg');

		  $("#"+ currentPlace.type +"_objects .objects table").append("<tr><td>"+currentPlace.name+"</td><td class=\"distance\"> m</td></tr>");
		  $("#"+ currentPlace.type +"_objects").show();

		  var start = this.map.getCenter();
		  var end = new google.maps.LatLng(currentPlace.geometry.location.lat, currentPlace.geometry.location.lng);
		  var request = {
			 origin:start,
			 destination:end,
			 travelMode: google.maps.DirectionsTravelMode.WALKING
		  };
		  this.directionService.route(request, function(result, status) {
			 if (status == google.maps.DirectionsStatus.OK) {
				distances.push(result.routes[0].legs[0].distance.value);
				var td = $(".objects td.distance");
				$(td[distances.length - 1]).empty().append(distances[distances.length-1]+ "m");
			 }
		  });
	   }
    }

}


/********** MAPA OPEN LAYERS ******/

function newMap() {

    this.map = null;
    this.layers = {};
    this.bounds = false;

    this.createMap = function (div){
	   OpenLayers.ImgPath = "/hb/img/";
	   this.map = new OpenLayers.Map(div,
	   {
		  controls:[
		  new OpenLayers.Control.Navigation(),
		  new OpenLayers.Control.PanZoomBar({'zoomStopHeight':'6'})
		  ]
		  }
	   );
	   this.layers.gmap = new OpenLayers.Layer.Google(
		  "GoogleStreets",
		  {
			 numZoomLevels: 20
		  }
		  );
	   this.map.addLayers([this.layers.gmap]);
    }


    this.setCenter = function(lat, lng) {
	   alert("lat: "+lat+" lng: "+lng);
	   
	   this.map.setCenter(new OpenLayers.LonLat(lat, lng), 14);
    }

    this.addLayer = function(name,options){
	   this.layers[name] = new OpenLayers.Layer.Vector(name,options);
	   this.map.addLayer(this.layers[name]);
    }

    this.hideLayers = function(){
	   for(var i in this.map.layers) {
		  if(this.map.layers[i].name != 'GoogleStreets')
			 this.map.getLayer(this.map.layers[i].id).display(false);
	   }
    }

    this.hideLayer = function(layer){
	   this.map.getLayer(layer).setVisibility(false);
    }

    this.showLayer = function(layer){
	   this.map.getLayer(layer).setVisibility(true);
    }

    this.addMarkers = function(json,layer){
		  var options = {
			 'internalProjection': this.map.baseLayer.projection,
			 'externalProjection': new OpenLayers.Projection("EPSG:4326")
		  };
		  var features = new OpenLayers.Format.GeoJSON(options).read(json);

		  if(features) {
			 var fl = features.length;
			 if(fl > 0){
				if(features.constructor != Array) {
				    features = [features];
				}
				for(var i=0; i<fl; ++i) {
				    if (!this.bounds) {
					   this.bounds = features[i].geometry.getBounds();
				    } else {
					   this.bounds.extend(features[i].geometry.getBounds());
				    }
				}
				this.layers[layer].addFeatures(features);
			 }
		  }
    }

    this.addClick = function (layer,select,unselect){

	   this.layers[layer].events.register("featureselected", this.layers[layer], select);
	   this.layers[layer].events.register("featureunselected", this.layers[layer], unselect);

	   control = new OpenLayers.Control.SelectFeature(this.layers[layer]);
	   this.map.addControl(control);
	   control.activate();
    }
}




function DivisionMap(json, address) {
    var map = new newMap();
    map.createMap('oddzial_mapka');
    map.addLayer("markers", {
	   styleMap: new OpenLayers.StyleMap({
		  externalGraphic: "/hb/img/hb_pointer.png",
		  backgroundGraphic: "/hb/img/hb_pointer_shadow.png",
		  backgroundXOffset: 8,
		  backgroundYOffset: -9,
		  graphicZIndex: 2000,
		  backgroundGraphicZIndex: 2001,
		  pointRadius: 10
	   })
    }
    );
    map.addMarkers(json, 'markers');
    var lonlat = map.bounds.getCenterLonLat();
    map.map.setCenter(new OpenLayers.LonLat(lonlat.lon,lonlat.lat), 16);
    map.addClick(
	   'markers',
	   function select (evt) {
		  feature = evt.feature;
		  popup = new OpenLayers.Popup.FramedCloud("featurePopup",
			 feature.geometry.getBounds().getCenterLonLat(),
			 new OpenLayers.Size(100,100),
			 '<p>Home Broker<br/>'+address+'</p>',
			 null,
			 true,
			 onPopupClose
			 );
		  feature.popup = popup;
		  popup.feature = feature;
		  map.map.addPopup(popup);
	   },
	   function unselect (evt) {
		  feature = evt.feature;
		  if (feature.popup) {
			 popup.feature = null;
			 map.map.removePopup(feature.popup);
			 feature.popup.destroy();
			 feature.popup = null;
		  }
	   }
    );
 
};


/************ MAPA OFERT ****************/

function OffersMap() {

    this.map = null;
    this.mapCreated = false;
    this.data = false;

    this.init = function(){

	   $.ajax({
		  url: '/wyniki_wyszukiwania/',
		  type: "POST",
		  dataType: "json",
		  success: function(json) {
			 if(json.count_offers > 0) {
				if(offerMap.mapCreated == true){
				    offerMap.addMarkers(json);
				}else{
				    offerMap.data = json;
				}

			 }
			 $("#offers_count").append('Znaleziono <span class="bold">'+json.count_offers+'</span> ofert');
		  }
	   });

	   this.map = new newMap();

	   this.map.createMap('wyniki_mapa');
	   this.map.addLayer("primary", {
		  styleMap: new OpenLayers.StyleMap({
			 externalGraphic: "/hb/img/offer_pointer.png",
			 backgroundGraphic: "/hb/img/hb_pointer_shadow.png",
			 backgroundXOffset: 8,
			 backgroundYOffset: -9,
			 graphicZIndex: 2000,
			 backgroundGraphicZIndex: 2001,
			 pointRadius: 10
		  })
	   });
	   this.map.addLayer("secondary", {
		  styleMap: new OpenLayers.StyleMap({
			 externalGraphic: "/hb/img/offer_pointer.png",
			 backgroundGraphic: "/hb/img/hb_pointer_shadow.png",
			 backgroundXOffset: 8,
			 backgroundYOffset: -9,
			 graphicZIndex: 2000,
			 backgroundGraphicZIndex: 2001,
			 pointRadius: 10
		  })
	   });
	   this.map.addLayer("mixed", {
		  styleMap: new OpenLayers.StyleMap({
			 externalGraphic: "/hb/img/offer_pointer.png",
			 backgroundGraphic: "/hb/img/hb_pointer_shadow.png",
			 backgroundXOffset: 8,
			 backgroundYOffset: -9,
			 graphicZIndex: 2000,
			 backgroundGraphicZIndex: 2001,
			 pointRadius: 10
		  })
	   });
	   for(var i in this.map.layers) {

		  if(this.map.layers[i].name == 'mixed') {
			 this.map.showLayer(this.map.layers[i].id);
		  } else if(this.map.layers[i].name != 'GoogleStreets') {
			 this.map.hideLayer(this.map.layers[i].id);
		  }
		  
	   }
	   this.map.addClick(
		  'primary',
		  function select (evt) {
			 feature = evt.feature;
			 popup = new OpenLayers.Popup.FramedCloud("featurePopup",
				feature.geometry.getBounds().getCenterLonLat(),
				new OpenLayers.Size(100,100),
				'<table><tr><td><a href="'+feature.attributes.link+'"><img src="'+feature.attributes.image+'" alt="nieruchomosc" /></a></td><td><a href="'+feature.attributes.link+'"><h2>'+feature.attributes.title + '</h2></a></td></tr></tr><td colspan="2">' + feature.attributes.description+'</td></tr></table>',
				null,
				true,
				onPopupClose
				);
			 feature.popup = popup;
			 popup.feature = feature;
			 offerMap.map.map.addPopup(popup);
		  },
		  function unselect (evt) {
			 feature = evt.feature;
			 if (feature.popup) {
				popup.feature = null;
				offerMap.map.map.removePopup(feature.popup);
				feature.popup.destroy();
				feature.popup = null;
			 }
		  }
		  );
	   this.map.addClick(
		  'secondary',
		  function select (evt) {
			 feature = evt.feature;
			 popup = new OpenLayers.Popup.FramedCloud("featurePopup",
				feature.geometry.getBounds().getCenterLonLat(),
				new OpenLayers.Size(100,100),
				'<table><tr><td><a href="'+feature.attributes.link+'"><img src="'+feature.attributes.image+'" alt="nieruchomosc" /></a></td><td><a href="'+feature.attributes.link+'"><h2>'+feature.attributes.title + '</h2></a></td></tr></tr><td colspan="2">' + feature.attributes.description+'</td></tr></table>',
				null,
				true,
				onPopupClose
				);
			 feature.popup = popup;
			 popup.feature = feature;
			 offerMap.map.map.addPopup(popup);
		  },
		  function unselect (evt) {
			 feature = evt.feature;
			 if (feature.popup) {
				popup.feature = null;
				offerMap.map.map.removePopup(feature.popup);
				feature.popup.destroy();
				feature.popup = null;
			 }
		  }
		  );
	   this.map.addClick(
		  'mixed',
		  function select (evt) {
			 feature = evt.feature;
			 popup = new OpenLayers.Popup.FramedCloud("featurePopup",
				feature.geometry.getBounds().getCenterLonLat(),
				new OpenLayers.Size(100,100),
				'<table><tr><td><a href="'+feature.attributes.link+'"><img src="'+feature.attributes.image+'" alt="nieruchomosc" /></a></td><td><a href="'+feature.attributes.link+'"><h2>'+feature.attributes.title + '</h2>' + feature.attributes.description+'</a></td></tr></table>',
				null,
				true,
				onPopupClose
				);
			 feature.popup = popup;
			 popup.feature = feature;
			 offerMap.map.map.addPopup(popup);
		  },
		  function unselect (evt) {
			 feature = evt.feature;
			 if (feature.popup) {
				popup.feature = null;
				offerMap.map.map.removePopup(feature.popup);
				feature.popup.destroy();
				feature.popup = null;
			 }
		  }
		  );

	   if(this.data != false){
		  this.addMarkers(this.data);
	   }else{
		  this.mapCreated = true;
	   }
    }

    this.addMarkers = function(json){
	   if(json.mixed.features)
		  this.map.addMarkers(json.mixed, 'mixed');
	   if(json.primary.features)
		  this.map.addMarkers(json.primary, 'primary');
	   if(json.secondary.features)
		  this.map.addMarkers(json.secondary, 'secondary');
	   this.map.map.zoomToExtent(this.map.bounds);
    }

    this.addClick = function(layer,text ) {
	   this.map.addClick(
		  layer,
		  function select (evt) {
			 feature = evt.feature;
			 popup = new OpenLayers.Popup.FramedCloud("featurePopup",
				feature.geometry.getBounds().getCenterLonLat(),
				new OpenLayers.Size(100,100),
				text,
				null,
				true,
				onPopupClose
				);
			 feature.popup = popup;
			 popup.feature = feature;
			 offerMap.map.map.addPopup(popup);
		  },
		  function unselect (evt) {
			 feature = evt.feature;
			 if (feature.popup) {
				popup.feature = null;
				offerMap.map.map.removePopup(feature.popup);
				feature.popup.destroy();
				feature.popup = null;
			 }
		  }
	   );
    }
}

/**************** MAPA OKOLICY ******************/
function neighbourhoodMap() {
    this.map = null;
    this.mapCreated = false;
    this.data = false;

    this.init = function(){
	   if(this.map)
		  return true;

	   this.map = new newMap();
	   $('#mapa_okolica').empty();
	   this.map.createMap('mapa_okolica');
	   this.map.addLayer("center", {
		  styleMap: new OpenLayers.StyleMap({
			 externalGraphic: "/hb/img/offer_pointer.png",
			 backgroundGraphic: "/hb/img/hb_pointer_shadow.png",
			 backgroundXOffset: 8,
			 backgroundYOffset: -9,
			 graphicZIndex: 2002,
			 backgroundGraphicZIndex: 2002,
			 pointRadius: 10
		  })
	   });
	   this.map.addLayer("obiekty_uslugowe", {
				styleMap: new OpenLayers.StyleMap({
				    externalGraphic: "/hb/img/services_ico.jpg",
				    backgroundGraphic: "/hb/img/hb_pointer_shadow.png",
				    backgroundXOffset: 8,
				    backgroundYOffset: -9,
				    graphicZIndex: 2000,
				    backgroundGraphicZIndex: 2001,
				    pointRadius: 10
				})
	   });
	   this.map.addLayer("gastronomia", {
				styleMap: new OpenLayers.StyleMap({
				    externalGraphic: "/hb/img/gastronomia_ico.jpg",
				    backgroundGraphic: "/hb/img/hb_pointer_shadow.png",
				    backgroundXOffset: 8,
				    backgroundYOffset: -9,
				    graphicZIndex: 2000,
				    backgroundGraphicZIndex: 2001,
				    pointRadius: 10
				})
	   });
	   this.map.addLayer("sport_rekreacja", {
				styleMap: new OpenLayers.StyleMap({
				    externalGraphic: "/hb/img/sport_ico.jpg",
				    backgroundGraphic: "/hb/img/hb_pointer_shadow.png",
				    backgroundXOffset: 8,
				    backgroundYOffset: -9,
				    graphicZIndex: 2000,
				    backgroundGraphicZIndex: 2001,
				    pointRadius: 10
				})
	   });
	   this.map.addLayer("edukacja", {
				styleMap: new OpenLayers.StyleMap({
				    externalGraphic: "/hb/img/education_ico.jpg",
				    backgroundGraphic: "/hb/img/hb_pointer_shadow.png",
				    backgroundXOffset: 8,
				    backgroundYOffset: -9,
				    graphicZIndex: 2000,
				    backgroundGraphicZIndex: 2001,
				    pointRadius: 10
				})
	   });
	   this.map.addLayer("sluzba_zdrowia", {
				styleMap: new OpenLayers.StyleMap({
				    externalGraphic: "/hb/img/health_ico.jpg",
				    backgroundGraphic: "/hb/img/hb_pointer_shadow.png",
				    backgroundXOffset: 8,
				    backgroundYOffset: -9,
				    graphicZIndex: 2000,
				    backgroundGraphicZIndex: 2001,
				    pointRadius: 10
				})
	   });
	   this.map.addLayer("muzea_galerie", {
				styleMap: new OpenLayers.StyleMap({
				    externalGraphic: "/hb/img/museum_ico.jpg",
				    backgroundGraphic: "/hb/img/hb_pointer_shadow.png",
				    backgroundXOffset: 8,
				    backgroundYOffset: -9,
				    graphicZIndex: 2000,
				    backgroundGraphicZIndex: 2001,
				    pointRadius: 10
				})
	   });
	   this.map.addLayer("kina_teatry", {
				styleMap: new OpenLayers.StyleMap({
				    externalGraphic: "/hb/img/culture_ico.jpg",
				    backgroundGraphic: "/hb/img/hb_pointer_shadow.png",
				    backgroundXOffset: 8,
				    backgroundYOffset: -9,
				    graphicZIndex: 2000,
				    backgroundGraphicZIndex: 2001,
				    pointRadius: 10
				})
	   });

	   var center = '{"type": "Point", "coordinates": ['+offer_lng+', '+ offer_lat + ']}';
	   this.map.addMarkers(center, 'center');
	   var lonlat = this.map.bounds.getCenterLonLat();
	   this.map.map.setCenter(new OpenLayers.LonLat(lonlat.lon,lonlat.lat), 16);
	   this.mapCreated = true;
	   

	   $.ajax({
		  url: '/ajax/getpointsneighbourhood/',
		  type: "post",
		  data : {id: offer_id, id_rubryka: offer_id_rubryka, id_podrubryka: offer_id_podrubryka},
		  dataType: "json",
		  success: function(json) {
			 
			 if(json.data) {
				nMap.addMarkers(json.data);
				nMap.showNeighbourhoodList(json.data);
			 }
		  }
	   });

    }


    this.addMarkers = function(json){
	   this.map.addMarkers(json.obiekty_uslugowe, 'obiekty_uslugowe');
	   this.map.addMarkers(json.gastronomia, 'gastronomia');
	   this.map.addMarkers(json.sport_rekreacja, 'sport_rekreacja');
	   this.map.addMarkers(json.edukacja, 'edukacja');
	   this.map.addMarkers(json.sluzba_zdrowia, 'sluzba_zdrowia');
	   this.map.addMarkers(json.muzea_galerie, 'muzea_galerie');
	   this.map.addMarkers(json.kina_teatry, 'kina_teatry');
    }

    this.showNeighbourhoodList = function(json) {
	   var types = new Array('obiekty_uslugowe', 'gastronomia', 'sport_rekreacja', 'edukacja', 'sluzba_zdrowia', 'muzea_galerie', 'kina_teatry');
	   $("#okolica .objects").empty();
	   $("#okolica .objects").append('<table></table>');
	   for(var i=0; i< types.length; i++) {
		  var data = eval("json."+types[i]);
		  if(data.features) {
			 for(var j=0; j< data.features.length; j++) {
				var name = (!data.features[j].properties.name || data.features[j].properties.name == null) ? data.features[j].properties.sub_type : data.features[j].properties.name;
				var distance = data.features[j].properties.distance;
				$("#"+types[i]+"_objects .objects table").append("<tr><td class=\"object_name\">"+name+"</td><td class=\"distance\">"+distance+" m</td></tr>");
				$("#"+types[i]+"_objects").show();
			 }
		  }
	   }
    }

}

/**************** MAPA TRANSPORTU ******************/

function transportMap() {
    this.map = null;
    this.mapCreated = false;
    this.data = false;

    this.init = function(){
	   if(this.map)
		  return true;
	   this.map = new newMap();
	   $('#mapa_komunikacja').empty();
	   this.map.createMap('mapa_komunikacja');
	   this.map.addLayer("center", {
		  styleMap: new OpenLayers.StyleMap({
			 externalGraphic: "/hb/img/offer_pointer.png",
			 backgroundGraphic: "/hb/img/hb_pointer_shadow.png",
			 backgroundXOffset: 8,
			 backgroundYOffset: -9,
			 graphicZIndex: 2002,
			 backgroundGraphicZIndex: 2002,
			 pointRadius: 10
		  })
	   });
	   this.map.addLayer("autobusy", {
				styleMap: new OpenLayers.StyleMap({
				    externalGraphic: "/hb/img/autobusy_ico.jpg",
				    backgroundGraphic: "/hb/img/hb_pointer_shadow.png",
				    backgroundXOffset: 8,
				    backgroundYOffset: -9,
				    graphicZIndex: 2000,
				    backgroundGraphicZIndex: 2001,
				    pointRadius: 10
				})
	   });
	   this.map.addLayer("lotniska", {
				styleMap: new OpenLayers.StyleMap({
				    externalGraphic: "/hb/img/lotnisko_ico.jpg",
				    backgroundGraphic: "/hb/img/hb_pointer_shadow.png",
				    backgroundXOffset: 8,
				    backgroundYOffset: -9,
				    graphicZIndex: 2000,
				    backgroundGraphicZIndex: 2001,
				    pointRadius: 10
				})
	   });
	   this.map.addLayer("kolej", {
				styleMap: new OpenLayers.StyleMap({
				    externalGraphic: "/hb/img/kolej_ico.jpg",
				    backgroundGraphic: "/hb/img/hb_pointer_shadow.png",
				    backgroundXOffset: 8,
				    backgroundYOffset: -9,
				    graphicZIndex: 2000,
				    backgroundGraphicZIndex: 2001,
				    pointRadius: 10
				})
	   });
	   this.map.addLayer("tramwaje", {
				styleMap: new OpenLayers.StyleMap({
				    externalGraphic: "/hb/img/tramwaje_ico.jpg",
				    backgroundGraphic: "/hb/img/hb_pointer_shadow.png",
				    backgroundXOffset: 8,
				    backgroundYOffset: -9,
				    graphicZIndex: 2000,
				    backgroundGraphicZIndex: 2001,
				    pointRadius: 10
				})
	   });
	   this.map.addLayer("metro", {
				styleMap: new OpenLayers.StyleMap({
				    externalGraphic: "/hb/img/metro_ico.jpg",
				    backgroundGraphic: "/hb/img/hb_pointer_shadow.png",
				    backgroundXOffset: 8,
				    backgroundYOffset: -9,
				    graphicZIndex: 2000,
				    backgroundGraphicZIndex: 2001,
				    pointRadius: 10
				})
	   });

	   var center = '{"type": "Point", "coordinates": ['+offer_lng+', '+ offer_lat + ']}';
	   this.map.addMarkers(center, 'center');
	   var lonlat = this.map.bounds.getCenterLonLat();
	   this.map.map.setCenter(new OpenLayers.LonLat(lonlat.lon,lonlat.lat), 16);
	   this.mapCreated = true;


	   $.ajax({
		  url: '/ajax/getpointstransport/',
		  type: "post",
		  data : {id: offer_id, id_rubryka: offer_id_rubryka, id_podrubryka: offer_id_podrubryka},
		  dataType: "json",
		  success: function(json) {

			 if(json.data) {
				tMap.addMarkers(json.data);
				tMap.showTransportList(json.data);
			 }
		  }
	   });

    }


    this.addMarkers = function(json){
	   this.map.addMarkers(json.autobusy, 'autobusy');
	   this.map.addMarkers(json.lotniska, 'lotniska');
	   this.map.addMarkers(json.kolej, 'kolej');
	   this.map.addMarkers(json.tramwaje, 'tramwaje');
	   this.map.addMarkers(json.metro, 'metro');
    }

    this.showTransportList = function(json) {
	   var types = new Array('autobusy', 'lotniska', 'kolej', 'tramwaje', 'metro');
	   $("#komunikacja .objects span").empty();
	   for(var i=0; i< types.length; i++) {
		  var data = eval("json."+types[i]);
		  if(data.features) {
			 var distance = data.features[0].properties.distance;
			 $("#"+types[i]+"_objects .objects span").text(distance);
			 $("#"+types[i]+"_objects").show();
			 $("#"+types[i]+"_objects objects_box").show();
		  }
	   }
    }

}


function onPopupClose(evt) {
	   var feature = this.feature;
	   if (feature.layer) {
		  control.unselect(feature);
	   } else {
		  this.destroy();
	   }
};


