var afisha = {
	loading:	false,
	root:		'',
	showSeance: function(id, veid, vpid){
		$(".seance_sel", $(id).parent()).each(function(){
			$(this).removeClass("seance_sel");
		});
		var td = $("td", $(id).parent().parent().next());
		var div = $("div", td);
		if ( div.css('display') == 'block' ) {
			div.slideUp('fast', function() {
				div.empty();
			});
		} else {
			div.slideUp('fast', function() {
				$.ajax({
					url: ".",
					type: "POST",
					dataType: "json",
					mode: 'abort',
					port: 'seances',
					data: {
						action: "get_seances",
						eid: veid,
						pid: vpid
					},
					success: function(json){
						if (json.success){
							div.html(json.html);
							$(id).addClass("seance_sel");
							div.slideDown('slow');
						} else {
							alert(json.html);
							div.hide();
						}
					},
					error: function(){
						alert("Ошибка запроса!");
					}
				});
			});
		}
	},

	search: function(url) {
		if ( this.loading )
			return false;

		if ( $.browser.msie ) {
			$('#afisha_search').html('<br/>');
			$('#afisha_events').html('<br/>');
		} else {
			$('#afisha_search').fadeTo("fast", 0.2);
			$('#afisha_events').fadeTo("fast", 0.2);
		}

		$('#afisha_events').append($('<div class="loading_message" style="display:block;">Загрузка...</div>'));

		this.loading = true;
		var self = this;

		$.ajax({
			url: url,
			type: 'POST',
			dataType: 'json',
			data: {
				action: 'get_block',
				name: 'search'
			},
			success: function(data) {
				self.loading = false;

				if ( data.success ) {
					if ( data.events ) {
						$('#afisha_events').replaceWith(data.events);
					}
					if ( data.search ) {
						$('#afisha_search').replaceWith(data.search);
					}
				}
				else
					document.location.href = url;

				if (typeof Backbone == "object") {
					$('A.ajaxrequest').click(function() {
						return afisha.requestHandler(this);
					});
				} else {
					$('A.ajaxrequest').click(function(){
						afisha.search(this.href);
						return false;
					});
				}

				if ( !$.browser.msie ) {
					$('#afisha_search').fadeIn("fast");
					$('#afisha_events').fadeIn("fast");
				}
			},
			failed: function() {
				document.location.href = url;
			}
		});
	},

	requestHandler: function(e) {
		var path = $(e).attr('href');
		if ( path.indexOf(afisha.root) >= 0 )
			path = path.substr(path.indexOf(afisha.root) + afisha.root.length);

		window.Router.navigate(path, true);
		return false;
	}
};

var afisha_rating = {
	moving:			false,
	hint:			null,
	hints:			{},
	
	Init: function(place, cnt, hint, hints)
	{
		$(place).each(function(i){
			var obj = $(".scale", this);
			afisha_rating.hint = hint;
			// вешаем обработчики событий
			obj.bind('mousemove', {scale_object: this, cnt_value: cnt}, function(e){afisha_rating.ScaleMousemove(e);});
			obj.bind('mouseout', {scale_object: this, cnt_value: cnt}, function(e){afisha_rating.ScaleMouseout(e);});
			obj.bind('click', {scale_object: this, cnt_value: cnt}, function(e){afisha_rating.ScaleClick(e);});
			// выставляем значение по-умолчанию
			afisha_rating.SetValue(this, $(".value", this).val());
		});
	},

	ScaleMousemove: function(e)
	{
		// выходим если еще выполняется другое пермещение
		if (this.moving)
		{
			return false;
		}
		this.moving = true;

		var value_width = Math.ceil($(".scale", e.data.scale_object).width() / e.data.cnt_value);
		var position = Math.ceil((e.pageX - $(".scale", e.data.scale_object).offset().left) / value_width);
		// если значение за пределами допустимого значение
		if ( position < 0 || position > e.data.cnt_value )
		{
			// то выходим
			this.moving = false;
			return false;
		}
		this.SetValue(e.data.scale_object, position);
		
		if ( this.hint != null )
		{
			this.hint.html(this.hints[position]);
		}
		
		this.moving = false;
	},
	
	ScaleMouseout: function(e)
	{
		var position = $(".value", e.data.scale_object).val();
		this.SetValue(e.data.scale_object, position);
		if ( this.hint != null )
		{
			this.hint.html('');
		}
	},
	
	ScaleClick: function(e)
	{
		var value_width = Math.ceil($(".scale", e.data.scale_object).width() / e.data.cnt_value);
		var position = Math.ceil((e.pageX - $(".scale", e.data.scale_object).offset().left) / value_width);
		// если значение за пределами допустимого значение
		if ( position < 0 || position > e.data.cnt_value )
		{
			return false;
		}
		
		$.ajax({
			type: 'POST',
			mode: 'abort',
			port: 'rating',
			dataType: 'json',
			data: {
				action: 'vote',
				mark: position
			},
			success: function (data) {
				if ( !data.success )
				{
					position = $(".value", e.data.scale_object).val();
					afisha_rating.SetValue(e.data.scale_object, position);
					alert('Ваш голос не принят');
					return;
				}
				$('#user_rating_count').html(data.count);
				$('#user_rating_td').remove();
				$('#user_rating div').attr('class', 'value_'+position);
			},
			fail: function (data) {
				position = $(".value", e.data.scale_object).val();
				afisha_rating.SetValue(e.data.scale_object, position);
				alert('Ваш голос не принят');
			}
		});
		
		this.SetValue(e.data.scale_object, position);
		$(".value", e.data.scale_object).val(position);
	},
	
	SetValue: function(scale, position)
	{
		$(".scale", scale).attr('class', 'scale value_'+position);
	}
};

$(document).ready(function() {
	if (typeof Backbone == "object") {
		afisha.root = window.location.href.match(/^http:\/\/[^\/]+(\/[a-zA-Z]+\/)/)[1] || '/afisha/';

		window.Router = new Backbone.Router();

		var start = null;

		window.Router.route('*path', 'root', function(path) {
            if ( window.history.pushState && Backbone.history.options.pushState )
			{
                if ( start === null )
                    return;
				afisha.search(afisha.root + path);
			}
			else
			{
                if ( start === null || path == '' )
                    return;

				if ( path != '' ) {
					afisha.search(afisha.root + path);
				} else {
					afisha.search(afisha.root + start);
				}
			}
		});

		$('A.ajaxrequest').click(function() {
			return afisha.requestHandler(this);
		});

		Backbone.history.start({root: afisha.root, pushState: (window.history && window.history.pushState)});

		start = Backbone.history.getFragment(null, true);
 	}
	else
	{
		$('A.ajaxrequest').click(function(){
			afisha.search(this.href);
			return false;
		});
	}
});

