﻿// JScript File

var searchResult = null;
var locations = null;
var locationTypes = null;


function Location(address, latitude, longitude)
{
	this.address = address;
	this.latitude = latitude;
	this.longitude = longitude;
	
} //Location


function GetMyself()
{
    var myself = null;    
	for(var i=0; i<locations.length; i++)
        if(locations[i].locationTypeId=='myself')
        {
	        myself = locations[i];
	        break;
	    }	    
	return myself;
}
	

function GetLocations_Succeeded(result)
{
	locations = result;

	MapaAPI.GetLocationTypes(GetLocationTypes_Succeeded);

} //GetLocations_Succeeded


function GetLocationTypes_Succeeded(result)
{
	locationTypes = {};

	var divGrupy = document.getElementById("divGrupy");

	// remember location-types & show it in gui
	for(var i=0; i<result.length; i++)
	{
	    var typeId = result[i].locationTypeId;

		// myself visible only if logged-in
		if(typeId!='myself' || wasLoggedInAtStartUp)
		{
			locationTypes[typeId] = result[i];
			locationTypes[typeId].isVisible = true;

			var img = document.createElement("img");
			img.setAttribute("src", result[i].iconUrl);
			divGrupy.appendChild(img);

			var cb = document.createElement("input");
			cb.setAttribute("type", "checkbox");
			cb.setAttribute("id", typeId);
			divGrupy.appendChild(cb);
			cb.setAttribute("checked", true);
			
			var lbl = document.createElement("label");
			divGrupy.appendChild(lbl);
			lbl.setAttribute("for", typeId);
			
			var txt = document.createTextNode(result[i].name);
			lbl.appendChild(txt);		

			divGrupy.appendChild(document.createElement("br"));

			// event handling
			var cbLocationType = document.getElementById(typeId);
			cbLocationType.onclick = function() { SetGroupVisibility(this.id, this.checked); };

		} //myself or isLoggedId

	} //for-each location-type

    mapProxy.ShowLocations();
	
} //GetLocations_Succeeded


function SetGroupVisibility(type, isVisibleChecked)
{
    locationTypes[type].isVisible = isVisibleChecked;

    // refresh
    mapProxy.ShowLocations();

} //SetGroupVisibility


function SearchAddress(addressString)
{
	// reset the result (will be set when an alternative is found)	
	searchResult = null;

    var geocoder = new GClientGeocoder();
    geocoder.getLocations
    (
        addressString,
        function(response)
        {
            if(!response || response.Status.code != 200)
                alert(addressString + " adresa sa nenašla");
            else
            {
                place = response.Placemark[0];
                point = new GLatLng(place.Point.coordinates[1], place.Point.coordinates[0], false);
                
                var lat24 = point.lat();
                var lon24 = point.lng();

                map.setCenter(point, 10);
           		searchResult = new Location(addressString, lat24, lon24);

		        // show found address info
		        var lblNajdenaAdresa = document.getElementById("lblNajdenaAdresa");
		        var s = place.address;
        			
		        if(showLatLon)
			         s += " " + "[WGS'84 lat/lon: " + lat24 + " / " + lon24 + "]";
            
    	        lblNajdenaAdresa.firstChild.data = s;
            }
        }
    );

} //SearchAddress


function AddMyself()
{
	if(!Sys.Services.AuthenticationService.get_isLoggedIn())
	{
		// logged-out
		alert('Najprv musíš byť prihlásený cez login, aby si sa mohol pridať na mapu.');
		return;		
	}

	if(searchResult==null)
	{
		// nothing found yet
		alert('Najprv musíš vyhľadať adresu, kam sa chceš umiestniť');
		return;
	}

	if(GetMyself()!=null)
		// already on map => remove first
		RemoveMyself();
		
	// remember myself-location: simulated db-item with additional 'address' property
	myself = { locationId: "myself", locationTypeId: "myself", info: "ja na mape", latitude: searchResult.latitude, longitude: searchResult.longitude, address: searchResult.address };
	locations[locations.length] = myself;
	
	// show on map
    mapProxy.ShowLocations();

	// set profile
	SaveMyselfToProfile();

} //AddMyself


function RemoveMyself()
{
    var ndx = -1;    
	for(var i=0; i<locations.length; i++)
        if(locations[i].locationTypeId=='myself')
        {
	        ndx = i;
	        break;
	    }	    

	if(ndx==-1)
	{
		alert('Z mapy sa môžeš odstrániť až vtedy, ak si už na nej umiestnený a si prihlásený cez svoj login.');
    }
    else
    {
        locations.splice(ndx, 1);        
    	SaveMyselfToProfile();
        mapProxy.ShowLocations();
    }
	
} //RemoveMyself


function SaveMyselfToProfile()
{
    myself = GetMyself();
    
	if(myself==null)
	{
		// myself not initialized => reset myself into profile
		Sys.Services.ProfileService.properties.Location_Address = '';
		Sys.Services.ProfileService.properties.Location_Longitude = 0;
		Sys.Services.ProfileService.properties.Location_Latitude = 0;
	}
	else
	{
		// myself initialized, use it values
		Sys.Services.ProfileService.properties.Location_Address = myself.address;
		Sys.Services.ProfileService.properties.Location_Longitude = myself.longitude;
		Sys.Services.ProfileService.properties.Location_Latitude = myself.latitude;
	}
	
	Sys.Services.ProfileService.save(
		new Array('Location_Address', 'Location_Longitude', 'Location_Latitude'),
		null, OnProfileSaveFailed, null);
		
} //SaveMyselfToProfile


function OnProfileSaveFailed(error_object, userContext, methodName)
{
	alert("Nepodarilo sa uložiť Tvoje nastavenia, pošli prosím túto chybovú správu na info@slovaci.ch: " + error_object.get_message());
}


function SetInfo(info)
{
	var lblInfo = document.getElementById("lblInfo");
	lblInfo.innerHTML = info;

} //SetInfo


