// JavaScript Document
function availscount() {
    var bounds = map.getBounds();
    var ne = bounds.getNorthEast();
    var sw = bounds.getSouthWest();
    var str = "nLat=" + Math.round(ne.lat() * 1000000)/1000000 + "&wLng=" + Math.round(sw.lng() * 1000000)/1000000 + "&ZOOM=" + map.getZoom() + "&sLat=" + Math.round(sw.lat() * 1000000)/1000000 + "&eLng=" + Math.round(ne.lng() * 1000000)/1000000 + "&" + __searchQuery; 
	var url = "/search/bin/index.php?overlord=fwCountBenches&" + str;

	$.ajax({
		url: url,
		cache: false,
		success: function(data) {
			updateCount(data);
		}
	});
}
function updateCount(response) {
	$("#gstatus").html("Showing <b>" + response + "</b> benches");
}
function getDistricts(id){
	if(id){
		$("#fwDistrict").html("<option>Loading...</option>");
		var coor=id.split(",");
		fwSetMapZoom(coor[1],coor[0],12);
		$.getJSON("/fwo.php",{overlord: "fwFillDistricts", id: coor[2] },function(j){
			var optn = '';
			optn += '<option value="">Select District</option>';
			for (var i = 0; i < j.length; i++) {
					optn += '<option value="' + j[i].id + '">' + j[i].name + '</option>';
			}
			$("#fwDistrict").empty();
			$("#fwDistrict").html(optn);
			$("#fwDistrict option:first").attr('selected', 'selected');
		});
	} else {
		$("#fwDistrict").empty();
		fwSetMapZoom("51.045","-114.057222",10);
		$("#gstatus").html("Zoom in to view available benches");
	}
	
}
function setSearchCriteria() {    
     var form = $('#avails');
    __searchQuery = form.serialize();	
}
function zoomDistricts(id){
	var coor=id.split(",");
	fwSetMapZoom(coor[1],coor[0],15);
}
function fwSetMapZoom(lat,lng,zoom){
	if(map.getZoom() == zoom) map.setCenter(new GLatLng(lat,lng), 12);
	else map.setCenter(new GLatLng(lat,lng), zoom);
}
function TBTileUrl(point,zoom) { 
	var ulp = new GPoint(point.x*256,point.y*256);
    var ul = G_NORMAL_MAP.getProjection().fromPixelToLatLng(ulp,zoom);
    var lrp = new GPoint((point.x*256)+255,(point.y*256)+255);
    var lr = G_NORMAL_MAP.getProjection().fromPixelToLatLng(lrp,zoom);
    var url = "" ;
    var tileUrl = "";
	
	 if(map.getZoom() > 11) {
        var url = "/search/bin/index.php?overlord=fwMapSearch&";
        var queryString = "nLat=" + Math.round(ul.lat() * 1000000)/1000000 + "&wLng=" + Math.round(ul.lng() * 1000000)/1000000 + "&ZOOM=" + zoom + "&sLat=" + Math.round(lr.lat() * 1000000)/1000000 + "&eLng=" + Math.round(lr.lng() * 1000000)/1000000  + "&" + __searchQuery;
		queueAjax(url + queryString,zoom,queryString);
    }
    return tileUrl;
}
function queueAjax(_url, _zoom, _key) {
	var a = {};
    a.url = _url;
    a.zoom = _zoom;
    a.key = _key;
    requestQueue.push(a);
	 if(interval == -1){
        interval = setInterval("executeAjax()",10);
    }
}
function executeAjax () {
    if(requestQueue.length == 0){
        clearInterval(interval);
        interval = -1;
        return;
    }
    if(inProgress < maxConcurrentRequests){
        var a = requestQueue.pop();
        if(a){
            if(a.zoom == map.getZoom()){
				$.getJSON(a.url,function(j){
					inProgress--;
					if(j) loadtb(j,a.zoom,a.key);
				});
                inProgress++;
            }
        }
    }    
}
function loadtb(r, zoom, key, clearOld) {
    var tbs = r.tbs;
    if(clearOld) {
        mgr.clearMarkers();
        delete(__loadedtb);
        __loadedtb = {};
    }
		if(tbs){
		   for(var ii = 0; ii < tbs.length; ii++) { 
				var tb = tbs[ii];                           
				var posn = new GLatLng(tb.location.lat,tb.location.lng);
				if(tb.id){
					var cachedtb = __loadedtb[tb.id];
					var newtb = null;
					if(!cachedtb) {
						newtb = {id:tb.id,minZoom:zoom};
					} else if (zoom < cachedtb.minZoom) {
						newtb = {id:tb.id,minZoom:zoom,maxZoom:cachedtb.minZoom--};
					}
					if (newtb) {
						__loadedtb[newtb.id] = newtb; 
						
						if(tb.package=="Y") {
							var marker = new GMarker(posn,{title: "Bench:" + tb.id + " \n " + tb.district +" \n "+ tb.intersection, icon:GetIcon(tb.icon)});
							marker.id = newtb.id;
						} else {
							var marker = new GMarker(posn,{title: "Bench:" + tb.id + " \n " + tb.district +" \n "+ tb.intersection + " \n\nClick icon to view more options", icon:GetIcon(tb.icon)});
							marker.id = newtb.id;
							marker.bid = tb.id;
							GEvent.addListener(marker, "click", function() {
									$("#gdetails").fadeIn("slow");
									showtb(this.id);  	
							 });
						}
						if(newtb.maxZoom) {
							mgr.addMarker(marker,newtb.minZoom,newtb.maxZoom);
						} else {
							mgr.addMarker(marker,newtb.minZoom);
						}
					}
				}
			} 
		}       
}
function showtb(id) {
    var url = "/search/bin/index.php?overlord=fwBenchDetails&@benchid=" + id;
	$.ajax({
		url: url,
		cache: false,
		success: function(data) {
			$("gdetails").corner("10px top");
			$("#gdetails").html(data);
			
			$("#closeDetails").click(function() {
				$("#gdetails").fadeOut("slow");
			});
			
			$("#reserveBench").click(function() {
				window.open("/search/bin/?overlord=fwReserve&@id="+$(this).attr("bid"),"_self");
			});
			
			$("#addBench").click(function() {
					var bid = $(this).attr("bid");
					if(!$("#fwReserveList").attr("bid")) $("#fwReserveList").attr("bid",bid);
					else $("#fwReserveList").attr("bid",$("#fwReserveList").attr("bid")+"-"+bid);
					
					if($("#gfavoritesTable tbody tr[id="+bid+"]").html()){
						alert("Bench already in your reservation list");
					} else {
						$.ajax({
							url: "/search/bin/?overlord=fwAddBench&@id="+bid,
							cache: false,
							success: function(data) {
								$("#gdetails").fadeOut("slow");
								$("#gfavoritesTable tbody").append(data);
								
								$(".gfavorites img").click(function() {
									$("#gfavoritesTable tbody tr[id="+$(this).attr("id")+"]").remove();
								});
							}
						});
					}
			});
			
			$("#zoomBenchIn").click(function() {
				_zoom = map.getZoom();
				if(_zoom==16) fwSetMapZoom($(this).attr("lat"),$(this).attr("lng"),13);
				else fwSetMapZoom($(this).attr("lat"),$(this).attr("lng"),16);
				
				if(_zoom==16) $(this).html("Zoom In");
				else $(this).html("Zoom Out");
			});
		}
	});

}
function GetIcon(ic){
	var tbIcon =new GIcon();
	tbIcon.image = "http://www.farwestoutdoor.com/search/i/" +ic +".png";
	tbIcon.iconSize=new GSize(10,10);
	tbIcon.iconAnchor=new GPoint(2,10);
	
	return tbIcon;

}
function showAddress(address) {
	__geoCoder.getLatLng(
	address,
	function(point) {
		if (!point) {
			alert(address + " not found");
		} else {
			map.setCenter(point, 15);
			var marker = new GMarker(point);
			map.addOverlay(marker);
			marker.openInfoWindowHtml(address +"<br><br>Click Icon to remove location from map");
			GEvent.addListener(marker, "click", function() {
				map.removeOverlay(this);	
		   });
		}
	}
  );

}
function filterMap(fl){
	setSearchCriteria();
	if(map.getZoom()>11 || fl==1){
	    $("#gstatus").html("Searching..");
		var bounds = map.getBounds();
		var ne = bounds.getNorthEast();
		var sw = bounds.getSouthWest();
		var str = "nLat=" + Math.round(ne.lat() * 1000000)/1000000 + "&wLng=" + Math.round(sw.lng() * 1000000)/1000000 + "&ZOOM=" + map.getZoom() + "&sLat=" + Math.round(sw.lat() * 1000000)/1000000 + "&eLng=" + Math.round(ne.lng() * 1000000)/1000000 + "&" + __searchQuery; 
		var url = "/search/bin/index.php?overlord=fwMapSearch&" + str;
		$.getJSON(url,function(j){
					if(j) loadtb(j,map.getZoom(),str,true);
				});
		availscount();
	} else {
		 $("#gstatus").html("Zoom in to view available benches");
	}
}