/**
 * Возвращает суффикс класса элемента по заданному префиксу.
 * @param {String|Element|jQuery} el
 * @param {String} prefix
 * @return {String}
 */
getSuffixClass = function(el, prefix) {
	if($(el).length){
		var classNames = $(el).attr('class').split(' ');
		for (var i = 0; i < classNames.length; i++) {
			if (prefix == classNames[i].substr(0, prefix.length)) {
				return classNames[i].substr(prefix.length);
			}
		}
	}
	return false;
}

Array.prototype.indexOf = function(elt){
	var len = this.length;
	var from = Number(arguments[1]) || 0;

	from = 0 > from ? Math.ceil(from) : Math.floor(from);

	if (0 > from) {
		from += len;
	}

	for (; from < len; from++) {
		if (from in this && this[from] === elt) {
			return from;
		}
	}

	return -1;
}
var MovieReminder = $.inherit({
	__constructor: function(oOptions){
		this.jButton = $(".release-notify-link");
		this.sLang = $("html").attr("lang");
		this.sCity = $("#city-selector option:selected").attr("abbr") || "";
		this.init();
	},
	init: function(){
		var oThis = this;
		this.jButton.click(function(event){ oThis.subscribe(event); return false; });
	},
	subscribe: function(event){
		var jCurrent = $(event.currentTarget);
		var iMovieId = getSuffixClass(jCurrent,"movie_");
		if(iMovieId){
			var oThis = this;
			$.get(
					"/ajax/mreminder/",
					{
						id: iMovieId ,
						lang: this.sLang,
						city: this.sCity
					},
					function(data){
						data = eval(data);
						if(data.status){
							if(data.status == 'ok'){
								jCurrent.animate({opacity: 0}, 500, function(){
									jCurrent.parent()
										.attr("class", "reminder-message")
										.css("opacity",0)
										.html(data.message)
										.animate({opacity: 1},500)
									;
								});
							} else {
								jCurrent.parent().html(data.message);
							}
						}
					}
			);
		}
	}
});


var Quiz = $.inherit(
	{
		__constructor: function(oOptions) {
			this.jResultContainer = oOptions.jResultContainer || $(".quiz-result");
			this.jFormContainer = oOptions.jFormContainer || $(".quiz-form");
			this.jForm = oOptions.jForm || $("#quiz-form");
			this.iQuizId = $("#quiz_id").val();
			this.iQuestionId = $("#question_id").val();

			if(this.jForm && this.iQuizId && this.iQuestionId){
				this.init();
			} else {
				this.showResult();
			}
		},
		init: function(){
			// если пользователь авторизован и есть форма для опроса
			// проверяем учавствовал ли пользователь в этом опросе
			var sVoted = $.cookie("qvoted") || "";
			var aVoted = sVoted.split(",");
			if(aVoted.indexOf(""+this.iQuizId) < 0){
				// пользователь еще не отвечал на опрос, поэтому показываем ему форму
				var oThis = this;
				this.jForm.submit(function(e){ oThis.vote(e); return false; })
				this.showForm();
			} else {
				// пользователь уже учавствовал
				this.showResult();
			}
		},
		vote: function(e){
			var q = $("#question_id").val();
			var aVal = [];
			var jOptions = $("input[name=question"+q+"_a]:checked",this.jForm);
			jOptions.each(function(i,j){ aVal[i] = $(j).val(); });
			var hData = {};
			hData.qid = $("#quiz_id").val();
			hData.q = $("#question_id").val();
			hData['q'+q+'_a'] = aVal;

			var oThis = this;
			$.get(
				"/ajax/quiz/",
				hData,
				function(status){
					oThis.setVoted();
					oThis.showResult();
				}
			);
			this.showResult();
		},

		setVoted: function(){
			if(this.iQuizId){
				$.cookie(
					"qvoted",
					$.cookie("qvoted") + ","  + this.iQuizId,
					{
						expires: new Date(2015, 0, 1),
						path: '/'
					}
				);
			}
		},
		showForm: function(){
			this.jFormContainer.show();
			this.jResultContainer.hide();
		},
		showResult: function(){
			this.jFormContainer.hide();
			this.jResultContainer.show();
		}

	}
);



var MovieRating = $.inherit(
	{
		__constructor: function(oOptions) {
			this.jContainer = oOptions.jContainer.eq(0);
			this.jVoteItems = $(".vote",this.jContainer);
			this.iMovieId = getSuffixClass(this.jContainer,"movie-");
			this.iValue = getSuffixClass(this.jContainer,"rating_");
			if(this.iMovieId && this.jVoteItems.length){
				this.init();
			} else {
				this.disable();
			}
		},
		init: function(){
			var oThis = this;
			$.get(
				"/ajax/mrating/",
				{ id: oThis.iMovieId },
				function(data){
					data = eval(data);
					if(data && data.rating){
						//alert(data.counter);
						oThis.setMovieVoted(Math.round(data.rating));
					} else {

					}
					oThis.jVoteItems.bind("click", function(){ oThis.vote(getSuffixClass(this,"vote-")) })
				}
			);
		},
		vote: function(iEstimate){
			var oThis = this;
			$.get(
				"/ajax/estimate/",
				{ id: oThis.iMovieId, e: iEstimate },
				function(status){
					if(status == 1){
						oThis.setMovieVoted(iEstimate);
					} else {
						oThis.disable();
					}
				}
			);
		},

		setMovieVoted: function(val){
			if(val && val>0 && val<6){
				this.jContainer.removeClass("rating_"+this.iValue);
				this.iValue = val;
				this.jContainer.addClass("rating_"+this.iValue);
			}
		},

		disable: function(){
			this.jContainer.removeClass("can-vote");
			if(this.jVoteItems.length){
				this.jVoteItems.unbind();
			}
		}

	}
);

var Question = $.inherit(
	{
		__constructor: function(oOptions) {
			this.sCategoryHref = oOptions.sCategoryHref;
			this.iCategoryId = oOptions.iCategoryId;
			this.jAddForm = $(oOptions.sAddFormSelector);
			this.init();
		},
		init: function() {
			this.jAddForm.attr("action",this.sCategoryHref);
			$("input[name='category']",this.jAddForm).val(this.iCategoryId);
			$("textarea#description").maxLength(4000);
		}
	}
);

var Comment = $.inherit(
	{
		__constructor: function(oOptions) {
			this.iUserId = oOptions.iUserId; // ид залогиненого пользователя
			this.isUserAdmin = oOptions.isUserAdmin || false;
			this.sSpamThanksMessage = oOptions.sSpamThanksMessage;
			this.jAddForm = $("#add-comment-form");
			this.jAddFormWrapper = $("#add-comment-form-wrapper");
			this.jIdInput = $("#cid");
			this.jTextarea = $("textarea#text");
			this.jjReplyLink = $("#content .comment .action.reply");
			this.jNewCommentLink = $("#content .comment .action.add-new-comment");
			this.jjSpamLink = $("#content .comment .action.spam");
			this.init();
		},
		init: function() {
			this.jAddFormWrapper.hide();
			this.jAddFormWrapper.removeClass("hidden");
			this.jAddForm.attr("action","");
			$("input[name='category']",this.jAddForm).val(this.iCategoryId);
			this.jTextarea.maxLength(this.isUserAdmin ? 4000 : 2000);

			if(this.iUserId){
				$(".comment.user-"+this.iUserId+" > .text , .comment-info .user-"+this.iUserId).addClass("loged");
			}

			var oThis = this;
			this.jjReplyLink.click(function(){
				var iCommentId = parseInt($(this).parent().attr("comment-id"));
				oThis.showForm(iCommentId);
			});
			this.jNewCommentLink.click(function(){
				oThis.showForm();
			});
			this.jjSpamLink.click(function(){
				var iCommentId = parseInt($(this).parent().attr("comment-id"));
				if( confirm($(this).attr("title")) ) {
					oThis.reportSpam(iCommentId);
				}

			});
			$(".spam:eq(0)", ".admin-comment").hide();
		},
		showForm: function(id){
			var oThis = this;
			this.jIdInput.val(id ? id : "");
			var jFormContainer = id ? $("#c-form-"+id) : $("#c-form"); // контейнер для формы коммента

			if( !$("form",jFormContainer).size() ){
				// если контейнер без формы
				this.jAddFormWrapper.slideUp("slow",function(){
					oThis.jAddFormWrapper.appendTo(jFormContainer);
					oThis.jAddFormWrapper.slideDown("fast",function(){
						oThis.jTextarea.focus();
					});
					oThis.jTextarea.focus();
				});
			} else {
				this.jAddFormWrapper.slideUp("fast",function(){
					oThis.jAddFormWrapper.appendTo("#content");
				});
			}
		},
		reportSpam: function(id){
			if(id){
				var oThis = this;
				$.get("/ajax/spam/", { id: id }, function(){ alert(oThis.sSpamThanksMessage) } );
			}
		}

	}
);


/**
 *  Maximal length limitation for textarea
 *	Usage: $('#textarea_id').maxLength(20);
 */
jQuery.fn.maxLength = function(max)
{
	this.each(function()
	{
     if(this.tagName.toLowerCase() == 'textarea')
     {
         this.onkeypress = function(e)
         {
             var ob = e || event;
             var keyCode = ob.keyCode;
             var hasSelection = document.selection? document.selection.createRange().text.length > 0 : this.selectionStart != this.selectionEnd;
             return !(this.value.length >= max && (keyCode > 50 || keyCode == 32 || keyCode == 0 || keyCode == 13) && !ob.ctrlKey && !ob.altKey && !hasSelection);
         };
         this.onkeyup = function()
         {
             if(this.value.length > max){
                 this.value = this.value.substring(0,max);
             }
         };
     }
 });
};



initInputPlaceHolder = function (jInput) {
	if (jInput.length && !$.browser.webkit) {
		var sInputPlaceholder = jInput.attr('placeholder');
		if(!jInput.val()){
			jInput
			.addClass("empty")
			.val(sInputPlaceholder);
		}
		jInput
			.focus(function(){
				$(this).hasClass("empty") && $(this).val('').removeClass("empty");
			})
			.blur(function(){
				!$(this).val() && $(this).val(sInputPlaceholder).addClass("empty");
			})
		;
	}
}



var SimpleSwitcher = $.inherit(
		{
			__constructor: function(oOptions) {
				var oThis = this;

				this.jContainer = oOptions.jContainer;
				this.jjItems = oOptions.jjItems || $(oOptions.items_selector || this.self.itemsSelector, this.jContainer);

				this.type = oOptions.type;
				this.location_hash = oOptions.location_hash;

				this.init_selected = (oOptions.init_selected != undefined) ? oOptions.init_selected : true;
				this.allow_second_click = oOptions.allow_second_click;

				this.actionSelector = oOptions.action_selector || this.self.actionSelector;

				this.data_options = oOptions.data || {};

				this.jjItems.find(this.actionSelector).click(function(){
					var parentItem = $(this).parent();
					var parentItemSelected = parentItem.hasClass("selected");

					var dataToSend = {};

					if (oThis.type) {
						dataToSend.new_value = getSuffixClass(parentItem, oThis.type + '-');
						if (oThis.data_options.container) dataToSend.container = oThis.jContainer;
						if (oThis.data_options.items) dataToSend.items = oThis.jjItems;
						if (oThis.data_options.selected_item) dataToSend.selected_item = parentItem;
					}

					if (!parentItemSelected) {
						oThis.jjItems.removeClass("selected");
						parentItem.addClass("selected");

						if (oThis.jSwitchingBodyFirstCorner){
							if (parentItem.index(this.jjItems) == 0){
								oThis.jSwitchingBodyFirstCorner.hide();
							} else {
								oThis.jSwitchingBodyFirstCorner.show();
							}
						}

						if (oThis.type) {
							// посылаем событие с типом нового выбранного элемента
							$.eventBus.trigger(oThis.type + "-switch", dataToSend);
						}

					}

					if (parentItemSelected && oThis.allow_second_click) {
						parentItem.toggleClass("second-click");

						if (oThis.type) {
							dataToSend.second_click = true;
							// посылаем событие с типом нового выбранного элемента
							$.eventBus.trigger(oThis.type + "-switch", dataToSend);
						}
					}

				});

				if (this.location_hash) {
					var jSelected = this.jjItems.filter("." + this.type + '-' + window.location.hash.slice(1));
					if (!jSelected.length) var jSelected = this.jjItems.eq(0);

					jSelected.parent().removeClass("selected");
					$(".pseudo", jSelected).click();
				}

				if (!this.jjItems.filter(".selected").length && this.init_selected){
					this.jjItems.eq(0).addClass("selected");
				}

				if (oOptions.immediate_trigger) {
					$(this.actionSelector, this.jjItems.filter(".selected").removeClass("selected")).click();
				}

				this.jSwitchingBody = oOptions.jSwitchingBody;
				if (this.jSwitchingBody) {
					this.jSwitchingBodyFirstCorner = $(".d-cn.d-tl:eq(0)", this.jSwitchingBody);

					if (this.jjItems.eq(0).hasClass("selected")) {
						this.jSwitchingBodyFirstCorner.hide();
					}
				}
			}
		},
		{
			itemsSelector: '> li',
			actionSelector: '> .pseudo'
		}
	);



$(function(){

	var sLang = $("html").attr("lang");
	$("#city-selector :button").click(function(){
		var newLocation = $("#city-selector select").val();

		if (newLocation != window.location.pathname) {
			window.location = newLocation;
		}
	});

	initInputPlaceHolder($("#footer .search input"));
	initInputPlaceHolder($(".search input[name='q']"));

	$.eventBus.bind("user-not-authorized", function(event, data){
		$("body").addClass("not-authorized-user");
	});

	$.eventBus.bind("user-authorized", function(event, data){
		$("#auth_block .authorised-user .name").html(data.email);
		//$("#auth_block .authorised-user .name").html(data.name);
		$("body").addClass("authorized-user");
		$("#auth_block .authorised-user .points").load("/ajax/auth/points/");
	});

	if($.cookie("cookie") == "on"){
		var oAuthData = eval($.cookie("authdata"));
		if(oAuthData && oAuthData.name){
			$.eventBus.trigger("user-authorized",oAuthData);
		} else {
			$.eventBus.trigger("user-not-authorized");
		}
	} else {
		$.eventBus.trigger("user-not-authorized");
	}

	new MovieReminder();

	$("#mob-app-promo")
		.css('left', 10)
		.delay(500)
		.animate({'opacity':1},800)
		.delay(2500)
		.animate({ 'left': -160, 'opacity':0.4 }, 400)
		.delay(300)
		.animate({'left': -140, 'opacity':1}, 300)
		.mouseover(function(){
			$(this).css({'opacity':1});
			$(this).stop().animate({'left': -10}, 200);
		})
		.mouseout(function(){
			$(this).stop().animate({'left': -140}, 200);
		});

});
