/**
 * @author Czort
 */

   	var nMapsClass= Class.create();
    var map;
	var gMarkerMenager;
	var om;
	var nControl = function() {};

	nControl.prototype = new GControl(true);
	nControl.prototype.initialize = function(map) {
		var container = document.createElement("div");
		container.innerHTML = '<img style="cursor:pointer" width="120px" height="32px" src="logo.gif" border="0">';
		container.style.width='120px';
		container.style.height='32px';
	
		GEvent.addDomListener(container, "click", function() {
//			document.location = "http://netris.pl/";
			window.open("http://www.netris.pl/");
		});
	
		map.getContainer().appendChild(container);
	
		return container;
	};

	nControl.prototype.getDefaultPosition = function() {
		return new GControlPosition(G_ANCHOR_BOTTOM_LEFT, new GSize(70, 0));
	};

	
	nMapsClass.prototype= {
		initialize: function() {
			urlquery=location.href.split("=")
			rnurlterms=(urlquery[1])?urlquery[1].split(","):"";
			
			om = new OverlayMessage(document.getElementById('map_canvas'));      
      		om.Set('<b>Loading...</b>');
			this.counter = 0;
      		//Inicjalizacja mapy
			map = new GMap2(document.getElementById("map_canvas"));
			map.addControl(new nControl());
			
			map.setCenter(new GLatLng(50.828670,20.517107), 10);
			map.setZoom(13);
			gMarkerMenager=new GMarkerManager(map,{borderPadding:1});
			this.retrieveMarkers();
        	map.addControl(new GLargeMapControl());
			var bottomRight = new GControlPosition(G_ANCHOR_BOTTOM_RIGHT, new GSize(10,10));
		  	map.addControl(new GMapTypeControl(), bottomRight);
			if(rnurlterms[0] && rnurlterms[1]) {
            	var latlng = new GLatLng(parseFloat(rnurlterms[0]),parseFloat(rnurlterms[1]));
				this.showPoint(latlng);
            } 
			////////////////////////////////////
			/*
			GEvent.addListener(map, "click", function(overlay, latlng) {
		        //only perform the click if the window is closed and the click was directly on the map.
		        if(!overlay) {
			        //create an HTML DOM form element
			        var inputForm = document.createElement("form");
			        inputForm.setAttribute("action","");
			        inputForm.onsubmit = function() {storeMarker(); return false;};
		
			        //retrieve the longitude and lattitude of the click point
			        var lng = latlng.lng();
			        var lat = latlng.lat();
		
			        inputForm.innerHTML = '<fieldset style="width:150px;">'
			              + '<legend>Nowa pozycja</legend>'
						  + '<label for="city">Miasto</label>'
			              + '<input type="text" id="city" style="width:100%"/>'
			              + '<label for="name">Adres</label>'
			              + '<input type="text" id="name" style="width:100%;"/>'
			              + '<label for="region">Województwo</label>'
			              + '<input type="text" id="region" style="width:100%;"/>'
			              + '<label for="zip">Kod pocztowy</label>'
			              + '<input type="text" id="zip" style="width:100%"/>'
						  + '<label for="mail">Mail</label>'
			              + '<input type="text" id="mail" style="width:100%"/>'						  
			              + '<input type="submit" value="Save"/>'
			              + '<input type="hidden" id="longitude" value="' + lng + '"/>'
			              + '<input type="hidden" id="latitude" value="' + lat + '"/>'
			              + '</fieldset>';
		
			        map.openInfoWindow (latlng,inputForm);
		        }
		       
		    }); */
			
			///////////////////////////////////
			//////////////////////////////////
	
  		},
		showPoint:function(latLng){
			map.setZoom(13);
			map.panTo(latLng);
		},
	
		zoomOut:function() {
			map.panTo(new GLatLng(50.828670,20.517107));
			map.setZoom(6);
		},
		createMarker:function(latlng, html, gIcon) {
		    if(gIcon) {
		        var marker = new GMarker(latlng,gIcon);
		    } else {
		        var marker = new GMarker(latlng);
		    }
		    GEvent.addListener(marker, 'click', function() {
		        var markerHTML = html;
		        marker.openInfoWindowHtml(markerHTML);
		    });
		    return marker;
		},
		
		storeMarker:function(){
		    var lng = document.getElementById("longitude").value;
		    var lat = document.getElementById("latitude").value;
		
		    var getVars =  "?name=" + document.getElementById("name").value
		        + "&city=" + document.getElementById("city").value
		        + "&zip=" + document.getElementById("zip").value
		        + "&region=" + document.getElementById("region").value
		        + "&mail=" + document.getElementById("mail").value
		        + "&lng=" + lng
		        + "&lat=" + lat ;
		
		    var request = GXmlHttp.create();
		
		    //open the request to storeMakres.php on your server
		    request.open('GET', 'storeMarker.php' + getVars, true);
		    request.onreadystatechange = function() {
		       if (request.readyState == 4) {
		            //the request in complete
		
		            var xmlDoc = request.responseXML;
		
		            //retrieve the root document element (response)
		            var responseNode = xmlDoc.documentElement;
		
		            //retrieve the type attribute of the node
		            var type = responseNode.getAttribute("type");
		
		            //retrieve the content of the responseNode
		            var content = responseNode.firstChild.nodeValue;
		
		            //check to see if it was an error or success
		            if(type!='success') {
		                alert(content);
		            } else {
////////////////////////						//////////////
		                //Create a new marker and add it's info window.
		                var latlng = new GLatLng(parseFloat(lat),parseFloat(lng));
		
		                var iconImage = responseNode.getAttribute("icon");
		                var marker = createMarker(latlng, content, iconImage)
		
		                map.addOverlay(marker);
		                map.closeInfoWindow();
///////////////////////////////////////////////////////////////////////
		            }
		       }
		    }
		    request.send(null);
		    return false;
		},

		
		retrieveMarkers:function () {
			var request = GXmlHttp.create();
    		request.open('GET', 'retrieveMarkers.php', true);
    		request.onreadystatechange = function() {
        	if (request.readyState == 4) {
				var xmlDoc = request.responseXML;
				var markers = xmlDoc.documentElement.getElementsByTagName("store");
              	for (var i = 0; i < markers.length; i++) {
					var lat = markers[i].getElementsByTagName("latitude")[0].childNodes[0].nodeValue;
                   	var lng = markers[i].getElementsByTagName("longitude")[0].childNodes[0].nodeValue;
                   	//check for lng and lat so MSIE does not error
                   	//on parseFloat of a null value
                   	if(lng && lat) {
                    	var latlng = new GLatLng(parseFloat(lat),parseFloat(lng));
                      	var html = '<div><b>Adres</b> '
                            + markers[i].getElementsByTagName("name")[0].childNodes[0].nodeValue
                            + '</div><div><b>Mail:</b> '
                            + markers[i].getElementsByTagName("mail")[0].childNodes[0].nodeValue
                           	+ '</div><div><b>Miasto:</b> '
                            + markers[i].getElementsByTagName("city")[0].childNodes[0].nodeValue
						    + '</div>';
						var gIcon=nMapsClass.prototype.createIcon();
                      	var marker = nMapsClass.prototype.createMarker(latlng, html, gIcon);
						gMarkerMenager.addMarker(marker,6,17); 	    				
    //                  	map.addOverlay(marker); zastapione przez GMarkerMenagera
                   }
              	} //for
 		      //om.Clear(); // Clear the loading message	
        	} //if
    	} //function
    	om.Clear();
    	request.send(null);
	},
	createIcon:function(){
	  var icon = new GIcon();
      icon.image = "mm_20_blue.png";
      icon.shadow = "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);      
	  return icon;
	}
	}; 
    function initialize() {
      if (GBrowserIsCompatible()) {
        var application = new nMapsClass();
      }
    }
	window.onload= initialize;
	window.onunload = GUnload;