var gw;
var sarchMap;
var friendly_num = 1;
zoomlevels = {
	"unknown":1,
	"country":5,
	"state":6,
	"city":10,
	"zip":12,
	"zip+4":12,
	"street":12,
	"address":13
};

$(document).ready(function () {		
	load_main(27.76,-82.75,1);
	$('#examples').cluetip({width: '250px'});	
	$('#tips').cluetip({width: '250px'});	
			
	$("#btnGeocode").click(function() {	
		geocode();
		return false;		
	});	
	
	init_loc = $('#search_addr').val();
	if (init_loc) {
		geocode();
	}	

  /*
	$('.toggle_geowake').click(function() {
		if($(this).attr("checked")) {
			gw.AddOverlay();
		} else {
			gw.RemoveOverlay();
		}
	}); */
});

function geocode() {
	$(".error").remove();
						
	$.ajax({
		url: "/places",
		dataType: "json",
		type: "GET",
		data: { authenticity_token: $('#token').val(),
				full_address: $('#search_addr').val() },					
		beforeSend: function(xhr) {
			xhr.setRequestHeader("Accept", "application/json");				
		},
		success: function(json) {									
			success = json.success;
			if (success) {						
				lat = json.lat;
				lng = json.lng;	
				$('#search_lat').attr("value",lat);
				$('#search_lng').attr("value",lng);
				prec = json.precision;
				zoom = zoomlevels[prec] || 7;					
				load_main(lat,lng,zoom);												
			} else {
				$('.container').prepend("<div class='error'>The location could not be found.  Please try again.</div>");
			}
        }
	});
}

function load_main(lat,lng,zoom) {
	if (GBrowserIsCompatible()) {    	
		map = new GMap2(document.getElementById("search_map"), { size: new GSize(590,400) });	
		var center = new GLatLng(lat,lng); 
		map.setCenter(center, zoom);				  	
		map.setMapType(G_HYBRID_MAP);
		var topLeft1 = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(10,40))
		map.addControl(new GSmallMapControl(), topLeft1);	
		var topLeft2 = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(10,10));
		map.addControl(new GMapTypeControl(), topLeft2);
		
		if (zoom > 1) {			
			fetch_for_bounds(map);	
		}
        
		GEvent.addListener(map, "moveend", function() {
		  var gbounds = map.getBounds();
		  fetch_for_bounds(map);
		});	
    
    //geowake
    /*
    gw = new gWake(map,"full");
    gw.AddOverlay(true);
    gw.updateOnMove(); */			
	}
}

function fetch_for_bounds(m) {
	var bnd = m.getBounds().toString();	
	$.ajax({
		url: "/slips",
		dataType: "json",
		type: "GET",
		data: { bounds:bnd },					
		beforeSend: function(xhr) {
			xhr.setRequestHeader("Accept", "application/json");				
		},
		success: function(json) {									
      friendly_num = 1;
			$('#listings').empty();
			for (var i = 0; i < json.length; i++) {										
				id = json[i].id;
				title = json[i].title;
				lat = json[i].lat;
				lng = json[i].lng;
				latlng = new GLatLng(lat,lng);
		
				//Map
				var icon = new GIcon();
				icon.image = '/images/greencircle.png';
				icon.iconSize = new GSize(32, 32);
				icon.iconAnchor = new GPoint(16, 16);
				icon.infoWindowAnchor = new GPoint(25, 7);
		
				opts = {
					"pk": id,
					"fid": friendly_num,
					"icon": icon,
					"clickable": true,
					"title": title,
					"labelText": friendly_num.toString(),
					"labelOffset": new GSize(-4, -10)
				};
				var marker = new LabeledMarker(latlng, opts);
        var handler = createMarkerClickHandler(id);
		
				GEvent.addListener(marker, "click", handler); 
				m.addOverlay(marker);
				
				//render row-view slip partial
        load_row_partial(id, friendly_num);
				
				friendly_num += 1;				
			}							

      //dislay summary
			count = friendly_num - 1;
			msg = "";
			if (count == 0) {
				msg = "No listings were found in this area.  Click the minus button on the map to search a larger area or try a different search.";				
        $('#msg').html("<p>" + msg + "</p>");				
			} else {
				listword = (count == 1 ? ' listing' : ' listings');
				msg = count + listword + " found";
        $('#msg').html("<h3>" + msg + "</h3>");				
			}
		}
	  });	
}

function createMarkerClickHandler(id) {
  return function() {
    window.location.href = "/slips/" + id;
  };
}

function load_row_partial(id, friendly_num) {
	$.ajax({		
		url: "/slips/" + id,
		dataType: "html",
		type: "GET",
		data: { row_view:true,
            friendly_id:friendly_num },					
		beforeSend: function(xhr) {
			xhr.setRequestHeader("Accept", "text/html");				
		},
		success: function(html) {	
      //append in the correct order (according to friendly_num)
			var alisting = '<div class="listing" id=\"' + friendly_num + '">' + html + '</div>';
      sortedInsert('#listings','#listings .listing',alisting,friendly_num);
    }
	});			
}

//custom sort function to add asynchronous 
//elements in sorted order by id
function sortedInsert(container,selector,element,id) {
  var insertAfter = null;
  $(selector).each(function(i) {
    var curEl = $(selector+":eq(" + i + ")");
    var curId = curEl.attr("id");
    if (id > curId) {
      insertAfter = curEl;
    }
  });

  if (insertAfter != null) {
    insertAfter.after(element);
  } else {
    //first element
    $(container).prepend(element);
  }
}
