﻿/* 
 * MapTips, v1.0
 * Author: Klaus Paiva (blog.klaus.pro.br)
 *
 * Copyright 2008, Klaus Paiva 
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License. 
*/



$.fn.extend(
	{
		// http://www.quirksmode.org/js/findpos.html
		find_pos : function()
		{
			if( !this.tagName && this.length )
			{
				obj = this[0];
			}
			else
			{
				return [0,0];
			}
			var curleft = curtop = 0;
			if (obj.offsetParent) {
				curleft = obj.offsetLeft;
				curtop = obj.offsetTop;
				while (obj = obj.offsetParent) {
					curleft += obj.offsetLeft;
					curtop += obj.offsetTop;
				}
			}
			return [curleft,curtop];
		}
	}
);

function MapTips( map )
{
	var self = this;
	var _map = map;
	this.add_tooltip = function( marker, text )
	{
		marker.tooltip = text;
		GEvent.addListener( marker, "mouseover", self.show_tooltip );
		GEvent.addListener( marker, "mouseout", self.hide_tooltip );
	};
	this.show_tooltip = function( marker )
	{
		// obtÃªm o x e y do marcador
		var marker_point = _map.fromLatLngToContainerPixel( this.getLatLng() );
		$( "body" ).append( '<div id="maptip" style="visibility: hidden;">' + this.tooltip + '</div>' );
		// pega a posiÃ§Ã£o do mapa atual do mapa, em x e y.
		var positions = $( _map.getContainer() ).find_pos();
		
		// calcula os trÃªs pontos para reposicionamento no mapa: left, right e top
		var map_left = positions[0];
		var map_right = positions[0] + $( _map.getContainer() ).width();
		var map_top = positions[1];
		
		// captura o tamanho do Ã­cone para fazer o posicionamento
		var icon_size = this.getIcon().iconSize;
		positions[0] += marker_point.x;
		positions[1] += marker_point.y - icon_size.height;
		var x_adjustment = $( "#maptip" )[0].offsetWidth / 2; // divide por 2 para ficar centralizado
		var y_adjustment = $( "#maptip" )[0].offsetHeight + 3;
		var left_value = positions[0] - x_adjustment; // calculo do valor "left" da maptip
		var top_value = positions[1] - y_adjustment // calculo do valor "top" da maptip
		
		// aqui sÃ£o feitos os cÃ¡lculos para corrigir o posicionamento quando a maptip aparece nos cantos do mapa
		// nÃ£o hÃ¡ necessidade de alterar esses valores
		var tip_left = positions[0] - x_adjustment;
		var tip_right = positions[0] - x_adjustment + $( "#maptip" )[0].offsetWidth;
		var tip_top = positions[1] - y_adjustment;
		if( map_left >= tip_left )
		{
			left_value += map_left - tip_left + 3; // + 3 Ã© para a borda nÃ£o colar na borda do mapa
		}
		else if( map_right <= tip_right )
		{
			left_value -= tip_right - map_right + 3; // + 3 Ã© para a borda nÃ£o colar na borda do mapa
		}
		if( map_top >= tip_top )
		{
			top_value += $( "#maptip" )[0].offsetHeight + icon_size.height + 6; // coloca abaixo do marcador
		}
		
		// por fim, atribui os valores calculados e exibe a maptip
		$( "#maptip" ).css( "left", left_value ).css( "top", top_value ).css( "visibility", "visible" );
		$( "#maptip" ).fadeIn( "medium" );
	};
	this.hide_tooltip = function()
	{
		$( "#maptip" ).remove();
	};
}

function initialize2()
{
	if( GBrowserIsCompatible() )
	{


      function createMarker(point,icon,height,width,url) {
        var marker = new GMarker(point, {icon:icon});
	icon.iconSize = new GSize(width,height);
	GEvent.addListener(marker, "click", function() {
        window.open(url);
        });

	return marker;
      }
	
    var PromoControl = function(url) {
    this.url_ = url;
    };
  
    PromoControl.prototype = new GControl(true);
  
    PromoControl.prototype.initialize = function(map) {
    var container = document.createElement("div");
    container.innerHTML = '<img style="cursor:pointer" src="' + wddir + '/nwn_small.png" border="0">';
    container.style.width='55px';
    container.style.height='59px';
  
    url = this.url_;
  
    GEvent.addDomListener(container, "click", function() {
    document.location = url;
    });
  
    map.getContainer().appendChild(container);
  
    return container;
    };
  
    PromoControl.prototype.getDefaultPosition = function() {
    return new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(5,5));
    };

    var options = { 'size' : new GSize( $("#map_canvas2").width(), $("#map_canvas2").height() ) };
    var map = new GMap2( $("#map_canvas2")[0], options );
    panControl = new GSmallMapControl();
    map.addMapType(G_PHYSICAL_MAP);
    map.addControl(new PromoControl());
    map.setCenter(new GLatLng(clat,clon), czoo, G_PHYSICAL_MAP); 
   // geocoder = new GClientGeocoder();
   // geocoder.setCache(new CapitalCitiesCache());

if(overlay == 1) {
      map.addOverlay(new GPolygon([new GLatLng(-85,0),new GLatLng(85,0),new GLatLng(85,90),new GLatLng(-85,90)],null,0,0,overlaycolor,overlayfade));
      map.addOverlay(new GPolygon([new GLatLng(-85,90),new GLatLng(85,90),new GLatLng(85,180),new GLatLng(-85,180)],null,0,0,overlaycolor,overlayfade));
      map.addOverlay(new GPolygon([new GLatLng(-85,180.000001),new GLatLng(85,180.000001),new GLatLng(85,270),new GLatLng(-85,270)],null,0,0,overlaycolor,overlayfade));
      map.addOverlay(new GPolygon([new GLatLng(-85,270),new GLatLng(85,270),new GLatLng(85,360),new GLatLng(-85,360)],null,0,0,overlaycolor,overlayfade));
       }

    map.addControl(panControl, new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(10, 75)));
    var mapControl = new GHierarchicalMapTypeControl();
    mapControl.clearRelationships();
    mapControl.addRelationship(G_SATELLITE_MAP, G_HYBRID_MAP, "Labels", false);   
    map.addControl(mapControl);
    var mm = new GMarkerManager(map); 
    var maptips = new MapTips( map ); // MapTips aqui!
	
    var datafile = maindir + "Nordic-conditions.php";

    // read the markers from the XML
    var gmarkersA = [];   
    var gmarkersB = [];   

    // read the markers from the XML
    $(document).ready(function(){ 
    // Open the students.xml file
    $.get(datafile,{},function(xml){
    $('marker',xml).each(function(i) {
    
    // obtain the attribues of each marker
    var lat = $(this).attr("lat");
    var lng = $(this).attr("lng");
    var alt = $(this).attr("alt");
    var name = $(this).attr("name");
    var url = $(this).attr("url");

    var software = $(this).attr("software");
    var hardware = $(this).attr("hardware");
    var tracker = $(this).attr("tracker");

    var ic = $(this).attr("icon");

    var time = $(this).attr("time");
    var tz = $(this).attr("tz");

    var temp = $(this).attr("temp");
    var matemp = $(this).attr("matemp");
    var mitemp = $(this).attr("mitemp");

    var wdir = $(this).attr("wdir");
    var wspd = $(this).attr("wspd");
    var humi = $(this).attr("humi");
    var baro = $(this).attr("baro");
    var trnd = $(this).attr("trnd");

    var rain = $(this).attr("rain");
    var snow = $(this).attr("snow");

    var condicon = $(this).attr("condicon");

    var maxtemp = $(this).attr("ymaxtemp");
    var mintemp = $(this).attr("ymintemp");
    var maxgust = $(this).attr("ymaxgust");
    var yrain = $(this).attr("yprecip");

    var track = $(this).attr("trac");

    var sunr = $(this).attr("sunr");
    var suns = $(this).attr("suns");

    var cam = $(this).attr("cam");
    
    var point = new GLatLng(lat,lng);

    today=new Date();
    var mo = today.getMonth();

if ((sunr == "--") && (mo < 4*1)) {
sundata = "<span>" + polar + "</span>";
} else 
if ((sunr == "--") && (mo > 4*1) && (mo < 9*1)) {
sundata = "<span>" + midnight + "</span>";
} else 
if ((sunr == "--") && (mo > 9*1)) {
sundata = "<span>" + polar + "</span>";
} else 
{ 
sundata = "<span><img src=\"" + icdir + "/up3.png\" /><small> " + sunr + " <img src=\"" + icdir + "/down3.png\" /> " + suns + "</small></span>";
}

if (trnd == "0") {
barotrnd = "";
} else {
barotrnd = "<img src=\"" + icdir + "/" + trnd + "\" alt=\"\"/>";
}

if (rain < "0.1") {
raintxt = txtnorain;
} else {
raintxt= txtrain + ": " + rain + " mm";
}

if (snow < "0.1") {
snowtxt = "";
} else {
snowtxt= txtsnow + " " + snow + " cm";
}

   // var marker = createMarker(point, icon, 25, 25, url);
   // gmarkersA.push(marker);

    var marker = createMarker(point, myIcons[ic], myIconsheight[ic], myIconswidth[ic], url);
   // gmarkersA.push(marker);
    var bmarker = createMarker(point, myBIcons[ic], myBIconsheight[ic], myBIconswidth[ic], url);
   // gmarkersB.push(bmarker);

    mm.addMarker(marker,0,5);
    mm.addMarker(bmarker,6,17);


    maptips.add_tooltip( marker, "<div class=\"GMtip_cty\"><span class=\"GMtip_time\">" + time + " " + tz + "</span><b>" + name + " (" + alt + " m)</b></div><table width=\"280\" class=\"GMtip\"><tr><td width=\"145px\" class=\"GMtip\"><span style=\"float: right;\"><img src=\"" + icdir + "/up2.png\" alt=\"\" /><span class=\"GMtip_max\">" + matemp + "&deg;C</span><br/><img src=\"" + icdir + "/down2.png\" alt=\"\" /><span class=\"GMtip_min\">" + mitemp + "&deg;C</span></span><img src=\"" + icdir + "/" + condicon + "\" align=\"left\" height=\"25\" width=\"25\" alt=\"\"/><div class=\"GMtip_tmp\">&nbsp;" + temp + "&deg;C</div>" + txtwind + ":&nbsp;&nbsp;<img src=\"" + icdir + "/" + wdir + ".png\" height=\"14\" width=\"14\" alt=\"\" />&nbsp;&nbsp;" + wspd + "&nbsp;m/s<br/>" + txthumi + ": " + humi + "&nbsp;%<br/>" + txtbaro + ": " + baro + "&nbsp;hPa&nbsp;" + barotrnd + "<br/>" + raintxt + "<br/>" + snowtxt + "" + track + "</td><td height=\"105\" align=\"center\" class=\"GMtip2\">" + sundata + "<div style=\"background: url('" + icdir + "/spinner.gif') no-repeat center center; height: 98px; width: 120px;\"><img src=\"" + maindir + "Nordic-webcams.php?id=" + name + "\" alt=\"\" height=\"98\" width=\"120\"/></div></td></tr></table><table width=\"285\" class=\"stat\" cellpadding=\"0\" cellspacing=\"0\"><tr><td width=\"50%\" class=\"subhead\">" + txtstat + " " + year + "</td><td class=\"subhead2\">" + txttecn + "</td></tr><tr><td width=\"50%\" class=\"subdata\">Max " + txttemp + ": " + maxtemp + "&deg;C<br/>Min " + txttemp + ": " + mintemp + "&deg;C<br/>Max " + txtwind + ": " + maxgust + " m/s<br/>" + txtrain + ": " + yrain + " mm<br/></td><td valign=\"top\" class=\"subdata\">" + softa + ": " + software + "<br/>" + hardw + ": " + hardware + "<br/>" + strack + ": " + tracker + "</td></tr></table>");


    maptips.add_tooltip( bmarker, "<div class=\"GMtip_cty\"><span class=\"GMtip_time\">" + time + " " + tz + "</span><b>" + name + " (" + alt + " m)</b></div><table width=\"280\" class=\"GMtip\"><tr><td width=\"145px\" class=\"GMtip\"><span style=\"float: right;\"><img src=\"" + icdir + "/up2.png\" alt=\"\" /><span class=\"GMtip_max\">" + matemp + "&deg;C</span><br/><img src=\"" + icdir + "/down2.png\" alt=\"\" /><span class=\"GMtip_min\">" + mitemp + "&deg;C</span></span><img src=\"" + icdir + "/" + condicon + "\" align=\"left\" height=\"25\" width=\"25\" alt=\"\"/><div class=\"GMtip_tmp\">&nbsp;" + temp + "&deg;C</div>" + txtwind + ":&nbsp;&nbsp;<img src=\"" + icdir + "/" + wdir + ".png\" height=\"14\" width=\"14\" alt=\"\" />&nbsp;&nbsp;" + wspd + "&nbsp;m/s<br/>" + txthumi + ": " + humi + "&nbsp;%<br/>" + txtbaro + ": " + baro + "&nbsp;hPa&nbsp;" + barotrnd + "<br/>" + raintxt + "<br/>" + snowtxt + "" + track + "</td><td height=\"105\" align=\"center\" class=\"GMtip\">" + sundata + "<div style=\"background: url('" + icdir + "/spinner.gif') no-repeat center center; height: 98px; width: 120px;\"><img src=\"" + maindir + "Nordic-webcams.php?id=" + name + "\" alt=\"\" height=\"98\" width=\"120\"/></div></td></tr></table><table width=\"285\" class=\"stat\" cellpadding=\"0\" cellspacing=\"0\"><tr><td width=\"50%\" class=\"subhead\">" + txtstat + " " + year + "</td><td class=\"subhead2\">" + txttecn + "</td></tr><tr><td width=\"50%\" class=\"subdata\">Max " + txttemp + ": " + maxtemp + "&deg;C<br/>Min " + txttemp + ": " + mintemp + "&deg;C<br/>Max " + txtwind + ": " + maxgust + " m/s<br/>" + txtrain + ": " + yrain + " mm<br/></td><td valign=\"top\" class=\"subdata\">" + softa + ": " + software + "<br/>" + hardw + ": " + hardware + "<br/>" + strack + ": " + tracker + "</td></tr></table>");

  
   // mm.addMarker(marker,0,5);
   // mm.addMarker(bmarker,6,17);


});
});

  
/*
    for (var i = 0; i < gmarkersA.length; i++) {
    mm.addMarker(gmarkersA[i],0,5);
    }
    for (var i = 0; i < gmarkersB.length; i++) {
    mm.addMarker(gmarkersB[i],6,17);
    }
*/
    mm.refresh();

      });
    }
}

$( function(){ setTimeout( initialize2, 500 ); } );
window.unload = GUnload;