﻿$(document).ready(function()
{
    window.Map = new GMapFull();
    if (InitSearch)
    {
        window.Map.Search();
    }
});

GMapFull.prototype = new GMapBase();
GMapFull.prototype.constructor = GMapFull;
GMapFull.prototype.Parent = GMapBase.prototype;

GMapFull.prototype.Dispose = function()
{
    this.Parent.Dispose.call(this);
    _Me = null;
};

function GMapFull()
{
    var _Me = this;
    var _MarkersMax = 1000;
    var _Container = document.getElementById("MapSearch");
	var _Markers = [];
	var _MarkerFlag = null;
	var _MarkerWin = new MarkerWindow();
	var _FieldPre = "#ctl00_plhMainContentArea_tbMembers_";

    this.Init("MapSearch", 62.915096, 17.525586, 5, { Clustered: false });
	this.AddControl(new GMapTypeControl());
	this.AddControl(_MarkerWin);
    $(GMapFull.prototype).bind("OnMarkerClick", Marker_Click);
    GEvent.addListener(this.GetMap(), "click", function(overlay) {if (overlay == null && _MarkerFlag != null) setTimeout(function() {_Me.RemoveOverlay(_MarkerFlag);}, 300);});

	$(_FieldPre + "txtQuery").keyup(function(e)
	{
		if (e.keyCode == 13)
		{
			_Me.Search();
			return false;
		}
	});

	this.Search = function()
	{
		var bounds = this.GetBounds();
		var ne = bounds.getNorthEast();
		var sw = bounds.getSouthWest();
		var lngn = ne.lng();
		var lngs = sw.lng();
		var late = ne.lat();
		var latw = sw.lat();
		var query = $(_FieldPre + "txtQuery").val();
		var type = $(_FieldPre + "ddlType").val();
		var nut = $(_FieldPre + "ddlNuts").val();
		var camping = $(_FieldPre + "cbCamping:checked").length;
		var interval = $(_FieldPre + "ddlInterval").val();
		var campingId = $(_FieldPre + "hfCampingId").val();
		var locationId = $(_FieldPre + "hfLocationId").val();


		if (_MarkerFlag != null)
		{
			_Me.RemoveOverlay(_MarkerFlag);
		}
		_MarkerWin.Hide();

		$("#MapSearch").loaderShow();
		$.getJSON("/ajax/map.ashx", { a: "search", lngn: lngn, lngs: lngs, late: late, latw: latw, q: query, t: type, d: interval, c: camping, n: nut, campid: campingId, locid:locationId }, Search_Callback);

		$(_FieldPre + "hfCampingId").val("0")
		$(_FieldPre + "hfLocationId").val("0")
		return false;
	};

	function Search_Callback(json)
	{
		$("#MapSearch").loaderHide();
		_Me.ClearMarkers(true);
		if (json.length == 1 && json[0].Lat == 0)
		{
			$("#NoHits").show();
			setTimeout(function() {$("#NoHits").hide();}, 5000);
			return;
		}
		_Markers = json;
		for (var i= 0; i < json.length; i++)
		{
			_Me.AddMarker(i, json[i].Lat, json[i].Lng, {Icon:_Me.GetIcon('marker', true)});
		}
		_Me.CenterOnMarkers();
	}

	function Marker_Click(e)
	{
		var marker = _Markers[e.Marker.Id];
		if (_MarkerFlag != null)
		{
			_Me.RemoveOverlay(_MarkerFlag);
		}
		_MarkerFlag = new MarkerFlag(e.Marker, marker.Location, marker.Municipality, marker.Images.length, marker.Galleries.length, marker.Blogs.length, marker.Clubs.length, marker.Topics.length);
		$(_MarkerFlag).bind("OnClick", MarkerFlag_Click);
		_Me.AddOverlay(_MarkerFlag);
	}

	function MarkerFlag_Click(e)
	{
		_Me.RemoveOverlay(_MarkerFlag);
		_MarkerWin.Open(_Markers[e.Marker.Id], e.EntityType);
	}
}


/* ---------------------------- MARKERFLAG ------------------------------------- */
function MarkerFlag(marker, title, areaName, imageCount, galleryCount, blogCount, clubCount, topicCount)
{
	this.Marker = marker;
	this.Title = title;
	this.AreaName = areaName;
	this.ImageCount = imageCount;
	this.GalleryCount = galleryCount;
	this.BlogCount = blogCount;
	this.ClubCount = clubCount;
	this.TopicCount = topicCount;
	var that = this;
	this.MarkerListener = GEvent.addDomListener(this.Marker, "mouseout", function() {
		$(that.Marker.Image).css("zIndex", 12);
	});
}

MarkerFlag.prototype = new GOverlay();

MarkerFlag.prototype.initialize = function(map)
{
    var that = this;
    this.Map = map;
    this.Container = document.createElement("div");

    var html = ['<div class="Content"><h3>' + this.Title + '</h3><ul>'];
    if (this.ImageCount > 0)
    {
        html.push('<li class="Images"><b>' + this.ImageCount + '</b> st bilder</li>');
    }
    if (this.GalleryCount > 0)
    {
        html.push('<li class="Galleries"><b>' + this.GalleryCount + '</b> st bildlabum</li>');
    }
    if (this.BlogCount > 0)
    {
        html.push('<li class="Blogs"><b>' + this.BlogCount + '</b> st restips</li>');
    }
    if (this.ClubCount > 0)
    {
        html.push('<li class="Clubs"><b>' + this.ClubCount + '</b> st klubbar</li>');
    }
    if (this.TopicCount > 0)
    {
        html.push('<li class="Topics"><b>' + this.TopicCount + '</b> st forumämnen</li>');
    }
    html.push('</ul></div>');

    $(this.Container).addClass("MarkerFlag").html(html.join('')).find("li").click(function(e) { var eType = $(e.target).closest("li").attr("class"); $(that).trigger({ type: "OnClick", Marker: that.Marker, EntityType: eType }); });
    map.getPane(G_MAP_MARKER_PANE).appendChild(this.Container);
    $(this.Container).css("zIndex", 11);
    $(this.Marker.Image).css("zIndex", 12);
};

MarkerFlag.prototype.remove = function()
{
	this.Container.parentNode.removeChild(this.Container);
	GEvent.removeListener(this.MarkerListener);
	$(this.Marker.Image).css("zIndex", this.Marker.ZIndex);
};

MarkerFlag.prototype.redraw = function(force)
{
    var latlng = this.Marker.getLatLng();
    var point = this.Map.fromLatLngToDivPixel(new GLatLng(latlng.lat(), latlng.lng()));
    var x = point.x - 43;
    var y = point.y - 165;
    $(this.Container).css({ left: x, top: y });
    //Is Flag outside map?
    if (force)
    {
        latlng = this.Map.fromDivPixelToLatLng(new GPoint(x, y));
        var mapBounds = this.Map.getBounds();
        if (!mapBounds.containsLatLng(latlng))
        {
            var pne = this.Map.fromLatLngToDivPixel(mapBounds.getNorthEast());
            this.Map.panBy(new GSize(0, pne.y - y));
        }
    }
};

/* ---------------------------- MARKERWINDOW ------------------------------------- */
function MarkerWindow()
{
	this.Entities = ["Images","Galleries","Blogs","Topics","Clubs","Campings"];
	this.Marker = null;
	this.ActiveTab = null;
	this.Container = document.createElement("div");
	this.Container.className = "MarkerWin";
	this.ClearData();
}

MarkerWindow.prototype = new GControl();

MarkerWindow.prototype.initialize = function(map)
{
    var html = [];
    var that = this;
    html.push('<div class="Row"><h3>Rubrik</h3>');
	html.push('<div class="Close"></div></div>');
    html.push('<div class="Menu"><ul><li><a href="javascript://" rel="Images">Bilder</a></li><li><a href="javascript://" rel="Blogs">Restips</a></li><li><a href="javascript://" rel="Clubs">Klubbar</a></li><li><a href="javascript://" rel="Topics">Foruminlägg</a></li><li><a href="javascript://" rel="Campings">Campingplatser</a></li></ul></div>');
    html.push('<div class="Content"></div>');
    html.push('<img src="/images/map/pagenext.png" class="Next" /><img src="/images/map/pageprev.png" class="Prev" />');
	$(this.Container).html(html.join(''))
		.find("div.Menu a").click(function(e) { that.MenuClick(e.target, $(e.target).attr("rel")); })
		.end()
		.find(".Close").click(function() {that.Hide(); })
		.end()
		.find("img.Next, img.Prev").click(function(e) { that.PageClick(e); })
		.end()
		.find(".Content").ajaxError(function(e, req, opts) {
			if ($(e.target).hasClass("Content"))
			{
				$(this).html('<b>Kunde tyvärr inte ladda in data. Försök senare.</b>').loaderHide();
			}
		});
	map.getContainer().appendChild(this.Container);
    return this.Container;
};

MarkerWindow.prototype.Open = function(marker, entityType)
{
    var that = this;
    var i = 0;
    this.Marker = marker;
    this.ClearData();
    this.CurrentType = entityType;
    var head = this.Marker.Location.substr(0, this.Marker.Location.length > 37 ? 37 : this.Marker.Location.length);
    if (this.Marker.Location.length > 37)
        head += "..";
    $(this.Container).find("h3").text(head);
    $(this.Container).find("li a").each(function()
    {
        $(this).parent().removeClass("Active");
        if ($(this).attr("rel") == entityType)
            $(this).parent().addClass("Active");
        if (($(this).attr("rel") == "Campings" && marker.Type == 2) || ($(this).attr("rel") != "Campings" && that.Marker[$(this).attr("rel")].length == 0))
            $(this).parent().hide();
        else
        {
            $(this).parent().show();
            i++;
        }
    });
    if (i <= 1)
        $(this.Container).find("ul").hide();
    else
        $(this.Container).find("ul").show();
    this.Show();
    this.LoadData(entityType, marker[entityType]);
};

MarkerWindow.prototype.MenuClick = function(target, entityType)
{
    $(target).addClass("Active").parent().addClass("Active").siblings().removeClass("Active").find("a").removeClass("Active");
	this.CurrentType = entityType;
    this.LoadData(entityType, this.Marker[entityType], this.Marker.Municipality);
};

MarkerWindow.prototype.LoadData = function(entityType, ids, areaName)
{
    var that = this;
    this.CurrentPage = 0;
    if (this["Data" + entityType] == null)
    {
        $(this.Container).find(".Content").empty().loaderShow({ height: 300, left: 10, top: 20 });
        var param = { a: entityType };
        if (ids) param.ids = ids.join(',');
        if (areaName) param.m = areaName;
        $.getJSON("/ajax/map.ashx", param, function(json) { that["Data" + entityType] = json; that.Render(json, 0); });
    }
    else
    {
        this.Render(this["Data" + entityType], 0);
    }
};

MarkerWindow.prototype.ClearData = function()
{
	for (var i = 0; i < this.Entities.length; i++)
	{
		this["Data" + this.Entities[i]] = null;
	}
};

MarkerWindow.prototype.PageClick = function(e)
{
    this.CurrentPage += ($(e.target).hasClass("Next") ? 1 : -1);
    this.Render(this["Data" + this.CurrentType], this.CurrentPage);
};

MarkerWindow.prototype.Render = function(json, page)
{
    var html = [];
    var count = json.Entities.length;
    var pageSize = 6;
    switch (json.Type.toLowerCase())
    {
        case "images":
            var imgs = json.Entities;
            for (var i = page * pageSize; i < page * pageSize + pageSize && i < imgs.length; i++)
            {
                html.push('<div class="Image"><a href="' + imgs[i].OrgImage + '" title="' + imgs[i].Title + '" id="img_' + i + '" class="thickbox"><img src="' + imgs[i].Image + '" alt="" /></a><span><a href="/sv/Profil/?userId=' + imgs[i].UserId + '">' + imgs[i].User + '</a></span></div>');
            }
            break;
        case "galleries":
            imgs = json.Entities;
            for (var i = page * pageSize; i < page * pageSize + pageSize && i < imgs.length; i++)
            {
                html.push('<div class="Image"><a href="' + json.Url + imgs[i].Id + '"><img src="' + imgs[i].Image + '" border="0" /></a><span><a href="/sv/Profil/?userId=' + imgs[i].UserId + '">' + imgs[i].User + '</a></span></div>');
            }
            break;
        case "blogs":
        case "clubs":
            pageSize = 3;
            var blogs = json.Entities;
            for (var i = page * pageSize; i < page * pageSize + pageSize && i < blogs.length; i++)
            {
                html.push('<div class="Blog"><img src="' + blogs[i].Image + '" /><div class="Text"><h4><a href="' + json.Url + blogs[i].Id + '">' + blogs[i].Title + '</a></h4><i>av <a href="/sv/Profil/?userId=' + blogs[i].UserId + '">' + blogs[i].User + '</a> ' + (blogs[i].Date ? blogs[i].Date : '') + '</i><span>' + blogs[i].Body + '</span></div></div>');
            }
            break;
        case "campings":
            pageSize = 3;
            var camps = json.Entities;
            for (var i = page * pageSize; i < page * pageSize + pageSize && i < camps.length; i++)
            {
				var img = camps[i].Image.indexOf("http") > -1 ? camps[i].Image : 'http://scr.basetool.se/upload/' + camps[i].Image;
                html.push('<div class="Blog"><img src="' + img + '" /><div class="Text" style="width:310px;"><h4><a href="' + json.Url + camps[i].Id + '">' + camps[i].Title + '</a></h4><span>' + camps[i].Body + '</span></div></div>');
            }
            break;
    }
    var pageCount = Math.ceil(count / pageSize);
    $(this.Container).find("img.Next, img.Prev").hide();
    if (count > pageSize)
    {
        if (page < pageCount - 1)
        {
            $(this.Container).find("img.Next").show();
        }
        if (page > 0)
        {
            $(this.Container).find("img.Prev").show();
        }
    }
    $(this.Container).find(".Content").loaderHide().html(html.join(''))[0].className = "Content " + json.Type;

    if (json.Type.toLowerCase() == "images")
    {
        $(this.Container).find("a.thickbox").bind("click", function()
        {
            $(".MapImage").remove();
            var idx = parseInt($(this).attr("id").split("_")[1]);

            var html = [];
            html.push('<div class="MapImage"><div class="Container" style="visibility:hidden;"><a href="#" class="Close"><img src="/images/map/markerwin_img_close.png" border="0" /></a>');
            html.push('<img src="" class="Big" />');
            html.push('<div class="Row"><span class="Left">');
            html.push($(this).attr("title"));
            html.push('</span><span class="Right"><a href="http://plus.camping.se/sv/Bilder/Mina-bilder/Bilder/Visa-Bild/?imageGalleryId=' + json.Entities[idx].GalleryId + '">Se fler bilder av ' + json.Entities[idx].User + '</a></span></div></div></div>');
            $("body").append(html.join(''));

            $(".MapImage").find("a.Close").one("click", function() { $(".MapImage").remove(); });
            $(".MapImage").find("img.Big").bind("load", function()
            {
                var pos = ($(this).parent().parent().height() / 2) - ($(this).parent().height() / 2);
				if (pos < 0)
					pos = 1;
                $(this).parent().css({ width: $(this).width() + 35, top: pos, visibility: 'visible' });
            }).attr("src", $(this).attr("href"));

            return false;
        });
    }
};

MarkerWindow.prototype.Hide = function() { $(this.Container).hide().find(".Content").empty(); };
MarkerWindow.prototype.Show = function() { $(this.Container).show(); };
MarkerWindow.prototype.getDefaultPosition = function() { return new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(10, 10)); };
MarkerWindow.prototype.printable = function() { return true; };
MarkerWindow.prototype.selectable = function() { return true; };	

