var ERROR_MESSAGES = {
		  'common': 'Ошибка при добавлении комментария. Если проблема повторяется, обратитесь в службу технической поддержки.'
		, 'empty': '(это поле не может быть пустым)'
		, 'long_nick': '(слишком длинное Имя)' 
		, 'wrong_email': '(Вы уверены, что E-Mail правильный)'
		, 'long_words': '(поле содержит недопустимо длинные слова)'
		, 'long_body': '(слишком длинный Комментарий)'
}

function CommentManager(objectName, formName) {
	
	var thisClass = this;	// экземпляр класса
	var thisObjectName = objectName; // имя объекта
	
	this.init = function(fName)
	{
		this.form = document.forms[fName];
		this.formPrefix = this.form.getAttribute('name').split('_')[2];
		this.userNick = this.form['noreg_login'];
		this.userEmail = this.form['noreg_email'];
		this.commentText = this.form['comment_body'];
		this.requestSource = this.form['requestSource'];
		this.itemId = this.form['itemDbId'];
		this.itemUrl = this.form['item_id'];
		this.commentParentId = this.form['cpid'];
		this.isOdd = this.form['isodd'];
		this.commentLevel = this.form['level'];		
	}
	
	this.loadData = function(url, params, funcName)
	{
		overlayMng.showOverlay();
		jQuery("input:button", this.form)[0].disabled = true;
		setReadyState( null, null, null, eval(funcName) );
		return !sendRequest(null, url, params, 'POST');
	}
	
	this.prepareParams = function()
	{
		var commentCount = jQuery('#comments_list > .commentItem').length;
		var params = 'resource_id=AddComment';
		params += '&requestSource=' + encodeURIComponent(this.requestSource.value);
		params += '&commentLevel='  + encodeURIComponent(this.commentLevel.value);
		params += '&noreg_login='   + encodeURIComponent(this.userNick.value);
		params += '&noreg_email='   + encodeURIComponent(this.userEmail.value);
		params += '&comment_body='  + encodeURIComponent(this.commentText.value);
		params += '&item_id=' 		+ encodeURIComponent(this.itemUrl.value);
		params += '&itemDbId=' 		+ encodeURIComponent(this.itemId.value);
		params += '&cpid=' 			+ encodeURIComponent(this.commentParentId.value);
		params += '&isodd=' 		+ encodeURIComponent(this.isOdd.value);
		params += '&comment_count=' + commentCount;
		return params;
	}
	
	this.addComment = function()
	{		
		if (!this.checkFields())
		{
			return false;
		}
				
		var url = '/dynamic_content.php';// + this.prepareData();
		initXMLHTTPRequest();
		thisClass.loadData(url, this.prepareParams(), 'thisClass.onLoadDataComplete');	
	}
	
	
	this.onLoadDataComplete = function(req)
	{
		data = req.responseText;
//		alert(data);
		if (!data)
		{
			thisClass.showError('comment_common_error_' + this.formPrefix, ERROR_MESSAGES['common']);
			return;
		}				
		data = data.replace('__Process', thisObjectName + '.__Process');
		if (req.status == '200')
		{		
			eval(data);
		}		
		if (!data['success'])
		{			
			jQuery("input:button", thisClass.form)[0].disabled = false;
			thisClass.showError('comment_' + data['field'] + '_error_' + thisClass.formPrefix, ERROR_MESSAGES[data['message']]);
			overlayMng.hideOverlay();			
			return;
		}		
		return false;
	}
	
	this.__Process = function(data)
	{
//		alert(data['value']);
		overlayMng.hideOverlay();
		jQuery("input:button", this.form)[0].disabled = false;
		if (!data)
		{
			return;
		}
		
		this.clearFields();
//		jQuery('#div' + data['parent_id']).css('display', 'none');
		jQuery('#div' + data['parent_id']).html('');
		
		var content = data['value'];
		if (!data['parent_id'])
		{			
			// вставляем в самый конец
			parentComment = jQuery('div.commentItem:last');
			if (parentComment.html())
			{
				jQuery(content).insertAfter(parentComment);
			}
			else
			{
				jQuery('h2#comments_head.red').css('display', 'block');
				jQuery('#comments_list').append( jQuery(content) );
			}
		}
		else
		{
			parentComment = jQuery('#div' + data['parent_id']).parent();
			
			// ищем после какого камента вставить			
			marginParent = getCommentMargin(parentComment);
			
			nextComment = parentComment.next(".commentItem");
			if (nextComment.html())
			{
				marginNext = getCommentMargin(nextComment);
				
				hasChilds = false;
				if (marginNext > marginParent)
				{			
					hasChilds = true;
					marginChild = marginNext;
				}
				
				if (!hasChilds)
				{
					//parentComment.css('background-color', 'red');
					jQuery(content).insertAfter(parentComment);
				}
				else
				{			
					while (marginNext >= marginChild)
					{
						//alert('Margin next: ' + marginNext + ' MarginChild: ' + marginChild);
						curItem = nextComment;
						curMargin = marginNext;
						nextComment = curItem.next(".commentItem");
						if (nextComment.html())
						{
							marginNext = getCommentMargin(nextComment);
						}
						else
						{
							marginNext = 0;
						}
					}
					if (nextComment.html())
					{
						jQuery(content).insertBefore(nextComment);
					}
					else
					{
						jQuery(content).insertAfter(curItem);
					}
				}	
			}
			else
			{
				jQuery(content).insertAfter(parentComment);
			}
		}				
		jQuery('#comments_list > .commentItem.odd').removeClass('odd');
		jQuery('#comments_list > .commentItem:even').addClass('odd');
		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').split('_')[1];	
		this.showError('comment_' + field + '_error_' + this.formPrefix, cv.getErrorMessage());
		return false;
	}
	if (!cv.isEmailValid(this.userEmail.value, 0))
	{
		field = this.userEmail.getAttribute('name').split('_')[1];		
		this.showError('comment_' + field + '_error_' + this.formPrefix, cv.getErrorMessage());
		return false;
	}
	if (!cv.isBodyValid(this.commentText.value, 1))
	{
		field = this.commentText.getAttribute('name').split('_')[1];
		this.showError('comment_' + field + '_error_' + this.formPrefix, 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.split('_')[1]);
	fields.push(this.userEmail.name.split('_')[1]);
	fields.push(this.commentText.name.split('_')[1]);
	for (var i = 0; i < fields.length; i++)
	{
		var elem = document.getElementById("comment_" + fields[i] + "_error_" + this.formPrefix);
		if (!elem)
		{
			continue;
		}
		elem.innerHTML = '';
		elem.style.display = 'none';
	}
}

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


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


function commentOverlayManager()
{
	var overlayOpacity = 0.25;
	var overlayDuration = 0.5;
	
	this.showOverlay = function()
	{
		var arrayPageSize = getPageSize();
		setPosition('commentLoader');
		jQuery('#commentLoader').show();
		jQuery('#commentOverlay').width(arrayPageSize[0]);
		jQuery('#commentOverlay').height(arrayPageSize[1]);
		jQuery('#commentOverlay').fadeTo(overlayDuration, overlayOpacity);		
		window.onscroll = function(){			
  			setPosition('commentLoader');
		};
	}
	
	this.hideOverlay = function()
	{
		jQuery('#commentLoader').hide();
		jQuery('#commentOverlay').hide();
		jQuery('#commentOverlay').fadeOut(overlayDuration);		
		window.onscroll = function(){return;}
	}
}

function setPosition(elemId)
{
	var arrayPageScroll = getPageScroll();
  	var top = arrayPageScroll[1] + (arrayPageSize[3] * 50 / 100);
	var left = arrayPageScroll[0] + (arrayPageSize[2] * 40 / 100);
	jQuery('#'+elemId).css({'top': top, 'left': left});
	
}

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;
}

//
// getPageScroll()
// Returns array with x,y page scroll values.
// Core code from - quirksmode.com
//
function getPageScroll(){

	var xScroll, yScroll;

	if (self.pageYOffset) {
		yScroll = self.pageYOffset;
		xScroll = self.pageXOffset;
	} else if (document.documentElement && document.documentElement.scrollTop){	 // Explorer 6 Strict
		yScroll = document.documentElement.scrollTop;
		xScroll = document.documentElement.scrollLeft;
	} else if (document.body) {// all other Explorers
		yScroll = document.body.scrollTop;
		xScroll = document.body.scrollLeft;	
	}

	arrayPageScroll = new Array(xScroll,yScroll) 
	return arrayPageScroll;
}

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