//Base functions
var agt = navigator.userAgent.toLowerCase();
var is_op = (agt.indexOf("opera") != -1);
var is_ie = (agt.indexOf("msie") != -1) && document.all && !is_op;
var is_ie5 = (agt.indexOf("msie 5") != -1) && document.all && !is_op;
var IE = is_ie?true:false

if (!Array.prototype.indexOf){
  Array.prototype.indexOf = function(elt /*, from*/){
    var len = this.length;
    var from = Number(arguments[1]) || 0;
    from = (from < 0)
         ? Math.ceil(from)
         : Math.floor(from);
    if (from < 0)
      from += len;

    for (; from < len; from++){
      if (from in this &&
          this[from] === elt)
        return from;
    }
    return -1;
  }
}

String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
}

MARKERS  = function () {


    var yt;
    var xt;
    var yb;
    var xb;
    MARKERS.prototype.markersId = new Array();
    
    MARKERS.prototype.status = 'none';
    MARKERS.prototype.controlStatus = 0;
    MARKERS.prototype.sMapType = '';
    
    
    var maxx = 0, maxy = 0, minx = 0, miny = 0;
    
    MARKERS.prototype.getMarkers = function (force){
        if(this.controlStatus == 1) return true;
        var bounds = map.getBounds();
         yt = bounds.getNorthEast().y.toFixed(3);
         xt = bounds.getNorthEast().x.toFixed(3);
         yb = bounds.getSouthWest().y.toFixed(3);
         xb = bounds.getSouthWest().x.toFixed(3);         
        //console.log('yt:'  + yt + ' yb:'  + yb + ' xt:'  + xt + ' xb:'  + xb);
        if(xt>maxx || yt>maxy || xb<minx || yb<miny || force > 0){
            var detx = xt - xb; 
            var dety = yt - yb;    
             //console.log('detx:'  + detx + ' dety:'  + dety);
            currentZoom = map.getZoom();
           
            //if(maxx<xt) 
            maxx = (xt*1 + detx).toFixed(3)*1;
            //if(maxy<xt) 
            maxy = (yt*1 + dety).toFixed(3)*1;
            
            //if(mixx>xb) 
            minx = (xb*1 - detx).toFixed(3)*1;
            //if(mixy>yb) 
            miny = (yb*1 - dety).toFixed(3)*1;  
           //console.log('maxy:' + maxy + ' miny:'  + miny + ' maxx:'  + maxx + ' minx:'  + minx     );
            if(currentZoom>16){maxy += 0.01;maxx += 0.01;miny -= 0.01;minx -= 0.01;  } 
            
            getUrl = "ajax/getpoints.php?yt=" + maxy.toFixed(3) + "&xt=" + maxx.toFixed(3) + "&xb=" + minx.toFixed(3) + "&yb=" + miny.toFixed(3) +"&zoom=" +  map.getZoom() +  this.sMapType;
            if(force>1) getUrl += '&nocache=1'
           
        	xmlhttp2 = window.XMLHttpRequest?new XMLHttpRequest(): new ActiveXObject("Microsoft.XMLHTTP");     		
        	//if(this.sMapType == '&stype=midmain') xmlhttp2.onreadystatechange =  this.showMidmain;
            //else 
            xmlhttp2.onreadystatechange =  this.downloadMarkeres;
            xmlhttp2.open("GET", getUrl, true); 		    	
            xmlhttp2.send(null);         
        //    if(debug==1) document.getElementById('debug').innerHTML += '<br><br>Letöltés.. ';
            this.markersId.push(0);
            maputil.mapInfo('<img src="/i/ajax_load1.gif" /> ' + ' Getting places');
            
            //this.status = 'download';
        }//else this.status = 'none';
            
            
    }
    
    MARKERS.prototype.downloadMarkeres = function(){
        if ((xmlhttp2.readyState == 4) && (xmlhttp2.status == 200)) { 	
           marker.processMarkeres(xmlhttp2.responseText); 
           //this.status = 'downloaded';
        }
    }

    MARKERS.prototype.showPointLabel = function (anchor){
        marker.showLabel(anchor.id);
        anchor.style.zIndex=4;        
        return false;
    }
    
    MARKERS.prototype.hidePointLabel = function (anchor){
        anchor.style.zIndex=1;
        document.getElementById("infoLabel").style.display = 'none';
        
        return false;
    }

    MARKERS.prototype.processMarkeres = function(m){
        var mapTray = map.getPane(G_MAP_MARKER_MOUSE_TARGET_PANE);
        var point = m.split("\n"); 
        processPointCount  = point.length ;
        allPoints = '';
        if(processPointCount>2) maputil.mapInfo('<img src="/i/ajax_load1.gif" /> <p>Processing markers: ' + (processPointCount - 1) + ' </p>');
        pointsDrawMode = point[0].split("|")[0];
        try{    
            document.getElementById('mapright').innerHTML;
            if(map.getZoom() < 8) maputil.mapRight();
            else{
                var cityId = (point[0].split("|")[1]) * 1;
                if( document.getElementById('maprightCityId').innerHTML != cityId && cityId>0 ) maputil.mapRight();
            }
        }catch(e){}
       var mwidth = 20;
       var mheight = 27;
       if(map.getZoom() < 7){
            var mwidth = 10;
            var mheight = 13;
       }
       
       if(map.getZoom() < 3){
            var mwidth = 5;
            var mheight = 7;
       }
       
       
        if(IE){
          for(i=1;i<point.length-1;i++){ 
            p = point[i].split("\|");
            if(marker.markersId.indexOf(p[0]+'')==-1){
                marker.markersId.push(p[0]);
               
                allMarkers = new Object();        
                allMarkers.id = p[0];
                allMarkers.lat = p[1];
                allMarkers.lng = p[2];
                allMarkers.label = p[3];
                allMarkers.typ = p[4];                
                allMarkers.status = 0;     
                
                var b=document.createElement('a');
                b.setAttribute('id','marker_' +  p[0]); 
                b.setAttribute('rel', allMarkers.label);
              
                b.setAttribute('href','javascript:void(0)');    
              
                
                b.onmouseover = function () {marker.showPointLabel(this)}
                b.onmouseout = function () {marker.hidePointLabel(this)}
                
                b.onclick = function () {marker.showInfoWindow(parseInt(this.id.substring(7)));return false;}                
                b.oncontextmenu=function(){return false;};
                document.body.appendChild(b);
                b.style.position='absolute';
               
                b.style.zIndex=1;           
               
                markerIcon = 'icons/'+allMarkers.typ+'.png';

                b.style.filter="progid:DXImageTransform.Microsoft.AlphaImageLoader(src='i/"+markerIcon+"', sizingMethod='scale')";
                b.style.cursor="hand";
                
                b.style.height = mheight+'px';
                b.style.width = mwidth+'px';
                
                
                mapTray.appendChild(b); 
                var pos=map.fromLatLngToDivPixel(new GLatLng( allMarkers.lat, allMarkers.lng));
                var x=parseInt(pos.x)- (mwidth/2);
                var y=parseInt(pos.y) - ((mheight)-1); 
                b.style.left = x + 'px';
                b.style.top = y + 'px';
            }
          }
        }else{
            for(i=1;i<point.length-1;i++){        
                  p = point[i].split("\|");
                  var pos=map.fromLatLngToDivPixel(new GLatLng( p[1],  p[2]));
                  var x = parseInt(pos.x) - (mwidth/2);
                  var y = parseInt(pos.y) - ((mheight)-1);                         
                  //style              
                  allPoints += '<a href="javascript:void(0)" class="marker" style="height:'+mheight+'px;width:'+mwidth+'px;';              
                  
                  //allPoints += "background:url('i/"+markerIcon+"');";              
                  allPoints += 'top:'+y+'px;left:'+x+'px;" ';
                  allPoints += 'id="marker_'+ p[0] + '" ';
                  //rel
                  allPoints += 'rel="'+p[3]+'" ';
                  //behavior              
                  allPoints += 'onmouseup="if(posSum == (map.getCenter().x + map.getCenter().y)) marker.showInfoWindow('+p[0]+');return false" ';
                  allPoints += 'onmousedown="posSum = map.getCenter().x + map.getCenter().y" ';            
                  
                  allPoints += 'oncontextmenu="return false" ';
                  allPoints += 'onmouseover="marker.showPointLabel(this)" ';
                  allPoints += 'onmouseout="marker.hidePointLabel(this)"';
                  allPoints += '>'
                  allPoints +=  '<img src="i/icons/'+p[4]+'.png" style="height:'+mheight+'px;width:'+mwidth+'px;" />';
                  allPoints += '</a>';
                  
            }  
            mapTray.innerHTML = allPoints;
        }
        
      if(pointsDrawMode == 0){
        maputil.mapInfo('');       
      }else{
        maputil.mapInfo(pointsDrawMode);        
      }
      
      //ujra rajzoljda a kezdopontot
      if(maputil.startPlaceCor) marker.showMarker(maputil.startPlaceCor);  
      //this.status = 'processed';
      
    }
    

   
    MARKERS.prototype.clearAll = function(){
        //allMarkers = new Array();
        marker.markersId = new Array();
       // map.clearOverlays();        
        var element = map.getPane(G_MAP_MARKER_MOUSE_TARGET_PANE);  
        while (element.firstChild) {
            element.removeChild(element.firstChild);        
        }
        maxx = 0, maxy = 0, minx = 0, miny = 0;        
    }
    
    MARKERS.prototype.clearMarkerPane = function(){
        var element = map.getPane(G_MAP_MARKER_SHADOW_PANE);  
        while (element.firstChild) {
            element.removeChild(element.firstChild);        
        }
         var element = map.getPane(G_MAP_MARKER_PANE);  
        while (element.firstChild) {
            element.removeChild(element.firstChild);        
        }
    }
    
    MARKERS.prototype.showLabel = function (markerObj){              
         try{
            document.getElementById('infoLabel').innerHTML;
            var label = document.getElementById('infoLabel');        
        }catch(e){
            var label = document.createElement('div');
            label.setAttribute('id','infoLabel');             
            label.onclick = function(){marker.hidePointLabelElement()}
            document.body.appendChild(label);            
        }      
        label.style.display='block';        
        var m = document.getElementById(markerObj); 
        var mapPos = this.findPos(document.getElementById('map'));
        var lY = map.getSize().height - (map.getSize().height/2 + map.fromLatLngToDivPixel(map.getCenter()).y - parseInt(m.style.top)) + mapPos[1] - 24;
        var lX = (map.getSize().width - (map.getSize().width/2 + map.fromLatLngToDivPixel(map.getCenter()).x - parseInt(m.style.left))) + mapPos[0] + 18;
        label.style.top = lY  + 'px';
        label.style.left = lX + 'px';    
        label.innerHTML = '<nobr>' +  m.rel + '</nobr>';         
    }
    
    MARKERS.prototype.findPos = function(obj) {        
        if (obj.offsetParent) {
            var curleft = obj.offsetLeft
            var curtop = obj.offsetTop
            while (obj = obj.offsetParent) {                    
                curleft += obj.offsetLeft
                curtop += obj.offsetTop
            }
            return [curleft,curtop];
        }    
    }
    
    MARKERS.prototype.showInfoWindow = function (mId){        
        return popuplayer.loadBlock('pointdetails', 'pid=' + mId);
    }
    
    MARKERS.prototype.showInfo = function(){
        if ((xmlhttp.readyState == 4) && (xmlhttp.status == 200)) { 	          
          var win = document.getElementById('infoWindow');
          if(win.innerHTML.length<5) win.innerHTML = xmlhttp.responseText;                        
          else ef.tmp = xmlhttp.responseText; 
          marker.status = 'infowindowon';          
        }
    }    
}
   
MAPUTILS  = function () {   

    MAPUTILS.prototype.selectedPointId = 0;    
    MAPUTILS.prototype.counter = 0;
    MAPUTILS.prototype.currentLat =  39.0;
    MAPUTILS.prototype.currentLng = -100.0;
    MAPUTILS.prototype.currentZoom = 4;
    MAPUTILS.prototype.currentMap = 0;


    MAPUTILS.prototype.startPlaceCor = 0;
    MAPUTILS.prototype.selectedLat = '';
    MAPUTILS.prototype.selectedLng = '';
    MAPUTILS.prototype.newPlaceBtn = '1';
    MAPUTILS.prototype.forceFilter = 0;
   
    MAPUTILS.prototype.mapTyp = new Array();

    
    
    MAPUTILS.prototype.initMap = function() {
            if (!GBrowserIsCompatible()) { 
                document.getElementById('map').innerHTML = 'Can\'t load map!';
                return false;
            }
        
            if (typeof GMap != "function") { 
                if (this.counter > 10) { 
                    alert('Error!Can\'t init map!'); 
                } else { com.timer = setTimeout(maputil.initmap, 1000); 
            } this.counter++; 
                return false; 
            }
            
  
            var decodeUrl = window.location.hash.substring(1).split('=');
            if(decodeUrl.length>4){
                if(parseInt(decodeUrl[1])) this.currentLat = parseInt(decodeUrl[1]) / 1000000;    
                if(parseInt(decodeUrl[2])) this.currentLng = parseInt(decodeUrl[2]) / 1000000;    
                if(parseInt(decodeUrl[3])) this.currentZoom = parseInt(decodeUrl[3]);
                if(parseInt(decodeUrl[4])>-1) this.currentMap = parseInt(decodeUrl[4]);                
            }
        
           
            map = new GMap2(document.getElementById("map"));
            
        
            //showStreet();            
            this.mapTyp[0] = G_NORMAL_MAP;    
            this.mapTyp[1] = G_SATELLITE_MAP;
            this.mapTyp[2] = G_HYBRID_MAP;
            this.mapTyp[3] = G_PHYSICAL_MAP;
        
            map.setCenter(new GLatLng(this.currentLat, this.currentLng), this.currentZoom, this.mapTyp[this.currentMap]);      
        
            map.enableDoubleClickZoom();
            map.enableContinuousZoom();
            map.enableScrollWheelZoom();
           // map.addControl(new GOverviewMapControl (/*new GSize(200,180)*/));      
            map.addControl(new GLargeMapControl());    //zoom and pan       
            map.addControl(new GMapTypeControl()); //Map/Sat/hybrid
        
        
            //events
            GEvent.addListener(map, "zoomend", function() {  
                marker.clearAll();                
                marker.getMarkers(1);                
                com.setSiteUrl();
                
            });      
            
            
            GEvent.addListener(map, "moveend", function() { 
                marker.getMarkers(0); 
                com.setSiteUrl(); 
            }); 
            
            
            marker.getMarkers(0);
        
    }
    
    MAPUTILS.prototype.mapInfo = function(str) {
        try{
        var obj = document.getElementById('mapinfo2');
        obj.style.display = 'block';
        obj.innerHTML =  str;
        if(str.length<1) obj.style.display = 'none';
        }catch(e){}
       
    }
    
    
    MAPUTILS.prototype.jumpToPoint = function(cor,pointid){                   
                this.jumpTo(cor);                
                this.selectedPointId = pointid;                
                this.counter = 0;
                //this.tryToShowInfoWindow();                
                if(marker.controlStatus == 1) marker.controlMarkers();
                //return popuplayer.loadBlock('pointdetails', 'pid=' + pointid);
		marker.showInfoWindow(pointid);
    }
    
    MAPUTILS.prototype.tryToShowInfoWindow = function(){
        
        com.timer = window.setTimeout(function() {
          try{      
             if(maputil.forceFilter == 0) marker.filterOff();
             document.getElementById('marker_'+this.selectedPointId).innerHTML ;  
console.log(document.getElementById('marker_'+this.selectedPointId).innerHTML );             
          }catch(e){
            if(marker.status != 'infowindow' && maputil.selectedPointId>-10){
              com.timer = window.setTimeout(function() {
                if(maputil.mapStatus  == 'moveend'){
                    map.setZoom(16);  
                    maputil.counter--;                    
                } //console.log('getStatus:' + maputil.mapStatus + marker.status + maputil.selectedPointId);
                maputil.tryToShowInfoWindow();
              }, 500);            
            }       
          }
             
        }, 500);  
    }
    
    MAPUTILS.prototype.jumpTo = function(cor){    
            var cor = cor + '';
            var cors = cor.split(",");
        	map.panTo(new GLatLng(cors[0],cors[1]));   
            if(this.mapStatus == 'moveend') marker.clearAll();
            marker.getMarkers(1);
    }
    
    MAPUTILS.prototype.jumpToAndZoom = function(cor,zoom){
        var cor = cor + '';
        var cors = cor.split(",");
        this.center = zoom;
        map.panTo(new GLatLng(cors[0],cors[1]));
        com.timer = window.setTimeout(function() {                
                 map.setZoom(maputil.center);                
            },1000
        );     
        
    }
    
    MAPUTILS.prototype.whereAmI = function(){
        this.center = map.getCenter();
        popuplayer.loadBlock('getwhereami', 'lat='+ this.center.y + '&lng=' + this.center.x);        
    }

    MAPUTILS.prototype.getStreet = function(address){
        map.clearOverlays();     
        if(marker.controlStatus == 0) marker.controlMarkers();
        //address += ', Hungary'
        geocoder = new GClientGeocoder();
        geocoder.getLatLng(
            address,
            function(point) {
                if (!point) {
                   alert(address + ' address invalid!');
                } else {
                   
                   map.setCenter(point, 17);                      
            
                  var newMarkerPoint = new GMarker(point, {draggable: true});
                  GEvent.addListener(newMarkerPoint, "dragend", function()  {                    
                      var point = newMarkerPoint.getPoint();
                      maputil.selectedLat = point.lat();
                      maputil.selectedLng = point.lng();
                      maputil.newPlace();
                  });
                  map.addOverlay(newMarkerPoint);                          
                }
            }
        );
        return false;   
    }

    MAPUTILS.prototype.newPlace = function(){       
            
            popuplayer.loadBlock('../admin/form_place', 'lat=' + maputil.selectedLat + '&lng=' + maputil.selectedLng);
    }
    
    MAPUTILS.prototype.addNewPlaceHelp = function(){       
        
        try{
        document.getElementById('newPlaceForm').style.display='block'; 
        }catch(e){}
       
        
        var mapTopLeft = map.getCurrentMapType().getProjection().fromLatLngToPixel(map.getBounds().getNorthEast(),map.getZoom());       
        var p = new GPoint( mapTopLeft.x, mapTopLeft.y); 
        //map.getCurrentMapType().getProjection().fromPixelToLatLng(p,map.getZoom())
        //console.log(map.fromPixelToLatLng(p));
        var newMarkerPoint = new GMarker(map.getCenter(), {draggable: true});
        GEvent.addListener(newMarkerPoint, "dragend", function()  {                    
            var point = newMarkerPoint.getPoint();
            maputil.selectedLat = point.lat();
            maputil.selectedLng = point.lng();
            maputil.newPlace();
        });
        map.addOverlay(newMarkerPoint);        
    }
    
    MAPUTILS.prototype.addNewPlaceHelpCancel = function(){
        //ef.Close2('newPlaceHelp');
        ef.Close2('newPlaceForm');
        popuplayer.hide();
        marker.clearAll();
        marker.getMarkers(1);
    }
    
    MAPUTILS.prototype.search = function(str){
        document.getElementById('searchProgress').style.display='block'; 
        document.getElementById('searchResult').style.display='none'; 
        document.getElementById('searchResults').innerHTML = '';
        document.getElementById('mapSearchResults').style.display='block'; 
        var bounds = map.getBounds();
        yt = bounds.getNorthEast().y.toFixed(2);
        xt = bounds.getNorthEast().x.toFixed(2);
        yb = bounds.getSouthWest().y.toFixed(2);
        xb = bounds.getSouthWest().x.toFixed(2);                             
        com.ajax("/ajax/search/?yt=" + yt + "&xt=" + xt + "&xb=" + xb + "&yb=" + yb +"&zoom=" +  map.getZoom() + '&str=' + str, maputil.showResults);
        return false;
    }
    
    MAPUTILS.prototype.showResults = function(){        
        if ((xmlhttp.readyState == 4) && (xmlhttp.status == 200)) { 	
           document.getElementById('searchProgress').style.display='none'; 
           document.getElementById('searchResult').style.display='block'; 
           document.getElementById('searchResults').innerHTML = xmlhttp.responseText;            
        }         
    }
  

}

COMMON  = function () {        
    
    COMMON.prototype.timer = 0;    
    COMMON.prototype.inputId = '';
    COMMON.prototype.url = '';
    COMMON.prototype.obj = '';
            
    COMMON.prototype.setSiteUrl = function(){              
            var center = map.getCenter();     
            //if(detailsPointId) var openWin = '&showDetails='+detailsPointId;
            //else 
            var openWin ='';
            window.location = window.location.pathname + '#lat=' + Math.round(center.y*1000000)  + '&lng=' + Math.round(center.x*1000000) + '&zoom=' + map.getZoom() + '&currentmap=' + maputil.currentMap + openWin;                 
    }
    
    
    COMMON.prototype.openBlank  = function(url){
        var newwin = window.open(url,"newpage","menubar=yes, toolbar=yes, location=yes, directories=no, scrollbars=yes, resizable=yes ,width=800, height=550, top=50, left=50, status=yes");
        try{
            newwin.focus();
        }catch(e){
            alert('Popup blocked!Please check your popup blocker!');
        }
        return false;
    }
    
    COMMON.prototype.openNewWin2  = function(url,w,h){
        var newwin = window.open(url,"newpage","menubar=no, toolbar=no, location=no, directories=no, scrollbars=yes, resizable=yes ,width="+w+", height="+h+", top=50, left=50, status=no");
        try{
            newwin.focus();
        }catch(e){
            alert('Popup blocked!Please check your popup blocker!');
        }
        return false;
    }
    
    
    COMMON.prototype.addToBookmark = function(url,title){            
        if (window.sidebar) { 
            window.sidebar.addPanel(title, url,"");
        } else if( window.external ) { 
            window.external.AddFavorite( url, title); }
        else if(window.opera && window.print) { 
            return true;     
        }
    }
    
    COMMON.prototype.ajax = function(url,action) {    
        try {
    		xmlhttp = window.XMLHttpRequest?new XMLHttpRequest(): new ActiveXObject("Microsoft.XMLHTTP"); 
    	} catch (e) { 
    		alert('Sorry! Your browser is too old. Please upgrade.\n\nVisit: mozilla.com/');
    	} 		
    	xmlhttp.onreadystatechange = action; 		
    	xmlhttp.open("GET", url, true); 		
    	xmlhttp.send(null);          
    }
    
    
    //paramsearch keres mezojeben beirva hivjuk meg
    COMMON.prototype.checkInput = function(input,url){
        this.url = url;
        this.inputId = input;
        if(com.timer == 0){
          com.timer = window.setTimeout(function() {                
                com.ajax('/ajax/'+com.url+'/?value=' + document.getElementById(''+com.inputId).value, com.showCheckInput);                
            },500
          );        
        }
    }

    //visszakapot eredmenyek feldolgozasa
    COMMON.prototype.showCheckInput = function(){
        if ((xmlhttp.readyState == 4) && (xmlhttp.status == 200)) {
            com.timer = 0;  
            document.getElementById(com.inputId+'result').innerHTML = xmlhttp.responseText; 
        }
    }
    
    COMMON.prototype.showDropDown = function(objid){
        var obj = document.getElementById(''+objid);
        if(obj.style.display == 'block'){
            obj.style.display = 'none';
        }else{
            obj.style.display = 'block';   
        }
    }
    
    COMMON.prototype.ajaxCall = function(url, objid){
        this.obj = document.getElementById(''+objid);
        this.obj.innerHTML = 'Please wait ... ';
        this.ajax(url,com.ajaxCallResults);
    }
    
    COMMON.prototype.ajaxCallResults = function(){
        if ((xmlhttp.readyState == 4) && (xmlhttp.status == 200)) {            
            com.obj.innerHTML = xmlhttp.responseText; 
        }
    }


    COMMON.prototype.selectTag = function(tag,inputField){
        var isTagExits = false;
        var tags = document.getElementById(inputField).value.split(',');
        for(i=0;i<tags.length;i++){
            if(tags[i].trim() == tag) isTagExits = true;        
        }
        
        if(!isTagExits){ 
            var commaPos = document.getElementById(inputField).value.length - document.getElementById(inputField).value.lastIndexOf(',');
            if( commaPos != 1 && commaPos != 2){
                document.getElementById(inputField).value += ', ';             
            }
            document.getElementById(inputField).value += tag + ', '; 
        }
    }
    
    COMMON.prototype.TabSelect = function(tabs,active){
        var oList = document.getElementById(tabs+'');
        var listNo = 1;
        for (j = 0; j < oList .childNodes.length; j++){
            var oP = oList.childNodes[j];
            if (oP.nodeName == "A"){            
                if(IE) oP.setAttribute('className','');
                else oP.className = '';
                if(listNo == active) if(IE) oP.setAttribute('className','active');else oP.className = 'active';
                listNo++;
            }
        }        
        return false;
    }
}

var POPUPLAYER = {};

POPUPLAYER = function () {
    //block amit be kell tolteni es parameterek
    POPUPLAYER.prototype.block = '';
    POPUPLAYER.prototype.param = '';
    POPUPLAYER.prototype.paramhistory = '';
    POPUPLAYER.prototype.blockhistory = '';
    POPUPLAYER.prototype.xmlhttp = '';
    //keprenyo meret
    POPUPLAYER.prototype.getPageSize = function (){
    	var xScroll, yScroll;

    	if (window.innerHeight && window.scrollMaxY) {
    		xScroll = document.body.scrollWidth;
    		yScroll = window.innerHeight + window.scrollMaxY;
    	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
    		xScroll = document.body.scrollWidth;
    		yScroll = document.body.scrollHeight;
    	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
    		xScroll = document.body.offsetWidth;
    		yScroll = document.body.offsetHeight;
    	}

    	var windowWidth, windowHeight;
    	if (self.innerHeight) {	// all except Explorer
    		windowWidth = self.innerWidth;
    		windowHeight = self.innerHeight;
    	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
    		windowWidth = document.documentElement.clientWidth;
    		windowHeight = document.documentElement.clientHeight;
    	} else if (document.body) { // other Explorers
    		windowWidth = document.body.clientWidth;
    		windowHeight = document.body.clientHeight;
    	}

    	// for small pages with total height less then height of the viewport
    	if(yScroll < windowHeight){
    		pageHeight = windowHeight;
    	} else {
    		pageHeight = yScroll;
    	}

    	// for small pages with total width less then width of the viewport
    	if(xScroll < windowWidth){
    		pageWidth = windowWidth;
    	} else {
    		pageWidth = xScroll;
    	}

        var scrOfX = 0, scrOfY = 0;
        if( typeof( window.pageYOffset ) == 'number' ) {
            //Netscape compliant
            scrOfY = window.pageYOffset;
            scrOfX = window.pageXOffset;
        } else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
            //DOM compliant
            scrOfY = document.body.scrollTop;
            scrOfX = document.body.scrollLeft;
        } else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
            //IE6 standards compliant mode
            scrOfY = document.documentElement.scrollTop;
            scrOfX = document.documentElement.scrollLeft;
        }

    	arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight,xScroll,yScroll,scrOfX,scrOfY);
    	return arrayPageSize;
    }

    //egy div atteszore allitas. param: div nev, opacity %
    POPUPLAYER.prototype.setOpacity = function(a, b){
        if(b<0){b=0;} if(b>100){b=100;}
        var c=b/100;
        var d=document.getElementById(a);
        if(typeof(d.style.filter)=='string'){d.style.filter='alpha(opacity:'+b+')';}
        if(typeof(d.style.KHTMLOpacity)=='string'){d.style.KHTMLOpacity=c;}
        if(typeof(d.style.MozOpacity)=='string'){d.style.MozOpacity=c;}
        if(typeof(d.style.opacity)=='string'){d.style.opacity=c;}
    }



    //layerek body ala szurasa, ha mar bent vannak akkor megmutatas
    POPUPLAYER.prototype.init = function(){
        
        //probaljuk meg megmutatni a layereket. Ha nem sikerul akkor hozzuk letre
        try{
            document.getElementById('popup').style.display = 'block';
            
        }catch(e){
            var objBody = document.getElementsByTagName("body").item(0);
            var a = document.createElement('div');
            a.innerHTML = '<div class="container"><div class="content"><div class="title" id="popuptitleframe"><span class="left" id="popuptitle">&nbsp;</span><a href="javascript:popuplayer.hide()" title="Close"><img src="i/popup_close.gif" alt="x" class="right"/></a><br /></div><div id="popupcontent">&nbsp;</div></div></div><div class="foot"></div>';
            a.setAttribute('id','popup');
            objBody.insertBefore(a, objBody.firstChild);
            DragHandler.attach(document.getElementById('popup'), document.getElementById('popuptitleframe'));
            this.resizeBack();
        }
    }

    //toltes effect
    POPUPLAYER.prototype.setLoading = function(){
       
        if(this.form){
            this.setTitle('<img src="/i/ajax_load.gif" /> <span style="font-weight:normal">Sending data ...</span>');
        }else{
            this.setTitle('<img src="/i/ajax_load.gif" /> <span style="font-weight:normal">Loading ...</span>');
        }
    }

    //popup bezar
    POPUPLAYER.prototype.hide = function(){
        //document.getElementById('popuplayerback').style.display = 'none';
        document.getElementById('popup').style.display = 'none';
        document.getElementById('popupcontent').innerHTML = '';
    }
    
    //title
    POPUPLAYER.prototype.setTitle = function(title){
        document.getElementById('popuptitle').innerHTML = title;
    }

    //ajax init, ha bongeszo nem tamogatja az ajaxot akkor atdobjuk a nem layeres verziora
    POPUPLAYER.prototype.ajax = function(){
        var url = 'ajax/' + this.block + '.php5?' + this.param;
        try {
    		this.xmlhttp = window.XMLHttpRequest?new XMLHttpRequest(): new ActiveXObject("Microsoft.XMLHTTP");
    	} catch (e) {
    		//Ha nincs ajax akkor atdobjuk a usert a block oldalra
            window.location = url;
    	}
        
    	this.xmlhttp.onreadystatechange = this.showResults;
    	this.xmlhttp.open("GET", url, true);
    	this.xmlhttp.send(null);

    }

    POPUPLAYER.prototype.form = '';

    //ajax post form. Elkuldi a megadott form-ot postba. Ha van fajlfeltolto iframe akkor eloszor azt kuldi majd postolja az adatokat
    POPUPLAYER.prototype.post = function(formObj){
        if(formObj) this.form = formObj;

            //fajl feltoltes
            var i=0;
            var element = false;
            var regexp = /^fileupload_name_(.*)/i;
            var fileuploadName = false;
            var iframe = false;
            
            for(i=0; i<this.form.elements.length; i++) {
                element = this.form.elements[i];
                 
                if(regexp.test(element.id)) {
                    fileuploadName = element.id.replace(regexp, '$1');
                    iframe = document.getElementById('fileupload_iframe_'+fileuploadName);
                  
                    if(iframe) {
                      try{
                        iframe.contentDocument.getElementById('uploadform').value;
                        iframe.contentDocument.getElementById('uploadform').onsubmit();
                        iframe.contentDocument.getElementById('uploadform').submit();
                        return false;
                      }catch(e) {}
                      try {
                        iframe.contentWindow.document.getElementById('uploadform').value;
                        iframe.contentWindow.document.getElementById('uploadform').onsubmit();
                        iframe.contentWindow.document.getElementById('uploadform').submit();
                        return false;
                      } catch(e) {}
                    }

                }
            }

            var url = 'ajax/' + this.block + '.php5?' + this.param;
            var parameters = '';
            for(i=0;i<this.form.length;i++){
                if(this.form.elements[i].type == 'text' || this.form.elements[i].type == 'select-one' || this.form.elements[i].type == 'hidden' || this.form.elements[i].type == 'textarea' || this.form.elements[i].type == 'password' ){
                	parameters += '&' + this.form.elements[i].name + '=' + encodeURIComponent(this.form.elements[i].value);
                }
                if(this.form.elements[i].type == 'radio'){
                    if(this.form.elements[i].checked) parameters += '&' + this.form.elements[i].name + '=' + encodeURIComponent(this.form.elements[i].value);
                }
                if(this.form.elements[i].type == 'checkbox'){
                    if(this.form.elements[i].checked) parameters += '&' + this.form.elements[i].name + '=' + encodeURIComponent(this.form.elements[i].value);
                }
                
                if(this.form.elements[i].alt == 'req' && this.form.elements[i].value.length == 0){                    
                    this.form.elements[i].style.border = '1px solid #c00';
                    alert('Error field can\'t be empty!');
                    return false;
                }else{
                    this.form.elements[i].style.border = '1px solid #999';
                }
            }

            try {
        		this.xmlhttp = window.XMLHttpRequest?new XMLHttpRequest(): new ActiveXObject("Microsoft.XMLHTTP");
        	} catch (e) {
        		//Ha nincs ajax akkor posotolja az adatokat
               return true;
        	}
        	this.xmlhttp.onreadystatechange = this.showResults;
        	this.xmlhttp.open("POST", url + '&ajax=1', true);
        	this.xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
            this.xmlhttp.setRequestHeader("Content-length", parameters.length);
            this.xmlhttp.setRequestHeader("Connection", "close");
            this.xmlhttp.send(parameters);
            //this.setLoading();

            //Andris: ha ezt nem tettem ide, akkor az onsubmit="return popuplayer.post(this)"
            //siman elpostolta a formot ajax hivas nelkul.. :(            
            return false;
    }

    //ajax callback. Megmutajuk az eredmenyt
	POPUPLAYER.prototype.showResults = function(){
		if ((popuplayer.xmlhttp.readyState == 4) && (popuplayer.xmlhttp.status == 200)) {
            document.getElementById('popupcontent').innerHTML = popuplayer.xmlhttp.responseText;
            document.getElementById('popupcontent').style.display = 'block';
           
            //bug:#174. Ha hiba van akkor a form tetejere scrollozunk
            window.scrollTo(0,parseInt(document.getElementById('popup').style.top)-90);

            // JS futtatasa a responsebol
            var resp = popuplayer.xmlhttp.responseText;
			var ra = resp.split('\n');
			var inJs = false;
			var js = '';
			var i=0;
			for(i=0; i<ra.length; i++) {
				if(ra[i].match(/<\/script/i)) inJs = false;
				if(inJs) js += ra[i]+"\n";
				if(ra[i].match(/<script/i)) inJs = true;
			}

			try {
				eval(js);
			} catch(e) {
				console.log(e);
			}
        }
    }

    //ajax get form. Elkuldi a megadott form-ot es megjeleniti popupban az eredmenyt
    POPUPLAYER.prototype.getForm = function(block,form){
        var parameters = '';
        if(form) this.form = form;
        if(block) this.block = block;
        for(i=0;i<this.form.length;i++){
            if(this.form.elements[i].type == 'text' || this.form.elements[i].type == 'select-one' || this.form.elements[i].type == 'hidden' || this.form.elements[i].type == 'textarea' || this.form.elements[i].type == 'password' ){
              	parameters += '&' + this.form.elements[i].name + '=' + encodeURIComponent(this.form.elements[i].value);
            }
        }
        this.loadBlock(block,parameters);
        return false;
    }

    //ezt a metodust hivjuk meg ha be akkorunk tolteni egy popupot
    POPUPLAYER.prototype.loadBlock = function(block,param){
        if(this.block){
            this.paramhistory = this.param;
            this.blockhistory = this.block;
        }
        this.init();
        this.setLoading();
        this.block = block;
        this.param = param;
        this.ajax();        
        return false;
    }

    //popuplayer.init();

    //bug: atmeretezi a fekete hateret, ablak atmeretezesnel, meg az ajax hivas utan hivjuk meg
    POPUPLAYER.prototype.resizeBack = function(){
        var pageSize = popuplayer.getPageSize();
        try{
            document.getElementById('popup').style.top = (pageSize[7] + 90) + 'px';
            document.getElementById('popup').style.left = ((pageSize[0]/2)-310)+'px';            
        }catch (e) {}
    }
    
    POPUPLAYER.prototype.back = function(){
        if(this.blockhistory){
            this.loadBlock(this.blockhistory,this.paramhistory);
        }else{
            this.hide();
        }
    }

}

var DragHandler = {


	// private property.
	_oElem : null,


	// public method. Attach drag handler to an element.
	attach : function(oElem,dragSpot) {
		//console.log(dragSpot);
        dragSpot.onmousedown = function(){ DragHandler._addDrag(oElem);}
        dragSpot.onmouseup = function(){ DragHandler._removeDrag(oElem);};
		
	},
    
    _removeDrag : function (obj){    
        obj.onmousedown = '';        
    },
    
    _addDrag : function (obj){
    
        obj.onmousedown = DragHandler._dragBegin;
        // callbacks
		obj.dragBegin = new Function();
		obj.drag = new Function();
		obj.dragEnd = new Function();

		return obj;
    
    },


	// private method. Begin drag process.
	_dragBegin : function(e) {
       
		var oElem = DragHandler._oElem = this;

		if (isNaN(parseInt(oElem.style.left))) { oElem.style.left = '0px'; }
		if (isNaN(parseInt(oElem.style.top))) { oElem.style.top = '0px'; }

		var x = parseInt(oElem.style.left);
		var y = parseInt(oElem.style.top);

		e = e ? e : window.event;
		oElem.mouseX = e.clientX;
		oElem.mouseY = e.clientY;

		oElem.dragBegin(oElem, x, y);

		document.onmousemove = DragHandler._drag;
		document.onmouseup = DragHandler._dragEnd;
		return false;
	},


	// private method. Drag (move) element.
	_drag : function(e) {
		var oElem = DragHandler._oElem;

		var x = parseInt(oElem.style.left);
		var y = parseInt(oElem.style.top);

		e = e ? e : window.event;
		oElem.style.left = x + (e.clientX - oElem.mouseX) + 'px';
		oElem.style.top = y + (e.clientY - oElem.mouseY) + 'px';

		oElem.mouseX = e.clientX;
		oElem.mouseY = e.clientY;

		oElem.drag(oElem, x, y);

		return false;
	},


	// private method. Stop drag process.
	_dragEnd : function() {
		var oElem = DragHandler._oElem;

		var x = parseInt(oElem.style.left);
		var y = parseInt(oElem.style.top);

		oElem.dragEnd(oElem, x, y);

		document.onmousemove = null;
		document.onmouseup = null;
		DragHandler._oElem = null;
	}

};

var maputil = new MAPUTILS;
var com = new COMMON;
var marker = new MARKERS;
var popuplayer = new POPUPLAYER();

