google.load('maps','2');
google.load('search' , '1');

var newLat = $.cookie("localLat");
var newLng = $.cookie("localLng");
var smallmap = "";
var gewijzigd = false;

var searcher;
var searchResults = [];
var searchForm;


function initialize() {
	
    smallmap = new google.maps.Map2(document.getElementById("smallmap_canvas"));
    smallmap.setCenter(new google.maps.LatLng(localLat, localLng), 9);
    //map.setUIToDefault();
    smallmap.addControl(new GSmallZoomControl3D());
    smallmap.disableDragging();
    smallmap.disableScrollWheelZoom();
       		
	mapLoaded();
}

function mapLoaded() {
	
    // initialize html
    if ($.cookie("savedSettings") == "true") {
    	$("#home_position_tekst").html("Uw locatie is nu ingesteld voor deze website. U kijkt via <strong>" + $.cookie("satname").replace(/\+/g, ' ') + ".</strong><br /><a href='javascript:wijzigLocation()'>Wijzig</a>");
//	   	$.cookie("showReady","false");
    } else {
    	
    	
    	
    	
    	$("#home_position_tekst").html("Selecteer dan uw satelliet:<br />");  
		//if ($.cookie("localLat") != null && ($.cookie("localLat") < 0 || $.cookie("localLat") > 0)  ) {  	

		
//alert($.cookie("localLat"));

		
    	if ($.cookie("localLat") != null && $.cookie("localLat") != null) {  	
    		
			$.get("/sat",{"newlat":newLat,"newlng":newLng, "get":"satellites"},loadSatReady_extern,"xml");    	
	    } 
	    else {
	    	
			$.get("/sat",{"ip":ip,"get":"satellites"},loadSatReady_extern,"xml");    	
    	}
    }
    
}



// Called when Local Search results are returned, we clear the old
// results and load the new ones.
function OnLocalSearch() {
	
	if (!searcher.results) return;
	
	/*
	
	var searcherResultContainer = document.getElementById("pep_location_content");

	// Clear the map and the old search well
	searcherResultContainer.innerHTML = "";
	for (var i = 0; i < searchResults.length; i++) {
  		map.removeOverlay(searchResults[i].marker());
	}
	
	*/

	searchResults = [];
	if (searcher.results.length > 0) {
		
		/*
		for (var i = 0; i < searcher.results.length; i++) {
			searchResults.push(new LocalResult(searcher.results[i]));
		}
		
		var attribution = searcher.getAttribution();
		if (attribution) {
			document.getElementById("pep_location_content").appendChild(attribution);
		}
	
		$('#pep_location_list').jScrollPane();		
	
		*/
		
		// move the map to the first result
		var first = searcher.results[0];
		smallmap.panTo(new google.maps.LatLng(first.lat, first.lng));
		
		$("#home_position_tekst").html("Klopt dit?<br /><a href='javascript:wijzigLocation()'>Nee, opnieuw bepalen.</a><br /><a href='javascript:wijzigSatelliet()'>Ja, ga verder.</a>");
				
		
	} else {
	
//		$("#pep_location_content").html("<p style='font-size:11px; width: 180px'>De door U opgegeven lokatie kan helaas niet gevonden worden. <br /><br />Om gerichter te zoeken, typ de plaatsnaam achter uw zoekopdracht.<br /><br />Bijvoorbeeld:<br />'Stationsplein, Hilversum'<br/>'Paradiso, Amsterdam'.</p>");
		
	}
		
//	map.setZoom(13);
//	searcher.setCenterPoint(map);	
}

 // Cancel the form submission, executing an AJAX Search API search.
function CaptureForm(value) {
	searcher.setCenterPoint(smallmap);	
	searcher.execute(value);
	return false;
}


function wijzigLocation() {
	
    smallmap.enableDragging();
	
	
	$("#home_position_tekst").html("Typ hier uw plaatsnaam of streek, en het bijbehorend land:<br /><div style='font-size:10px; color: #666'>(Bijvoorbeeld: 'Parijs, Frankrijk')</div>");
	
	var form = $(document.createElement('form'));
	
	var input = $(document.createElement('input'));
	
	input.attr("id","home_position_location");
	input.attr("type","text");
	input.width(140);
	form.append(input);
	
	input.bind("keypress", function(e) {
		if (e.keyCode == 13) {			
			CaptureForm($('#home_position_location').val());			
			return false;
		}
	});
		
	var button = $(document.createElement('input'));
	button.attr("type","button");
	button.attr("value","ok");
	button.mousedown(function() {
	
		CaptureForm($('#home_position_location').val());			
	
	});
	
	
	form.append(button);	
	
	$("#home_position_tekst").append(form);

	// initialize Searcher and Searchform	
	searchForm = new google.search.SearchForm(false, document.getElementById("home_position_location"));		
    searcher = new google.search.LocalSearch();
    searcher.setCenterPoint(smallmap);
    searcher.setSearchCompleteCallback(null, OnLocalSearch);	
	
	
}


function wijzigSatelliet() {
	
    smallmap.disableDragging();	
	
	gewijzigd = true;
	
	newLat = smallmap.getBounds().getCenter().lat(); 
	newLng = smallmap.getBounds().getCenter().lng()	

	$("#home_position_tekst").html("Selecteer uw satelliet:");	
	
	
   	if (newLat != null) {  	
		
		$.get("/sat",{"newlat":newLat,"newlng":newLng, "get":"satellites"},loadSatReady_extern,"xml");    	
    } else {	
		$.get("/sat",{"ip":ip,"get":"satellites"},loadSatReady_extern,"xml");  
    }

}

function loadSatReady_extern(data,status){
	
	
	$.cookie("savedSettings","false",{ expires: 10000, path: '/'});

	
	//alert(data);
	
	var form = $(document.createElement('form'));
	form.attr("id","home_position_form");
	
	var select = $(document.createElement('select'));
	
	select.attr("id","select_sat");
	form.append(select);
	
	$(data).find("satellite").each(function(){
	
		var option = $(document.createElement('option'));
		option.attr("value",$(this).attr("id"));
		var displayName = unescape( $(this).attr("name").replace(/\+/g, ' ') );
		option.html( displayName.replace(/\+/g, ' ') );
		select.append(option);
	});
	
	var button = $(document.createElement('input'));
	button.attr("type","button");
	button.attr("value","ok");
	button.mousedown(function() {
	
		$.cookie("satId",$("#select_sat :selected").attr("value"),{ expires: 10000, path: '/'});

		$.cookie("satname",$("#select_sat :selected").text(),{ expires: 10000, path: '/'});
		$.cookie("localLat",newLat,{ expires: 10000, path: '/'});
		$.cookie("localLng",newLng,{ expires: 10000, path: '/'});
		$.cookie("savedSettings","true",{ expires: 10000, path: '/'});
		
		
		
		if(window.location.hash == "#popup"){
			
			window.opener.location.href = window.opener.location.href.replace(/\?u=(.*)/,"")+"?u="+Math.round(Math.random()*100000);
			window.close();
		}
		else{
			
			window.location.href = window.location.href.replace(/\?u=(.*)/,"")+"?u="+Math.round(Math.random()*100000);
		}
		
		
		
	});
	
	
	form.append(button);

	$("#home_position_tekst").append(form);
			
	if (!gewijzigd) {
		$("#home_position_tekst").append("<div style='margin-top: 15px'><span>Klopt uw locatie of tijd niet? Klikt u dan <a href='javascript:wijzigLocation()'>hier</a>.</span></div>");
	}	
	
}


$(document).ready(function(){
 	 	
 	initialize();
 	
})