/* 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 that = this;
	var container = $(this.map.getContainer());
	container.append($("<div/>", {
		id: 'map-type',
		title: 'Показать спутниковую фотографию'
	}).click(function() {
		that.toggleType();
	}));
	container.append($('<div id="zoom-in"></div>').click(function() {
		if (that.map.getZoom() < 18) {
			that.map.zoomIn()
		}
	}));
	container.append($('<div id="zoom-out"></div>').click(function() {
		if (that.map.getZoom() > 14) {
			that.map.zoomOut();
		}
	}));
	GEvent.addListener(this.map, 'zoomend', function() {
		that.updateZoom();
	});
	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();
	$("#zoom-in", context).toggleClass("disabled", zoom >= 18);
	$("#zoom-out", context).toggleClass("disabled", zoom <= 14);
	if (zoom >= 18) {
		this.map.disableDoubleClickZoom();
	} else {
		this.map.enableDoubleClickZoom();
	}
},
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(18, 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 */
init.facts = function () {
	var form = $('#new-fact').submit(function(event) {
		event.preventDefault();
		if (this.title.value) {
			addAjax.send({
				pid: this.pid.value,
				title: this.title.value.capitalize(),
				pm: this.pm.value
			});
		} else {
			$(this.title).focus();
		}
	});
	var update = function(s) {
		var content = $(s), frame = $('#' + content.attr('id'));
		frame.find('.facts').replaceWith(content.html());
	};
	var addAjax = ajax('fact/create', {
		control: form.find('.smart-button').smartButton(),
        process: function(s) {
            form.hide();
            update(s);
        }
	});
	$('#pfacts, #mfacts').delegate('.vote', 'click', function() {
		var el = $(this);
		ajax('fact/vote', update).send({
			pm: el.closest('.facts').attr('data-type'),
			fid: el.attr('data-fid')
		});
	}).delegate('.add .link', 'click', function() {
		var list = $(this).closest('.facts'), type = list.attr('data-type');
		form.hide().prev('.section').children('.add').show();
		form.find('h5').html('Новый ' + (type == 'p' ? 'плюс' : 'минус'));
		list.find('.add').hide();
		form.insertAfter(list).show();
		$(form.get(0).pm).val(type);
		$(form.get(0).title).val('').focus();
	});
}

/* Comments */
var commentsList = {
init: function(pid) {
	this.pid = pid;
	this.loading = false;
	this.activate();
	var that = this;
	this.fasten = function() {
		$(this).css('height', 'auto').children('.slider').removeClass('slider');
		if ($('.load-more', that.context).is(':hidden')) {
			$('.loader', that.context).hide();
		}
		that.loading = false;		
	};
},
activate: function() {
	var self = this;
	this.context = $('#comments');
	this.context.find('.loader .link').click(function() {
		if (self.loading) return false;
		self.load($(this).parent());
	}).parent().bind('send', function() {
		$(this).addClass('loading');
	}).bind('error success', function() {
		$(this).removeClass('loading');
	});
},
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);
		this.context.find('.load-more .link').html('Показать ещё ' + (more < 10 ? more : 10));
	} else {
		amount.html('Всего ' + loaded.inflect('комментарий', 'комментария', 'комментариев'));
		this.context.find('.load-more, .load-all').hide();
	}
},
load: function(el) {
	var self = this;
	ajax('comment/get', {
        control: el,
        process: function(s) {
            self.add(s)
        }
	}).send({
		pid: this.pid,
		before_cid: $('dl.comment', this.context).eq(0).attr('id').substr(1),
		load_all: el.hasClass('load-all') ? 1 : 0
	});
	this.loading = true;
},
add: function(s) {
	var group = $(s).css('height', 10);
	this.context.find('.group').eq(0).before(group);
	var h = group.find('.slider').height();
	var time = Math.min(Math.round(h / 3), 1500);
	group.animate({height: h}, time, 'linear', this.fasten);
	this.update();
}
};

var commentsForm = {
init: function(pid) {
	var that = this;
	this.pid = pid;
	this.el = $('#new-comment').submit(function(event) {
        event.preventDefault();
        that.send();
    });
	this.createAjax = ajax('comment/create', {
    	control: this.el.find('.submit .smart-button').smartButton(),
        title: 'Сохранение комментария…',
        process: function(s) {
        	$('#comments').replaceWith(s);
        	commentsList.activate();
        	that.fields.comment.value = '';
        	that.recognize();
        }
    });
	$('.rename span', this.el).click(function() {
		that.rename()
    });
    this.fields = this.el.get(0);
	this.recognize();
},
send: function() {
    var f = this.el.get(0);
	if (f.comment.value) {
		this.createAjax.send({
			pid: this.pid,
			author: f.author.value,
			content: f.comment.value
		});
	} else {
		$(f.comment).focus();
	}
},
recognize: function() {
	var author = this.fields.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.fields.author).focus();
},
appeal: function(obj) {
	var field = $(this.fields.comment);
	field.focus().val($(obj).text() + ', ' + field.val());
}
};

init.children = function() {
	var list = $('#children.majors');
	if (list.length) {
		var items = list.find('li');
		var limit = Math.min(7, items.length);
		items.not('.major').slice(0, limit - items.filter('.major').length).addClass('major');
	}
};

