//usually in acl-general.js
function $id(sId) { return document.getElementById(sId); }
if (!window['acldefined']) {var acl={};window['acldefined']=true;};//only set the acl namespace once, then set a flag
acl.r=function(s){window.location=s};
String.prototype.format = function() {
	var s = this;
	for (var i=0; i < arguments.length; i++){
		s = s.replace("{" + (i) + "}", arguments[i]);
	}
	return(s);
};
var jslog = {debug:function(){},info:function(){}, 
	warning:function(){}, error:function(){},
	text:function(){}}; var debug=function(){};
if (location.href.match(/enablejslog/)){
		document.write('<script type="text/javascript" src="http://earthcode.com/includes/scripts/jslog.js"></script>');};	

var G_baseIcon = '';
var G_shopsLoaded={};
var G_clusterer = null;

$(document).ready(function(){
  $('#search-input').focus(function(){$(this).val('').unfocus()});
});

/*------------------------------------------------------------------------------*/
/* review functions */
// show the form
function showReviewForm() {
	$('#review-area').addClass("show-form");
	//$('#review-textarea').focus();
  jslog.debug("showReviewForm");
}

function checkReviewForm(){
  if ($id("review_author").value.trim() == '') {
    alert("Please provide a name");
    return false;
  }
}

// cancel review form
function discardReview() {
  if (confirm("Really discard this review?")) {
	  $id('review-area').className='';
	  $('#review-form').value="";
  }
}

/*------------------------------------------------------------------------------*/
/* rating-related functions */
function rateCafe(nRatingId,nRating){
	// show a spinner
  $("#rating-spinner-"+nRatingId).show();
	$("#rater_"+nRatingId).html("");
	//AJAX
	$.post(G_urls.rateShop,{
		rating_id: nRatingId,
		rating: nRating
    },function(sResponse){
      $("#rating-wrapper-"+nRatingId).html(sResponse);
  });  	
}

function rateHover(nRatingId,sText){
  $id("rater_"+nRatingId+"_choicetext").innerHTML=sText;
}

/*------------------------------------------------------------------------------*/
/* map page functions */
function createMarker(point,html,id,name,wirelessIsFree) {
	//for custom icons
	var icon = new GIcon(G_baseIcon);
	icon.image=wirelessIsFree?"/images/teardrop-green.png":"/images/teardrop-dollar.png";
	//var marker = new PdMarker(point,icon);
	//marker.setTooltip(name);
	//marker.setOpacity(70);
	var marker=new GMarker(point,{icon:icon,title:name});
	
	GEvent.addListener(marker, "click", function() {
	  marker.openInfoWindowHtml(getDetailHTML(id));
	});
	
	GEvent.addListener(marker, "mouseover", function() {
	  
	});

	
	oMarkers[id] = marker;
  return marker;
}

function getDetailHTML(id){
  return htmls[id];
}
  
function markerClick(id) {
  oMarkers[id].openInfoWindowHtml(htmls[id]);
}

function mapDetail(id) {
  oMap.showMapBlowup(oMarkers[id].getPoint(),{mapType:G_HYBRID_MAP,zoomLevel:18});
}

function zoomTo(lat,lng,zoom) {
  if (zoom==null) zoom=oMap.getZoom()+3;
  oMap.setCenter(new GLatLng(lat,lng),zoom);
}

function createLargeMap(lat,lng,nZoom,bSearchResults) {
  G_tabs= [
    new GInfoWindowTab("Info", "This is tab #1 content"),
    new GInfoWindowTab("Ratings", "This is tab #2 content"),
    new GInfoWindowTab("Reviews", "This is tab #3 content")];
    
  G_baseIcon=new GIcon();
  G_baseIcon.iconSize = new GSize(20, 34);
  G_baseIcon.iconAnchor = new GPoint(9, 34);
  G_baseIcon.infoWindowAnchor = new GPoint(9, 2);

 
  G_baseIcon.shadowSize = new GSize(37, 34);
  G_baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
  G_baseIcon.infoShadowAnchor = new GPoint(18, 25);    
  
	oMap = new GMap2($id("large-google-map"));
	oMap.addControl(new GSmallMapControl());
	oMap.addControl(new GMapTypeControl());
	oMap.addControl(new GScaleControl());
	oMap.addControl(new GOverviewMapControl());
  oMap.setCenter(new GLatLng(lat,lng), nZoom);

  clusterIcon=new GIcon();
  clusterIcon.image = "/images/map/cluster.png";
  clusterIcon.shadow = "/images/map/cluster_shadow.png";
  clusterIcon.iconSize = new GSize(63.0, 75.0);
  clusterIcon.shadowSize = new GSize(101.0, 75.0);
  clusterIcon.iconAnchor = new GPoint(31.0, 37.0);
  clusterIcon.infoWindowAnchor = new GPoint(31.0, 37.0);

  G_clusterer = new Clusterer(oMap);
  G_clusterer.SetIcon(clusterIcon);
  
  //G_clusterer.SetMaxVisibleMarkers(120);
	
	if (bSearchResults) {
  	// if this is search results, add the shops and bound the map
    var bounds = new GLatLngBounds();
  	for (i=0;i<aShops.length;i++) {
      var marker=addShop(aShops[i]);
      bounds.extend(marker.getPoint()); //only used for search results mode
  	}
    oMap.setZoom(oMap.getBoundsZoomLevel(bounds));
    var clat = (bounds.getNorthEast().lat() + bounds.getSouthWest().lat()) /2;
    var clng = (bounds.getNorthEast().lng() + bounds.getSouthWest().lng()) /2;
    oMap.setCenter(new GLatLng(clat,clng));  
	} else {
  	// load any additional shops that are in the current view
  	loadShopsInView();
    GEvent.addListener(oMap, "moveend", function() {
    	loadShopsInView();
    });
  }
}

function addShop(oShop){
  sDisplay="<div class='map-balloon'><strong>"+oShop.name+
		"</strong><br /> "+oShop.full_address +
		"<br />&nbsp;&nbsp;<a href='javascript:mapDetail("+oShop.id+")'><img width='12' height='12' src='/images/zoom-in.gif' />closeup map</a>"+
		"<br />&nbsp;&nbsp;<a href='"+G_urls.showShop+"/"+oShop.id+"'><img width='12' height='12' src='/images/icon-about.gif' /> see full listing &raquo;</a>"+
    "</div>";
  htmls[oShop.id]=sDisplay;
  G_shopsLoaded[oShop.id]=true;
	var oMarker = createMarker(new GLatLng(oShop.lat,oShop.lng),sDisplay,oShop.id,oShop.name,oShop.wireless_is_free);
  G_clusterer.AddMarker(oMarker, oShop.name);
  //oMap.addOverlay(oMarker);
  debug("finished addShop for "+oShop.name);
  return oMarker;
}

/* HACKING: shop.to_json returns boolean as "1" string, whereas my own shop rendering produces true/false*/
function loadShopsInView() {
  $('#map-loading-indicator').show();
  ne = oMap.getBounds().getNorthEast();
  sw = oMap.getBounds().getSouthWest();
  GDownloadUrl(G_urls.map_data+"?ne="+ne.toUrlValue()+"&sw="+sw.toUrlValue(), function(data, responseCode) {
    spots=eval('('+data+')');
    for (i=0;i<spots.length;i++) {
      s=spots[i];
      s.wireless_is_free = (s.wireless_is_free=='1')? true : false; 
      if (G_shopsLoaded[s.id]!=true) {
        addShop(s);   
      }
    }
  $('#map-loading-indicator').hide();    
  });
}

/* For displaying all the cities  */
function initCitiesMap() {
	oMap = new GMap2($id("cities-map"));

	oMap.addControl(new GSmallMapControl());
  oMap.setCenter(new GLatLng(39.7,-99.6), 3);

	for (i=0;i<cities.length;i++) {
    oMarker=createCityMarker(cities[i],i+1);
    oMap.addOverlay(oMarker);
	}
  // now that map is zoomed to bounds at the smaller size, open it up a bit
  $('#cities-map').css('height','600px')
}

//called by initCountryMap
function createCityMarker(city,rank){
  marker = new PdMarker(new GLatLng (city.lat, city.lng ));
  marker.setTooltip(city.name);
  marker.setOpacity(80);
  
  GEvent.addListener(marker, "click", function() {
    document.location=G_urls.city+'/'+city.link;
	});
	
	return marker;
}

/* for displaying the Cafes for a specific city */
function initCityMap(oCity){
	map = new GMap2($id("large-google-map"));
	map.addControl(new GLargeMapControl ());
  map.setCenter(new GLatLng(oCity.lat,oCity.lng), oCity.nZoom);
  marker = new PdMarker(new GLatLng (oCity.lat, oCity.lng ));
  map.addOverlay(marker);
  GEvent.addListener(map, "moveend", function() {
    var center = map.getCenter();
    $id("city_latitude").value = center.lat();
    $id("city_longitude").value = center.lng();
    $id("city_latitude_display").innerHTML = center.lat();
    $id("city_longitude_display").innerHTML = center.lng();
  });  
  GEvent.addListener(map, "zoomend", function(nOld,nNew) {
    $id("city_map_zoom").value = nNew;
    $id("city_map_zoom_display").innerHTML = nNew;    
  });  
}

/*------------------------------------------------------------------------- */
/* Initializes a small map for shop edit and show. Expects oShopLocation to be set up in the main page */
function initSmallMap(oShop) {
  oMap = new GMap2($id("small-google-map"));
  oMap.addControl(new GSmallMapControl());
  oLatLng = new GLatLng (oShop.lat, oShop.lng );
  oMap.setCenter(oLatLng, 15);    
  oMarker = new PdMarker(oLatLng);
  oMarker.setTooltip(oShop.sName);
  oMarker.setOpacity(70);  
  oMap.addOverlay(oMarker);
  // TODO: add other shops in view with small markers
}
  
function initSmallMapNewShop(oCity){  
  oMap = new GMap2($id("small-google-map"));
  oMap.addControl(new GSmallMapControl());
  oMap.setCenter(new GLatLng(oCity.lat,oCity.lng), oCity.nZoom);
}

// Called from the create button on the form
// G_bValidGeocode is set when the page renders, and also when the address is changed/checked
function addressKeyup(sValue) {
  if (sValue == G_sKnownGoodAddress && G_sKnownGoodAddress != '') {
    $("#address-container").attr('class','address-good');
  } else {
    $("#address-container").attr('class','address-unsure');
  }
}

function addressKeypress(e) {
  if (!e) e=window.event;
  if (e.keyCode==13) {
    checkAddress(); 
    e.cancelBubble = true;
    if (e.stopPropagation) e.stopPropagation();
    return false;
  }
}

function checkAddressForSubmit() {
  bRes=G_bValidGeocode;
	if(!G_bValidGeocode){
		alert("Please validate the address by clicking on the 'check address' button.");
	} else if ($('#shop_full_address').val() != G_sKnownGoodAddress) {
		alert("You've changed the address since it was validated. Plase click 'check address' to validate the address.");   
		bRes=false;
	}
	return bRes;
}

// called from the check address button
function checkAddress(){
  oAddress=$id("shop_full_address");
	oAddress.disabled=true;
	sAddress=oAddress.value;
	
	$('#check_address_button').css('display','none');
	$('#check_address_working').css('display','inline');
	
	debug("checking "+sAddress);
	$.post(G_urls.validateAddress,{
	  address: sAddress
	},parseAddressJSON);    
}

function parseAddressJSON (sResult){
	$('#check_address_button').css('display','inline');
	$('#check_address_working').css('display','none');
	$id("shop_full_address").disabled=false;
	
	var bRes=false;
	var bValid = false;
	var oRes={};
	try {
		var oRes = eval('(' + sResult + ')');
		if (oRes.success) {
	    bValid = true;
		}
	} catch (e) {
		 jslog.warning("check address: failed to parse JSON resuls: "+sResult);
	}

	if (bValid) {
		debug("validated the address from geocoding. City name="+oRes.city);
		if (oRes.duplicate_listing !=null) {
		  var txt="We already have <a style='font-weight:bold' href='{0}'>{1}</a> listed at <strong>{2}</strong>. Please only reuse this address if there is a good reason (for example, if the location is a mall with multiple shops at a single address).".format(G_urls.showShop+'/'+oRes.duplicate_listing.id, oRes.duplicate_listing.name, oRes.full_address);
		  $('#duplicate-address-message').html(txt).css({display:'block'});
		} else {
		  $('#duplicate-address-message').css('display','none');
		} 
		$('#shop_lng').val(oRes.lng);
		$('#shop_lat').val(oRes.lat);
		$('#shop_full_address').val(oRes.full_address);
		$('#shop_city_name').val(oRes.city);		
		$('#shop_state').val(oRes.state);
		$('#shop_zipcode').val(oRes.zip);
		$('#shop_country_code').val(oRes.country_code);

		$('#map-message, #map-cover').css('display','none');
		$("#address-container").attr('class','address-good');
		G_bValidGeocode=true;
		$('#shop_full_address').val(oRes.full_address);
		G_sKnownGoodAddress=oRes.full_address;

		oLatLng = new GLatLng (oRes.lat, oRes.lng );
		oMap.setCenter(oLatLng,15);
		
		if (oMarker != null){
			oMap.removeOverlay(oMarker);
		} 
	  oMarker = new PdMarker(oLatLng);
	  oMarker.setTooltip($("#shop_name").val());
	  oMarker.setOpacity(70);  
		oMap.addOverlay(oMarker);             
	
	  bRes=true;
	  debug("done generating map");
	  
	} else {
		$('#map-message, #map-cover').css('display','block');
		$("#map-message").html("Could not validate the address. Please check the address and try again. Include the full address, including city/state or zip code.").css({backgroundColor:'yellow',fontWeight:'bold'});
	  debug("Problem validating address, JSON="+oRes);
		$("#address-container").attr('class','address-warning');	  
	}
  return bRes;
}
