(function ($) {

$(function () {
	$(".agm_google_maps").each(function () {
		var $me = $(this),
			$cache = $me.find(".mlm-cached,.agm_google_maps-loading_message")
		;

		if (!$cache.length) return true;
		if ($cache.is(".mlm-cached")) {
			$me.addClass("agm-mlm-cached_map");
		} else {
			$me.attr("data-mlm-cache-key", $cache.attr("data-mlm-cache-key"));
		}
	});
});

$(document).on("agm_google_maps-user-map_initialized", function (e, map, data) {
	var $map = $(map.getDiv()).closest(".agm_google_maps");
	if ($map.is(".agm-mlm-cached_map")) return false;

	google.maps.event.addListener(map, "tilesloaded", function () {
		var $parent = $(map.getDiv()).closest(".agm_google_maps");
		if (!$parent.length) return false;

		var $pc = $parent.clone();
		$pc.find(".agm_mh_container,.agm_panoramio_container").remove();
		var $map = $("<div />").append($pc);
		$.post(_agm.ajax_url, {
			action: "agm-mlm-store-cache",
			map_id: data.id,
			cache: $map.html(),
			key: $parent.attr("data-mlm-cache-key")
		});
	});
});
})(jQuery);