var ERROR_MESSAGES = {
		  'common': 'Ошибка при добавлении комментария. Если проблема повторяется, обратитесь в службу технической поддержки.'
		, 'body_empty': 'Ну скажите же что-нибудь!'
		, 'login_empty': 'Пожалуйста, представьтесь!'
		, 'login_long': 'Простите, но мы не в состоянии запомнить такое длинное имя'
		, 'email_empty': 'Укажите Ваш Электронный адрес!'
		, 'email_wrong': 'Электронный адрес указан не верно!'
		, 'long_words': 'Поле содержит недопустимо длинные слова!'
}

function CommentManager(objectName, formName) {

	var thisClass = this;	// экземпляр класса
	var thisObjectName = objectName; // имя объекта
	var form;

	this.init = function(fName)
	{
		this.form = document.forms[fName];
		this.userNick = this.form['unreg_login'];
		this.userEmail = this.form['unreg_email'];
		this.commentText = this.form['comment_body'];
		this.resourceId = this.form['resource_id'];
		this.sourceId = this.form['source_id'];
		this.itemId = this.form['item_id'];
		this.listId = this.form['list_id'];
		this.loginType = this.form['login_type'];
		this.commentParentId = this.form['cpid'];
	}

	this.loadData = function(url, params, funcName)
	{
		//$("input:button", this.form)[0].disabled = true;// jQuery
		$('commentForm').getElementsBySelector('input[type="button"]').invoke('disable');
		setReadyState( null, null, null, eval(funcName) );
		return !sendRequest(null, url, params, 'POST');
	}

	this.prepareParams = function()
	{
		//var commentCount = $('div.commentList > .commentItem').length + 1;// jQuery
		var commentCount = $('comment_list').getElementsByClassName('commentItem').length + 1;
		var params = 'resource_id=' + this.resourceId.value;
		params += '&source_id=' + this.sourceId.value;
		params += '&unreg_login=' + this.userNick.value;
		params += '&unreg_email=' + this.userEmail.value;
		params += '&comment_body=' + this.commentText.value;
		params += '&item_id=' +  this.itemId.value;
		params += '&list_id=' + this.listId.value;
		params += '&cpid=' + this.commentParentId.value;
		params += '&cnum=' + commentCount;
//		alert(params);
		return params;
	}

	this.addComment = function()
	{
		if (!this.checkFields())
		{
			return false;
		}

		var url = '/goods/index.php';
		initXMLHTTPRequest();
		thisClass.loadData(url, this.prepareParams(), 'thisClass.onLoadDataComplete');
	}


	this.onLoadDataComplete = function(req)
	{
		data = req.responseText;
//		alert(data);
		if (!data)
		{
			thisClass.showError('comment_bodyErr', ERROR_MESSAGES['common']);
			return;
		}
		data = data.replace('__Process', thisObjectName + '.__Process');
		if (req.status == '200')
		{
			eval(data);
		}
		if (!data['success'])
		{
			//$("input:button", thisClass.form)[0].disabled = false;// jQuery
			$('commentForm').getElementsBySelector('input[type="button"]').invoke('enable');
			thisClass.showError(data['field'] + 'Err', ERROR_MESSAGES[data['message']]);
			return;
		}
		return false;
	}

	this.__Process = function(data)
	{
//		alert(data['value']);
		//var commentCount = $('div.commentList > .commentItem').length + 1;// jQuery
		var commentCount = $('comment_list').getElementsByClassName('commentItem').length + 1;
		//$("input:button", this.form)[0].disabled = false;// jQuery
		$('commentForm').getElementsBySelector('input[type="button"]').invoke('enable');
		if (!data)
		{
			return;
		}

		this.clearFields();
		/* jQuery */
		/*
		if ($('div.commentEmpty').html())
		{
			$('div.commentEmpty').remove();
		}
		$('span#comment_num').html(commentCount);
		*/
		var emptyComment = $('comment_list').getElementsByClassName('commentEmpty');
		if (emptyComment.length > 0)
		{
			emptyComment[0].remove();
		}
		$('comment_num').innerHTML = commentCount;
		var content = data['value'];
		if (!data['parent_id'])
		{
			// вставляем в самый конец
			/*parentComment = $('div.commentItem:last');
			if (parentComment.html())
			{
				$(content).insertAfter(parentComment);
			}
			else
			{
				$('div.commentList').append( $(content) );
			}*/
			new Insertion.Bottom('commentList', content);
			var commentTopDiv = document.getElementById('commentTop');
			commentTopDiv.className='commentTop';
		}
		//thisClass.scrollTo('c' + data['comment_id']);
		return false;
	}

	this.init(formName);
}


CommentManager.prototype.checkFields = function()
{
	this.clearErrors();
	var cv = new CommentValidator();
	if (!cv.isLoginValid(this.userNick.value, 1))
	{
		field = this.userNick.getAttribute('name');
		this.showError(field + 'Err', cv.getErrorMessage());
		return false;
	}
	if (!cv.isEmailValid(this.userEmail.value, 0))
	{
		field = this.userEmail.getAttribute('name');
		this.showError(field + 'Err', cv.getErrorMessage());
		return false;
	}
	if (!cv.isBodyValid(this.commentText.value, 1))
	{
		field = this.commentText.getAttribute('name');
		this.showError(field + 'Err', cv.getErrorMessage());
		return false;
	}
	return true;
}


CommentManager.prototype.showError = function(fieldId, errorMsg)
{
	var elem = document.getElementById(fieldId);
	if (!elem)
	{
		return;
	}
	elem.innerHTML = errorMsg;
	elem.style.display = 'block';
}

CommentManager.prototype.clearFields = function()
{
	var fields = new Array();
	fields.push(this.userNick.name);
	fields.push(this.userEmail.name);
	fields.push(this.commentText.name);
	for (var i = 0; i < fields.length; i++)
	{
		this.form[fields[i]].value = '';
	}
}

CommentManager.prototype.clearErrors = function()
{
	var fields = new Array();
	fields.push(this.userNick.name);
	fields.push(this.userEmail.name);
	fields.push(this.commentText.name);
	for (var i = 0; i < fields.length; i++)
	{
		var elem = document.getElementById(fields[i] + "Err");
		if (!elem)
		{
			continue;
		}
		elem.innerHTML = '';
		elem.style.display = 'none';
	}
}

//CommentManager.prototype.scrollTo = function(commentId)
//{
//	$('a[@name='+commentId+']').ScrollTo(700, 'easeout');
//}


// заглушка для неудачников
function __Process()
{
	return false;
}


/*function commentOverlayManager()
{
	var overlayOpacity = 0.5;
	var overlayDuration = 0.5;

	this.showOverlay = function()
	{
		var arrayPageSize = getPageSize();
		$('#commentOverlay').width(arrayPageSize[0]);
		$('#commentOverlay').height(arrayPageSize[1]);
		$('#commentOverlay').fadeTo(overlayDuration, overlayOpacity);
	}

	this.hideOverlay = function()
	{
		$('#commentOverlay').hide();
		$('#commentOverlay').fadeOut(overlayDuration);
	}
}


function getPageSize(){

	var xScroll, yScroll;

	if (window.innerHeight && window.scrollMaxY) {
		xScroll = window.innerWidth + window.scrollMaxX;
		yScroll = window.innerHeight + window.scrollMaxY;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.body.offsetHeight;
	}

	var windowWidth, windowHeight;

//	console.log(self.innerWidth);
//	console.log(document.documentElement.clientWidth);

	if (self.innerHeight) {	// all except Explorer
		if(document.documentElement.clientWidth){
			windowWidth = document.documentElement.clientWidth;
		} else {
			windowWidth = self.innerWidth;
		}
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}

	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else {
		pageHeight = yScroll;
	}

//	console.log("xScroll " + xScroll)
//	console.log("windowWidth " + windowWidth)

	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){
		pageWidth = xScroll;
	} else {
		pageWidth = windowWidth;
	}
//	console.log("pageWidth " + pageWidth)

	arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight)
	return arrayPageSize;
}

function getCommentMargin(item)
{
	return parseInt(item.css("margin-left").slice(0, -2));
}*/

function CommentValidator()
{
	var errMessage = '';

	this.isLoginValid = function(value, notempty)
	{
		if (value == '' && notempty)
		{
			this.errMessage = ERROR_MESSAGES['login_empty'];
			return false;
		}
		if (value.length > 64)
		{
			this.errMessage = ERROR_MESSAGES['login_long'];
			return false;
		}
		return true;
	}

	this.isBodyValid = function(value, notempty)
	{
		if (value == '' && notempty)
		{
			this.errMessage = ERROR_MESSAGES['body_empty'];
			return false;
		}
		/*if (value.match(/\S{30,}/))
		{
			this.errMessage = '(поле содержит недопустимо длинные слова)';
			return false;
		}*/
		return true;
	}

	this.isEmailValid = function(value, notempty)
	{
		if (value == '' && notempty)
		{
			this.errMessage = ERROR_MESSAGES['email_empty'];
			return false;
		}
		if (value != '' && !value.match(/^([A-Za-z0-9\-])+(\.[A-Za-z0-9\-]+)*@(([A-Za-z0-9](-[A-Za-z0-9]+)*)+\.)+[A-Za-z]{2,6}$/))
		{
			this.errMessage = ERROR_MESSAGES['email_wrong'];
			return false;
		}
		return true;
	}

	this.getErrorMessage = function()
	{
		return this.errMessage;
	}
}