var cMaps = function() {
	var customIcons = [];
	var iconBlue = new GIcon(); 
    iconBlue.image = 'http://milan.m115.server4u.cz/pubber/themes/images/icon_beer.png';
    iconBlue.shadow = 'http://labs.google.com/ridefinder/images/mm_20_shadow.png';
    iconBlue.iconSize = new GSize(25, 25);
    iconBlue.shadowSize = new GSize(22, 20);
    iconBlue.iconAnchor = new GPoint(6, 10);
    iconBlue.infoWindowAnchor = new GPoint(5, 1);

    var iconRed = new GIcon(); 
    iconRed.image = 'http://milan.m115.server4u.cz/pubber/themes/images/icon_wine.png';
    iconRed.shadow = 'http://labs.google.com/ridefinder/images/mm_20_shadow.png';
    iconRed.iconSize = new GSize(25, 25);
    iconRed.shadowSize = new GSize(22, 20);
    iconRed.iconAnchor = new GPoint(6, 10);
    iconRed.infoWindowAnchor = new GPoint(5, 1);

	var iconGray = new GIcon(); 
    iconGray.image = 'http://coolkeg.devel.nydrle.net/themes/images/map_keg3.png';
    iconGray.shadow = 'http://labs.google.com/ridefinder/images/mm_20_shadow.png';
    iconGray.iconSize = new GSize(17, 19);
    iconGray.shadowSize = new GSize(22, 20);
    iconGray.iconAnchor = new GPoint(6, 10);
    iconGray.infoWindowAnchor = new GPoint(5, 1);
	
	var icon1 = new GIcon(); 
    icon1.image = 'http://cmss-liska.devel.nydrle.net/themes/images/icon_photo.png';
    icon1.iconSize = new GSize(28, 26);
    icon1.iconAnchor = new GPoint(10, 10);
    icon1.infoWindowAnchor = new GPoint(10, 10);
	
	var icon2 = new GIcon(); 
    icon2.image = 'http://cmss-liska.devel.nydrle.net/themes/images/icon_poradca.png';
    icon2.iconSize = new GSize(19, 19);
    icon2.iconAnchor = new GPoint(10, 10);
    icon2.infoWindowAnchor = new GPoint(10, 10);
	
	var icon3 = new GIcon(); 
    icon3.image = 'http://milan.devel.nydrle.net/facebook/shineyourcity/icon_3.png';
    icon3.iconSize = new GSize(19, 19);
    icon3.iconAnchor = new GPoint(10, 10);
    icon3.infoWindowAnchor = new GPoint(10, 10);
	
	var icon4 = new GIcon(); 
    icon4.image = 'http://milan.devel.nydrle.net/facebook/shineyourcity/icon_4.png';
    icon4.iconSize = new GSize(19, 19);
    icon4.iconAnchor = new GPoint(10, 10);
    icon4.infoWindowAnchor = new GPoint(10, 10);
	
	var icon5 = new GIcon(); 
    icon5.image = 'http://milan.devel.nydrle.net/facebook/shineyourcity/icon_5.png';
    icon5.iconSize = new GSize(19, 19);
    icon5.iconAnchor = new GPoint(10, 10);
    icon5.infoWindowAnchor = new GPoint(10, 10);
	
   // customIcons["green"] = iconGreen;
	customIcons["icon1"] = icon1;
	customIcons["icon2"] = icon2;
	customIcons["icon3"] = icon3;
	customIcons["icon4"] = icon4;
	customIcons["icon5"] = icon5;
	
	var styles = [[{
        url: ROOT + 'themes/images/m1.png',
        height: 52,
        width: 53,
        opt_anchor: [20, 24],
        opt_textColor: '#FFFFFF'
      },
      {
        url: ROOT + 'themes/images/m2.png',
        height: 56,
        width: 55,
        opt_anchor: [21, 22],
        opt_textColor: '#FFFFFF'
      },
      {
        url: ROOT + 'themes/images/m3.png',
        height: 66,
        width: 65,
        opt_anchor: [27, 24],
		opt_textColor: '#FFFFFF'
      }]];

	
	/* INITIALIZE GOOGLE MAP, SET CENTER, ZOOM, CONTROLS */
    this.initialize = function(lat,lng,zoom,target,control,bar) {
    	if (GBrowserIsCompatible()) {
			map = new GMap2(document.getElementById(target));
			// set center
			map.setCenter(new GLatLng(lat, lng), zoom);
			// set controls
			
			if (!control) control = "none"; 
			if (control == "large") 
				map.addControl( new GLargeMapControl3D())
			else if (control == "small") 
				map.addControl( new GSmallZoomControl3D());
				map.setMapType(G_PHYSICAL_MAP );
			if (!bar) bar = true; 
			if (bar == true) map.enableGoogleBar();
			/*map.addControl(new GMapTypeControl());*/	
			gdir = new GDirections(map);
		    GEvent.addListener(gdir, "error", handleErrors);
			GEvent.addListener(gdir, "load", onGDirectionsLoad);
		   	/* MARKER DRAG LISTENER*/
			GEvent.addListener(map, "zoomend",
			function(){
					//$("#loading_overlay").hide();
					if (map.getZoom() < 7 ) {
						map.setZoom(7);
					} else {
						
						$("#info_box").hide();
					};
				}
			);
			GEvent.addListener(map, "dblclick", 
			function(){
				/*	if ($("#loading_overlay").css("display") != "none") {
						$("#loading_overlay").show();
					};
				*/
				}
			);
			//mMaps.locationShow();
	        window.setTimeout("mMaps.locationShow();", 100);

		}
    };
	this.markers = [];
	this.markersId = [];
	this.markersType = [];
	/* READ AND PARSE XML FILE WITH LOCATIONS */
	this.locationShow = function(locationId) {
				if ( !locationId ) locationId = 0;
				GDownloadUrl(ROOT + "cs/xml_create.xml", 
					function(data) {
						var xml = GXml.parse(data);
						var markers = xml.documentElement.getElementsByTagName("marker");
						
						var batch = [];
						var batchId = [];
						var batchType = [];
						var id;
						for (var i = 0; i < markers.length; i++) {
						//for (var i = 0; i < 10; i++) {
							id = markers[i].getAttribute("id");
							type = markers[i].getAttribute("type");
							var point = new GLatLng(parseFloat(markers[i].getAttribute("lat")),
													parseFloat(markers[i].getAttribute("lng")));
							if (type == 1) {
								var marker = new GMarker(point, { icon: customIcons["icon2"] });
							} else {
								var marker = new GMarker(point, { icon: customIcons["icon1"] });
							}
							batch.push(marker);
							batchId.push(id);
							batchType.push(type);
						};
						mMaps.markers = batch;
						mMaps.markersId = batchId;
						mMaps.markersType = batchType;
						$(batch).each(function(i,marker){
										GEvent.addListener(marker, "click", function(){
											mMaps.displayPoint(marker, i);
								});
						});
						var markerCluster = new MarkerClusterer(map, batch, {gridSize: 40, maxZoom: 12, styles: styles[0]});
						$("#loading_overlay").fadeOut();
						//var markerCluster = new MarkerClusterer(map, batch)
					}
				);
	};
	
	this.locationShowJson = function(){
    	$.getJSON("xml_create_json.xml", function(json) {
			var batch = [];
			var batchId = [];
			var batchType = [];
			var id;
			if (json.Locations.length > 0) {
				   for (i=0; i<json.Locations.length; i++) {
						  	llocation = json.Locations[i];
							id = llocation.id;
							type = llocation.type;
							var point = new GLatLng(parseFloat(llocation.lat),
													parseFloat(llocation.lng));
							if (type == 1) {
								var marker = new GMarker(point, { icon: customIcons["icon2"] });
							} else {
								var marker = new GMarker(point, { icon: customIcons["icon1"] });
							}
							batch.push(marker);
							batchId.push(id);
							batchType.push(type);
					  }
			};
			mMaps.markers = batch;
			mMaps.markersId = batchId;
			mMaps.markersType = batchType;
			$(batch).each(function(i,marker){
							GEvent.addListener(marker, "click", function(){
								mMaps.displayPoint(marker, i);
					});
			});
			var markerCluster = new MarkerClusterer(map, batch, {gridSize: 40, maxZoom: 12, styles: styles[0]});
			$("#loading_overlay").fadeOut();
        });
	};
	
	function importanceOrder (marker) {
        return marker.importance*1000000;
    };
	
    this.displayPoint = function(marker, index){
	   $("#info_box").hide();
		var index = index;
		if (marker.getLatLng() != map.getCenter()) {
			  var moveEnd = GEvent.addListener(map, "moveend", function(){
				//GEvent.addListener(marker, "click", function(){
				  PAGE.getMarkerInfo(mMaps.markersId[index], marker, mMaps.markersType[index]);
				  GEvent.removeListener(moveEnd);
			  });
		} else {
			PAGE.getMarkerInfo(mMaps.markersId[index], marker, mMaps.markersType[index]);
		};
        map.panTo(marker.getLatLng());
    };

	/* CREATE MARKER WITH SET OF INSTANCE */
    this.createMarker = function(point, html, icon, drag, cond) {
		if (point == "center") {
			point = map.getCenter();
		};
		if ( cond == "find" ) {
		};
		if (drag == true) 
			//var marker = new GMarker(point, {draggable: true}, customIcons[icon])
			var marker = new GMarker(point, {draggable: true})
		else 
			var marker = new GMarker(point, {icon:customIcons[icon], zIndexProcess:importanceOrder});
		return marker;
    };
		
	/* FUNCTION WILL FIND LAT,LNG FROM ADDRESS */
	this.findTrue = false;
	this.locationFinder = function(address,  callback, finder) {
		if (!address) {
			var address;
			address = document.getElementById('address').value;
		};
		var finder = finder;
		var geocoder = new GClientGeocoder();
		geocoder.getLatLng(
			address, 				
			function(point) {
				if (!point) { 
					PAGE.showAlert(ERR.e02);
					/*
						$("#address").focus();
						$("#address").css({"background-color":"#F4E1D0"});
					*/
				}
				else {
					map.setZoom(17);
					map.setCenter(point);
					html = "";
					if (finder == true) {
						var markerFind = mMaps.createMarker(point,html,"icon",true,"find");
					} else {
						var markerFind = mMaps.createMarker(point,html,"icon1",false,"");
					};
					mMaps.findTrue = true;
					map.addOverlay(markerFind);
					lng = point.lng();
					lat = point.lat();
					$("#lat").val(point.lat());
					$("#lng").val(point.lng());
					eval(callback);
					/*document.getElementById('lat').value = point.lat();
					document.getElementById('lng').value = point.lng();
					$("#address").css({"background-color":"#FFF"});*/
				}
			}
		  );
	};
	this.poradciInput = function(address, id, callback) {
		if (!address) {
			var address;
			address = document.getElementById('address').value;
		};
		var geocoder = new GClientGeocoder();
		geocoder.getLatLng(
			address, 				
			function(point) {
				if (!point) { 
					return;
					alert(ERR.e02);
				}
				else {
					lng = point.lng();
					lat = point.lat();
					var params = {lat:lat,lng:lng,id:id,checked:1};
					var str = $.param(params);
					
					$.post(ROOT + "db_input2.html", str,
					  function(data){
						  $("#poradci_counter").append(" a");
					});
					
				}
			}
		  );
	};
	/* FUNCTION WILL HANDLE DIRECTION ERRORS */
    function handleErrors(){
				   if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
					 alert("No corresponding geographic location could be found for one of the specified addresses. This may be due to the fact that the address is relatively new, or it may be incorrect.\nError code: " + gdir.getStatus().code);
				   else if (gdir.getStatus().code == G_GEO_SERVER_ERROR)
					 alert("A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known.\n Error code: " + gdir.getStatus().code);
				   
				   else if (gdir.getStatus().code == G_GEO_MISSING_QUERY)
					 alert("The HTTP q parameter was either missing or had no value. For geocoder requests, this means that an empty address was specified as input. For directions requests, this means that no query was specified in the input.\n Error code: " + gdir.getStatus().code);
			
				//   else if (gdir.getStatus().code == G_UNAVAILABLE_ADDRESS)  <--- Doc bug... this is either not defined, or Doc is wrong
				//     alert("The geocode for the given address or the route for the given directions query cannot be returned due to legal or contractual reasons.\n Error code: " + gdir.getStatus().code);
					 
				   else if (gdir.getStatus().code == G_GEO_BAD_KEY)
					 alert("The given key is either invalid or does not match the domain for which it was given. \n Error code: " + gdir.getStatus().code);
			
				   else if (gdir.getStatus().code == G_GEO_BAD_REQUEST)
					 alert("A directions request could not be successfully parsed.\n Error code: " + gdir.getStatus().code);
					
				   else alert("An unknown error occurred.");
	}
	function onGDirectionsLoad(){
		dis = gdir.getDistance();
		//alert(dis.html);
	}
	/* SHOW ROUTE DIRECTIONS */
	this.showDirection = function(from, to) {
						  //gdir.load(from + " to " + to);
						  gdir.load("from:"+from+" to:"+to);
	};
	/* FUNCTION CREATED TO MOVE MAP USING EXTERNAL CUSTOM BUTTONS  */
	this.customMove = function(direction,target) {
		var x = document.getElementById(target).offsetHeight;
		var y = document.getElementById(target).offsetWidth;
		
		switch(direction){
			case 'right':
				x = x/2;
			break;    
			case 'left':
				x = x/2;
				y = 0;
			break;
			case 'top':
				x = 0;
				y = y/2;
			break;
			case 'bottom':
				y = y/2;
			break;
			case 'center':
				x = x/2;
				y = y/2;
			break;
			case 'infoOn':
				y = 18*y/30;
				x = x/2;
			break;
			case 'infoOff':
				y = 15*y/30;
				x = x/2;
			break;
			default:
		}
				
		var point = map.fromContainerPixelToLatLng(new GPoint(y,x));
		map.panTo(point);
	};
	this.customZoom = function(direction){
		switch(direction){
			case 'in':
				map.setZoom(map.getZoom()+1);
			break;    
			case 'out':
				map.setZoom(map.getZoom()-1);
			break;
			default:
		};
	};
	var checkform = function(form) {
		if (form.address.value == "") {
			alert( "Please enter values" );
			return false;
		}
		else {
			if ((form.lat.value == "") || (form.lng.value == "")) {
					mMaps.locationFinder();
					document.getElementById("alertbox").innerHTML = "Je tato adresa spravna, posunte ikonu ak nie je na spravne miesto"
					return false;					
			}
			return true;
		}
	};
};
var mMaps = new cMaps();