/**
 * @author Alfred Broda
 */
var opis;
var removed;
var persistent;
var temp_latlng = null;

function map_show_icons(cat) {
	showCat(cat);
}

function showCat(url) {
	new Ajax.Request(url, {
	asynchronous:true,
	evalScripts:false,
	method:'get',
	onComplete:function(request, json){
		Element.hide('wait');
	},
	onLoading:function(request, json){
		Element.show('wait');
	},
	onSuccess:function(response) {
		if (response.status == 200) {
			var list = String(response.responseText);
			list = list.evalJSON();
			var cats = Object.values(list.cats);
			cats._each(function(list){
				if (typeof(list)=="object") {
					allcats[list.id] = list;
				}
			});
			redrawCats();
	/*		
			var ne = new GPoint(list.maxx, list.maxy);
			var sw = new GPoint(list.minx, list.miny);
			var mid = new GLatLng(list.posn[0], list.posn[1]);
			var bounds = new GLatLngBounds(sw, ne);
			var z = map.getBoundsZoomLevel(bounds);
			map.setCenter(mid, z);
	*/
		}		
	},
	parameters:'&rand='+rand(1000)
	});
}

function hideCat(cat) {
	removed = allcats[cat];
	allcats.splice(cat,1);
//	removed._each(function(overlay){
//		map.removeOverlay(overlay);
//	});
	//if (persistent) {
	//	showCat(persistent);
	//} else {
		redrawCats();
	//}
}

function redrawCats(){
	/* Uwaga! clearPolys usówa i wielokąty i linie! */
	clearMarkers();
	clearPolys();
//	map.C._each(function(overlay){
//		map.removeOverlay(overlay);
//	});
	allcats._each(function(cat){
		if (typeof(cat)=='object') {
			if (typeof(cat.lines)=='object')
				makeLines(cat);
			if (typeof(cat.polys)=='object')
				makePolys(cat);
			if (typeof(cat.places)=='object')
				makeMarkers(cat);
		}
	});
}

/* Obsolete
function get_obj(id) {
	oid = id;
	//FIXME: Stare linki!
	new Ajax.Request('map.php/iobiekt/get-'+id+'.json', {
	asynchronous:true,
	evalScripts:false,
	method:'get',
	onComplete:function(request, json){
		Element.hide('wait');
	},
	onLoading:function(request, json){
		Element.show('wait')
	},
	onSuccess:function(res) {
		curro = res.responseText.evalJSON();
		curro = curro[0];
// 		clearMarkers();
		if (curro.posn[0]==0 && curro.posn[1]==0) {
			geocoder.getLatLng(curro.addr, addAddressToMap);
		} else {
//			var point = new GLatLng(curro.posn[0],curro.posn[1]);
			wskaz(curro.posn[0],curro.posn[1],curro.zoom);
		}
	},
	parameters:'id='+id.toJSON()+'&rand='+rand(1000)
	});
}
*/

function catch_pos(latlng) {
	temp_latlng = latlng;
}

/**
 * Pokazuje opis klikniętego markera wyciągając go z bazy AJAXem
 * @param {Object} marker Objekt markera
 */
function get_opis(marker){
	if (marker && typeof(marker)=='object' && marker.item) {
		new Ajax.Request(marker.item.desc, {
			asynchronous: true,
			evalScripts: false,
			method: 'get',
			onComplete: function(request, json){
				Element.hide('wait');
			},
			onLoading: function(request, json){
				Element.show('wait');
			},
			onSuccess: function(res){
				var temp = res.responseText;
				/* Tniemy odpowiedź na bloki */
				var head = temp.slice(0, temp.match("<!--head-end").index);
				var opis = temp.slice(temp.match("<!--head-end").index, temp.match("<!--opis-end").index);
				var lokacja = temp.slice(temp.match("<!--opis-end").index, temp.match("<!--loka-end").index);
				var szukanie = temp.slice(temp.match("<!--loka-end").index, temp.match("<!--srch-end").index);
				var trasa = temp.slice(temp.match("<!--srch-end").index, temp.match("<!--trak-end").index);
				var reszta = temp.slice(temp.match("<!--trak-end").index);
				
				var contentDiv = document.createElement('div');
				//contentDiv.innerHTML = temp;
				contentDiv.id = marker.id;
				//contentDiv.style.marginRight = "10px";
				var fullDiv = contentDiv.cloneNode(true);
				fullDiv.innerHTML = head + reszta + lokacja; 
				/* opis pełny */
				var maxopts = {
					maxContent: fullDiv,
					maxTitle: marker.item.name
				}
				
				/* zakładki dymka */
				contentDiv.className = "gpopup";
				var descDiv = contentDiv.cloneNode(true);
				descDiv.innerHTML = head + opis;
				var locDiv = contentDiv.cloneNode(true);
				locDiv.innerHTML = head + lokacja;
				var srchDiv = contentDiv.cloneNode(true);
				srchDiv.innerHTML = szukanie;
				var trakDiv = contentDiv.cloneNode(true);
				trakDiv.innerHTML = trasa;
				/* Wrzucamy fragmenty w divy i wyświetlamy */
				var gtabs = [
					new GInfoWindowTab("Opis", descDiv), 
					new GInfoWindowTab("Lokalizacja", locDiv),
					new GInfoWindowTab("Szukaj", srchDiv),
					new GInfoWindowTab("Trasa", trakDiv)];
				if (typeof(marker.getLatLng) != 'function') {
					latlng = new GLatLng(marker.item.posn[0], marker.item.posn[1]);
				} else {
					latlng = marker.getLatLng();
				}
				map.openInfoWindowTabs(latlng, gtabs, maxopts);
			}
		});
	}
}

function rssubmit(form) {
	var params = Form.serialize(form);
	var link = form.link.value;
	new Ajax.Request(link, {
		asynchronous:true, 
		evalScripts:false,
		method: 'post',
		onSuccess:function(response) {
			if (response.status == 200) {
				//var list = response.headerJSON;
				var list = response.responseText;
				list = list.evalJSON();
				//$('rsresults').innerHTML = ''; 
				if (list.count == 0) { 
					alert("Brak Wyników!");
				} else {
					//$('rsresults').innerHTML = response.responseText; 
					allcats = Array();
					var cats = Object.values(list.cats);
					cats._each(function(scategory){
						if (typeof(scategory)=='object') {
							if (typeof(hideCat)=='function') hideCat(scategory.id);
							allcats[scategory.id] = scategory;
						}
					});
					redrawCats();
					rsend();
				}
			}
		},
		parameters:params}); 
}

var rsstarted = null;
//var rscursor = null;
//var rsposition = null;

function rsstart(text) {
	endall();
	
	if (rsstarted == null) {
		alert(text);
		rsstarted = GEvent.addListener(map, 'click', function(junk, latlng){
			$('lat').value = latlng.y;
			$('lng').value = latlng.x;
			Element.show($('rswin'));
			$('map').appendChild($('rswin'));
			new Draggable('rswin');
		});
		//cursor = getCursor();
		//rscursor = GEvent.addListener(map, 'mousemove', function(e){getMousePosition(e)});
	} else {
		rsend();
	}
}

function rsend() {
	GEvent.removeListener(rsstarted);
	rsstarted = null;
	//GEvent.removeListener(rscursor);
	//rscursor = null;
	Element.hide($('rswin'));
}

//Returns mouse position
function getMousePosition(e) {
    //e = e ? e : window.event;
    var position = {
        'x' : e.y,
        'y' : e.x
    }
    //rsposition = position;
    return position;
}

var linkman;

function linker(text,text2,base){
	alert(text);
	endall();
	linkman = GEvent.addListener(map, 'click', function(junk, latlng){
		var z = map.getZoom();
		var x = String(latlng.y).replace('.','&dot;');
		var y = String(latlng.x).replace('.','&dot;');
		x = x.replace('-','&shy;');
		y = y.replace('-','&shy;');
		var link = "http://"+base+"/index.php/maplink-"+x+"-"+y+"-"+z+".html";
		map.openInfoWindowHtml(latlng,text2+"<br/><input class='ginput' value='"+link+"'/>");
		GEvent.removeListener(linkman);
		linkman = null;
	});
}

/*
 * Zakańcza wszelkie nasłuchujące demony
 */
function endall() {
	if (rsstarted && rsstarted != null) {
		GEvent.removeListener(rsstarted);
		rsstarted = null;
		Element.hide($('rswin'));
	}
	if (linkman && linkman != null) {
		GEvent.removeListener(linkman);
		linkman = null;
	}
	if (routeman && routeman != null) {
		GEvent.removeListener(routeman);
		routeman = null;
		Element.hide($('plwin'));
	}
}
