var map;
var markers;
var infoBox;
var gmarker;
var po;

var cloudHTML = '\
<div class="owncloud1">\
	<div class="owncloud2">\
		<div class="owncloud_top"></div>\
		<div class="owncloud_bottom">\
			<div class="owncloud_border">\
				<div class="owncloud_content">\
					<div class="owncloud_close"></div>\
					<div class="title"></div>\
					<div class="description"></div>\
				\
				</div>\
			</div>\
		</div>\
	</div>\
</div>\
';

function findMarkerById(id){
    for(i=0;i<markers.length;i++){
		if(markers[i].pageId==id){
			return markers[i];
		}
    }
}

function switchCategory(cat) {
    cat = "marker_" + cat;

    for(i=0;i<markers.length;i++){
	if (markers[i] != undefined && markers[i].icon == eval(cat)) {
	    if (markers[i].getMap() == null) {
		markers[i].setMap(map);
	    } else {
		markers[i].setMap(null);
	    }
	}
    }
}
function save_marker(id){
	alert(id);
	popupManager.close();
}
function edit_marker(marker,extra){
	//alert('id: '+extra['id']);
	//marker.id = extra['id'];
	//start_saving();
	/*
	var out = '';
	for(var s in marker){
		out += s+': '+marker[s]+'\n';
	}
	alert(out)
	*/

	var id = marker.markerid.split('map').pop();
	var icon_type = marker.icon.url.split('marker_').pop().split('.').shift();
	var type = markers_labels[icon_type];
	var dane = {title:marker.title,description:marker.description,id:id};

	ajax('Template.getForm',{formName:'locationForm',dane:dane},function(result){
		popupManager.endSaving();
		popupManager.save();
		var popup_content = $('#popup_content');
		popup_content.html(result);

		var inp_data = $('<input/>');
		inp_data.attr('name','marker_data');
		inp_data.attr('type','hidden');
		var marker_data = dane;
		inp_data.val(JSON.stringify({id:dane.id}));

		popup_content.find('form').append(inp_data);
		init_form(popup_content.find('form'));

		popupManager.init();
		init_tabs($('#popup'),$('#popup_content'),'popuptab','tabtitle','naglowek_popup',false);
		$('#cover').show('fade',200,function(){
			$('#popup').show('fade',200);
		});
		$('#tcover').show('fade',200);
		
		$('.usunHide').click(function(){
			ajax('MapController.removeMarker', {marker_id: id}, function(result){
				what = $.parseJSON(result);
				if(what.success == true) {
					afterMapPopup();
				}
			});
		});
		
		$('.anulujHide').click(function(){
			afterMapPopup();
		});
	});
}

function afterMapPopup(f,r) {
	//alert('After popup');
	//alert(f);
	//alert(r);
	
	//htmltrace(htmlExplode(f));
	//htmltrace(htmlExplode(r));
	
	//alert(r.callback);
	
	if(r.callback){
		eval(r.callback);
	}
	
	$('#popup').hide('fade',200,function(){
		$('#popup_content').html('');
		$('#tcover').hide('fade',200);
		$('#cover').hide('fade',200);
		//add_marker_to_map();
	});
	
}
function open_cloud(marker){
    if (marker == undefined) {
		return;
    }

    gmarker = marker;
	var icon_type = marker.icon.url.split('marker_').pop().split('.').shift();

	/*
	var al = '';
	for(var i in marker.icon){
		al += i+': '+marker.icon[i]+'\n';
	}
	alert(al);
	*/
    if (infoBox.getPanes() == undefined) {
		setTimeout("open_cloud(gmarker)", 100);
		return;
    }

    var chmurka = $(infoBox.div_);

		chmurka.find('.title').text(marker.title);
	chmurka.find('.description').text(marker.description);
	
	chmurka.attr('class','owncloud');
	chmurka.addClass('owncloud_'+icon_type);
	//owncloud owncloud_culture

    chmurka.show();
//    chmurka.find('.miniatura').attr('src','');
//    chmurka.find('.miniatura').attr('src',marker.thumb);

    if(!marker.firma||marker.firma==''||marker.firma==' '){
		chmurka.find('.firma').hide();
    }else{
		chmurka.find('.firma').show();
    }

    chmurka.find('.firma').html(marker.firma);
    chmurka.find('.lokalizacja').html(marker.lokalizacja);
//    chmurka.find('.zobacz,.miniatura').unbind('click');
//    chmurka.find('.zobacz,.miniatura').click(function(){
//        init_gallery_zwei(marker);
//    });

    chmurka.find('.owncloud_close').click(function(){chmurka.hide()});

    infoBox.latlng_ = marker.position;
    infoBox.draw();
    infoBox.panMap();
}

/* An InfoBox is like an info window, but it displays
 * under the marker, opens quicker, and has flexible styling.
 * @param {GLatLng} latlng Point to place bar at
 * @param {Map} map The map on which to display this InfoBox.
 * @param {Object} opts Passes configuration options - content,
 *   offsetVertical, offsetHorizontal, className, height, width
 */
function InfoBox(opts) {
    google.maps.OverlayView.call(this);
    this.latlng_ = opts.latlng;
    this.map_ = opts.map;
    this.offsetVertical_ = 0;
    this.offsetHorizontal_ = -145;
    this.height_ = 100;
    this.width_ = 561;

    var me = this;
    this.boundsChangedListener_ = google.maps.event.addListener(this.map_, "bounds_changed", function() {
	return me.panMap.apply(me);
    });

    this.setMap(this.map_);
}

/* InfoBox extends GOverlay class from the Google Maps API
 */
InfoBox.prototype = new google.maps.OverlayView();

/* Creates the DIV representing this InfoBox
 */
InfoBox.prototype.remove = function() {
    if (this.div_) {
	this.div_.parentNode.removeChild(this.div_);
	this.div_ = null;
    }
};
/* Redraw the Bar based on the current projection and zoom level
 */
InfoBox.prototype.draw = function() {
    // Creates the element if it doesn't exist already.
    this.createElement();
    if (!this.div_) return;
    // Calculate the DIV coordinates of two opposite corners of our bounds to
    // get the size and position of our Bar
    var pixPosition = this.getProjection().fromLatLngToDivPixel(this.latlng_);
    if (!pixPosition) return;

    // Now position our DIV based on the DIV coordinates of our bounds
    this.div_.style.width = this.width_ + "px";
    this.div_.style.left = (pixPosition.x + this.offsetHorizontal_) + "px";
    this.div_.style.height = this.height_ + "px";
    this.div_.style.top = (pixPosition.y + this.offsetVertical_) + "px";
    //this.div_.style.display = 'block';
};

/* Creates the DIV representing this InfoBox in the floatPane.  If the panes
 * object, retrieved by calling getPanes, is null, remove the element from the
 * DOM.  If the div exists, but its parent is not the floatPane, move the div
 * to the new pane.
 * Called from within draw.  Alternatively, this can be called specifically on
 * a panes_changed event.
 */
InfoBox.prototype.createElement = function() {
    var panes = this.getPanes();
    var div = this.div_;

    if (panes == undefined) {
		return;
    }

    if (!div) {
		// This does not handle changing panes.  You can set the map to be null and
		// then reset the map to move the div.
		div = this.div_ = document.createElement("div");

		$(div).append(cloudHTML);
		$(div).addClass("owncloud");
		panes.floatPane.appendChild(div);

		function removeInfoBox(ib) {
			return function() {
			ib.setMap(null);
			};
		}

		if(document.location.hash.length==5){
			gmarker = findMarkerById(document.location.hash.substr(1,4))
			open_cloud(gmarker);
		}

		this.panMap();
    } else if (div.parentNode != panes.floatPane) {
		// The panes have changed.  Move the div.
		div.parentNode.removeChild(div);
		panes.floatPane.appendChild(div);
    } else {
		// The panes have not changed, so no need to create or move the div.
    }
}

/* Pan the map to fit the InfoBox.
 */
InfoBox.prototype.panMap = function() {
  // if we go beyond map, pan map
  var map = this.map_;
  var bounds = map.getBounds();
  if (!bounds) return;

   this._height = $(".owncloud2").height();

  // The position of the infowindow
  var position = this.latlng_;

  // Padding on the infowindow
  var padX = 40;
  var padY = 40;

  // The degrees per pixel
  var mapDiv = map.getDiv();
  var boundsSpan = bounds.toSpan();
  var longSpan = boundsSpan.lng();
  var latSpan = boundsSpan.lat();
  var degPixelX = longSpan / mapDiv.offsetWidth;
  var degPixelY = latSpan / mapDiv.offsetHeight;

  // The bounds of the map
  var mapWestLng = bounds.getSouthWest().lng();
  var mapEastLng = bounds.getNorthEast().lng();
  var mapNorthLat = bounds.getNorthEast().lat();
  var mapSouthLat = bounds.getSouthWest().lat();

  // The bounds of the infowindow
  var iwWestLng = position.lng() + (this.offsetHorizontal_ - padX) * degPixelX;
  var iwEastLng = position.lng() + (this.offsetHorizontal_ + this.offsetHorizontal_ + this.width_ + padX) * degPixelX;
  var iwNorthLat = position.lat() - (this.offsetVertical_ - this.height_ - padY) * degPixelY;
  var iwSouthLat = position.lat() - (this.offsetVertical_ + padY) * degPixelY;

  // calculate center shift
  var shiftLng =
      (iwWestLng < mapWestLng ? mapWestLng - iwWestLng : 0) +
      (iwEastLng > mapEastLng ? mapEastLng - iwEastLng : 0);
  var shiftLat =
      (iwNorthLat > mapNorthLat ? mapNorthLat - iwNorthLat : 0) +
      (iwSouthLat < mapSouthLat ? mapSouthLat - iwSouthLat : 0);

  // The center of the map
  var center = map.getCenter();

  // The new map center
  var centerX = center.lng() - shiftLng;
  var centerY = center.lat() - shiftLat;

  // center the map to the new shifted center
  map.setCenter(new google.maps.LatLng(centerY, centerX));

  // Remove the listener after panning is complete.
  google.maps.event.removeListener(this.boundsChangedListener_);
//  this.boundsChangedListener_ = null;
};

function add_marker_to_map(marker){
	marker.icon = new google.maps.MarkerImage(base+"templates/img/google_map_marker.png");
	active_markers.push(marker);
	google.maps.event.addListener(marker, 'click', function() {
		open_cloud(this);
	});
}

var added_marker;

var active_map;
var active_markers;

var markers_labels = {qh:0,food:1,museum:2,culture:3};

var marker_qh = new google.maps.MarkerImage("/templates/img/marker_qh.png", new google.maps.Size(50, 50), new google.maps.Point(0, 0), new google.maps.Point(25, 25));
var marker_culture = new google.maps.MarkerImage("/templates/img/marker_culture.png", new google.maps.Size(50, 50), new google.maps.Point(0, 0), new google.maps.Point(25, 25));
var marker_food = new google.maps.MarkerImage("/templates/img/marker_food.png", new google.maps.Size(50, 50), new google.maps.Point(0, 0), new google.maps.Point(25, 25));
var marker_museum = new google.maps.MarkerImage("/templates/img/marker_museum.png", new google.maps.Size(50, 50), new google.maps.Point(0, 0), new google.maps.Point(25, 25));

function init(){
	$('.map_canvas').each(function(){
		var map_canvas = $(this);
		var gmap = $(map_canvas).parent();
		$(".mapLink").click(function(){
		open_cloud(
			findMarkerById(
			$(this).attr("id").split('map').pop()));
		});

		var myCenter = new google.maps.LatLng(52.23, 21.01);
		//google.maps.

		var myOptions = {
			zoom: 12,
			center: myCenter,
			mapTypeId: google.maps.MapTypeId.ROADMAP
		}

		map = new google.maps.Map(map_canvas[0], myOptions);

		geocoder = new google.maps.Geocoder();
		//map.prototype = new google.maps.OverlayView();

		po = new ProjectedOverlay(map);

		//alert(po.getProjection());

		//eval(mdata);
		
		for (i = 0; i < markersData.length; i++) {
			markers[i] = new google.maps.Marker({
				markerid: 'map' + markersData[i].id,
				position: new google.maps.LatLng(markersData[i].latitude, markersData[i].longitude),
				title: markersData[i].title,
				description: markersData[i].description,
				icon: new google.maps.MarkerImage(base+"templates/img/google_map_marker.png"),
				map: map
			});
		}
		
		infoBox = new InfoBox({latlng: myCenter, map: map});

		for (i=0;i<markers.length;i++) {
			if (markers[i] != undefined) {
				google.maps.event.addListener(markers[i], 'click', function() {
											open_cloud(this);
									});
			}
		}
		
			})

}


function ProjectedOverlay(map) {
	google.maps.OverlayView.call(this);

	this.map_ = map;

	this.setMap(map);
}

ProjectedOverlay.prototype = new google.maps.OverlayView();

ProjectedOverlay.prototype.createElement = function()
{
 var panes = this.getPanes() ;
 var div = this.div_ ;

 if (!div)
 {
  div = this.div_ = document.createElement("div");
  div.style.position = "absolute" ;
  div.setAttribute('id',this.id_) ;
  this.div_ = div ;
  this.lastZoom_ = -1 ;
  if( this.percentOpacity_ )
  {
   this.setOpacity(this.percentOpacity_) ;
  }
  panes.overlayLayer.appendChild(div);
 }
}

// Remove the main DIV from the map pane

ProjectedOverlay.prototype.remove = function()
{
 if (this.div_)
 {
  this.setMap(null);
  this.div_.parentNode.removeChild(this.div_);
  this.div_ = null;
 }
}

// Redraw based on the current projection and zoom level...

ProjectedOverlay.prototype.draw = function(firstTime)
{
 // Creates the element if it doesn't exist already.

 this.createElement();

 if (!this.div_)
 {
  return ;
 }

}
