var events_containers = 1;
var comments_containers = 1;
var nothing = REQ_EMPTY;
var comments=new Array();
var loader = '<div class="ajaxLoader" align="center" style="width:100%;"></div>';
var last_comment = 0;
var last_comment_id = 0;
var comments_id_filter = /last_comment_id\=([0-9]{3,8})\;/;
//root = "http://mokinukai.lt"; 
function keyPressed(e, element_id, element) {
    if (e.shiftKey==0 && e.keyCode == 13) { 
        var el = document.getElementById(element_id.replace('_text', '_button'));
		if(el!=null){ el.click(); }//trigger event
        return false;
    }
}
function add_element(id){ 

	found = false;
	for(i=0; i<comments.length; i++){ //alert(comments[i][0]);
			if(comments[i][0]==id){comments[i][1]= comments[i][1]+1; found=true; break; }
	}
	if(found==false){ comments.push(new Array(2)); comments[i][0]=id; comments[i][1]=1; }
	//alert(id+' '+comments[i][1]);
}
function reduce_element(id){ //alert(id); 
	found = false;
	for(i=0; i<comments.length; i++){ //alert(comments[i][0]);
			if(comments[i][0]==id){comments[i][1]=comments[i][1]-1; found=true; break; }
	}
}
function reset_element(id){ //alert(id); 
	found = false;
	for(i=0; i<comments.length; i++){ //alert(comments[i][0]);
			if(comments[i][0]==id){comments[i][1]= 0; found=true; break; }
	}
}
function check_elements(id){
	var i =0;
	for(i=0; i<comments.length; i++){
			//document.write(comments);
			if(comments[i][0]==id){ break; }
		}
		//document.write(comments[i]);
		//comments.splice(i,1);
		if(typeof comments[i] == 'undefined') return 0;
		return comments[i][1];
}


function ajaxObject(layer, url) {                                    // This is the object constructor
   var that=this;                                                    // A workaround for some javascript idiosyncrocies
   var updating = false;                                             // Set to true if this object is already working on a request
   this.callback = function() {}                                     // A post-processing call -- a stub you overwrite.

   this.update = function(passData, showLoader) {                                // Initiates the server call.
   	  if(typeof showLoader == 'undefined'){ showLoader=1;}
      if (updating==true) { return false; }                          // Abort if we're already processing a call.
      updating=true;                                                 // Set the updating flag.
      var AJAX = null;                                               // Initialize the AJAX variable.
      if (window.XMLHttpRequest) {                                   // Are we working with mozilla?
         AJAX=new XMLHttpRequest();                                  //  Yes -- this is mozilla.
      } else {                                                       // Not Mozilla, must be IE
         AJAX=new ActiveXObject("Microsoft.XMLHTTP");                //  Wheee, ActiveX, how do we format c: again?
      }                                                              // End setup Ajax.
      if (AJAX==null) {                                              // If we couldn't initialize Ajax...
         alert(REQ_NO_AJAX);                // Sorry msg.                                              
         return false                                                // Return false (WARNING - SAME AS ALREADY PROCESSING!)
      } else {
         AJAX.onreadystatechange = function() {                    // When the browser has the request info..
		 	if(loader!="" && showLoader==1) {LayerID.innerHTML = loader;} 
            if (AJAX.readyState==4 || AJAX.readyState=="complete") { //   see if the complete flag is set.
               LayerID.innerHTML=AJAX.responseText; //alert('ajax updated:'+ LayerID.innerHTML + '  LayerID:');                 //   It is, so put the new data in the object's layer
			   //alert(LayerID.innerHTML);
               delete AJAX;                                          //   delete the AJAX object since it's done.
               updating=false;
			   //alert("AJAX result: "+LayerID.innerHTML);                                          //   Set the updating flag to false so we can do a new request
               that.callback();                                   //   Call the post-processing function.
            }                                                        // End Ajax readystate check.
         }                                                           // End create post-process fucntion block.
         var timestamp = new Date();                                 // Get a new date (this will make the url unique)
         var uri=urlCall+'?'+passData+'&timestamp='+(timestamp*1);   // Append date to url (so the browser doesn't cache the call)
         AJAX.open("GET", uri, true);                                // Open the url this object was set-up with.
         AJAX.send(null);                                            // Send the request.
         return true;                                                // Everything went a-ok.
      }                                                              // End Ajax setup aok if/else block                 
   }
      
   // This area set up on constructor calls.
   var LayerID = document.getElementById(layer);                     // Remember the layer associated with this object.
   var urlCall = url;                                                // Remember the url associated with this object.
}                                                                    // End AjaxObject

function add_comment_guest(code1, code2, target_type, target, owner_id, user_id, language, filter, element_id, member, root){
	var code1_value=document.getElementById(code1).value;
	var code2_value=document.getElementById(code2).value;	
	if(code1_value.length>1){
		if(md5(code1_value)==code2_value) { 
			add_comment(target_type, target, owner_id, user_id, language, filter, element_id, member, root, 0);
			document.getElementById(code1).value = "";
		}
		else{ // ERROR 
			alert(REQ_COMMENT_CODE_ERROR);
		}
	}else{
		alert(REQ_COMMENT_NO_CODE);	
	}	
	
}
function add_comment(target_type, target, owner_id, user_id, language, filter, element_id, member, root, notify, event_id, direction, track_comments){
	// Comments function; Last update: 2010-12-03
	//alert(filter);
	if(notify==undefined){ notify = 0;}
	if(direction==undefined){ direction = 'asc';}
	if(track_comments==undefined){ track_comments=0;}
	var content=document.getElementById(element_id);
	var text=document.getElementById(element_id+"_text");
	var text_value=text.value;
	if(text_value.length > 511) text_value=text_value.substr(0,510)+'..';
	var button=document.getElementById(element_id+"_button");	
	if(text_value.length > 1){ 
		text.value = "";
		button.disabled = true;
		//alert('ADD:'+element_id+'; Text:'+text_value+' | user_id: '+user_id);
		
		var old_content = content.innerHTML;
		
		//add_element(element_id+'_new');
		//element_no = check_elements(element_id+'_new');
		//new_field = ''+element_id+'_new_'+element_no;
		add_element(element_id+'');
		element_no = check_elements(element_id+'');
		new_field = ''+element_id+'_'+element_no;	
	
		if(document.getElementById(new_field)==null){ //alert(direction); 
			if(direction=="asc"){
				content.innerHTML = old_content + '<div id="'+new_field+'" style="margin:0px;"></div>' ; // FORM ON THE BOTTOM
			}else{
				content.innerHTML = '<div id="'+new_field+'" style="margin:0px;"></div>' + old_content ; //FORM ON TOP
			}
		} 
		//field.style.visibility="hidden";
		//field.innerHTML = '<div align="center" style="width:100%;"><img src="'+root+'/images/loading1.gif" border=0></div>';
		//alert('new field: '+new_field);
		// NEW //
		var commentObj = new ajaxObject(new_field, root+'inc/request.php');
			commentObj.callback = 
				function() { //alert('start callback');
					var rfield = document.getElementById(new_field);  //alert(rfield);
					var result = rfield.innerHTML; //alert(new_field+"\n"+result);
					if(rfield){  
						comments_containers++;  //alert("result: "+result+" ; innerHTML:"+ document.getElementById(new_field).innerHTML);
						if(result==0){ rfield.innerHTML = '' ; text.value = text_value; button.disabled = false;} //empty
						else{ 
							if(result==-1){  // BLOCKED
								rfield.innerHTML = loader ;
								window.location.reload();
							}
							else{		
																	
								rfield.style.visibility="visible"; //alert("result: "+result+" ; innerHTML:"+ document.getElementById(new_field).innerHTML);
								rfield.innerHTML = ""+result;
								show(rfield.id);
								//add_element(element_id);
								button.disabled = false;
								text.value = "";
								text.focus();
								text.style.height = 20;
								var empty_item=document.getElementById(element_id+"_empty"); 
								if(empty_item != null){ empty_item.style.display = "none"; }
								var parse_result = result.match(comments_id_filter); //alert(parse_result);
								if(parse_result!=null){ last_comment_id = parse_result[1]; } //alert(last_comment_id);
							}
						}//end else
					  }
			  }// end of callback function
					  
		if(track_comments==1){ last_comment = last_comment_id; }else{ last_comment=0; }	  
		// CALL Object
		//alert(filter);		
		commentObj.update("function=add_comment&content="+target+"&content_type="+target_type+"&comment_text="+urlencode((text_value))+"&language="+language+"&owner_id="+owner_id+"&comment_member="+member+"&comment_notify="+notify+"&event_id="+event_id+"&comment_filter="+filter+'&direction='+direction+'&last_comment_id='+last_comment);
	}//END IF LENGTH
	else{
		alert(REQ_COMMENT_NO_TEXT);	
	}
	
}
function refresh_comments(target, mod, limit, start, element_id, root, mo, language, filter, direction){
	// Comments function; Last update: 2010-12-03
	reset_element(element_id);
	//add_element(element_id);
	var element_no = check_elements(element_id);
	var new_field = ''+element_id+'_'+element_no;//comments_containers; //PROBLEMA	
	//reduce_element(element_id);
	//alert(new_field + ' No: '+element_no);
	if(direction==undefined) direction = 'desc';
	list = document.getElementById(element_id); list.innerHTML = loader;
	if(document.getElementById(new_field)==null) list.innerHTML = '<div id="'+new_field+'" style="margin:0px;"></div>';
	field = document.getElementById(new_field);
	//field.style.visibility="hidden";
	//field.innerHTML = '<div align="center" style="width:100%;"><img src="'+root+'/images/loading1.gif" border=0></div>';
	
	// NEW //
	var commentObj = new ajaxObject(new_field, root+'inc/request.php');
        commentObj.callback = 
			function() { //alert('start callback');
				var rfield = document.getElementById(new_field); 
				var result = rfield.innerHTML;// alert(result);
				if(rfield){  
					comments_containers++; // alert("result: "+result+" ; innerHTML:"+ document.getElementById(new_field).innerHTML);
					if(result==0){ rfield.innerHTML = '<li class="commentItem tac" id="comment_0">'+REQ_COMMENTS_EMPTY+'</li>' ;}
					else{
						rfield.style.visibility="visible"; //alert("result: "+result+" ; innerHTML:"+ document.getElementById(new_field).innerHTML);
						rfield.innerHTML = ""+result;
						//add_element(element_id);
						// RESTORE SHOW ALL button
						var show_all_button = document.getElementById(element_id+'_show_all_button'); //alert(show_all_button);
						if(show_all_button!=null) show_all_button.style.display = "block";
					}
				  }
		  }// end of callback function
				  
				  
	// CALL Object
	//alert('objects created');
	//alert((parseInt(start)+parseInt((limit*(element_no-1)))));
	commentObj.update("function=show_comments&target="+target+"&mod="+mod+"&limit="+limit+"&start="+(parseInt(start)+parseInt((limit*(element_no))))+"&modify="+mo+"&language="+language+"&filter="+filter+'&direction='+direction);
	
}


function get_comments(target, mod, limit, start, element_id, root, mo, language, filter, direction){
	// Comments function; Last update: 2010-12-03	
	add_element(element_id);
	element_no = check_elements(element_id); //alert('Element no: '+element_no+ ' id:'+element_id);
	new_field = ''+element_id+'_'+element_no;//comments_containers; //PROBLEMA	
	//reduce_element(element_id); 
	if(direction==undefined) direction = 'desc';
	//alert(new_field + ' No: '+element_no);
	
	list = document.getElementById(element_id);
	if(document.getElementById(new_field)==null) list.innerHTML = '<div id="'+new_field+'" style="margin:0px;"></div>' + list.innerHTML;
	field = document.getElementById(new_field);
	//field.style.visibility="hidden";
	//field.innerHTML = '<div align="center" style="width:100%;"><img src="'+root+'/images/loading1.gif" border=0></div>';
	
	// NEW //
	var commentObj = new ajaxObject(new_field, root+'inc/request.php');
        commentObj.callback = 
			function() { //alert('start callback');
				var rfield = document.getElementById(new_field); 
				var result = rfield.innerHTML;// alert(result);
				if(rfield){  
					comments_containers++; // alert("result: "+result+" ; innerHTML:"+ document.getElementById(new_field).innerHTML);
					if(result==0){ rfield.innerHTML = '<h2 align="center">'+nothing+'</h2>' ;}
					else{
					
						parse_result = result.match(comments_id_filter);
						last_comment_id = parse_result[1]; //alert(last_comment_id);
						rfield.style.visibility="visible"; //alert("result: "+result+" ; innerHTML:"+ document.getElementById(new_field).innerHTML);
						rfield.innerHTML = ""+result;
						//add_element(element_id);
						// REMOVE SHOW ALL button
						var show_all_button = document.getElementById(element_id+'_show_all_button'); //alert(show_all_button);
						if(show_all_button!=null) show_all_button.style.display = "none";
					}
				  }
		  }// end of callback function
				  
				  
	// CALL Object
	//alert('objects created');
	//alert((parseInt(start)+parseInt((limit*(element_no-1)))));
	commentObj.update("function=show_comments&target="+target+"&mod="+mod+"&limit="+limit+"&start="+(parseInt(start)+parseInt((limit*(element_no-1))))+"&modify="+mo+"&language="+language+"&filter="+filter+'&direction='+direction);
	
}

function delete_event(item_id, user_id, root, field, created){
	var rs = confirm(REQ_DELETE_CONFIRM);
	if(rs){		
		var content = document.getElementById(field);
		var new_field = field+'_delete_result';
		if(content!=null){ content.innerHTML=content.innerHTML+'<div id="'+new_field+'" style="display:none;"></div>';}
		var delObj = new ajaxObject(new_field, root+'inc/request.php');
			delObj.callback = 
				function() { //alert('start callback');
					var rfield = document.getElementById(new_field); 
					var result = rfield.innerHTML;// alert(result);
					if(rfield){						
						if(result==0){ alert('Klaida') ;}
						else{ 
							hide(field);
						}
					}
			  }// end of callback function
					  
		// CALL Object
		delObj.update("function=delete_event&item_id="+item_id+"&user_id="+user_id+"&created="+created);	
	}//end if confirm
}

function delete_item(item_type, item_id, user_id, key, root, field, field_show){

	var rs = confirm(REQ_DELETE_CONFIRM);
	if(rs){		
		var content = document.getElementById(field);
		var new_field = field+'_delete_result';
		if(content!=null){ content.innerHTML=content.innerHTML+'<div id="'+new_field+'" style="display:none;"></div>';}
		var delObj = new ajaxObject(new_field, root+'inc/request.php');
			delObj.callback = 
				function() { //alert('start callback');
					var rfield = document.getElementById(new_field); 
					var result = rfield.innerHTML;// alert(result);
					if(rfield){						
						if(result==0){ alert(REQ_DELETE_ERROR1) ;}
						else{ 
							hide(field);
							if(field_show!=undefined){ show(field_show); }
						}
					}
			  }// end of callback function
					  
		// CALL Object
		delObj.update("function=delete_"+item_type+"&item_id="+item_id+"&user_id="+user_id+"&key="+key);	
	}//end if confirm
}

function delete_comment(id, user_id, root, mo, created){
	item_id='comment_'+id;
	var rs = confirm(REQ_DELETE_CONFIRM);
	if(rs){
		var xmlhttp;  
		if (window.XMLHttpRequest)
		  {
		  // code for IE7+, Firefox, Chrome, Opera, Safari
		  xmlhttp=new XMLHttpRequest();
		  }
		else
		  {
		  // code for IE6, IE5
		  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
		  }
		xmlhttp.onreadystatechange=function()
				{
				if(xmlhttp.readyState==4)
				  {	
				  if(xmlhttp.status == 200){
					 // alert('test'+comments_containers);
					  
					  if(field){  
						comments_containers++; 
						if(xmlhttp.responseText==0){ alert(REQ_DELETE_ERROR1); }
						else if(xmlhttp.responseText==1){
							//field.style.visibility="visible";
							//field.innerHTML = ""+xmlhttp.responseText;
							//alert(xmlhttp.responseText);
							hide(item_id);
							
						}else{ alert(REQ_ERROR + " "+xmlhttp.responseText); }
					  }
				 }else{ alert(REQ_DELETE_ERROR2); }
				  
				  }
				}	
		var url = root+"inc/request.php";
		
		url = url + "?function=delete_comment&item_id="+id+"&user_id="+user_id+"&modify="+mo+"&created="+created;
		
		xmlhttp.open("GET",url,true);
		xmlhttp.send(null);
	}//end if confirmed
	
			
}
// LIKES //
function like(target_type, target, owner_id, user_id, language, element_id, root, notify){
	// Comments function; Last update: 2010-12-03
	if(notify==null){ notify=0;}
	var content=document.getElementById(element_id);		
	var old_content = content.innerHTML; //alert(old_content);
	var new_field = element_id+'_result';
	content.innerHTML = old_content + '<span id="'+new_field+'" style="visibility:hidden; display:none;"></span>';
	var count=document.getElementById(element_id+'_count');
	// NEW //
	var likeObj = new ajaxObject(new_field, root+'inc/request.php');
		likeObj.callback = 
			function() { //alert('start callback');
				var result = document.getElementById(new_field).innerHTML; //alert(result);
				if(result){  
					if(result==0){ content.innerHTML = REQ_YOU_LIKE_ALREADY;} //empty
					else{
						content.style.visibility="visible"; //alert("result: "+result+" ; innerHTML:"+ document.getElementById(new_field).innerHTML);
						content.innerHTML = REQ_YOU_LIKE;//+result;
						content.disabled = true;
						count.innerHTML = '(<i>'+result+'</i>)';
						count.style.display = 'block';
						content.href = null;	
						content.onclick = null;
						content.disabled = true;
					}
				  }
		  }// end of callback function
				  
				  
	// CALL Object
	//alert(text_value);
	likeObj.update("function=add_like&content="+target+"&content_type="+target_type+"&language="+language+"&owner_id="+owner_id+"&user_id="+user_id+'&notify='+notify, 0);
	
	
}

function remove_like(target, target_type, owner_id, user_id, language, element_id, root){
	// Comments function; Last update: 2010-12-03
	var content=document.getElementById(element_id);		
	var old_content = content.innerHTML; //alert(old_content);
	var new_field = element_id+'_result';
	content.innerHTML = old_content + '<span id="'+new_field+'" style="visibility:hidden; display:none;"></span>';
	// NEW //
	var likeObj = new ajaxObject(new_field, root+'inc/request.php');
		likeObj.callback = 
			function() { //alert('start callback');
				var result = document.getElementById(new_field).innerHTML; //alert(result);
				if(result){  
					if(result==0){ content.innerHTML = REQ_YOU_LIKE_ALREADY;} //empty
					else{
						content.style.visibility="visible"; //alert("result: "+result+" ; innerHTML:"+ document.getElementById(new_field).innerHTML);
						content.innerHTML = REQ_YOU_LIKE;//+result;
						content.disabled = true;
					}
				  }
		  }// end of callback function
				  
				  
	// CALL Object
	//alert(text_value);
	likeObj.update("function=add_like&content="+target+"&content_type="+target_type+"&language="+language+"&owner_id="+owner_id+"&user_id="+user_id);
	
	
}
// END LIKES //



function get_events(target, limit, element_id, root, language, filter){ //alert(language);
	new_field = 'event_'+element_id+'_'+events_containers;
	list = document.getElementById(element_id);
	if(document.getElementById(new_field)==null) list.innerHTML =list.innerHTML+ '<div id="'+new_field+'" style="margin:0px;"></div>';
	field = document.getElementById(new_field);
	//field.style.visibility="hidden";
	field.innerHTML = '<div align="center" style="width:100%;">'+loader+'</div>';
	
	// NEW //	
	var eventObj = new ajaxObject(new_field, root+'inc/request.php');
        eventObj.callback = 
			function() { 
				var rfield = document.getElementById(new_field); 
				var result = rfield.innerHTML; //alert(result);
				if(rfield){  
				    events_containers++; 
					if(result==0){ 
						events_containers=events_containers-1; 
						rfield.innerHTML = '<ul class="GUI_List eventList"><li class="GUI_Item Item tac Empty" id="'+element_id+'_0">'+nothing+'</li></ul>';//'<h2 align="center">'+nothing+'</h2>'; 
						var show_more = document.getElementById(element_id+'_show_more');
						if(show_more!=null) show_more.style.display = 'none';
						}
					else{
						rfield.style.visibility="visible";
						rfield.innerHTML = result;
					}
				  }
								
		  }// end of callback function
				  
				  
	// CALL Object
	eventObj.update("function=show_events&user_id="+target+"&language="+language+"&limit="+limit+"&start="+(limit*(events_containers-1))+"&filter="+filter);		
}
function rate(target1, target2, target_type, vote){
	item_id='rate_'+target1+'_'+target2+'_'+target_type;
	field = document.getElementById(item_id);
		var xmlhttp;  
		if (window.XMLHttpRequest)
		  {
		  // code for IE7+, Firefox, Chrome, Opera, Safari
		  xmlhttp=new XMLHttpRequest();
		  }
		else
		  {
		  // code for IE6, IE5
		  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
		  }
		xmlhttp.onreadystatechange=function()
				{
				if(xmlhttp.readyState==4)
				  {	
				  if(xmlhttp.status == 200){
					  //alert(xmlhttp.responseText);
					  
						//events_containers++; 
						if(xmlhttp.responseText==0){ alert(REQ_DELETE_ERROR1); }
						else if(xmlhttp.responseText==1){
							//field.style.visibility="visible";
							field.innerHTML = "Ačiū. Jūsų balas: "+vote;
							//alert(xmlhttp.responseText);
							//alert('Ačiū');
							//hide(item_id);
							
						}else if(xmlhttp.responseText<0){ field.innerHTML = REQ_ALREADY_VOTED+" "+xmlhttp.responseText.replace('-',''); 
						}else{ alert(REQ_ERROR + " "+xmlhttp.responseText); }
					  
				 }else{ alert(REQ_DELETE_ERROR1); }
				  
				  }
				}	
		var url = this_root+"inc/request.php";
		
		url = url + "?function=add_rating&target1="+target1+"&target2="+target2+"&target_type="+target_type+"&vote="+vote;
		
		xmlhttp.open("GET",url,true);
		xmlhttp.send(null);
			
}	


function FitToContent(id, maxHeight)
{
   var text = id && id.style ? id : document.getElementById(id);
   if ( !text )
      return;

   var adjustedHeight = text.clientHeight;
   if ( !maxHeight || maxHeight > adjustedHeight )
   {
      adjustedHeight = Math.max(text.scrollHeight, adjustedHeight);
      if ( maxHeight )
         adjustedHeight = Math.min(maxHeight, adjustedHeight);
      if ( adjustedHeight > text.clientHeight )
         text.style.height = adjustedHeight + "px";
   }
}
function AutoSizeText(element_id){
	document.getElementById(element_id).onkeyup = function() {
      FitToContent( this, 200 )
    };
}
