var g_refresh = true;
var refresh = true;
var map = null;
var lastswlat = 0;
var lastswlong = 0;
var lastnelat = 0;
var lastnelong = 0;
var member = new Array();
var member_html = new Array();
var info_log = '';
var geschlecht_html = new Array(new Array("m","#0057e8"),new Array("w","#e80083"));
var geocoder = null;

function vergleiche2D(x,y)
{
	spalte = 2;
if(x[spalte]<y[spalte]){res=-1} else if(y[spalte]<x[spalte]){res=1} else{res=0}
return(res);
}


// Felder
function Rectangle(bounds, wieviel) {
	this.bounds_ = bounds;
	this.weight_ = 1;
	this.color_ = "#888888";
	this.text_ = wieviel;
}
Rectangle.prototype = new GOverlay();
Rectangle.prototype.initialize = function(map) {
	var div = document.createElement("div");
	div.style.border = this.weight_ + "px solid " + this.color_;
	div.className = "bereich";
	div.style.position = "absolute";
	div.innerHTML = this.text_  ;
	div.bounds_gps =  this.bounds_;
	
	div.onclick = function() { 
		bounds_gps = this.bounds_gps;
		map.setZoom(map.getBoundsZoomLevel(bounds_gps));
		map.setCenter(bounds_gps.getCenter()); 
	}

	div.onmouseover = function() { 
		this.className = "bereich_o";
	}

	div.onmouseout = function() { 
		this.className = "bereich";
	}
	
	map.getPane(G_MAP_MAP_PANE).appendChild(div);
	this.map_ = map;
	this.div_ = div;
}

Rectangle.prototype.remove = function() {
	this.div_.parentNode.removeChild(this.div_);
}

Rectangle.prototype.copy = function() {
	return new Rectangle(this.bounds_, this.weight_, this.color_, this.backgroundColor_, this.opacity_);
}

Rectangle.prototype.redraw = function(force) {
	if (!force) return;
	
	var c1 = this.map_.fromLatLngToDivPixel(this.bounds_.getSouthWest());
	var c2 = this.map_.fromLatLngToDivPixel(this.bounds_.getNorthEast());
	
	this.div_.style.width = Math.abs(c2.x - c1.x) + "px";
	this.div_.style.height = Math.abs(c2.y - c1.y) + "px";
	this.div_.style.left = (Math.min(c2.x, c1.x) - this.weight_) + "px";
	this.div_.style.top = (Math.min(c2.y, c1.y) - this.weight_) + "px";
}



























    function createMarker(nr,map, point, theHtml, type, gender, gps,nick) {
    	var icon = new GIcon(G_DEFAULT_ICON);
      if (gps == 1) {
	      if (gender == 0){
	      	 icon.image = "/img/flirt/map/iconbe.png";
	     }else{
	     	 icon.image = "/img/flirt/map/iconre.png";
		}
	}else{
		if (gender == 0){
	      	 icon.image = "/img/flirt/map/iconb.png";
	     }else{
	     	 icon.image = "/img/flirt/map/iconr.png";
		}
	}

      var marker = new GMarker(point, icon);
      
      member[nr] = marker;
      member_html[nr] = theHtml;
      if (type == "bunch") {
        GEvent.addListener(marker, "click", function() {
          map.zoomIn();
          map.setCenter(marker.getPoint());
        });
        GEvent.addListener(marker, "mouseover", function() {
          marker.openInfoWindowHtml(theHtml);
        });
        GEvent.addListener(marker, "mouseout", function() {
          map.closeInfoWindow();
        });
      } else {
        GEvent.addListener(marker, "click", function() {
          // marker.openInfoWindowHtml(theHtml);
          profil(nick);
        });
        
        GEvent.addListener(marker, "mouseover", function() {
        	g_refresh = false;
          marker.openInfoWindowHtml(theHtml);
        });
        
                GEvent.addListener(marker, "mouseout", function() {
          // map.closeInfoWindow();
        });
        

      }

      return marker;
    }

    function getPoints(map) { 
    	 var center = map.getCenter();
      
      var bounds = map.getBounds();
      var mapsw = bounds.getSouthWest();
      var mapne = bounds.getNorthEast();
      var mapswlat = mapsw.lat();
      var mapswlong = mapsw.lng();
      var mapnelat = mapne.lat();
      var mapnelong = mapne.lng();

      var dataswlat = mapswlat - (mapnelat-mapswlat)/2;
      var dataswlong = mapswlong - (mapnelong-mapswlong)/2;
      var datanelat = mapnelat + (mapnelat-mapswlat)/2;
      var datanelong = mapnelong + (mapnelong-mapswlong)/2;
      
	document.getElementById("ak_link").href = "?p=" + center.lat().toFixed(6) + "," + center.lng().toFixed(6) + "&z=" + map.getZoom() + "&t=" + map.getCurrentMapType().getUrlArg();
	document.getElementById("ak_input").value = "http://www.section.at/flirt/karte.html?p=" + center.lat().toFixed(6) + "," + center.lng().toFixed(6) + "&z=" + map.getZoom() + "&t=" + map.getCurrentMapType().getUrlArg();

	// map.getZoom()
/*
      document.getElementById("mapsw").innerHTML = mapswlat+','+mapswlong;
      document.getElementById("mapne").innerHTML = mapnelat+','+mapnelong;
*/

      if (g_refresh && (refresh || mapswlat < lastswlat || mapswlong < lastswlong || mapnelat > lastnelat || mapnelong > lastnelong)) {
      document.getElementById("member_liste").innerHTML = '<div style="background:#c34;color:white;font-weight:bold;">Lade...</div>';
      document.getElementById("deaktiviere").style.visibility = 'visible';
      document.getElementById("zoom_sel").selectedIndex = map.getZoom();
        lastswlat = dataswlat;
        lastswlong = dataswlong;
        lastnelat = datanelat;
        lastnelong = datanelong;
        /*
        document.getElementById("datasw").innerHTML = dataswlat+' '+dataswlong;
        document.getElementById("datane").innerHTML = datanelat+' '+datanelong;
        */
        map.clearOverlays();
         
         
        // bundeländer-zonen
      var marker = new GMarker(new GLatLng(48.197218, 16.337528));      
      // map.addOverlay(marker);
      
      // fotos
      var icon = new GIcon(G_DEFAULT_ICON);
      icon.image = "http://maps.google.com/mapfiles/kml/pal4/icon46.png";   
      icon.shadow = "http://maps.google.com/mapfiles/kml/pal4/icon46s.png";  
      icon.iconSize = new GSize(24, 24); 
      // map.addOverlay(new GMarker(new GLatLng(48.197218, 16.537528),icon));

// Aktueller Standort
var icon = new GIcon();
icon.image = "http://labs.google.com/ridefinder/images/mm_20_red.png";
icon.shadow = "http://labs.google.com/ridefinder/images/mm_20_shadow.png";
icon.iconSize = new GSize(12, 20);
icon.shadowSize = new GSize(22, 20);
icon.iconAnchor = new GPoint(6, 20);
icon.infoWindowAnchor = new GPoint(5, 1);
map.addOverlay(new GMarker(ME_position,icon));
      
        GDownloadUrl("/xml/map_data.html?swlat="+dataswlat+"&swlong="+dataswlong+"&nelat="+datanelat+"&nelong="+datanelong, function(data, responseCode) {
        	 var xml = GXml.parse(data);
          var markers = xml.documentElement.getElementsByTagName("marker");
          var info = xml.documentElement.getElementsByTagName("info");
          
          info_log = '';
          for(i=0;i<info.length;i++){
          	info_log += GXml.value(info[i]) + '\n';
          }
           // document.getElementById("info_log").innerHTML = info_log;
          
          var a_member_liste = new Array();
          var a_orte_liste = new Array();
          // Position ermitteln -> für danach ob der punkt neu geladen werden muss
              	 var ncenter = map.getCenter();
           var nbounds = map.getBounds();
	      var nmapsw = nbounds.getSouthWest();
	      var nmapne = nbounds.getNorthEast();
	  
	      var dis_lat = (nmapne.lat() - nmapsw.lat()) / 2;
	      var dis_long = (nmapne.lng() - nmapsw.lng()) / 2;
          var dis_m_lat = ncenter.lat();
          var dis_m_long = ncenter.lng();
          
          for (var i = 0; i < markers.length; i++) {
          	if(markers[i].getAttribute("type") == "bunch"){
          		
         
       var anzahl = parseInt(markers[i].getAttribute("anzahl"));
        var rectBounds = new GLatLngBounds(
            new GLatLng(parseFloat(markers[i].getAttribute("lat")),
                        parseFloat(markers[i].getAttribute("lng"))),
            new GLatLng(parseFloat(markers[i].getAttribute("lat2")),
                        parseFloat(markers[i].getAttribute("lng2"))));
                        
                        rechteck = new Rectangle(rectBounds,anzahl);
        map.addOverlay(rechteck);
         a_orte_liste[a_orte_liste.length] = new Array(i,markers[i].getAttribute("name"),anzahl);
          }else{
          	var p_lat = parseFloat(markers[i].getAttribute("lat"));
          	var p_lng = parseFloat(markers[i].getAttribute("lng"));
            var point = new GLatLng(p_lat,p_lng);
             var d2ME = (ME_position.distanceFrom(point)/1000).toFixed(1);   
             var d2PO = (center.distanceFrom(point)/1000).toFixed(1);
             var m_nick = markers[i].getAttribute("nick");
             var geschlecht = markers[i].getAttribute("gender");
             var alter = markers[i].getAttribute("alter"); 
             var foto = markers[i].getAttribute("foto"); 
             
             if(foto == 0){
             	foto_url = 'http://www.section.at/img/flirt/no.gif';
             }else{
          		foto_url = 'http://www.section.at/fotos/' + foto + '_normal.jpg';
          	}
             
             var t_html = '<table  border="0" cellspacing="0" cellpadding="10" width="200" height="100"><tr><td width="75"><img src="' + foto_url + '" width="75" height="100"></td><td><font style="font-weight:bold;color:'+geschlecht_html[geschlecht][1]+';">' + m_nick + '</font><br>             	'+alter+' Jahre<br><br><b>Entfernung:</b><br>' + d2ME  + ' km<br><br><a href="#" onclick="var tmp_nick = \'' + m_nick + '\';profil(tmp_nick.toLowerCase())">zum Profil</a></td>        	</tr>             </table>';
             
             // HTML INHALT -> GXml.value(markers[i]) 
            map.addOverlay(createMarker(i,map, point,t_html,markers[i].getAttribute("type"),geschlecht,markers[i].getAttribute("gps"),m_nick.toLowerCase()
                                               ));
                                               

                                           
                                            // document.getElementById("member_liste").innerHTML += '<a href="javascript:member['+i+'].openInfoWindowHtml(member_html['+i+']);">'+ m_nick + '</a><br>';
                                            
                                      if(p_lat + dis_lat < lastswlat || p_lat + dis_lat > lastnelat || p_lng + dis_long < lastswlong || p_lng + dis_long > lastnelong){
                                     	// if(p_lat + dis_lat < lastswlat || p_lat + dis_lat > lastnelat || p_lng + dis_long < lastswlong || p_lng + dis_long > lastnelong){
                                     
                                    	var a_l_new = 1;
                                   }else{
                              		var a_l_new = 0;
                              	}
                                     a_member_liste[a_member_liste.length] = new Array(i,m_nick,d2PO,a_l_new,p_lat,p_lng,geschlecht,alter);       
                                         
                                         /*
                                         0 marker_nr
                                         1 nickname
                                         2 position zur mitte in KM
                                         3 1,0 ob die daten neu geladen werden müssen
                                         4 lat
                                         5 lng
                                         6 geschlecht
                                         7 alter
                                         */
                                         
                                            
                                         }
           
          }
         
          a_member_liste = a_member_liste.sort(vergleiche2D);


       
       
       var u_on_card = '';
       var u_off_card = '';
       var u_anzahl_off = 0;
       var u_anzahl_on = 0;
         for(i=0;i<a_member_liste.length;i++){ 
         		if(!a_member_liste[i][3]){
         			 u_on_card += '<div style="cursor:pointer;color:'+geschlecht_html[a_member_liste[i][6]][1]+'"><span onmouseover="g_refresh = false;member['+a_member_liste[i][0]+'].openInfoWindowHtml(member_html['+a_member_liste[i][0]+']);" onclick="var tmp_nick = \'' + a_member_liste[i][1] + '\';profil(tmp_nick.toLowerCase())">' + a_member_liste[i][1] + ', '+a_member_liste[i][7]+'</span></div>';	
         			 u_anzahl_on = 1;
         		}else{
         			 u_off_card += '<div style="cursor:pointer;color:'+geschlecht_html[a_member_liste[i][6]][1]+'"><span onclick="map.setCenter(new GLatLng('+a_member_liste[i][4]+ ','+a_member_liste[i][5]+ '));">' + a_member_liste[i][1] + ', ' +a_member_liste[i][7]+'</span></div>';
         			u_anzahl_off = 1;
         		}
             
            } 
            
            if(u_anzahl_off == 0){
          	u_off_card = '<div style="color:#b9b9b9;">Keine</div>';
          	}
          	
          	            if(u_anzahl_on == 0){
          	u_on_card = '<div style="color:#b9b9b9;">Keine</div>';
          	}
            
            
            a_orte_liste = a_orte_liste.sort(vergleiche2D);
            a_orte_liste.reverse();
            var u_orte = '';
          for(i=0;i<a_orte_liste.length;i++){ 
         		 u_orte += '<div style="cursor:pointer;"><span>' + a_orte_liste[i][1] + '</span></div>';	
         		
           }                                                     
          // document.getElementById("member_liste").innerHTML = '<div style="font-weight:bold;">Mitglieder</div>' + u_on_card + '<span style="color:#ff0000">Gebiete:</span>' + u_orte +'<div style="font-weight:bold;">Mitglieder in der N&auml;he</div>' + u_off_card;
          document.getElementById("member_liste").innerHTML = '<div style="font-weight:bold;">Mitglieder</div>' + u_on_card + '<br><div style="font-weight:bold;">Mitglieder in der N&auml;he</div>' + u_off_card;
          document.getElementById("deaktiviere").style.visibility = 'hidden';
        });
        refresh = false;
      }
    }

 function load() {
      if (GBrowserIsCompatible()) {

function neuAufbau(){
	var hght=document.documentElement.clientHeight;
	var wght=document.documentElement.clientWidth;
	document.getElementById("map").style.height=hght - parseInt(document.getElementById("navi_div").style.height) +"px";
	document.getElementById("map").style.width=wght - 6 -parseInt(document.getElementById("member_liste").style.width) +"px";
	// margin & border = 6
	document.getElementById("member_liste").style.height= hght - 5 - parseInt(document.getElementById("navi_div").style.height)+"px";
	document.getElementById("deaktiviere").style.height= parseInt(document.getElementById("navi_div").style.height) + 1 +"px";
	
	document.getElementById("info_link").style.left = (parseInt(document.getElementById("map").style.width) / 2 - parseInt(document.getElementById("info_link").style.width) / 2) +"px";
	document.getElementById("show_link").style.left = (parseInt(document.getElementById("map").style.width) / 2 - parseInt(document.getElementById("show_link").style.width) / 2) +"px";
	document.getElementById("info_hinweis").style.left = (parseInt(document.getElementById("map").style.width) / 2 - parseInt(document.getElementById("info_hinweis").style.width) / 2) +"px";
	document.getElementById("info_hinweis").style.top = (parseInt(document.getElementById("map").style.height) / 2 - parseInt(document.getElementById("info_hinweis").style.height) / 2) +"px";
	
}
neuAufbau();
window.onresize = neuAufbau;


        map = new GMap2(document.getElementById("map"));
        // map.addControl(new GLargeMapControl());
        map.enableDoubleClickZoom();
        /*
        var Tsize = new GSize(160, 120);
	    map.addControl(new GOverviewMapControl(Tsize));
        */
        
        
        
        
        
        
        
        
        
        
        
        
        


        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        map.setCenter(START_position, START_zoom, START_map);
        geocoder = new GClientGeocoder();
        GEvent.addListener(map, "moveend", function(){
          getPoints(map);
          g_refresh = true;
        });
        GEvent.addListener(map, "zoomend", function(	oldLevel,  newLevel){
        	g_refresh = true;
          refresh = true;
          getPoints(map);
        });
        GEvent.addListener(map, "click", function(marker, point){
        	if (!marker) {
            map.closeInfoWindow();
          }
        });
        getPoints(map);
      }


	var publisherID = 'ca-pub-2647936654788997';

      var adsManagerOptions = {
        maxAdsOnMap : 2,
        style: 'adunit',
        // The channel field is optional - replace this field with a channel number 
        // of your own for Google AdSense tracking
        channel: '6871290448'  
      };

      adsManager = new GAdsManager(map, publisherID, adsManagerOptions);
      adsManager.enable();


}

         function go_ort(wohin){
         	g_refresh = true;
         	wohin = wohin.split(",");
	map.setCenter(new GLatLng(parseFloat(wohin[0]),parseFloat(wohin[1])), 13);
}

function showAddress(address) {
      if (geocoder) {
        geocoder.getLatLng(
          address,
          function(point) {
            if (!point) {
              alert(address + " wurde nicht gefunden\n\nEingabeschema: Strasse, Bundesland, Staat");
            } else {
              map.setCenter(point, 14);
            }
          }
        );
      }
    }
