/* Map */
var googleMap = {
init: function(data) {
	this.el = $("#gmap");
	this.place = data && data.place;
	this.station = data && data.station;
	this.map = new GMap2($(".box", this.el).get(0), {backgroundColor: "#eeebe4"});
	this.icon = new GIcon({
		image: "/app/gmap/pin.png",
		iconSize: new GSize(17, 41),
		iconAnchor: new GPoint(8, 35),
		shadow: "/app/gmap/shadow.png",
		dragCrossImage: "/app/gmap/sight.png",
		dragCrossSize: new GSize(7, 39),
		dragCrossAnchor: new GPoint(3, 35),
		maxHeight: 20
	});
	var container = $(this.map.getContainer());
	container.append($("<div/>").attr("id", "map-type").attr("title", "Показать спутниковую фотографию").click(this.toggleType.use(this)));
	container.append($("<div/>").attr("id", "zoom-in").click(this.zoomIn.use(this)));
	container.append($("<div/>").attr("id", "zoom-out").click(this.zoomOut.use(this)));
	GEvent.addListener(this.map, "zoomend", this.updateZoom.use(this));
	this.reset();
},
reset: function() {
	this.map.clearOverlays();
	if (this.station) {
		this.map.enableDragging();
		this.map.enableDoubleClickZoom();
		if (this.place) {
			this.map.setCenter(this.getMiddle(), this.getOptimalZoom());
			this.addMarker(this.place);
		} else {
			this.map.setCenter(this.station, 15);
		}
		this.el.addClass("active");
	} else {
		this.el.removeClass("active");
		this.map.disableDragging();
		this.map.disableDoubleClickZoom();
		this.map.setCenter(new GLatLng(55.751463, 37.621651), 11);
	}
},
toggleType: function() {
	var isNormal = (this.map.getCurrentMapType() == G_NORMAL_MAP);
	this.map.setMapType(isNormal ? G_SATELLITE_MAP : G_NORMAL_MAP);
	$("#map-type").toggleClass("satellite", isNormal).attr("title", isNormal ? "Показать карту" : "Показать спутниковую фотографию");
	$("#logocontrol").toggleClass("satellite", isNormal);
	this.updateZoom();
},
updateZoom: function() {
	var context = this.map.getContainer(), zoom = this.map.getZoom();
	var maxZoom = (this.map.getCurrentMapType() == G_NORMAL_MAP) ? 17 : 18;
	$("#zoom-in", context).toggleClass("disabled", zoom >= maxZoom);
	$("#zoom-out", context).toggleClass("disabled", zoom <= 14);
	if (zoom >= maxZoom) {
		this.map.disableDoubleClickZoom();
	} else {
		this.map.enableDoubleClickZoom();
	}
},
zoomIn: function() {
	var maxZoom = (this.map.getCurrentMapType() == G_NORMAL_MAP) ? 17 : 18;
	if (this.map.getZoom() < maxZoom) this.map.zoomIn()
},
zoomOut: function() {
	if (this.map.getZoom() > 14) this.map.zoomOut();
},
getOptimalZoom: function() {
	var bounds = new GLatLngBounds();
	var slat = this.station.lat(), slng = this.station.lng();
	var plat = this.place.lat(), plng = this.place.lng();
	bounds.extend(new GLatLng(plat * 1.5 - slat * 0.5, plng * 1.5 - slng * 0.5));
	bounds.extend(this.station);
	return Math.min(17, this.map.getBoundsZoomLevel(bounds));
},
getMiddle: function() {
	var lat = (this.station.lat() + this.place.lat()) / 2;
	var lng = (this.station.lng() + this.place.lng()) / 2;
	return new GLatLng(lat, lng);
},
addMarker: function(latlng) {
	this.marker = new GMarker(latlng, {icon: this.icon});
	this.map.addOverlay(this.marker);
}
};

/* Facts */
function newFact(pm) {
	var el = $("#new-fact").hide(), facts = $("#" + pm + "facts");
	el.prev(".section").children(".add").show();
	$("h5", el).html(pm == "p" ? "Новый плюс" : "Новый минус");
	$(".add", facts).hide();
	var form = el.appendTo(facts).show().get(0);
	$(form.pm).val(pm);
	$(form.title).val("").focus();
}
function createFact() {
	var form = $("#new-fact").get(0);
	if (form.title.value) {
		ajaxFor("create_fact").send({
			pid: form.pid.value,
			pm: form.pm.value,
			title: form.title.value
		}, {
			control: $(".ajax-control input", form),
			state: $(".ajax-control .state", form)
		});
	}
}
function updateFacts(s) {
	var content = $(s), id = content.attr("id");
	$("#" + id + " .facts").replaceWith(content.html());
}
setAjaxFor("create_fact", function(s) {
	$("#new-fact").hide();
	updateFacts(s);
});
setAjaxFor("vote_fact", updateFacts);

/* Comments */
var commentsList = {
init: function(pid) {
	this.pid = pid;
	setAjaxFor("get_comments", this.add.use(this));
	this.loading = false;
	this.activate();
},
activate: function() {
	this.context = $("#comments");
	var f = this.load.use(this);
	$(".load-more span", this.context).click(f);
	$(".load-all span", this.context).click(f);
},
update: function() {
	var amount = $(".amount", this.context);
	var total = parseInt(amount.html().split(" ").last());
	var loaded = $(".comment", this.context).length;
	var more = total - loaded;
	if (more > 0) {
		amount.html(loaded.inflect("последний комментарий", "последних комментария", "последних комментариев") + " из " + total);
		$(".load-more span", this.context).html("Показать ещё " + (more < 10 ? more : 10));
	} else {
		amount.html("Всего " + loaded.inflect("комментарий", "комментария", "комментариев"));
		$(".load-more", this.context).hide();
		$(".load-all", this.context).hide();
	}
},
load: function(e) {
	if (this.loading) return false;
	var link = e.target;
	ajaxFor("get_comments").send({
		pid: this.pid,
		before_cid: $("dl.comment", this.context).eq(0).attr("id").substr(1),
		load_all: $(link).parent().hasClass(".load-all") ? 1 : 0
	}, {
		control: link,
		state: $(link).next(".state")
	});
	this.loading = true;
},
add: function(s) {
	var group = $(s).css("height", 10);
	$(".group", this.context).eq(0).before(group);
	var h = $(".slider", group).height();
	var time = Math.min(Math.round(h / 2), 1500);
	group.animate({height: h}, time, "linear", deactivateSlider);
	this.update();
}
};
function deactivateSlider() {
	var cl = commentsList;
	$(this).css("height", "auto").children(".slider").removeClass("slider");
	if ($(".load-more", cl.context).is(":hidden")) {
		$(".loader", cl.context).hide();
	}
	cl.loading = false;		
}

var commentsForm = {
init: function(pid) {
	this.pid = pid;
	this.el = $("#new-comment").submit(this.send.use(this)).get(0);
	$(".rename span", this.el).click(this.rename.use(this));
	this.recognize();
},
send: function(e) {
	e.preventDefault();
	if (!this.el["comment"].value) return false;
	ajaxFor("create_comment").send({
		pid: this.pid,
		author: this.el["author"].value,
		comment: this.el["comment"].value
	}, {
		control: $(":submit", this.el),
		state: $(".state", this.el)
	});
},
recognize: function() {
	var author = this.el["author"].value;
	if (author) {
		$(".author", this.el).addClass("hidden", Boolean(author));
		$(".rename", this.el).show().prev().html("Ваш комментарий, " + author);
	}
},
rename: function() {
	$(".author", this.el).removeClass("hidden");
	$(".rename", this.el).hide().prev().html("Ваш комментарий");
	$(this.el["author"]).focus();
},
appeal: function(obj) {
	var f = this.el["comment"];
	$(f).focus().val($(obj).text() + ", " + f.value);
}
};
setAjaxFor("create_comment", function(s) {
	$("#comments").replaceWith(s);
	commentsList.activate();
	commentsForm.el.comment.value = "";
	commentsForm.recognize();
});

function showChildren() {
	var list = $("#children");
	if (list && list.hasClass("majors")) {
		var limit = Math.min(7, $("li", list).length);
		while ($("li.major").length < limit) {
			$($("li:not(.major)", list).get().random()).addClass("major");
		}
}
}
