// JavaScript Document
var myGlobalHandlers = {
onCreate: function(){
	clearTimeout(loadDelay);	
	loadDelay = setTimeout(function() {$D('showing animation'); Element.show('requesting_data')}, 1000);
},
onComplete: function() {
	clearTimeout(loadDelay);	
	$D('hiding animation')
	Element.hide('requesting_data');
}
};
Ajax.Responders.register(myGlobalHandlers);

var searchPoints;
function goSearch() {
	var searchTerm = $F('mapSearch');
	
	if (searchTerm == "" || searchTerm == null) {
		displayMessage("Please enter a search term");
		return;
	}	
	
	
//	renderQueueClear();
//	clearCheckboxes();
//	clearRequests();
	
//	showOnce = true;
	
	var pars = sprintf('request=search&term=%s', searchTerm);

//	map.clearOverlays();
	Element.show('requesting_data');
	$D("SEARCH");
	ajaxSearchRequest = new Ajax.Request( "/map/MapsAjaxHandler.aspx", { method: 'get', onlyLatestOfClass: 'search', parameters: pars, onComplete: function(originalRequest) {																																							
		Element.hide('requesting_data');
		var response = originalRequest.responseText;
		$D("SEARCH RESULTS:"  + response)
		eval(sprintf('searchPoints = %s.compact()', response ));
		displayMessage(sprintf('Your search returned %d result%s.', searchPoints.length, (searchPoints.length == 1 ? '' : 's')));
		setSearchPoints(response);
		//generateMapItems();
		ajaxSearchRequest = null;
	  }
	});
}

function displayMessage(wMessage) {
	var searchResultsDiv = $('searchResultsMessage');
	searchResultsDiv.innerHTML = wMessage;
	searchResultsDiv.style.display = 'block';
	setTimeout(function() { searchResultsDiv.style.display='none'; }, 3000);	
}

function setSearchPoints() {	// parses searchPoints and sets them
	//if (mapHook) GEvent.removeListener(mapHook);	
	
	$D("generate search results");
	if (!searchPoints || searchPoints.length == 0) return;
	var bounds = new GLatLngBounds(searchPoints[0].Pos, searchPoints[0].Pos);

	searchPoints.each(function(item, index) {
		if (item)  {			
			var marker = createSearchMarker(item);
			bounds.extend(item.Pos);
			map.addOverlay(marker);
//			renderQueueAdd(item.UnitID, marker)		
			if (searchPoints.length == 1)
				GEvent.trigger(marker, "click");
		}
	}) 
	
	
	
//	map.setZoom(Math.min(Math.max(map.getBoundsZoomLevel(bounds), maxZoom),minZoom));
	map.setZoom(map.getBoundsZoomLevel(bounds));
	map.setCenter(bounds.getCenter());

	Element.hide('requesting_data');
	$D("generate search results done");
	registerMapMoveHook();

}


function createSearchMarker(unit) {    
	var point = unit.Pos;
	var pinLabel = unit.pinLabel;
	var html;
	html = sprintf("<iframe src='/map/mapWindow.aspx?unit=%s' width='290' height='170' scrolling='no' frameborder='0' class='segFrame'></iframe>", unit.UnitID);
//	html = sprintf("<iframe src='/byobmap/mapWindow.aspx?unit=%s' width='290' height='170' scrolling='no' frameborder='0' class='segFrame'></iframe>", unit.UnitID);
	
	var icon = new GIcon();
	icon.shadow =  "/assets/images/maps/map_icons/shadow.png";
	icon.iconSize = new GSize(23, 30);
	icon.shadowSize = new GSize(46, 31);
	icon.iconAnchor = new GPoint(6, 38);  

	icon.image = sprintf("/assets/images/maps/map_icons/06_general.png");
	//$D("createMapMarker: " +  icon.image);

	icon.infoWindowAnchor = new GPoint(10, 10);
	var marker = new GMarker(point,{ icon: icon, title: pinLabel } );
	if (html == null) return marker;
	
	GEvent.addListener(marker, "click", function() {		
		marker.openInfoWindowHtml(html);
		setRenderPause(3000)
	});
	GEvent.addListener(marker, "click", function() {		// remove hook when automatic repositioning
		removeMapMoveHook();
	});
	return marker;
}


// Creates a marker at the given point with the given number label
    function createMapMarker(unit,isByob,isLiquor, wCuisine) {    //wNum refers to the number of the item within the list
		var point = unit.Pos;
		var pinLabel = unit.pinLabel;
		var html;
		html = sprintf("<iframe src='/map/mapWindow.aspx?unit=%s' width='290' height='170' scrolling='no' frameborder='0' class='segFrame'></iframe>", unit.UnitID);
//		html = sprintf("<iframe src='/byobmap/mapWindow.aspx?unit=%s' width='290' height='170' scrolling='no' frameborder='0' class='segFrame'></iframe>", unit.UnitID);		
		
	
        var icon = new GIcon();


        if (isLiquor) {
            icon.image = "/assets/images/maps/pins/LiquorStore/pin.png";
            icon.shadow =  "/assets/images/soundabout/pins/segshadow.png";
            icon.iconSize = new GSize(31, 40);
            icon.shadowSize = new GSize(70, 55);
            icon.iconAnchor = new GPoint(16, 19);        
		}
        else if (isByob) {
            icon.image = "/assets/images/maps/pins/byob/pin" + wCuisine +  ".png";
            icon.shadow = "/assets/images/maps/pins/byob/shadow.png";
            icon.iconSize = new GSize(31, 40);
            icon.shadowSize = new GSize(70, 55);
            icon.iconAnchor = new GPoint(15, 33);
        }
        else {
            icon.image = "/assets/images/soundabout/pins/segpin.png";
            icon.shadow =  "/assets/images/soundabout/pins/segshadow.png";
            icon.iconSize = new GSize(31, 40);
            icon.shadowSize = new GSize(70, 55);
            icon.iconAnchor = new GPoint(6, 10);            
        }

        
        
        icon.infoWindowAnchor = new GPoint(10, 10);
      var marker = new GMarker(point,{ icon: icon, title: pinLabel } );
      if (html == null) return marker;

      GEvent.addListener(marker, "click", function() {
        marker.openInfoWindowHtml(html);
      });
      return marker;
    }
    
    var segmentWindows = [];
    var map = null;
    var centerPoint = null;
    var bounds = null;
    
 var cDrop;
var dropTimeout;
function showDrop(show, element) {
	if (cDrop != $(element))	hideDropNow(cDrop);		// hide any open menus	
	cDrop = $(element) || cDrop;
	if (!cDrop) return;
	window.clearTimeout(dropTimeout);	
	if (show) 
		cDrop.style.display = "block";
	else 
		dropTimeout = window.setTimeout(function() { hideDropNow(cDrop); },350);
}

    
function hideDropNow(obj) {
	if (!cDrop) cDrop = obj;
	if (!cDrop) return;
	clearTimeout(dropTimeout);
	cDrop.style.display = "none";
}
    
    function Gload() {
      if (GBrowserIsCompatible()) {
	  Element.hide('requesting_data');
        map = new GMap2(document.getElementById("map"));
        centerPoint = new GLatLng(39.9495, -75.1720) 
        map.setCenter(centerPoint);
        map.setZoom(15);
//        map.addControl(new GSmallMapControl());
		map.addControl(new GLargeMapControl());		
        var points = [ ];
        var bounds = new GLatLngBounds(centerPoint, centerPoint);
		
        generateMapItems();
      }
    }
    
    var bounds = null;
    function setPoints(cuisineID, units, isByob) {
        if (!GBrowserIsCompatible() || !units) return;
        var dateObj = new Date();
        units.each(function(unit, index) {
            if (!unit) return;
            bounds.extend(unit.Pos);
            map.addOverlay(createMapMarker(unit, isByob, !isByob, cuisineID));
        });
      var dateObj2 = new Date();
      $D(sprintf('setPoints(%s) took: %s', cuisineID, dateObj2-dateObj));
    }

    var currentMapPoints = {};
	var isStart = true
    function generateMapItems() {
		
	  if (isStart) {
	  	isStart = false;
		 var html = "<img src='/assets/images/maps/welcome.jpg' width='339' height='251'>";
		 var startPos = new GLatLng(40.100294113159144, -75.15657424926759) 
		 map.openInfoWindow(map.getCenter(),html);
		 return;
		}
	

      if (!GBrowserIsCompatible()) return;

      var selectedNeighborhood = $F('drpNeighboorhood')

      $D(sprintf('generateMapItems(%s)', selectedNeighborhood));
      if (typeof(currentMapPoints[selectedNeighborhood]) == "undefined") {
        $D('Requesting from server.');
        var pars = 'neighborhood=' + selectedNeighborhood;

        //$D('Parameters: ' + pars);
        new Ajax.Request( "/byobmap/MapsAjaxHandler.aspx", { method: 'get', parameters: pars, onComplete: function(originalRequest) {
          var response = originalRequest.responseText;
         $D(response)
          eval('currentMapPoints[selectedNeighborhood] = ' + response);
          setMapPoints(currentMapPoints[selectedNeighborhood]);
          }
        });
      }
      else
      {
        $D('Value from cache');
        setMapPoints(currentMapPoints[selectedNeighborhood]);
      }
    }
    
    function displayMsg(show) {
        var noItems = document.getElementById("noitems");
        if (noItems) {
            if (show) {
                noItems.style.display = 'block';
            }
            else {
                noItems.style.display = 'none';
            }
        }
    }
    
    var showAll = true;
    function toggleAll() {
        showDrop(true);
        showAll = !showAll;
        runAllInputs($('CuisineSelector2'), 'checkbox', function(obj) { obj.checked = showAll });
        setTimeout('generateMapItems();', 100);
		var showText = document.getElementById("showText");
		var showTextHTML;
		if (!showAll) showTextHTML = "Show All";
		else showTextHTML = "Hide All";
		showText.innerHTML = showTextHTML;
		
		
    }
	

		
    
    function setMapPoints(points) {


      var selectedCuisines = [];
      map.clearOverlays();
      var pointsLength = $H(points).keys().length
      $D('Points ' + pointsLength);
      if (pointsLength == 0)  resetMap();
      
	    displayMsg(pointsLength == 0);
      
      runAllInputs($('CuisineSelector2'), 'checkbox', function(obj) { selectedCuisines.push({ cuisine: obj.parentNode.attributes.getNamedItem("CuisineID").value, checked: obj.checked }); });
      bounds = new GLatLngBounds();
      selectedCuisines.each(function(item, index) {
        if (item) {
          if (item.checked)
            setPoints(item.cuisine, points[item.cuisine], true);
        }
      });
      
      setPoints(-1, points['LiquorStores'], false);
      
      $D(sprintf('ZoomLevel %s Center %s', map.getBoundsZoomLevel(bounds), bounds.getCenter()));
      if (bounds.isEmpty())
      { 
        resetMap();
        displayMsg(true);
        return;
      }

      map.setCenter(bounds.getCenter());
      map.setZoom(map.getBoundsZoomLevel(bounds));
    }
    function resetMap()
    {
        map.setCenter(centerPoint);
        map.setZoom(10);
    }
    