/**
 * JavaScript functionality for the map display for Schweizerbauer
 * 
 *
 * @author Christian Studer <christian.studer@meteotest.ch>
 */
// Global variables
var map;
var geocoder;

// Setting up the page
$(document).ready(function () {
	// Load map first
	if (GBrowserIsCompatible()) {
		map = new GMap2($('#mtmap')[0]);
		var center = new GLatLng(46.848921,8.547363);
        map.enableScrollWheelZoom();
		map.setCenter(center, 7);
		map.addControl(new GSmallMapControl());
		geocoder = new GClientGeocoder();
	}
	
	
	// Set up toggles
	$('#mtmaptoggle').html('<a href="">Karte ausblenden</a>');
	$('#mtmaptoggle').click(mtmaptoggle);	
	$('#mthelptoggle').html('<a href="">Hilfe einblenden</a>');
	$('#mthelptoggle').click(mthelptoggle);	

	// Draw crosshair on map and fetch its clicks
	$('#mtmap').append('<div id="mtcrosshair"></div>');
    $('#mtcrosshair').append('<a href=""><img src="http://schweizerbauer.meteotest.ch/images/fadenkreuz.gif" border="0" alt="Prognose hier anzeigen" title="Klicken um hier die Prognose anzuzeigen" /></a>');
    $('#mtcrosshair').css({
        position: 'absolute',
        zIndex: 5000,
        left: '212px',
        top: '130px'});
    $('#mtcrosshair').click(locateOnMap);
	
	// Fetch submit clicks
	$('#mtsubmit').click(function() {
		var currentValue = $('#mtlocationinput').val();
		
		if(currentValue == '') {
			locateOnMap();
		} else {
			loadWeather(currentValue);
		}
		
		$('#mtlocationinput').val('');
		return false;
	});
	
	$('#mtlocationinput').keydown(function(e){
        if (e.keyCode == 13) {
        	loadWeather($('#mtlocationinput').val());
    		$('#mtlocationinput').val('');
            return false;
        }
    });
	
	// On leaving the page, unload the map to prevent memory leaks
	$(document).unload(GUnload);
});

// Toggle map display
function mtmaptoggle() {
	if($('#mtmap').is(':visible')) {
		$('#mtmap').slideUp();
		$('#mtmaptoggle').html('<a href="">Karte einblenden</a>');
	} else {
		$('#mtmap').slideDown();
		$('#mtmaptoggle').html('<a href="">Karte ausblenden</a>');		
	}
	
	return false;
}

//Toggle help display
function mthelptoggle() {
	if($('#mthelp').is(':visible')) {
		$('#mthelp').slideUp();
		$('#mthelptoggle').html('<a href="">Hilfe einblenden</a>');
	} else {
		$('#mthelp').slideDown();
		$('#mthelptoggle').html('<a href="">Hilfe ausblenden</a>');		
	}
	
	return false;
}

// Always take the weather with you...
// iFrame version
function loadWeather(loc) {
	window.scrollTo($('#mtweather').position().left, $('#mtweather').position().top);
	$('#mtweatherframe').slideDown().attr('src', serviceurl + '/getweatheriframe/' + loc);
}

// Locate current center on map and show nearest weather
function locateOnMap() {
	window.scrollTo($('#mtweather').position().left, $('#mtweather').position().top);
	var center = map.getCenter();
	$('#mtweatherframe').slideDown().attr('src', serviceurl + '/getweatheriframecoordinates/' + center.lat() + '/' + center.lng());
	
	return false;
}
