var map;
var temOverlay;
var szsNum=0; // megjegyzi melyik színsémát választotta. Alapértelmezett 0.
var aktMezonev=''; //megjegyzi, melyik mezőről készült a tematikus térkép.
function initMap() {
	var maptab = centertabs.findById('gmap');

  map = new GMap2(maptab.body.dom); 

    CustomGetTileUrl=function(a,b){
  			var domnum = (a.x+a.y)%5+1;
       	var subdomname = "hmap"+domnum;
        if (((b==7) && (a.x<=72) && (a.x>=69) && (a.y<=46) && (a.y>=43)) || 
            ((b==8) && (a.x<=145) && (a.x>=138) && (a.y<=92) && (a.y>=87)) || 
            ((b==9) && (a.x<=291) && (a.x>=276) && (a.y<=185) && (a.y>=174)) || 
            ((b==10) && (a.x<=583) && (a.x>=552) && (a.y<=371) && (a.y>=349)) || 
            ((b==11) && (a.x<=1166) && (a.x>=1104) && (a.y<=742) && (a.y>=699)) || 
            ((b==12) && (a.x<=2333) && (a.x>=2208) && (a.y<=1485) && (a.y>=1398)) || 
            ((b==13) && (a.x<=4666) && (a.x>=4413) && (a.y<=2970) && (a.y>=2797)) || 
            ((b==14) && (a.x<=9332) && (a.x>=8833) && (a.y<=5940) && (a.y>=5594)) || 
            ((b==15) && (a.x<=18665) && (a.x>=17667) && (a.y<=11881) && (a.y>=11189)) || 
            ((b==16) && (a.x<=37330) && (a.x>=35333) && (a.y<=23762) && (a.y>=22378)))
        {
            if (b<10)
                return "http://"+subdomname+".hidadatok.hu/0"+b+"/MOMAPX_"+b+"_"+a.x+"_"+a.y+".png";
            else if (b<13)
                return "http://"+subdomname+".hidadatok.hu/"+b+"/MOMAPX_"+b+"_"+a.x+"_"+a.y+".png";
            else {
                d= a.x;
                d += '';
                while (d.length<6) {
                    d="0"+d;
                }
//                url = "http://www.kenyi.hu/gmap/"+b+"/"+d+"/MOMAPX_"+b+"_"+a.x+"_"+a.y+".png"
								var url = "http://"+subdomname+".hidadatok.hu/"+b+"/"+d+"/MOMAPX_"+b+"_"+a.x+"_"+a.y+".png";
                //alert(url);
                return url;
            }
        } else {
//          return "http://www.kenyi.hu/gmap/blank.png";
					return "http://"+subdomname+".hidadatok.hu/blank.png";
        }
      }
      
			var llSW = new GLatLng(45.72, 16.083);
			var llNE = new GLatLng(48.5833, 23,4333);
			var llbMO = new GLatLngBounds(llSW, llNE);

      var copyright = new GCopyright(1, llbMO,
          6, ' Adatok: &copy; HM Térképészeti Kht., 2008.');

      var copyrightCollection = new GCopyrightCollection('Feldolgoz&aacute;s: <A HREF="http://www.cartosoft.hu" STYLE="cursor: hand; color: #7777CC; text-decoration:underline"> Cartosoft</A>');
      copyrightCollection.addCopyright(copyright);
      

      var tilelayers = [new GTileLayer(copyrightCollection,7,16)];
      tilelayers[0].getTileUrl = CustomGetTileUrl;
      
      var custommap = new GMapType(tilelayers, G_SATELLITE_MAP.getProjection(), "MAPX");
      map.addMapType(custommap);
      //map.addControl(new GLargeMapControl());
			//map.addControl(new GSmallZoomControl());
			map.addControl(new SelectFromMapControl());
      map.addControl(new CSZoomInControl());
      map.addControl(new CSZoomOutControl());
      map.addControl(new GScaleControl());
      map.enableScrollWheelZoom();
			map.enableContinuousZoom();
			var z = map.getBoundsZoomLevel(llbMO);
      map.setCenter(llbMO.getCenter(), z, custommap);
			
			maptab.on('bodyresize', function(){
				map.checkResize();
			});
}

//Tematikus terkep

function getMapPanel() {
	var bdef = getCenteredButton('Tematikus térkép definiálása', 210, 'btntmapdef', showTMapDefWin);
	var bdel = getCenteredButton('Tematikus térkép kikapcsolása', 210, 'btntmapdel', removeOverlay);
	var bszin = getCenteredButton('Színséma kiválasztása', 210, 'btntmapdef', showSzinsemaWin);
		
	return new Ext.Panel({
		title : 'Tematikus térképek',
		id : 'mapmenu',
		border : false,
		autoScroll: true,
		iconCls : 'temmap',
	//	layout:'border',
	  items : [
			getTMapTree(),
			bdef, bdel,bszin,
			getJKPanel()]
	})
}

function getTMapTree(){
	var Tree = Ext.tree;
	var temMapTree = new Tree.TreePanel({
				id: 'temmaptree',
				autoScroll : true,
				border : false,				
				region : 'center',
				rootVisible : false,
				containerScroll : true,		
				height :120,	
				loader : new Tree.TreeLoader({
							dataUrl : 'phpk/fixtree.php'
						})
	});
	var temMapTreeRoot = new Tree.AsyncTreeNode({
				text : 'Fix tablók',
				draggable : false,
				id : 'temmaptreeroot'
	});		
	temMapTree.setRootNode(temMapTreeRoot);

	temMapTree.on("dblclick", function(node) {
		 if (node.leaf) {
		 	if (node.id != "HFANYTS") {
				var valasz = hezJog('func', 5, 'csakreg');
				if (valasz) {
					addTemOverlayMinosites(node.id);
					var maptab = centertabs.findById('gmap');
					centertabs.setActiveTab(maptab);

				}
			}
			else {
				addTemOverlayMinosites(node.id);
				var maptab = centertabs.findById('gmap');
				centertabs.setActiveTab(maptab);
			}
		}
	});

	temMapTreeRoot.expand(false, false);
	return temMapTree;
}

function getTMapDef() {
	var btn = new Ext.Button({
		text : 'Tematikus térkép definiálása',
		minWidth : 200,
		iconCls : 'btntmapdef',
		handler : function(){		
		    var valasz = hezJog('func',5,'csakreg');
			if(valasz){						
				showTMapDefWin
			}
		}		
	});
	return new Ext.Panel({
		border : false,
		buttonAlign : 'center',
		buttons: [btn]
	});
}
function showSzinsemaWin(){
	var btnCancel = new Ext.Button({
		text : 'Mégsem',
		minWidth : 80,
		iconCls : 'cancel',
		handler : function() {
			winszin.hide();
			winszin.destroy();
		}
	});
	
    var szinekDataStore = [
        ['Eredeti',0],
        ['Erős színek',1],
		['Halvány pasztell színek',2],
        ['Zöld árnyalatok',5]
    ];
   var store = new Ext.data.SimpleStore({
        fields: [
           {name: 'SZINEK'},
           {name: 'ID', type: 'int'}
        ]
    });
	store.loadData(szinekDataStore,true);

   var szinTabla = new Ext.grid.GridPanel({
        store: store,
        columns: [
            {id:'szinek', width: 150, dataIndex: 'SZINEK'},
            {header: "ID", width: 0, hidden:true, dataIndex: 'ID'}
        ],
		enableColumnHide: true,
		border:false,
        autoExpandColumn: 'szinek',
		scrollable:false,
		closable: true,
        height:260,
        width:200
    });
	szinTabla.addListener({	
	'celldblclick':{
		fn: function(szinTabla, rowIndex, columnIndex, event){
			var record = szinTabla.getStore().getAt(rowIndex);
			var fieldName = szinTabla.getColumnModel().getDataIndex(1);
			szsNum = record.get(fieldName);
			addTemOverlayMinosites('nincs');
		}
		,scope:this
	 }
	 });

	var winszin = new Ext.Window({
		title : 'Színsémák',
		height: 300,
		width: 220,
		modal: true,
		resizable : false,
		layout : 'fit',
		items: [szinTabla],
		buttonAlign: 'center',
		buttons: [btnCancel]
	});
	winszin.show();
}

function showTMapDefWin(){
	var valasz = hezJog('func',5,'csakreg');
	if(valasz){	
		var mapfieldcb = getTMapcombo();
		var p = new Ext.Panel({
			layout: 'form',
			defaults: {
				width: 350,
				anchor: '100%'
			},
			bodyStyle: 'padding: 15px 5px 5px 5px;',
			baseCls: 'x-plain',
			labelWidth: 65,
			defaultType: 'textfield',
			items: [mapfieldcb]
		});

		var btnOK = new Ext.Button({
			text : 'Rendben',
			minWidth : 120,
			iconCls : 'ok',
			handler : function() {
				addTemOverlayMinosites(mapfieldcb.getValue());
				closeWin();
				var maptab = centertabs.findById('gmap');
				centertabs.setActiveTab(maptab);
			}
		});
	  var btnCancel = new Ext.Button({
			text : 'Mégsem',
			minWidth : 120,
			iconCls : 'cancel',
			handler : function() {
				closeWin();
			}
		});
	
		var win = new Ext.Window({
			title : 'Tematikus térkép készítése',
			height: 120,
			width: 500,
			iconCls : 'deftmap',
			modal: true,
			resizable : false,
			layout : 'fit',
			items: [p],
			buttonAlign: 'right',
			buttons: [btnCancel, btnOK]
		});
		win.show();
		
		function closeWin() {
				win.hide();
				win.destroy();
		}
	}

	function getTMapcombo() {
		var cb = new Ext.form.ComboBox({
	                        fieldLabel: 'Adatmező',
	                        hiddenName:'tmapfield',
							allowBlank : false,
	                        store: new Ext.data.JsonStore({
								url: 'phpk/tab/kertabdefcb.php',
								params : {t:'r'}, 
								root: 'r',
								id : 'kod',
								fields: ['kod', 'leir']
	                        }),
	                        valueField:'kod',
	                        displayField:'leir',
	                        typeAhead: true,
	                        mode: 'local',
	                        triggerAction: 'all',
	                        emptyText:'A tematikus térkép generálásához használandó mező...',
	                        selectOnFocus:true,
							width:90,
							listeners: {
								specialkey: function(f, e){
									if (e.getKey() == e.ESCAPE || e.getKey() == e.ESCAPE) {
										closeWin();								
									}
								},
								specialkey: function(f, e){
									if (e.getKey() == e.RETURN || e.getKey() == e.ENTER) {
										addTemOverlayMinosites(cb.getValue());		
										closeWin();													
									}
								}
							}
	                    });
		cb.store.load({params:{t:'r'}});
		return cb;
	}

}


/*
function getTMap1Button(caption, fieldname) {
	var btn = new Ext.Button({
		text : caption,
		minWidth : 200,
		handler : function () {
			addTemOverlayMinosites(fieldname);
		}
	});
	return new Ext.Panel({
		border : false,
		buttonAlign : 'center',
		buttons: [btn]
	});
}
*/
function getJKPanel() {
	var btn = new Ext.Button({
		text : 'Tematikus réteg kikapcsolása',
		minWidth : 200,
		iconCls : 'btntmapdel',
		handler : removeOverlay
	});
		
	return new Ext.Panel({
		border : false,
		autoHeight : true,
		bodyStyle:"padding:0px 0px 0px 15px",
		id : 'jkpanel',
		region : 'north'/*,
		buttonAlign : 'center',
		buttons: [btn]*/
	});
}

function removeOverlay() {
  if (GBrowserIsCompatible()) {
		if (temOverlay != null) {
			map.removeOverlay(temOverlay);
			temOverlay = null;
		}
	}
	var p = Ext.getCmp('jkpanel');
	var m = Ext.getCmp('mapmenu');
	if (p != null) {
		p.body.update('');
		m.doLayout();
	}
}

function addTemOverlayMinosites(mezonev) {	
  removeOverlay();
  if(mezonev != 'nincs')
  	aktMezonev = mezonev;

	if (GBrowserIsCompatible()) {
		 
		var myCopyright = new GCopyrightCollection("c ");
		myCopyright.addCopyright(new GCopyright(1, new GLatLngBounds(new GLatLng(-90,-180), new GLatLng(90,180)), 0,'KKK'));
	
		var tilelayer = new GTileLayer(myCopyright);
		tilelayer.getTileUrl = function(tile,zoom) {
			var most = new Date();
      var ts = most.getTime();
			var url = "phpk/map/tilemin.php?ma="+zoom+"&x="+tile.x+"&y="+tile.y+"&fn="+aktMezonev+"&ts="+ts+"&szinlista="+szsNum;
		
			return url;
		};
		
		tilelayer.isPng = function() { return true;};
		tilelayer.getOpacity = function() { return 1.0; };
		
		temOverlay = new GTileLayerOverlay(tilelayer);       
 
		map.addOverlay(temOverlay);
		
		var p = Ext.getCmp('jkpanel');
		if (p != null) {
			//p.body.update('<DIV style="height: 100%; overflow:auto"><IMG src="phpk/map/legend.php?fn=' + mezonev + '" alt="Jelkulcs betöltése folyamatban..."/></DIV>');
			p.body.update('<IMG src="phpk/map/legend.php?fn=' + aktMezonev + '&szinlista='+szsNum+'" alt="Jelkulcs betöltése folyamatban..."/>');
    }		
  }
}

//custom map controls

var controlsize = 32;

function SelectFromMapControl() {
}

SelectFromMapControl.prototype = new GControl();

SelectFromMapControl.prototype.initialize = function(map) {
  var container = document.createElement("div");

  var zoomInDiv = document.createElement("div");
  this.setButtonStyle_(zoomInDiv);
  zoomInDiv.id = "map";
	zoomInDiv.title = "Hidak kiválasztása az aktuális nézetről";
	
  container.appendChild(zoomInDiv);
  zoomInDiv.appendChild(document.createTextNode(""));
  GEvent.addDomListener(zoomInDiv, "click", function() {
    //map.zoomIn();
		clickMapBtn();
  });

  map.getContainer().appendChild(container);
  return container;
}

SelectFromMapControl.prototype.getDefaultPosition = function() {
  return new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(7, 7));
}

SelectFromMapControl.prototype.setButtonStyle_ = function(button) {
  //button.style.textDecoration = "underline";
 // button.style.color = "#0000cc";
 // button.style.backgroundColor = "white";
	button.style.backgroundImage = "url(css/MapCollect32.png)";
	button.style.backgroundRepeat = "no-repeat";
  //button.style.font = "small Arial";
 // button.style.border = "0px solid black";
  //button.style.padding = "0px";
  //button.style.marginBottom = "0px";
 // button.style.textAlign = "center";
  button.style.width = controlsize + "px";
	button.style.height = controlsize + "px";
  button.style.cursor = "pointer";
}

function CSZoomInControl() {
}

CSZoomInControl.prototype = new GControl();

CSZoomInControl.prototype.initialize = function(map) {
  var container = document.createElement("div");

  var zoomInDiv = document.createElement("div");
  this.setButtonStyle_(zoomInDiv);
	zoomInDiv.title = "Nagyítás";
	
  container.appendChild(zoomInDiv);
  zoomInDiv.appendChild(document.createTextNode(""));
  GEvent.addDomListener(zoomInDiv, "click", function() {
    map.zoomIn();
  });

  map.getContainer().appendChild(container);
  return container;
}

CSZoomInControl.prototype.getDefaultPosition = function() {
  return new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(45, 7));
}

CSZoomInControl.prototype.setButtonStyle_ = function(button) {
  button.style.backgroundImage = "url(css/MapZoomIn32.png)";
	button.style.backgroundRepeat = "no-repeat";
  button.style.width = controlsize + "px";
	button.style.height = controlsize + "px";
  button.style.cursor = "pointer";
}


function CSZoomOutControl() {
}

CSZoomOutControl.prototype = new GControl();

CSZoomOutControl.prototype.initialize = function(map) {
  var container = document.createElement("div");

  var zoomInDiv = document.createElement("div");
  this.setButtonStyle_(zoomInDiv);
	zoomInDiv.title = "Kicsinyítés";
	
  container.appendChild(zoomInDiv);
  zoomInDiv.appendChild(document.createTextNode(""));
  GEvent.addDomListener(zoomInDiv, "click", function() {
    map.zoomOut();
  });

  map.getContainer().appendChild(container);
  return container;
}

CSZoomOutControl.prototype.getDefaultPosition = function() {
  return new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(83, 7));
}

CSZoomOutControl.prototype.setButtonStyle_ = function(button) {
  button.style.backgroundImage = "url(css/MapZoomOut32.png)";
	button.style.backgroundRepeat = "no-repeat";
  button.style.width = controlsize + "px";
	button.style.height = controlsize + "px";
  button.style.cursor = "pointer";
}

