﻿function LabeledMarker(latlng, opt_opts) {
    this.opts_ = opt_opts;

    this.labelText_ = opt_opts.labelText || "";
    this.labelClass_ = opt_opts.labelClass || "LabeledMarker_markerLabel";
    this.labelOffset_ = opt_opts.labelOffset || new GSize(0, 0);

    this.clickable_ = opt_opts.clickable || true;
    this.title_ = opt_opts.title || "";
    this.labelVisibility_ = true;
    this.ownVisibility_ = true;

    this.div_ = document.createElement("div");
    this.div_.className = this.labelClass_;
    this.div_.innerHTML = this.labelText_;
    this.div_.style.position = "absolute";
    this.div_.style.cursor = "pointer";
    this.div_.title = this.title_;

    if (opt_opts.draggable) {
        // This version of LabeledMarker doesn't support dragging.
        opt_opts.draggable = false;
    }

    GMarker.apply(this, arguments);
}

LabeledMarker.prototype = new GMarker(new GLatLng(0, 0));

LabeledMarker.prototype.initialize = function(map) {
    // Do the GMarker constructor first.
    GMarker.prototype.initialize.apply(this, arguments);

    this.map_ = map;

    if (!this.ownVisibility_) {
        this.hide();
    }
    this.applyLabelVisibility_();
    map.getPane(G_MAP_MARKER_PANE).appendChild(this.div_);

    if (this.clickable_) {
        // Pass through events fired on the text div to the marker.
        var eventPassthrus = ['click', 'dblclick', 'mousedown', 'mouseup',
                          'mouseover', 'mouseout'];
        for (var i = 0; i < eventPassthrus.length; i++) {
            var name = eventPassthrus[i];
            GEvent.addDomListener(this.div_, name,
                            GEvent.callback(GEvent, GEvent.trigger,
                                            this, name, this.getLatLng()));
        }
    }
};


LabeledMarker.prototype.redraw = function(force) {
    GMarker.prototype.redraw.apply(this, arguments);
    this.redrawLabel_();
};

LabeledMarker.prototype.redrawLabel_ = function() {
    // Calculate the DIV coordinates of two opposite corners of our bounds to
    // get the size and position of our rectangle
    var p = this.map_.fromLatLngToDivPixel(this.getLatLng());
    var z = GOverlay.getZIndex(this.getLatLng().lat());

    // Now position our div based on the div coordinates of our bounds
    this.div_.style.left = (p.x + this.labelOffset_.width) + "px";
    this.div_.style.top = (p.y + this.labelOffset_.height) + "px";
    this.div_.style.zIndex = z; // in front of the marker
};

LabeledMarker.prototype.remove = function() {
    GEvent.clearInstanceListeners(this.div_);
    if (this.div_.outerHTML) {
        this.div_.outerHTML = ""; //prevent pseudo-leak in IE
    }
    if (this.div_.parentNode) {
        this.div_.parentNode.removeChild(this.div_);
    }
    this.div_ = null;
    GMarker.prototype.remove.apply(this, arguments);
};

LabeledMarker.prototype.copy = function() {
    var newMarker = new LabeledMarker(this.getLatLng(), this.opts_);
    // copy visibility properties as they are not controlled by opts_
    newMarker.labelVisibility_ = this.labelVisibility_;
    newMarker.ownVisibility_ = this.ownVisibility_;
    return newMarker;
};

LabeledMarker.prototype.show = function() {
    GMarker.prototype.show.apply(this, arguments);
    this.ownVisibility_ = true;
    this.applyLabelVisibility_();
};


LabeledMarker.prototype.hide = function() {
    GMarker.prototype.hide.apply(this, arguments);
    this.ownVisibility_ = false;
    this.applyLabelVisibility_();
};

LabeledMarker.prototype.setLabelVisibility = function(visibility) {
    this.labelVisibility_ = visibility;
    this.applyLabelVisibility_();
};

LabeledMarker.prototype.getLabelVisibility = function() {
    return this.labelVisibility_;
};


LabeledMarker.prototype.applyLabelVisibility_ = function() {
    if ((!this.isHidden()) && this.labelVisibility_) {
        this.div_.style.display = 'block';
    } else {
        this.div_.style.display = 'none';
    }
};


LabeledMarker.prototype.setLabelText = function(text) {
    this.labelText_ = text;
    this.div_.innerHTML = text;
    // save new label text in opts_, it may be required for copy()
    this.opts_.labelText = text;
};


//
// Author: Logutov Michael
// Date: 04 december 2008
// Description: This plugin handle query string operations
// Methods:
//		load() - parses current url hash into $.queryString.hash
//		save() - saves $.queryString.hash values into current url hash. Only values that has not null value will be saved.
//

; (function($) {
	$.queryString = new Object();

	$.queryString.parse = function(str) {
		var parts = str.split('|');
		var regex_name_value = /^\s*(.*?)\s*\=\s*(.*?)\s*$/i;
		var res = new Object();

		for (k = 0; k < parts.length; k++) {
			var part = $.trim(parts[k]);

			if (!part || part.length < 1)
				continue;

			var sub_parts = regex_name_value.exec(part);
			if (sub_parts)
				res[sub_parts[1]] = sub_parts[2];
			else
				res[part] = part;
		}

		return res;
	}

	$.queryString.load = function() {
		this.hash = new Object();
		if (document.location.hash)
			this.hash = $.queryString.parse(window.location.hash.substring(1));
	}

	$.queryString.save = function() {
		if (!this.hash)
			return;

		var new_hash = null;
		$.each(this.hash, function(key, val) {
			if (val == null)
				return;

			if (new_hash)
				new_hash += "|";
			else
				new_hash = "#";

			if (key != val)
				new_hash += key + "=" + val;
			else
				new_hash += key;
		});

		window.location.hash = new_hash;
	}

})(jQuery);

var map;
var minLon;
var maxLat;
var maxLon;
var minLat;
var bFirstLoad = true;
var mapRequestTimer = null;
var mapAjaxRequest = null;

var lastReqDateTime = (new Date()).getTime();

var clearMarkers = true;
var bHandler = function(e) {

    return $(this).data("tp");

};
var AddPercent = function(x, percent) {
    return x * (1 + percent / 100);
};

var ReloadMarkers = function() {

    clearTimeout(mapRequestTimer);
    if (mapAjaxRequest != null)
        mapAjaxRequest.abort();
        
    mapRequestTimer = setTimeout(function() {
	
	var bounds = map.getBounds();
	map.my.isMarkersLoading = true;
	mapAjaxRequest = $.jmsajax
	(
	{
		contentType: "application/json; charset=utf-8",
		url: "/WebServices/GMap.asmx/GetMarkers",
		data: {

			"southWestLat": bounds.getSouthWest().lat(),
			"northEastLat": bounds.getNorthEast().lat(),
			"southWestLng": bounds.getSouthWest().lng(),
			"northEastLng": bounds.getNorthEast().lng(),
			"maxMarkers": map.my.maxMarkers,
			"filter": filter

		},
		cache: false,
		success: function(data, textStatus) {
			if (!data)
				return;


			minLon = data.MinLon;
			maxLat = data.MaxLat;
			maxLon = data.MaxLon;
			minLat = data.MinLat;

			var items = data.itms;
			var i;
			map.clearOverlays();
			for (i = 0; i < items.length; i++) {

				var item = items[i];
				var point = new GLatLng(item.Lt, item.Lg);
				var m = CreateCustomMarker2(point, item);
				map.addOverlay(m);
				var tooltiptext = "<div style=''><div class='conten'><div class='type'>" + item.GName + "</div><div class='name'>" + item.N + "</div>" + ((item.Ph.length > 0) ? "тел. " + item.Ph + "<br/>" : " ") + item.Add + "</div><div class='vtooltip_block'>&#160;</div></div>";

				if (tooltiptext && m.div_) {


				 $(m.div_).data("tp", tooltiptext).tooltip
				({
						bodyHandler: bHandler,
						showURL: false,
						fixPNG: true,
						extraClass: "vtooltip"
				});
				    
			
				}                               
 
			}
			if (i == 0 && bFirstLoad) {
				$("#ID_notfound").show();
			}
			else {
				$("#ID_notfound").hide();
			}
			if (bFirstLoad) {
				var leftLon = minLon;
				var topLat = maxLat;
				var rightLon = maxLon;
				var bottomLat = minLat;
				if (leftLon != 5000 && topLat != 5000 && rightLon != 5000 && bottomLat != 5000) {
					var percent = (topLat - bottomLat) / bottomLat;
					topLat = AddPercent(topLat, percent * 10);
					bottomLat = AddPercent(bottomLat, percent * (-10));
					var rectBounds = new GLatLngBounds(new GLatLng(bottomLat, leftLon), new GLatLng(topLat, rightLon));
					var center = rectBounds.getCenter();
					var zoom = map.getBoundsZoomLevel(rectBounds);
					if (zoom >= 10)
						map.setCenter(center, zoom);
				}

				bFirstLoad = false;
			}

			map.my.isMarkersLoading = false;
			if (map.my.viewingMarker)
				GEvent.trigger(map.my.viewingMarker, "click");
		}
		
	});
	
	}, 400);
}
function randOrd() { return (Math.round(Math.random()) - 0.5); }
function GMapSaveToHash(map) {
	$.queryString.hash["lt"] = map.getCenter().lat();
	$.queryString.hash["lg"] = map.getCenter().lng();
	$.queryString.hash["z"] = map.getZoom();
	$.queryString.save();
}

var CreateCustomMarker2 = function(point, item) {
    var icon = new GIcon();
    icon.image = "/img/map/c_0" + item.GId + ".png";
    icon.iconSize = new GSize(29, 38);
    icon.iconAnchor = new GPoint(14, 38);
    icon.infoWindowAnchor = new GPoint(29, 0);

	var m = new LabeledMarker(point,
	{
	    "icon": icon,
	    "clickable": true,
	    "labelText": "&#160;",
		"labelOffset": new GSize(-14, -38),
		"labelClass": "gmapMarkerMedium",
		"title": ""

	});

	GEvent.addListener(m, "click", function() {
	    window.location.href = "/company/" + item.Al + "/";
	});

    return m;
}


var CreateCustomMarker = function(point, item) {

	var icon = new GIcon();
	icon.image = "/img/map/c_0" + item.GId + ".png";
	icon.iconSize = new GSize(29, 38);
	icon.iconAnchor = new GPoint(14, 38);
	icon.infoWindowAnchor = new GPoint(29, 0);
	var m = new GMarker(point,
	{
		"icon": icon
	});

	GEvent.addListener(m, "click", function() {
		window.location.href = "/company/" + item.Al +"/";
	});
	return m;
};


var GoogleMapsLoaded = function() {
	map.my =
		{
			maxMarkers: 100,
			defaultCityZoom: 13
		};
	map.addControl(new ExtLargeMapControl());
	map.addControl(new GMapTypeControl());
	//map.disableDoubleClickZoom();
	map.disableContinuousZoom();
	//map.enableScrollWheelZoom();
	GEvent.addListener(map, "zoomend", function(oldLevel, newLevel) {
		if (oldLevel == newLevel)
			return;
		    GMapSaveToHash(map);
		//ReloadMarkers();
	});

	GEvent.addListener(map, "moveend", function() {
		GMapSaveToHash(map);
		if(!bFirstLoad)
		    ReloadMarkers();
	});
	ReloadMarkers();
}

//$(document).ready(function() {


	map = new GMap2(document.getElementById("gmap"));
	$.queryString.load();
	var lt = parseFloat($.queryString.hash["lt"]);
	var lg = parseFloat($.queryString.hash["lg"]);
	var z = parseInt($.queryString.hash["z"]);
	if (isFinite(lt) && isFinite(lg) && isFinite(z))
		map.setCenter(new google.maps.LatLng(lt, lg), z);
	else if(RegionPrefix == '/spb')
	    map.setCenter(new google.maps.LatLng(59.95000001, 30.316666676667), 10);
    else
		map.setCenter(new google.maps.LatLng(55.751849391735284, 37.62044906616211), 10);
	GMapSaveToHash(map);
	GoogleMapsLoaded();
//} );

