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

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);
		}
	});
}

function resetCats() {
	var to_hide = new Array();
	allcats._each( function(cat) {
		if (typeof (cat) == 'object') {
			to_hide.Push(cat.id);
		}
	});
	to_hide._each( function(cat) {
		hideCat(cat);
	});
	allcats = Array();
	map.clearOverlays();
}

/*
 * 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, junk) {
		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 = addListener( 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() {
	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 = addListener( function(junk, latlng) {
		if (typeof (latlng) == 'object') {
			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 + "'/>");
			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'));
	}
}

var PDir;

function plotBetween(url) {
	PDir = new GDirections(map);
	var wpoints = Array();
	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;
						wpoints = list.plot;
					}
				});
				redrawCats();
				PDir.loadFromWaypoints(wpoints, {
					getPolyline :true
				});
			}
		},
		parameters :'&rand=' + rand(1000)
	});
}

var listeners = Array();

function addListener(listener) {
	listeners.push(listener);
	return listeners.length - 1;
}

function removeListener(listener) {
	listeners.splice(listener, 1);
}

function runListeners(item, point) {
	if (typeof(item) == 'object' ||  typeof(point) == 'object')
	listeners._each( function(func) {
		func(item, point);
	});
}
