﻿(function ($, window) {
	var setCursorPosition = (function () { 
		if (document.createElement('textarea').setSelectionRange) {
			return function (dText, pos) {
				dText.setSelectionRange(pos, pos);  
				dText.focus();
			};
		} else {
			return function (dText, pos) {
				var tRange = dText.createTextRange();
				tRange.collapse(true);
				tRange.moveStart("character", pos);
				tRange.moveEnd("character", 0);
				tRange.select();
			};
		}
	})();
	$(function () {
		var isAuthenticated = function () {
			return !!($('#portal-menu__user-email').text().length);
			//по наличию e-mail в портальной шапке догадываемся что пользователь аутентифицирован
		};
		//if (isAuthenticated) {
		var jCommentBlock = $('.js-comments-block'), jItemsBlock = jCommentBlock.find('div.items'),
			pidRegExp = /rid_([0-9]*)/i, jCommentForm = $('.js-addcomment').hide(), 
			jCommentBody = jCommentForm.find('textarea[name=comment_body]'), dTextarea = jCommentBody[0],
			jWriteBtns = jCommentBlock.find('.add_comment'), hashBang, jTarget, jCloseCForm = jCommentForm.find('a.js-close'),
			showPostForm = function () {
				var jElem = arguments[0], isReply, appendFunc = 'insertAfter', withQuote, pId = '', 
					quoteText = '', jParent, quoteTemplate;
				if (typeof jElem == 'undefined' || !(jElem instanceof $)) {
					return false;
				}
				isReply = arguments[1];
				if (typeof isReply == 'undefined') {
					isReply = true;
				} else if (isReply == false) {
					appendFunc = arguments[2];
					withQuote = false;
				}
				if (isReply) {
					withQuote = arguments[2];
					jParent = jElem;
					jElem = jElem.find('footer');
					//jParent = jElem.parents('div[id*=rid_]:first');
					pId = jParent.attr('id').match(pidRegExp)[1];
				}
				jCommentForm.find('input:hidden[name=pid]').val(pId);
				jCommentForm[appendFunc](jElem).show();
				if (withQuote) {
					quoteText = jParent.find('header a.js-login').text() + ', ';
					quoteText += '"' + jParent.find('article').text() + '"';
					quoteTemplate = ['<i>', '</i>'];
					quoteTemplate.splice(1, 0, quoteText);
					quoteText = quoteTemplate.join('') + '\n';
				}
				jCommentBody.val(quoteText);
				setCursorPosition(dTextarea, quoteText.length);
				jCommentBody.focus();
			};
		jCommentBlock.bind('click.cmntsReply', function (e) {
			if (!isAuthenticated()) {
				return;
			}
			var jTarget = $(e.target), butNo, isBtn = jTarget.is('.add_comment'), isReply = jTarget.is('.link_add_comment, .link_add_comment_quote');
			if (isBtn) {
				butNo = jWriteBtns.index(jTarget);
				e.preventDefault();
				showPostForm(jItemsBlock, false, (butNo == 0 ? 'prependTo' : 'appendTo'));
			} else if (isReply) {
				e.preventDefault();
				showPostForm(jTarget.parents('div[id*=rid]'), true, jTarget.is('.link_add_comment_quote'));
			}
		});
		jCloseCForm.bind('click.cmntsformHide', function (e) {
			if (!isAuthenticated()) {
				return;
			}
			e.preventDefault();
			jCommentForm.hide();
		});
		if (window.location.hash.length) {
			var oPageState = $(window).data('pageStateObj')/*, hashBang = []*/, aModes = ['reply', 'quote', 'comment_ok', 'comment_fail', 'comment_banned'],
				oCurState = oPageState.getStateKeys(aModes), aArgs, scrollTo, isReply, isQuote, hasTarget, jMessage;
			for (var keyName in oCurState) {
				if (oCurState.hasOwnProperty(keyName)) {
					var modeVal = oCurState[keyName];
					if (typeof modeVal != 'undefined') {
						hasTarget = modeVal !== null;
						if (hasTarget) {
							jTarget = $('#rid_' + modeVal);
						} else {
							jTarget = jItemsBlock;
						}
						isReply = keyName == 'reply';
						isQuote = keyName == 'quote';
						switch (keyName) {
						case 'reply':
						case 'quote':
							aArgs = [jTarget, hasTarget, isReply && hasTarget ? isQuote : 'prependTo'];
							break;
						case 'comment_ok':
							jMessage = jCommentBlock.find('.js-comment_ok');
							break;
						case 'comment_fail':
							jMessage = jCommentBlock.find('.js-comment_fail');
							aArgs = [jTarget, hasTarget, hasTarget ? false : 'prependTo'];
							break;
						case 'comment_banned':
							jMessage = jCommentBlock.find('.js-comment_banned');
							break;
						default: break;
						}
					}
				}
			}
			if (aArgs && aArgs.length) {
				showPostForm.apply(null, aArgs);
				scrollTo = (hasTarget ? jTarget : jCommentForm).offset().top;
			}
			if (jMessage) {
				jMessage.prependTo(hasTarget ? jTarget.find('div.ico_nextlevel section.comment_user') : jTarget);
				jMessage.show()
				scrollTo = jMessage.offset().top;
			}
			if (scrollTo) {
				$('body, html').scrollTop(scrollTo);
			}
		}
	});
})(jQuery, self);
