//Ajax Sync
(function($) {
	
	var ajax = $.ajax;
	
	var pendingRequests = {};
	
	var synced = [];
	var syncedData = [];
	
	$.ajax = function(settings) {
		// create settings for compatibility with ajaxSetup
		settings = jQuery.extend(settings, jQuery.extend({}, jQuery.ajaxSettings, settings));
		
		var port = settings.port;
		
		switch(settings.mode) {
		case "abort": 
			if ( pendingRequests[port] ) {
				pendingRequests[port].abort();
			}
			return pendingRequests[port] = ajax.apply(this, arguments);
		case "queue": 
			var _old = settings.complete;
			settings.complete = function(){
				if ( _old )
					_old.apply( this, arguments );
				jQuery([ajax]).dequeue("ajax" + port );;
			};
		
			jQuery([ ajax ]).queue("ajax" + port, function(){
				ajax( settings );
			});
			return;
		case "sync":
			var pos = synced.length;
	
			synced[ pos ] = {
				error: settings.error,
				success: settings.success,
				complete: settings.complete,
				done: false
			};
		
			syncedData[ pos ] = {
				error: [],
				success: [],
				complete: []
			};
		
			settings.error = function(){ syncedData[ pos ].error = arguments; };
			settings.success = function(){ syncedData[ pos ].success = arguments; };
			settings.complete = function(){
				syncedData[ pos ].complete = arguments;
				synced[ pos ].done = true;
		
				if ( pos == 0 || !synced[ pos-1 ] )
					for ( var i = pos; i < synced.length && synced[i].done; i++ ) {
						if ( synced[i].error ) synced[i].error.apply( jQuery, syncedData[i].error );
						if ( synced[i].success ) synced[i].success.apply( jQuery, syncedData[i].success );
						if ( synced[i].complete ) synced[i].complete.apply( jQuery, syncedData[i].complete );
		
						synced[i] = null;
						syncedData[i] = null;
					}
			};
		}
		return ajax.apply(this, arguments);
	};
	
})(jQuery);

var centerLatitude = 35;
var centerLongitude = 33.3;
var startZoom = 9;

var map;
var marker;
var overviewMap;
var $f; // from Date
var $u; // Until Date
var $m; //current marker
var cluster;
var markersArray=[];

var iconMole = new GIcon(); 
iconMole.image = '/images/gmap/icon.png';
iconMole.shadow = '/images/gmap/shicon.png';
iconMole.iconSize = new GSize(15, 27);
iconMole.shadowSize = new GSize(35, 27);
iconMole.iconAnchor = new GPoint(7, 26);
iconMole.infoWindowAnchor = new GPoint(7, 1);

var ClusterIcon = new GIcon(); 
ClusterIcon.image = '/images/gmap/cicon.png';
ClusterIcon.shadow = '/images/gmap/shicon.png';
ClusterIcon.iconSize = new GSize(15, 27);
ClusterIcon.shadowSize = new GSize(35, 27);
ClusterIcon.iconAnchor = new GPoint(7, 26);
ClusterIcon.infoWindowAnchor = new GPoint(7, 1);
	 
$(document).ready(function(){
    if (GBrowserIsCompatible()) {	
		map = new GMap2(document.getElementById("map"));
		var location = new GLatLng(centerLatitude, centerLongitude);
		map.setCenter(location, startZoom);
		//var controlpos = new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(20, 20));
		//map.addControl(new GLargeMapControl(), controlpos);
		map.addControl(new GLargeMapControl());
		map.addControl(new GMapTypeControl());
		map.setMapType(G_HYBRID_MAP);
		map.enableScrollWheelZoom();
		map.enableContinuousZoom();

		overviewMap = new GOverviewMapControl(new GSize(175,150));
		//overviewMap.setMapType(G_SATELLITE_MAP);
		map.addControl(overviewMap);
		
		//setTimeout("overviewMap.getOverviewMap().setMapType(G_SATELLITE_MAP);",5000); 
		
		G_HYBRID_MAP.getMinimumResolution = function () { return 9 };
		G_HYBRID_MAP.getMaximumResolution = function () { return 18 };
		
		function myClusterClick(args) {
			if(this._map.getBoundsZoomLevel(args.clusterMarker.clusterGroupBounds) < 16){
				$bzl = this._map.getBoundsZoomLevel(args.clusterMarker.clusterGroupBounds);
			} else {
				$bzl = 16;
			}
			this._map.setCenter(args.clusterMarker.getLatLng(), $bzl);
		}
		
		cluster=new ClusterMarker(map, { markers:markersArray, fitMapToMarkers:false, clusterMarkerIcon:ClusterIcon, clusterMarkerTitle:'Click to zoom in and see %count venues', clusterMarkerClick:myClusterClick } );
		
		updateMarkers();
		
      // Add a move listener to restrict the bounds range
      GEvent.addListener(map, "move", function() {
        checkBounds();
      });

      // The allowed region which the whole map must be within
      var allowedBounds = new GLatLngBounds(new GLatLng(34.4,31.9), new GLatLng(35.9,34.9));
      
      // If the map position is out of range, move it back
      function checkBounds() {
        // Perform the check and return if OK
        if (allowedBounds.contains(map.getCenter())) {
          return;
        }
        // It`s not OK, so find the nearest allowed point and move there
        var C = map.getCenter();
        var X = C.lng();
        var Y = C.lat();

        var AmaxX = allowedBounds.getNorthEast().lng();
        var AmaxY = allowedBounds.getNorthEast().lat();
        var AminX = allowedBounds.getSouthWest().lng();
        var AminY = allowedBounds.getSouthWest().lat();

        if (X < AminX) {X = AminX;}
        if (X > AmaxX) {X = AmaxX;}
        if (Y < AminY) {Y = AminY;}
        if (Y > AmaxY) {Y = AmaxY;}
        //alert ("Restricting "+Y+" "+X);
        map.setCenter(new GLatLng(Y,X));
      }

		/*
		GEvent.addListener(map,'zoomend',function() {
			updateMarkers();
		});
		GEvent.addListener(map,'moveend',function() {
			updateMarkers();
		});*/
		
    }
});

function updateMarkers() {
	$('#loading').show();
	//Get Dates
	if($docsize){
		$fromDate = $("#inlineFrom").datepicker('getDate');
		$untilDate = $("#inlineUntil").datepicker('getDate');
	} else {
		$fromDate = $("#popFrom").datepicker('getDate');
		$untilDate = $("#popUntil").datepicker('getDate');
	}
	$f = $.datepicker.formatDate('yy-mm-dd', $fromDate);
	$u = $.datepicker.formatDate('yy-mm-dd', $untilDate);
	//Get Categories
	$cats = new Array();
	$(".category input").each(function(){
		if($(this).attr('checked')){
			$cats.push($(this).val());
		}
	});
	$c=$cats.join(",")
	//Get Keyword
	$k=$('#keyword').val();
	//retrieve the points using Ajax
	$.ajax({
		type: "GET",
		url: "/mapfiles/map_data.php",
		data: "f="+$f+"&u="+$u+"&c="+$c+"&k="+$k,
		mode: "abort",
		success: function(msg){
			//remove the existing points
			map.clearOverlays();
			//Stop info window
			$m = 0;
			markersArray.length = 0
			if(msg != ''){
				$locs = msg.split(";");
				for(var n in $locs){
					$loc = $locs[n].split(",");
					var point = new GLatLng($loc[1],$loc[2]);
					var marker = createMarker(point,$loc[0],$loc[3]);
					//map.addOverlay(marker);
					markersArray.push(marker); // Clustering
				}
			}
			$('#loading').hide();
			//For clustering:
			cluster.removeMarkers();
			cluster.addMarkers(markersArray);
			cluster.refresh();
			map.savePosition();
		}
	});
}

var delay;
function updateMarkersDelay(){
	clearTimeout(delay);
	delay = setTimeout(updateMarkers, 550);
}

function createMarker(point, locID, eventIDs) {
	var marker = new GMarker(point, {icon:iconMole});
	GEvent.addListener(marker, 'click', function() {
		$('#loading').show();
		$m = locID;
		$.ajax({
			type: "GET",
			url: "/"+langurl+"locdata/",
			data: "l="+locID+"&e="+eventIDs+"&f="+$f+"&u="+$u,
			success: function(msg){
				if($m == locID){
					$tabs = msg.split("##%##");
					$eventstab = '<div id="content">'+$tabs[0]+'</div>';
					$loctab = '<div id="content">'+$tabs[1]+'</div>';
					var infoTabs = [
						new GInfoWindowTab("Events", $eventstab),
						new GInfoWindowTab("Venue", $loctab)
					];
					marker.openInfoWindowTabsHtml(infoTabs);
					$('#loading').hide();
				}
			}
		});
	});
	return marker;
}



window.onunload = GUnload;
