var map = {};
var current_labels = [];
var bubble = {};

function EfficityType(tileSize) {
	this.tileSize = tileSize;
};

var POPUP = $(document.createElement('div')).hide().addClass('baro_popup');
//var POPUP = $(document.createElement('div')).addClass('baro_popup');
var POPUP_VISIBLE = false;

EfficityType.prototype.getTile = function(coord, zoom, ownerDocument) {
	var div = ownerDocument.createElement('DIV');
	var tileSrc = STATICSERVER + "\/tiles/" + ZID + "\/" + zoom + "\/" + coord.x.toString() + "\/" + coord.y.toString() + '.png'; 
	div.innerHTML = '<img class="btile" src="'+tileSrc+'"/>';
	div.style.width = '256px';
	div.style.height = '256px';
	return div;
};

function add_lv3 (id, map_id, map, txt, lng, lat) {
	var lbl = new Label({map: map}, id);
	lbl.set('position', new google.maps.LatLng(lat, lng));
	lbl.set('text', txt);
	$(lbl.span_).mousemove(show_popup('#'+map_id)).mouseout(hide_popup).click(function() {document.location = CHILDREN_INFOS[this.id.split('_')[1]].url;})
}

function remove_labels() {
}

function map_add_labels(items, map_id) {
	// Be sure there's no more labels :
	remove_labels();
	for (var id in items) {
		var item = items[id];
		add_lv3('zone_'+id, map_id, map, item.lbl, item.lng, item.lat);
	};
}

function load_gmap(map_id) {
	var efftiles_added = false;
	var centrum = new google.maps.LatLng(CENTER_LAT, CENTER_LNG);
	var mapTypeId = google.maps.MapTypeId.SATELLITE;
	if (SHOW_PARCEL) {mapTypeId = google.maps.MapTypeId.HYBRID;};
	var mapOptions = {
		zoom:ZOOM,
		center:centrum,
		mapTypeId:mapTypeId,
		disableDefaultUI:true,
		scrollwheel:false,
		disableDoubleClickZoom:true
	};
	map = new google.maps.Map(document.getElementById(map_id),mapOptions);

	google.maps.event.addListener(map, 'tilesloaded', function() {
		if (!efftiles_added) {
			$('#'+ map_id).prepend(POPUP);
			map_add_labels(CHILDREN_INFOS, map_id);
			map.overlayMapTypes.insertAt(0, new EfficityType(new google.maps.Size(256, 256)));
			efftiles_added = true;
		}
	});
	map.controls[google.maps.ControlPosition.TOP_LEFT].push(new ZoomPanControl(map));

	if (SHOW_PARCEL) {
		// Handle click (on parcels only)
		google.maps.event.addListener(map, 'click', function(event) {
			var latlng = event.latLng;
			if (latlng) {
				var url = '\/prix-immobiliers\/zone_url\/'+latlng.lng()+'\/'+latlng.lat()+'\/';
				$.getJSON(url, function (res){
					if (res) {
						document.location = res;
					}
				});
			}
		});
	};
}

function load_gmarker(address) {
	var centrum = new google.maps.LatLng(CENTER_LAT, CENTER_LNG);

    var icon = new google.maps.MarkerImage(
        '/images/pict/pin_bien.png',
        new google.maps.Size(35, 42),
        centrum,
        new google.maps.Point(18, 42)
    );
    var shadow = new google.maps.MarkerImage(
        '/images/pict/shadow.png',
        new google.maps.Size(64, 36),
        centrum,
        new google.maps.Point(18, 42)
    );
    var markerOptions = {
        map:        map,
        position:   centrum,
        icon:       icon,
        shadow:     shadow
    };
    var marker = new google.maps.Marker(markerOptions);

    var infoWindow = new google.maps.InfoWindow({
        content: '<div class="phead">' + ADDRESS + '</div>' +
                 '<div>' + 'Prix moyen du m2 : ' + AVG_PRICE + '</div>'
    });
    google.maps.event.addListener(marker, 'click', function() {
        infoWindow.open(map, marker);
    });
}

/** 
* CUSTOM PAN CONTROL
*@preserve Maintained by the Office of Web & New Media, Missouri State University.
* Compacted version available at
* http://search.missouristate.edu/map/mobile/examples/ZoomPanControl_compiled.js
*
*/

/**
* @param {string} tagName
* @param {Object.<string, string>} properties
* @returns {Node}
*/
function CreateElement(tagName, properties) {
    var elem = document.createElement(tagName);
    for (var prop in properties) {
        if (prop == "style")
            elem.style.cssText = properties[prop];
        else if (prop == "class")
            elem.className = properties[prop];
        else
            elem.setAttribute(prop, properties[prop]);
    }
    return elem;
}

/**
* @constructor
* @param {google.maps.Map} map
*/
function ZoomPanControl(map) {
    this.map = map;
    this.originalCenter = map.getCenter();

    var t = this;
    var zoomPanContainer = CreateElement("div", { 'style': "position: relative; padding: 5px;" });

    //Pan Controls
    var PanContainer = CreateElement("div", { 'style': "position: relative; left: 2px; top: 5px; width: 56px; height: 50px; padding: 5px; overflow: hidden;" });
    zoomPanContainer.appendChild(PanContainer);
    var div = CreateElement("div", { 'style': "width: 56px; height: 46px; overflow: hidden;" });
    div.appendChild(CreateElement("img", { 'alt': ' ', 'src': 'http://maps.gstatic.com/intl/en_ALL/mapfiles/mapcontrols3d5.png', 'style': "position: absolute; left: 0px; top: -1px; -moz-user-select: none; border: 0px none; padding: 0px; margin: 0px; width: 59px; height: 492px;" }));
    PanContainer.appendChild(div);    
    
    div = CreateElement("div", { 'style': "position: absolute; left: 0px; top: 19px; width: 18.6667px; height: 18.6667px; cursor: pointer;", 'title': 'Pan left' });
    google.maps.event.addDomListener(div, "click", function() { t.pan(PanDirection.LEFT); });
    PanContainer.appendChild(div);
    div = CreateElement("div", { 'style': "position: absolute; left: 37px; top: 19px; width: 18.6667px; height: 18.6667px; cursor: pointer;", 'title': 'Pan right' });
    google.maps.event.addDomListener(div, "click", function() { t.pan(PanDirection.RIGHT); });
    PanContainer.appendChild(div);
    div = CreateElement("div", { 'style': "position: absolute; left: 19px; top: 0px; width: 18.6667px; height: 18.6667px; cursor: pointer;", 'title': 'Pan up' });
    google.maps.event.addDomListener(div, "click", function() { t.pan(PanDirection.UP); });
    PanContainer.appendChild(div);
    div = CreateElement("div", { 'style': "position: absolute; left: 19px; top: 37px; width: 18.6667px; height: 18.6667px; cursor: pointer;", 'title': 'Pan down' });
    google.maps.event.addDomListener(div, "click", function() { t.pan(PanDirection.DOWN); });
    PanContainer.appendChild(div);
    div = CreateElement("div", { 'style': "position: absolute; left: 19px; top: 19px; width: 18.6667px; height: 18.6667px; cursor: pointer;", 'title': 'Reset center' });
    google.maps.event.addDomListener(div, "click", function() { t.map.setCenter(t.originalCenter); });
    PanContainer.appendChild(div);

    return zoomPanContainer;
}

/** @param {PanDirection} direction */
ZoomPanControl.prototype.pan = function(direction) {
    var panDistance = 50;
    if (direction == PanDirection.UP || direction == PanDirection.DOWN) {
        panDistance = Math.round(this.map.getDiv().offsetHeight / 2);
        this.map.panBy(0, direction == PanDirection.DOWN ? panDistance : -1 * panDistance);
    }
    else {
        panDistance = Math.round(this.map.getDiv().offsetWidth / 2);
        this.map.panBy(direction == PanDirection.RIGHT ? panDistance : -1 * panDistance, 0);
    }
}

/** @param {ZoomDirection} direction */
ZoomPanControl.prototype.zoom = function(direction) {
    var zoom = this.map.getZoom();
    if (direction == ZoomDirection.IN && zoom < 19)
        this.map.setZoom(zoom + 1);
    else if (direction == ZoomDirection.OUT && zoom > 1)
        this.map.setZoom(zoom - 1);
}

/** @enum */
var PanDirection = {
    LEFT: 0,
    RIGHT: 1,
    UP: 3,
    DOWN: 4
}

/** @enum */
var ZoomDirection = {
    IN: 0,
    OUT: 1
}

