/**
 * @projectDescription TÉKA térképi inicializáló funkciók 
 * @version 1.0
 * @author BERÉNYI Attila 
 */

//useful for debug
var map;

//to support onresize event
var panel;

//to be able to hndle new LVs
var userLayer;

//to be able to handle not clusterized LVs
var tempLVLayer;

//to be able to display search results with different style
var LVSearchResultLayer;

//container
var LVLayers;

//to be able to turn off and on the navigation control
var navigationControl;

//measure distance
var drawLine;

//measure area;
var drawPolygon;

//draw polygon
var drawPolygonControl;

//to be able to deactivate controls
var searchLVControl;
var addLVControl;
var drawOrderBoxControl;

//print related stuff
var printPropertiesWindow;

//WMS
var insertWMSWindow;

//highlight google geocoder search results
var geocodeSearchResultHighlighted = false;
var geocodeSearchResultHighlightedLayer;

//EOV
Proj4js.defs["EPSG:23700"] = "+proj=somerc +lat_0=47.14439372222222 +lon_0=19.04857177777778 +x_0=650000 +y_0=200000 +ellps=GRS67 +units=m +no_defs";

//permalink button
var permalink;

//language
if ($_GET('currentLanguage') === undefined)
{
    var currentLanguage = (window.location.pathname.split("/")[1] == "hu") ? "hu" : "en";
}
else
{
    var currentLanguage = $_GET('currentLanguage');
}

/*
 * PHP like $_GET (http://www.onlineaspect.com/2009/06/10/reading-get-variables-with-javascript/)
 */
function $_GET(q,s)
{
    s = s ? s : window.location.search;
    var re = new RegExp("&" + q + "(?:=([^&]*))?(?=&|$)","i");
    return (s=s.replace(/^\?/,'&').match(re)) ? (typeof s[1] == 'undefined' ? '' : decodeURIComponent(s[1])) : undefined;
} 

/**
 * AJAX support
 * @param {String} url Honnan jön az info.
 * @param {String} method GET/POST.
 * @param {String} params Paraméterek (csak POST).
 * @param {Boolean} async true/false.
 * @param {String} responseType XML/text.
 * @return {Object} response Az eredmény.
 */
function AJAXRequest(url, method, params, async, responseType)
{
	//create a xmlhttp object for cross browser support
	if (window.XMLHttpRequest)
	{
	    // code for IE7+, Firefox, Chrome, Opera, Safari
	    xmlhttp = new XMLHttpRequest();
	}
	else 
	{
	    // code for IE6, IE5
	    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
	}
	
	xmlhttp.open(method, url, async);
	
	if (method == "POST") 
	{
	    xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	}
	xmlhttp.send(params);
	
	//return the result in the specified format
	if (responseType == 'XML')
	{
	    var response = xmlhttp.responseXML;
	}
	else
	{
	    var response = xmlhttp.responseText;
	}
	
	return response;
}

/*
 * Locale support
 * @param {String} language Current language
 * @param {Integer} id Number of the locale
 * @return {String} Localized string
 */
function getLocalizedStrings(language)
{
	//query locale
	var localizedStringRequest = JSON.decode
	(
	    AJAXRequest
	    (
		SQLParser,
		"POST",
		"query=queryLocales&language=" + language,
		false,
		"JSON"
	    )
	);
	
	if (localizedStringRequest.success) return localizedStringRequest.localizedStringsArray;
}

var localizedStringsArray = getLocalizedStrings(currentLanguage);

/*
 * Global init function
 * @param {integer} env Environment variable
 */
function init(env)
{
    Ext.onReady(function()
    {
	//init tooltips
	Ext.QuickTips.init();
	
	/*
	* map related stuff
	*/
	OpenLayers.IMAGE_RELOAD_ATTEMPTS = 1;
	OpenLayers.Util.onImageLoadErrorColor = "transparent"; 
	
	navigationControl = new OpenLayers.Control.Navigation
	({
	    zoomWheelEnabled: false
	});
	
	permalink = new OpenLayers.Control.Permalink('hiddenpermalink', domainName + '/map/bongesz.html');
	
	map = new OpenLayers.Map({
	    projection: new OpenLayers.Projection('EPSG:900913'),
	    resolutions: [2445.98490513, 1222.99245256, 611.496226281, 305.748113141, 152.87405657, 76.4370282852, 38.2185141426, 19.1092570713, 9.55462853565, 4.77731426782, 2.38865713391, 1.19432856696, 0.597164283478, 0.298582141739],
	    units: 'm',
	    controls: 
	    [
		navigationControl,
		permalink
	    ],
	    maxExtent: new OpenLayers.Bounds(1533500.85621, 5446915.9969, 4038189.39906, 6699260.26832),
	    restrictedExtent: new OpenLayers.Bounds(1591724.80, 5469621.25, 3030211.69, 6352432.22)
	});
	
	var ures = new OpenLayers.Layer("Üres háttér", {
	    isBaseLayer: true
	});
	
	map.addLayer(ures);
	
	var gmap = new OpenLayers.Layer.Google
	(
	    "Google Streets",
	    {
		numZoomLevels: 20,
		sphericalMercator: true
	    }
	);
	
	var gphy = new OpenLayers.Layer.Google
	(
	    "Google Physical",
	    {
		type: google.maps.MapTypeId.TERRAIN,
		sphericalMercator: true
	    }
	);
	
	var ghyb = new OpenLayers.Layer.Google
	(
	    "Google Hybrid",
	    {
		type: google.maps.MapTypeId.HYBRID,
		numZoomLevels: 20,
		sphericalMercator: true
	    }
	);
	
	var gsat = new OpenLayers.Layer.Google
	(
	    "Google Satellite",
	    {
		type: google.maps.MapTypeId.SATELLITE,
		numZoomLevels: 22,
		sphericalMercator: true
	    }
	);
	
	map.addLayers([gmap, gphy, ghyb, gsat]);
	
	var osm = new OpenLayers.Layer.OSM();
	
	map.addLayer(osm);
	
	/*
	 * WMS
	 */
	var EKF = new OpenLayers.Layer.WMS
	(
	    'Első katonai felmérés (1780-1784)', 
	    tileCacheService, 
	    {
		layers: "EKF_EOV",
		format: 'image/png'
	    },
	    {
		isBaseLayer: false,
		visibility: false,
		displayInLayerSwitcher: true
	    }
	);
	
	var MKF = new OpenLayers.Layer.WMS
	(
	    'Második katonai felmérés (1806-1869)',
	    tileCacheService,
	    {
		layers: "MKF_EOV",
		format: 'image/png'
	    },
	    {
		isBaseLayer: false,
		visibility: false,
		displayInLayerSwitcher: true
	    }
	);
	
	var HKF = new OpenLayers.Layer.WMS
	(
	    'Harmadik katonai felmérés (1869-1884)',
	    tileCacheService,
	    {
		layers: "HKF_EOV",
		format: 'image/png'
	    },
	    {
		isBaseLayer: false,
		visibility: false,
		displayInLayerSwitcher: true
	    }
	);
	var NKF = new OpenLayers.Layer.WMS
	(
	    'Negyedik katonai felmérés (1896-1914)',
	    tileCacheService,
	    {
		layers: "NKF_EOV",
		format: 'image/png'
	    },
	    {
		isBaseLayer: false,
		visibility: false,
		displayInLayerSwitcher: true
	    }
	);
	
	var gyor_megye = new OpenLayers.Layer.WMS
	(
	    'Győr megyei archív kataszteri térkép',
	    tileCacheService,
	    {
		layers: "gyor_megye",
		format: 'image/png'
	    },
	    {
		isBaseLayer: false,
		visibility: false,
		displayInLayerSwitcher: true
	    }
	);
	
	var veszprem_megye = new OpenLayers.Layer.WMS
	(
	    'Veszprém megyei archív kataszteri térkép',
	    tileCacheService,
	    {
		layers: "veszprem_megye",
		format: 'image/png'
	    },
	    {
		isBaseLayer: false,
		visibility: false,
		displayInLayerSwitcher: true
	    }
	);
	
	var mao_t_100e = new OpenLayers.Layer.WMS
	(
	    'Topográfiai térkép 1:100 000',
	    tileCacheService,
	    {
		layers: "Mao_t_100e",
		format: 'image/png'
	    },
	    {
		buffer: 0,
		isBaseLayer: false,
		visibility: false,
		displayInLayerSwitcher: true
	    }
	);
	
	var mao_t_10e = new OpenLayers.Layer.WMS
	(
	    'Topográfiai térkép 1:10 000',
	    tileCacheService,
	    {
		layers: "Mao_t_10e",
		format: 'image/png'
	    },
	    {
		buffer: 0,
		isBaseLayer: false,
		visibility: true,
		displayInLayerSwitcher: true
	    }
	);
	
	var orto2000 = new OpenLayers.Layer.WMS
	(
	    'Ortofotó 2000',
	    tileCacheService,
	    {
		layers: "orto2000",
		format: 'image/png'
	    },
	    {
		buffer: 0,
		isBaseLayer: false,
		visibility: false,
		displayInLayerSwitcher: true
	    }
	);
	
	map.addLayers([EKF, MKF, HKF, NKF, gyor_megye, veszprem_megye, mao_t_10e, mao_t_100e, orto2000]);
	
	/*
	 * WMS (mapserver)
	 */
	telepules = new OpenLayers.Layer.WMS
	(
	    'Közigazgatási határok',
	    mapserverURL, 
	    {
		layers: 'telepules',
		format: 'image/png',
		transparent: true
	    },
	    {
		buffer: 0,
		singleTile: true,
		isBaseLayer: false,
		visibility: false
	    }
	);
	
	tajertekek = new OpenLayers.Layer.WMS(
	    "Tájértékek",
	    mapserverURL,
	    {
		layers: 'tajertekek',
		format: 'image/png',
		transparent: true
	    },
	    {
		buffer: 0,
		singleTile: true,
		isBaseLayer: false,
		visibility: true
	    }
	);
	
	fomi_pontok = new OpenLayers.Layer.WMS(
	    'FÖMI pontok',
	    mapserverURL,
	    {
		layers: "fomi_pontok",
		format: 'image/png',
		transparent: true
	    },
	    {
		buffer: 0,
		isBaseLayer: false,
		visibility: false,
		displayInLayerSwitcher: true
	    }
	);
	
	Natura_2000_SCI_google = new OpenLayers.Layer.WMS
	(
	    "Natura 2000 SCI",
	    mapserverURL,
	    {
		layers: 'Natura_2000_SCI_google',
		format: 'image/png',
		transparent: true
	    },
	    {
		isBaseLayer: false,
		visibility: false
	    }
	);
	
	Natura_2000_SPA_google = new OpenLayers.Layer.WMS
	(
	    "Natura 2000 SPA",
	    mapserverURL,
	    {
		layers: 'Natura_2000_SPA_google',
		format: 'image/png',
		transparent: true
	    },
	    {
		isBaseLayer: false,
		visibility: false
	    }
	);
	
	Nemzeti_Park_google = new OpenLayers.Layer.WMS
	(
	    "Nemzeti Park",
	    mapserverURL,
	    {
		layers: 'Nemzeti_Park_google',
		format: 'image/png',
		transparent: true
	    },
	    {
		isBaseLayer: false,
		visibility: false
	    }
	);
	
	Tajvedelmi_korzet_google = new OpenLayers.Layer.WMS
	(
	    "Tájvédelmi körzet",
	    mapserverURL,
	    {
		layers: 'Tajvedelmi_korzet_google',
		format: 'image/png',
		transparent: true
	    },
	    {
		isBaseLayer: false,
		visibility: false
	    }
	);
	
	termeszetvedelmi_terulet_google = new OpenLayers.Layer.WMS
	(
	    "Természetvédelmi terület",
	    mapserverURL,
	    {
		layers: 'termeszetvedelmi_terulet_google',
		format: 'image/png',
		transparent: true
	    },
	    {
		isBaseLayer: false,
		visibility: false
	    }
	);
	
	map.addLayers([Natura_2000_SCI_google, Natura_2000_SPA_google, Nemzeti_Park_google, Tajvedelmi_korzet_google, termeszetvedelmi_terulet_google, telepules, fomi_pontok, tajertekek]);
	
	var infoControl = new OpenLayers.Control.WMSGetFeatureInfo
	({
	    url: mapserverURL,
	    infoFormat: 'application/vnd.ogc.gml',
	    maxFeatures: 1,
	    eventListeners: 
	    {
		getfeatureinfo: function(event)
		{
		    //debug
		    //console.log(event);
		
		    //init
		    var contentArray = [];
		
		    //loop through the features that contain object at the given coordinate
		    for (var i = 0; i < event.features.length; i++)
		    {
			//derive the layer name
			var layerName = event.features[i].type;
			
			//inspect the visibility status of the particular layer 
			if (window[layerName].visibility == true)
			{
			    //debug
			    //console.log(layerName);
			
			    if (layerName.indexOf('Natura_2000') >= 0)
			    {
				if (event.features[i].attributes.Azonosito)
				{
				    contentArray.push(String(window[layerName].name + ': ' + event.features[i].attributes.Azonosito));
				}
				else 
				{
				    contentArray.push(String(window[layerName].name + ': ' + event.features[i].attributes.AZONOSITO));
				}
			    }
			    else
			    {
				if (layerName.indexOf('tajertek') >= 0)
				{
				    var languagePrefix = (currentLanguage == "hu") ? "/hu" : "";
				    contentArray.push(String('<a href="' + domainName + languagePrefix + '/node/' + event.features[i].attributes.nid + '">' + event.features[i].attributes.teka_megnevezes + '</a>'));
				}
				else if (layerName.indexOf('fomi_pontok') >= 0)
				{
				    contentArray.push(String(event.features[i].attributes.teka_megnevezes));
				}
				else if (layerName.indexOf('telepules') >= 0)
				{
				    contentArray.push(String(window[layerName].name + ': ' + event.features[i].attributes.nev));
				}
				else
				{
				    contentArray.push(String(window[layerName].name + ': ' + event.features[i].attributes.ROVID_NEV));
				}
			    }
			}
		    }
		
		    if (contentArray.length >= 1)
		    {
			for (var j = 0; j < contentArray.length; j++)
			{
			    if (j != contentArray.length - 1)
			    {
				contentArray[j] = contentArray[j] + '<br />';
			    }
			}
			
			var WMSPopup = new GeoExt.Popup
			({
			    title: 'Info',
			    map: map,
			    location: map.getLonLatFromPixel(new OpenLayers.Pixel(event.xy.x, event.xy.y)),
			    width: 200,
			    html: contentArray,
			    maximizable: false,
			    collapsible: false,
			    panIn: false
			});
			
			WMSPopup.show();
		    }
		}
	    }
	});
	
	map.addControl(infoControl);
	infoControl.activate();
	
	//foreign WMS from config.js (will be DEPRECATED in the future)
	map.addLayers(WMSLayers);
	
	/*
	 * WFS
	 */
	 
	//user requested...
	var redStyle = new OpenLayers.StyleMap
	({
	    "default": new OpenLayers.Style
	    ({
		fillColor: "red",
		strokeColor: "red",
		strokeWidth: 1,
		fillOpacity: 0.5,
		pointRadius: 6
	    })
	});
	
	//to display features created by the user
	userLayer = new OpenLayers.Layer.Vector
	(
	    "Felhasználói krumplik",
	    {
		displayInLayerSwitcher: false,
		styleMap: redStyle
	    }
	);
	
	var highlightStyle = new OpenLayers.Style();
	
	var highlightStyleMap = new OpenLayers.StyleMap
	({
	    "default": highlightStyle
	});
	
	var pointRule = new OpenLayers.Rule
	({
	    filter: new OpenLayers.Filter.Comparison
	    ({
		type: OpenLayers.Filter.Comparison.EQUAL_TO,
	        property: "geomType",
	        value: "OpenLayers.Geometry.Point"
	    }),
	    symbolizer:
	    {
		pointRadius: 10, 
		fillOpacity: 0,
		strokeColor: "blue"
	    }
	});
	
	var notPointRule = new OpenLayers.Rule
	({
	    filter: new OpenLayers.Filter.Comparison
	    ({
		type: OpenLayers.Filter.Comparison.NOT_EQUAL_TO,
	        property: "geomType",
	        value: "OpenLayers.Geometry.Point"
	    }),
	    symbolizer:
	    {
		fillOpacity: 0.5,
		fillColor: "red",
		strokeWidth: 2.5,
		strokeColor: "red"
	    }
	});
	
	highlightStyle.addRules([pointRule, notPointRule]);
	
	//to be able to display a few LV
	tempLVLayer = new OpenLayers.Layer.Vector
	(
	    "Átmeneti tájérték réteg",
	    {
		//multi mode
		//strategies: [new OpenLayers.Strategy.Cluster()],
		displayInLayerSwitcher: false,
		styleMap: highlightStyleMap
	    }
	);
	
	LVSearchResultLayer = new OpenLayers.Layer.Vector
	(
	    "Keresési eredmények",
	    {
		displayInLayerSwitcher: false,
		styleMap: highlightStyleMap
	    }
	);
	
	//container
	LVLayers = [userLayer, tempLVLayer, LVSearchResultLayer];
	
	map.addLayers(LVLayers);
	
	//added to map automatically
	pageLayer = new OpenLayers.Layer.Vector
	(
	    "Nyomtatási terület",
	    {
		displayInLayerSwitcher: false,
		visibility: false
	    }
	);
	
	/*
	 * controls
	 */
	var zoomToRectangle = new OpenLayers.Control.ZoomBox();
	map.addControl(zoomToRectangle);
	
	var overviewLayer = new OpenLayers.Layer.Image
	(
	    'overviewLayer',
	    '/map/hungary_overview_small.png',
	    new OpenLayers.Bounds(1757307, 5724534, 2579158, 6247975),
	    new OpenLayers.Size(167, 106),
	    {
		numZoomLevels: 1
		}
	);
	
	var overviewControl = new OpenLayers.Control.OverviewMap
	({
	    mapOptions: 
	    {
		projection: "EPSG:900913",
		units: "m",
		maxExtent: new OpenLayers.Bounds(1757307, 5724534, 2579158, 6247975),
		numZoomLevels: 1
	    },
	    size: new OpenLayers.Size(167, 106),
	    layers:
	    [
		overviewLayer
	    ]
	});
	
	map.addControl(overviewControl);
	
	var mousePosition = new OpenLayers.Control.MousePosition
	({
	    displayProjection: new OpenLayers.Projection("EPSG:23700"),
	    numDigits: 0
	});
	
	map.addControl(mousePosition);
	
	/*
	 * toolbar
	 */
	var toolBarItems = 
	[
	    {
		xtype: "textfield",
		name: "address",
		id: "geocodeTextField",
		tooltip:  localizedStringsArray[21],
		emptyText: localizedStringsArray[13],
		listeners: 
		{
		    specialkey: function(field, e)
		    {
			if (e.getKey() == e.ENTER)
			{
			    geocode(field.getValue());
			}
		    }
		}
	    },
	    "-",
	    {
		xtype: "tbbutton",
		id: "pan",
		cls: 'x-btn-icon',
		tooltip:  localizedStringsArray[22],
		icon: domainName + '/sites/default/files/pan.png',
		enableToggle: true,
		toggleGroup: "permanentControls",
		toggleHandler: function(button, state)
		{
		    if (state)
		    {
			navigationControl.activate();
		    }
		    else
		    {
			navigationControl.deactivate();
		    }
		}
	    },
	    {
		xtype: "tbbutton",
		id: "zoomIn",
		cls: 'x-btn-icon',
		tooltip: localizedStringsArray[23],
		icon: domainName + '/sites/default/files/mapicon_zoomin.png',
		handler: function(button)
		{
		    map.zoomIn();
		}
	    },
	    {
		xtype: "tbbutton",
		id: "zoomOut",
		cls: 'x-btn-icon',
		tooltip: localizedStringsArray[24],
		icon: domainName + '/sites/default/files/mapicon_zoomout.png',
		handler: function(button)
		{
		    map.zoomOut();
		}
	    },
	    {
		xtype: "tbbutton",
		id: "zoomBox",
		cls: 'x-btn-icon',
		tooltip: localizedStringsArray[25],
		icon: domainName + '/sites/default/files/mapicon_zoom_rectangle.png',
		enableToggle: true,
		toggleGroup: "permanentControls",
		toggleHandler: function(button, state)
		{
		    if (state)
		    {
			zoomToRectangle.activate();
		    }
		    else
		    {
			zoomToRectangle.deactivate();
			navigationControl.activate();
		    }
		}
	    },
	    "-",
	    {
		xtype: "button",
		id: "measureDistance",
		cls: 'x-btn-icon',
		tooltip: localizedStringsArray[26],
		icon: domainName + '/sites/default/files/mapicon_measure_distance.png',
		enableToggle: true,
		toggleGroup: "permanentControls",
		toggleHandler: function(button, state)
		{
		    if (state)
		    {
			measureDistance();
		    }
		    else
		    {
			drawLine.deactivate();
			navigationControl.activate();
		    }
		}
	    },
	    {
		xtype: "button",
		id: "measureArea",
		tooltip: localizedStringsArray[27],
		icon: domainName + '/sites/default/files/mapicon_measure_area.png',
		enableToggle: true,
		toggleGroup: "permanentControls",
		toggleHandler: function(button, state)
		{
		    if (state)
		    {
			measureArea();
		    }
		    else
		    {
			drawPolygon.deactivate();
			navigationControl.activate();
		    }
		}
	    },
	    "-",
	    {
	        xtype: "button",
	        id: "displayPrintForm",
	        tooltip: localizedStringsArray[28],
	        icon: domainName + '/sites/default/files/mapicon_print.png',
	        enableToggle: true,
	        toggleHandler: function(button, state)
	        {
		    if (state)
		    {
		        printPropertiesWindow.show();
		        pageLayer.setVisibility(true);
		        fixCSS();
		    }
		    else
		    {
		        printPropertiesWindow.hide();
		        pageLayer.setVisibility(false);
		    }
		}
	    }
	];
	
	
	switch (env)
	{
	    case 0: //bongesz
	    break;
	    case 1: //rögzít
		toolBarItems.push
		(
		    "-",
		    {
			xtype: "button",
			id: "addLVPoint",
			tooltip: localizedStringsArray[31],
			icon: domainName + '/sites/default/files/mapicon_add_point.png',
			enableToggle: true,
			toggleGroup: "permanentControls",
			toggleHandler: function(button, state)
			{
			    if (state)
			    {
				addLV("point");
			    }
			    else
			    {
				addLVControl.deactivate();
				navigationControl.activate();
			    }
			}
		    },
		    {
			xtype: "button", 
			id: "addLVLine",
			tooltip: localizedStringsArray[32],
			icon: domainName + '/sites/default/files/mapicon_add_line.png',
			enableToggle: true,
			toggleGroup: "permanentControls",
			toggleHandler: function(button, state)
			{
			    if (state)
			    {
				addLV("line");
			    }
			    else
			    {
				addLVControl.deactivate();
				navigationControl.activate();
			    }
			}
		    },
		    {
			xtype: "button",
			id: "addLVPolygon",
			tooltip: localizedStringsArray[33],
			icon: domainName + '/sites/default/files/mapicon_add_polygon.png',
			enableToggle: true,
			toggleGroup: "permanentControls",
			toggleHandler: function(button, state)
			{
			    if (state)
			    {
				addLV("polygon");
			    }
			    else
			    {
				addLVControl.deactivate();
				navigationControl.activate();
			    }
			}
		    },
		    "-",
		    {
			xtype: "button",
			id: "clearLVs",
			tooltip: localizedStringsArray[30],
			icon: domainName + '/sites/default/files/mapicon_deleteall.png',
			handler: function(button)
			{
			    clearLVs();
			    document.getElementById('edit-field-wkt-0-value').value = null;
			    document.getElementById('edit-field-wkt-centroid-0-value').value = null;
			    document.getElementById('edit-field-telepules-value').value = null;
			    document.getElementById('edit-field-megye-value').value = null
			}
		    }
		);
	    break;
	    case 2: //keres
		toolBarItems.push
		(
		    "-",
		    {
			xtype: "button",
			id: "searchLVsBox",
			tooltip: localizedStringsArray[29],
			icon: domainName + '/sites/default/files/mapicon_zoom_rectangle.png',
			toggleGroup: "permanentControls",
			enableToggle: true,
			toggleHandler: function(button, state)
			{
			    if (state)
			    {
				searchLV("square");
			    }
			    else
			    {
				searchLVControl.deactivate();
			    }
			}
		    },
		    {
			xtype: "button",
			id: "searchLVsCircle",
			tooltip: localizedStringsArray[29],
			icon: domainName + '/sites/default/files/mapicon_cicrle.png',
			toggleGroup: "permanentControls",
			enableToggle: true,
			toggleHandler: function(button, state)
			{
			    if (state)
			    {
				searchLV("circle");
			    }
			    else
			    {
				searchLVControl.deactivate();
			    }
			}
		    },
		    "-",
		    {
			xtype: "button",
			id: "clearLVs", 
			tooltip: localizedStringsArray[30],
			icon: domainName + '/sites/default/files/mapicon_deleteall.png',
			handler: function(button)
			{
			    clearLVs();
			}
		    }
		);
		
	    break;
	    case 3: //rendel
		orderLVs();
		toolBarItems.push
		({
		    xtype: "button",
		    id: "orderLVsButton",
		    text: "Kijelölés aktív",
		    toggleGroup: "permanentControls",
		    enableToggle: true,
		    pressed: true,
		    toggleHandler: function(button, state)
		    {
			if (state)
			{
			    drawOrderBoxControl.activate();
			}
			else
			{
			    drawOrderBoxControl.deactivate();
			    navigationControl.activate();
			}
		    }
		});
	    break;
	    //TODO: merge with case 1
	    case 4: //szerkeszt
		toolBarItems.push
		(
		    "-",
		    {
			xtype: "button",
			id: "addLVPoint",
			tooltip: localizedStringsArray[31],
			icon: domainName + '/sites/default/files/mapicon_add_point.png',
			enableToggle: true,
			toggleGroup: "permanentControls",
			toggleHandler: function(button, state)
			{
			    if (state)
			    {
				addLV("point");
			    }
			    else
			    {
				addLVControl.deactivate();
				navigationControl.activate();
			    }
			}
		    },
		    {
			xtype: "button", 
			id: "addLVLine",
			tooltip: localizedStringsArray[32],
			icon: domainName + '/sites/default/files/mapicon_add_line.png',
			enableToggle: true,
			toggleGroup: "permanentControls",
			toggleHandler: function(button, state)
			{
			    if (state)
			    {
				addLV("line");
			    }
			    else
			    {
				addLVControl.deactivate();
				navigationControl.activate();
			    }
			}
		    },
		    {
			xtype: "button",
			id: "addLVPolygon",
			tooltip: localizedStringsArray[33],
			icon: domainName + '/sites/default/files/mapicon_add_polygon.png',
			enableToggle: true,
			toggleGroup: "permanentControls",
			toggleHandler: function(button, state)
			{
			    if (state)
			    {
				addLV("polygon");
			    }
			    else
			    {
				addLVControl.deactivate();
				navigationControl.activate();
			    }
			}
		    },
		    "-",
		    {
			xtype: "button",
			id: "clearLVs",
			tooltip: localizedStringsArray[30],
			icon: domainName + '/sites/default/files/mapicon_deleteall.png',
			handler: function(button)
			{
			    clearLVs();
			    document.getElementById('edit-field-wkt-0-value').value = null;
			    document.getElementById('edit-field-wkt-centroid-0-value').value = null;
			    document.getElementById('edit-field-telepules-value').value = null;
			    document.getElementById('edit-field-megye-value').value = null
			}
		    }
		);
	    break;
	};
	
	/*
	 * the big picture
	 */
	var zoom = $_GET('zoom');
	var lon = $_GET('lon');
	var lat = $_GET('lat');
	
	if (!(zoom && lon && lat))
	{
	    lon = 2185355;
	    lat = 5966687;
	    zoom = 1;
	}
	
	var mapPanel = new GeoExt.MapPanel
	({
	    height: 450,
	    width: 600,
	    map: map,
	    prettyStateKeys: true,
	    border: false,
	    center: new OpenLayers.LonLat(lon, lat),
	    zoom: zoom, //1 = google: 7
	    items:
	    [{
		xtype: "gx_zoomslider",
		vertical: true,
		height: 100,
		x: 10,
		y: 20
	    }],
	    tbar: toolBarItems,
	    stateId: "map" //needed only for GeoExt permalink provider and therefore deprecated?
	});
	
	//tooltip for geocode textfield
	Ext.QuickTips.register
	({
	    target: Ext.getCmp('geocodeTextField'),
	    text: localizedStringsArray[21]
	});
	
	layerTreePanel = new Ext.tree.TreePanel
	({
	    width: layerTreePanelWidth,
	    autoHeight: true,
	    autoWidth: true,
	    border: false,
	    root: new GeoExt.tree.LayerContainer
	    ({
		layerStore: mapPanel.layers,
		expanded: true
	    }),
	    rootVisible: false,
	    listeners:
	    {
		click: function(node)
		{
		    layerOpacitySlider.setLayer(node.layer);
		}
	    }
	});
	
	var layerOpacitySlider = new GeoExt.LayerOpacitySlider
	({
	    layer: null,
	    aggressive: true,
	    width: layerOpacitySliderWidth,
	    height: 25,
	    isFormField: false,
	    inverse: true,
	    fieldLabel: "opacity"
	});
	
	panel = new Ext.Panel
	({
	    layout: 'border',
	    border: false,
	    width: 1000, //init, controlled by resizePanel
	    height: 500, //init, controlled by resizePanel
	    renderTo: 'mappanel',
	    autoScroll: true,
	    bodyStyle: 'background-color: white',
	    items:
	    [
		{
		    title: localizedStringsArray[14],
		    region: 'center',
		    layout: 'fit',
		    frame: false,
		    border: true,
		    items:
		    [
			mapPanel
		    ]
		},
		{
		    id: 'layersPanel',
		    title: localizedStringsArray[15],
		    region: 'east',
		    frame: false,
		    border: true,
		    autoScroll: true,
		    width: layerTreePanelWidth,
		    collapsed: true,
		    margins:
		    {
			left: 5
		    },
		    collapsible: true,
		    tbar:
		    [{
		        xtype: "button",
		        id: "displayInsertWMSWindow",
		        text: "WMS",
		        enableToggle: true,
		        toggleHandler: function(button, state)
		        {
			    if (state)
			    {
				insertWMSWindow.show();
				fixCSS();
			    }
			    else
			    {
			    insertWMSWindow.hide();
			    }
			}
		    }],
		    items:
		    [
			{
			    frame: false,
			    border: false,
			    autoWidth: true,
			    height: null,
			    items:
			    [
				layerTreePanel
			    ],
			    autoScroll: true
			},
			{
			    title: localizedStringsArray[16],
			    frame: false,
			    border: false,
			    autoWidth: true,
			    margins:
			    {
				top: 2000
			    },
			    height: 50,
			    items:
			    [
				layerOpacitySlider
			    ]
			}
		    ],
		    toggleTip:
		    {
			text: localizedStringsArray[36]
		    },
		    listeners:
		    {
			"afterrender" : function(c)
			{
			    c.toggleTip.target = c.tools['toggle'];
			    Ext.QuickTips.register(c.toggleTip);
			}
		    }
		}
	    ],
	    toggleTip:
	    {
		text: localizedStringsArray[34]
	    },
	    listeners:
	    {
		"afterrender": function(c)
		{
		    c.toggleTip.target = c.layout.east.collapsedEl.dom.firstChild;
		    Ext.QuickTips.register(c.toggleTip);
		}
	    }
	});
	
	//init
	resizePanel();
	window.onresize = resizePanel;
	
	/*
	 * print related stuff
	 */
	printProvider = new GeoExt.data.PrintProvider
	({
	    method: "POST",
	    capabilities: printCapabilities
	});
	
	printForm = new GeoExt.ux.SimplePrint
	({
	    mapPanel: mapPanel,
	    layer: pageLayer,
	    autoFit: false,
	    printProvider: printProvider,
	    bodyStyle:
	    {
		padding: "5px"
	    },
	    labelWidth: 65,
	    defaults:
	    {
		width: 115
	    },
	    region: "east",
	    border: false,
	    width: 200
	});
	
	printForm.insert
	(
	    0,
	    {
		xtype: "textfield",
		name: "mapTitle",
		fieldLabel: localizedStringsArray[1],
		value: localizedStringsArray[2],
		plugins: new GeoExt.plugins.PrintPageField
		({
		    printPage: printForm.printPage
		})
	    }
	);
	
	printForm.insert
	(
	    1,
	    {
		xtype: "textarea",
		name: "comment",
		fieldLabel: localizedStringsArray[3],
		value: localizedStringsArray[4],
		plugins: new GeoExt.plugins.PrintPageField
		({
		    printPage: printForm.printPage
		})
	    }
	);
	
	map.events.register
	(
	    "moveend",
	    map,
	    function(event)
	    {
		printForm.onMoveend();
	    }
	);
	
	printPropertiesWindow = new Ext.Window
	({
	    title: localizedStringsArray[5],
	    width: 215,
	    height: 250,
	    plain: true,
	    closeAction: "hide",
	    items:
	    [
		printForm
	    ],
	    listeners:
	    {
		'hide': function()
		{
		    var button = Ext.getCmp('displayPrintForm');
		    if (button.pressed = true) button.toggle();
		}
	    }
	});
	
	/*
	 * WMS
	 */
	var insertWMSURLData =
	[
	    [
		'http://webgis.fmt.bme.hu/cgi-bin/howtos',
		'A BME FMT teszt szervere, mapserver 5.6.3'
	    ]/*,
	    [
		'http://terkep.torokbalint.hu/tbalint_allinone_from_sql_wms/request.aspx',
		'Törökbálint Önkormányzata'
	    ]*/
	];
	
	var insertWMSURLStore = new Ext.data.ArrayStore
	({
	    fields:
	    [
		'URL',
		'tooltip'
	    ],
	    data : insertWMSURLData
	});
	
	var insertWMSForm = new Ext.FormPanel
	({
	    labelWidth: 50,
	    frame: true,
	    width: 288,
	    defaults:
	    {
		width: 200 //textfield
	    },
	    items:
	    [
		{
		    xtype: 'textfield',
		    id: 'insertWMSFormName',
		    allowBlank: false,
		    fieldLabel: localizedStringsArray[6],
		    emptyText:  localizedStringsArray[7]
		},
		{
		    xtype: 'combo',
		    fieldLabel: 'URL',
		    store: insertWMSURLStore,
		    emptyText: localizedStringsArray[8],
		    displayField: 'URL',
		    id: 'insertWMSFormURL',
		    allowBlank:false,
		    mode: 'local',
		    typeAhead: true,
		    selectOnFocus:true
		},
		{
		    xtype: 'textfield',
		    fieldLabel: localizedStringsArray[9],
		    id: 'insertWMSFormLayer',
		    allowBlank:false,
		    emptyText: localizedStringsArray[10]
		}
	    ],
	    buttons: 
	    [{
		text: localizedStringsArray[11],
		handler: function(button)
		{
		    insertWMS(Ext.get('insertWMSFormName').getValue(), Ext.get('insertWMSFormURL').getValue(), Ext.get('insertWMSFormLayer').getValue());
		}
	    }]
	});
	
	insertWMSWindow = new Ext.Window
	({
	    title: localizedStringsArray[12],
	    width: 300,
	    height: 155,
	    border: false,
	    items:
	    [
		insertWMSForm
	    ],
	    closeAction: 'hide',
	    listeners:
	    {
		'hide': function()
		{
		    var button = Ext.getCmp('displayInsertWMSWindow');
		    if (button.pressed = true) button.toggle();
		}
	    }
	});
    });
};
