// AJAX Section
function loader(method,url,_function){ 
    if(window.XMLHttpRequest){
      infoRequest = new XMLHttpRequest();
      infoRequest.onreadystatechange = _function;
      infoRequest.open(method, url, true);
      infoRequest.send(null);
    }else if(window.ActiveXObject){
      infoRequest = new ActiveXObject("Microsoft.XMLHTTP");
      if(infoRequest){
        infoRequest.onreadystatechange = _function;
        infoRequest.open(method, url, true);
        infoRequest.send(null);
      }
    }
}

var globalPageId;
var spamControlPass;
var commentsBlockId = "commentsBlock";
var commentsFormId = "pageCommentsForm";
var commentsTextareaId = "commentsText";
var errorBlockId = "errorBlockPlace";


function sendComments( parentPageId ){

	globalPageId = parentPageId;

	checkForLastCommentDate();
	
}

function writeComments(){

	commentsText = document.getElementById( commentsTextareaId ).value;
		
	loader("get","/gate.php?a=addComment&parentPageId="+globalPageId+"&commentText="+encodeURIComponent(commentsText), checkCommentsSuccess);

}

function checkCommentsSuccess(){

	if (infoRequest.readyState == 4 && infoRequest.status == 200){
	
		showCommentsList( globalPageId );
		buildErrorBlock("success","Сообщение успешно размещено");
	
	}

}

function showCommentsList( pageId ){

	loader("get","/gate.php?a=getCommentsList&pageId="+pageId, buildCommentsList);

}

function buildCommentsList(){

	if (infoRequest.readyState == 4 && infoRequest.status == 200 && infoRequest.responseText != "NoAuth"){
		
		clearCommentsList();
		container = document.getElementById('commentsList');
		
		if( infoRequest.responseText != "null" ){
		
			list = eval(infoRequest.responseText);
			
			dom_ul = document.createElement("ul");
			
			for( x in list ){
				dom_li = document.createElement("li");
				
				dom_li_span = document.createElement("span");
				
				dom_li_a = document.createElement("a");
				dom_li_a.setAttribute("href", "/forum/?showuser="+list[x]['userId']);
				dom_li_a.appendChild( document.createTextNode( list[x]['userName'] ) );
				
				dom_li_span.appendChild( dom_li_a );
				
				mnth = returnMonthStr(list[x]['comDate'].split("-")[1]);
				
				dom_li_span.appendChild( document.createTextNode( list[x]['comDate'].replace(/\-\d\-/, " "+mnth+" ") ) );
				
				dom_li.appendChild( dom_li_span );

				dom_li.appendChild( document.createTextNode( html_entity_decode(list[x]['comment'] )) );
				
				dom_ul.appendChild( dom_li );
			
			}
			
			container.appendChild(dom_ul)
		
		} else {
		
			dom_p = document.createElement("p");
			dom_p.id = "noCommentsNow";
			dom_p.appendChild( document.createTextNode("Комментариев пока нет") );
			container.appendChild( dom_p );
		
		}
		
		
	}

}

function clearCommentsList(){

	if( document.getElementById('noCommentsNow') ){
	
		document.getElementById( 'commentsList' ).removeChild( document.getElementById('noCommentsNow') );
	
	}

	uls 	  = document.getElementById('commentsList').getElementsByTagName("ul")[0];
	if( typeof(uls) != "undefined" ){
		uls.parentNode.removeChild(uls);
	}

}

/*	Last comment check	*/

function checkForLastCommentDate(){

	loader("get","/gate.php?a=checkLastCommendDate", showLastCommentDate);

}

function showLastCommentDate(){

	if (infoRequest.readyState == 4 && infoRequest.status == 200){
		
		if(infoRequest.responseText == "true"){

			writeComments();
		
		} else {

			buildErrorBlock("warn","Превышена частота отправки сообщений. Интервал между сообщениями должен составлять не менее 10 секунд");
			
		}
	
	}

}

/*	// Last comment check	*/

/*	Common blocks	*/

function buildErrorBlock( type, str ){

	/*killErrorBlock();*/

	errorBlock = document.createElement("div");
	tmpId = "eb_"+Math.random();
	errorBlock.setAttribute("id", tmpId);
	h4 = document.createElement('h4');
	
	if( type == "success" ){
	
		errorBlock.className = "success-block";
		h4.appendChild( document.createTextNode( "Все получилось" ) );
	
	}
	if( type == "warn" ){
	
		errorBlock.className = "warn-block";
		h4.appendChild( document.createTextNode( "Внимание" ) );
	
	}
	if( type == "error" ){
	
		errorBlock.className = "error-block";
		h4.appendChild( document.createTextNode( "Внимание" ) );

	}
	
	eSpan = document.createElement('span');
	eSpan.appendChild( document.createTextNode( str ) );

	errorBlock.appendChild( h4 );
	errorBlock.appendChild( eSpan );

	prnt = document.getElementById( errorBlockId );
		
	lastDiv = prnt.getElementsByTagName('div')[0];
	
	/*	If we have error div, insert new one before him	*/
	if( lastDiv ){
		prnt.insertBefore( errorBlock, lastDiv );
	} else {
	/*	If we don't, insert new before form	*/
		prnt.appendChild( errorBlock );
	}
	
	setTimeout("killErrorBlock('"+tmpId+"')", 3000);

}

function killErrorBlock( tmpBlockId ){

	if( tmpBlockId != "" ){
	
		bId = tmpBlockId;
		document.getElementById( errorBlockId ).removeChild( document.getElementById( bId ) );
		
	} else {
		
		document.getElementById( errorBlockId ).removeChild( document.getElementsByTagName( div ) );
		
	}

}

/*	String functions	*/

function returnMonthStr( month ){

	mn = new Array('января','февраля','марта','апреля','мая','июня','июля','августа','сентября','октября','ноября','декабря');
	
	return( mn[month-1] );

}

function html_entity_decode(str) {
	var ta=document.createElement("textarea");
	ta.innerHTML=str.replace(/</g,"&lt;").replace(/>/g,"&gt;");
	return ta.value;
}