var url = 'f/ajax.php';

function initTextarea()
{
	if($('btn-link') && $('btn-bold') && $('btn-italic') && $('btn-underline') && $('btn-del') && $('forum-textarea'))
	{
		Event.observe($('btn-bold'), 'click', function(){ surroundText('[b]', '[/b]', $('forum-textarea')); });
		Event.observe($('btn-italic'), 'click', function(){ surroundText('[i]', '[/i]', $('forum-textarea')); });
		Event.observe($('btn-underline'), 'click', function(){ surroundText('[u]', '[/u]', $('forum-textarea')); });
		Event.observe($('btn-del'), 'click', function(){ surroundText('[d]', '[/d]', $('forum-textarea')); });
		Event.observe($('btn-link'), 'click', function(){ 
			var txt = prompt("въведете текст на линка", ""); 
			var link = prompt("въведете линк", ""); 

			// Добавяне на http:// 
			if(link.substring(0, 7) != 'http://')
				link = 'http://' + link;

			if(link != null && link.trim() != '') 
				surroundText('[url=' + link + ']' + txt + '[/url]', '', $('forum-textarea')); 
			});
		
	}
	
	$A(document.getElementsByClassName('allemos')).each(function(img){
		Event.observe(img, 'mouseover', swapEmo);
		Event.observe(img, 'mouseout', swapEmo);
		Event.observe(img, 'click', insertEmo);
	});
}
function initPollbuttons()
{
	var pollans = 2;
	if($('forum-addans-btn'))
		Event.observe($('forum-addans-btn'), 'click', function(){ 
			if(pollans > 9) 
				alert('Не може да има повече от 10 отговора.');
			else{
				pollans ++;
				var newdiv = document.createElement('div');
				newdiv.setAttribute('id', 'answer' + pollans);
				newdiv.setAttribute('class', 'sep');
				newdiv.innerHTML = 'Отговор ' + pollans + ': <input type="text" name="answer[]" class="ans-input"/>';
				$('answers').appendChild(newdiv);
			}
		});

	if($('forum-removeans-btn'))
		Event.observe($('forum-removeans-btn'), 'click', function(){ 
	
			if(pollans < 3) 
				alert('Не може да има по-малко от 2 отговора.');
			else{
				$('answers').removeChild($('answer' + pollans));
				pollans --;
			}			
		});
	if($('f-newpoll-add'))
		Event.observe($('f-newpoll-add'), 'click', function(){ 
			if($('polltitle').value.trim() == '') 
			{
				alert("Попълнета всички полета!"); return;
			} 
			var has_empty = false;
			$A(document.getElementsByClassName('ans-input')).each(function(inp){ 
				if(inp.value.trim() == ''){ has_empty = true;}
			});			
			if(has_empty)
			{
				alert("Попълнета всички полета!"); return;
			}
			$('newtopic-form').submit();
		});
}
Event.onDOMReady( function(){ 

	initTextarea();
	initPollbuttons();

	if($('f-newtopic-add'))
		Event.observe($('f-newtopic-add'), 'click', function(){ if($('topictitle').value.trim() == '' || $('forum-textarea').value.trim() == '') {alert("Попълнета всички полета!"); return;} $('newtopic-form').submit(); });

	if($('f-newpost-add'))
		Event.observe($('f-newpost-add'), 'click', function(){ if($('forum-textarea').value.trim() == '') {alert("Напишете отговор!"); return;} $('newpost-form').submit(); });

	$A(document.getElementsByClassName('forum-quote-btn')).each(function(obj){ 
		Event.observe(obj, 'click', function(){ 
			if($('forum-textarea'))
			{
				temp = this.rel.split(','); 
				var pars = 'action=getpost&post_id=' + temp[1];
				var myAjax = new Ajax.Request(
				url, 
				{
					method: 'post', 
					parameters: pars, 
					onComplete: function(originalRequest){ $('forum-textarea').value += '[цитат=' + temp[0] + ']' + originalRequest.responseText + '[/цитат]';}
				});		

				/* OLD temp = this.rel.split(','); 
				temp2 = $('post' + temp[1]).innerHTML;
				temp2 = temp2.replace(/<div class="forum-quoted">/g, '[цитат]');
				temp2 = temp2.replace(/<\/div>/g, '[/цитат]');
				$('forum-textarea').value += '[цитат]' + temp[0] + "\n" + temp2.stripTags() + '[/цитат]';
				*/
			}
		});
	});
/* #############
	$A(document.getElementsByClassName('forum-edit-btn')).each(function(obj){ 
		Event.observe(obj, 'click', function(){ 
			temp = this.rel.split('-'); 
			postarea = $('post' + temp[1]);
			
			var pars = 'action=getpost&post_id=' + temp[1];
			var myAjax = new Ajax.Request(
				url, 
				{
					method: 'post', 
					parameters: pars, 
					onComplete: function(originalRequest){ postarea.innerHTML = '<textarea name="editpost" id="editpost">' + originalRequest.responseText + '</textarea><a href="javascript:;" class="forum-save-btn" onclick="updatepost(' + temp[1] + ')">промени</a>';}
				});			
			
		});
	});
*/	
	// Block
	$A(document.getElementsByClassName('forum-btn-block')).each(function(obj){ 
		Event.observe(obj, 'click', function(){ 
			if(confirm('Блокиране?'))
			{
				temp = this.rel.split('-'); 
				
				var pars = 'action=block&block_id=' + temp[1];
				var myAjax = new Ajax.Request(
					url, 
					{
						method: 'post', 
						parameters: pars, 
						onComplete: function(originalRequest){ alert(originalRequest.responseText); window.location.reload(); }
					});	
			}
			
		});
	});

	// UnBlock
	$A(document.getElementsByClassName('forum-btn-unblock')).each(function(obj){ 
		Event.observe(obj, 'click', function(){ 
			if(confirm('Премахване от блокираните?'))
			{
				temp = this.rel.split('-'); 
				
				var pars = 'action=unblock&block_id=' + temp[1];
				var myAjax = new Ajax.Request(
					url, 
					{
						method: 'post', 
						parameters: pars, 
						onComplete: function(originalRequest){ window.location.reload(); }
					});	
			}
			
		});
	});
	
	// Remove from favourites
	$A(document.getElementsByClassName('forum-btn-unfav')).each(function(obj){ 
		Event.observe(obj, 'click', function(){ 
			if(confirm('Премахване от любими?'))
			{
				temp = this.rel.split('-'); 
				
				var pars = 'action=unfav&fav_id=' + temp[1];
				var myAjax = new Ajax.Request(
					url, 
					{
						method: 'post', 
						parameters: pars, 
						onComplete: function(originalRequest){ window.location.reload(); }
					});	
			}
			
		});
	});

	// Add to favourites
	$A(document.getElementsByClassName('forum-btn-addf')).each(function(obj){ 
		Event.observe(obj, 'click', function(){ 
			
			temp = this.rel.split('-'); 
			
			if(this.className == 'forum-btn-addf')
				this.className = 'forum-btn-addf forum-btn-addf-on';
			else
				this.className = 'forum-btn-addf';

			var pars = 'action=addf&fav_id=' + temp[1];
			var myAjax = new Ajax.Request(
				url, 
				{
					method: 'post', 
					parameters: pars, 
					onComplete: function(originalRequest){ alert(originalRequest.responseText); }
				});	
			
			
		});
	});

	$A(document.getElementsByClassName('forum-delete-btn')).each(function(obj){ 
		Event.observe(obj, 'click', function(){ 
			if(confirm('Изтриване?'))
			{
				temp = this.rel.split('-'); 
				postbox = $('postbox' + temp[1]);
				
				var pars = 'action=deletepost&post_id=' + temp[1];
				var myAjax = new Ajax.Request(
					url, 
					{
						method: 'post', 
						parameters: pars, 
						onComplete: function(){ postbox.hide();}
					});	
			}
			
		});
	});

	if($('forum-lock-btn'))
		Event.observe($('forum-lock-btn'), 'click', function(){ 
			if(confirm('Да заключа/отключа темата?'))
			{
				temp = this.rel.split('-'); 
				
				var pars = 'action=locktopic&topic_id=' + temp[1];
				var myAjax = new Ajax.Request(
					url, 
					{
						method: 'post', 
						parameters: pars, 
						onComplete: function(){ window.location.reload(); }
					});	
			}
			
		});

	if($('forum-userlock-btn'))
		Event.observe($('forum-userlock-btn'), 'click', function(){ 
			if(confirm('Да заключа/отключа темата?'))
			{
				temp = this.rel.split('-'); 
				
				var pars = 'action=userlocktopic&topic_id=' + temp[1];
				var myAjax = new Ajax.Request(
					url, 
					{
						method: 'post', 
						parameters: pars, 
						onComplete: function(){ window.location.reload(); }
					});	
			}
			
		});

	if($('forum-deltopic-btn'))
		Event.observe($('forum-deltopic-btn'), 'click', function(){ 
			if(confirm('Да изтрия ли темата?'))
			{
				temp = this.rel.split('-'); 
				
				var pars = 'action=deltopic&topic_id=' + temp[1];
				var myAjax = new Ajax.Request(
					url, 
					{
						method: 'post', 
						parameters: pars, 
						onComplete: function(){ window.location = 'forum.php'; }
					});	
			}
			
		});

	if($('forum-lockcomment-btn'))
		Event.observe($('forum-lockcomment-btn'), 'click', function(){ 
			
			var comment = prompt("въведете причина за заключване", "");

			temp = this.rel.split('-'); 
			
			var pars = 'action=lockcomment&topic_id=' + temp[1] + '&comment=' + comment;
			var myAjax = new Ajax.Request(
				url, 
				{
					method: 'post', 
					parameters: pars, 
					onComplete: function(){  }
				});	

			
		});
	
	if($('forum-move-btn'))
		Event.observe($('forum-move-btn'), 'click', function(){ 
			if(confirm('Да преместя темата в изтрити/или обратно?'))
			{
				var comment = prompt("въведете причина за изтриване", "");
				temp = this.rel.split('-'); 
				
				var pars = 'action=movetopic&topic_id=' + temp[1] + '&comment=' + comment;
				var myAjax = new Ajax.Request(
					url, 
					{
						method: 'post', 
						parameters: pars, 
						onComplete: function(){  }
					});	
			}
			
		});
	
	$A(document.getElementsByClassName('forum-spam-btn')).each(function(obj){ 
		Event.observe(obj, 'click', function(){ 
			if(confirm('Да преместя маркирам/отмаркирам като спам?'))
			{
				temp = this.rel.split('-'); 
				var pars = 'action=spam&post_id=' + temp[1];
				var myAjax = new Ajax.Request(
					url, 
					{
						method: 'post', 
						parameters: pars, 
						onComplete: function(){ window.location.reload(); }
					});	
			}
		});
	});

	if($('forum-cool-btn'))
		Event.observe($('forum-cool-btn'), 'click', function(){ 
			if(confirm('Да включа/изключа темата от готини?'))
			{
				temp = this.rel.split('-'); 
				
				var pars = 'action=cooltopic&topic_id=' + temp[1];
				var myAjax = new Ajax.Request(
					url, 
					{
						method: 'post', 
						parameters: pars, 
						onComplete: function(){  }
					});	
			}
			
		});

	if($('forum-favshow-btn'))
		Event.observe($('forum-favshow-btn'), 'click', function(){ 
			if($('forum-favexpand').style.display == '')
				$('forum-favexpand').style.display = 'block';

			if($('forum-favexpand').style.display == 'block')
			{
				this.src = 'img/hide_off.png';
				$('forum-favexpand').style.display = 'none';
			}else{
				this.src = 'img/hide_on.png';
				$('forum-favexpand').style.display = 'block';
			}			
		});
	
	
	if($('forum-jump'))
		Event.observe($('forum-jump'), 'change', function(){ 
			window.location = 'forum.php?action=listtopics&section=' + this.value;
		});

});

function insertEmo()
{
	surroundText(this.title, '', $('forum-textarea'));
	//$('forum-textarea').value += ' ' + this.title;
}
function swapEmo()
{
	emoid = this.id.replace('emo', '');

	if(this.className == 'allemos static')
	{
		this.src = 'f/img/emo/' + emoid + '.gif';
		this.className = 'allemos';
	}else{
		this.src = 'f/img/emo/' + emoid + '-static.gif';
		this.className = 'allemos static';
	}
}

function surroundText(text1, text2, textarea)
{

	if(textarea.isTextEdit){ textarea.focus(); textarea.caretPos = document.selection.createRange();}


   // Can a text range be created?
   if (typeof(textarea.caretPos) != "undefined" && textarea.createTextRange)
   {
      var caretPos = textarea.caretPos, temp_length = caretPos.text.length;

      caretPos.text = caretPos.text.charAt(caretPos.text.length - 1) == ' ' ? text1 + caretPos.text + text2 + ' ' : text1 + caretPos.text + text2;

      if (temp_length == 0)
      {
         caretPos.moveStart("character", -text2.length);
         caretPos.moveEnd("character", -text2.length);
         caretPos.select();
      }
      else
         textarea.focus(caretPos);
   }
   // Mozilla text range wrap.
   else if (typeof(textarea.selectionStart) != "undefined")
   {
      var begin = textarea.value.substr(0, textarea.selectionStart);
      var selection = textarea.value.substr(textarea.selectionStart, textarea.selectionEnd - textarea.selectionStart);
      var end = textarea.value.substr(textarea.selectionEnd);
      var newCursorPos = textarea.selectionStart;
      var scrollPos = textarea.scrollTop;

      textarea.value = begin + text1 + selection + text2 + end;

      if (textarea.setSelectionRange)
      {
         if (selection.length == 0)
            textarea.setSelectionRange(newCursorPos + text1.length, newCursorPos + text1.length);
         else
            textarea.setSelectionRange(newCursorPos, newCursorPos + text1.length + selection.length + text2.length);
         textarea.focus();
      }
      textarea.scrollTop = scrollPos;
   }
   // Just put them on the end, then.
   else
   {
      textarea.value += text1 + text2;
      textarea.focus(textarea.value.length - 1);
   }
}
function updatepost(id)
{
	postarea = $('post' + id);

	var pars = 'action=updatepost&post_id=' + temp[1] + '&post=' + Base64.encode($('editpost').value);
	var myAjax = new Ajax.Request(
		url, 
		{
			method: 'post', 
			parameters: pars, 
			onComplete: function(originalRequest){ postarea.innerHTML = originalRequest.responseText;}
		});	
}
function updatepost2(id)
{
	postarea = $('post' + id);
	var topictitle = "";
	
	if($('topictitle'))
		topictitle = '&topictitle=' + Base64.encode($('topictitle').value);

	if($('forum-textarea').value.trim() == '')
	{
		alert('Вкарайте по-дълъг текст!'); return;
	}
	$('hideedit').hide();
	var pars = 'action=updatepost&post_id=' + id + '&post=' + Base64.encode($('forum-textarea').value) + topictitle;
	var myAjax = new Ajax.Request(
		url, 
		{
			method: 'post', 
			parameters: pars, 
			onComplete: function(originalRequest){ postarea.innerHTML = originalRequest.responseText; Modalbox.hide(); window.location.reload();}
		});	
}

function updatetopic(id)
{

	var topictitle = "";
	
	if($('topictitle'))
		topictitle = '&topictitle=' + Base64.encode($('topictitle').value);

	if($('section_id'))
		section = '&section_id=' + $('section_id').value;

	$('hideedit').hide();
	var pars = 'action=edittopic&topic_id=' + id + '&post=' + section + topictitle;
	var myAjax = new Ajax.Request(
		url, 
		{
			method: 'post', 
			parameters: pars, 
			onComplete: function(originalRequest){ Modalbox.hide(); window.location.reload();}
		});	
}
