var ajax_url = 'f/ajax.php';
var numAttached = 0;

function showQuote(quo)
{
	$('hidden_'+quo).show();
	$('showquo_'+quo).hide();
}
function favExpand(id)
{
	if($('hid_'+id).visible())
	{
		$('hid_'+id).hide();
		$('exp_'+id).innerHTML = '+ покажи още';
	}
	else
	{
		$('hid_'+id).show();
		$('exp_'+id).innerHTML = '- скрий';
	}
}

function initTextarea()
{
	if($('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')); });
		
		if($('btn-video')) {
		
		Event.observe($('btn-video'), 'click', function(){
			var yt_pattern = /http:\/\/youtube.com\/watch\?v=([A-Za-z0-9_\-]+)/i;
			var vb_pattern = /http:\/\/vbox7.com\/play:([a-z0-9]+)/i;
			var vc_pattern = /http:\/\/videoclip.bg\/watch\?v=([0-9a-zA-Z\-]+)/i;
			var link = prompt("Въведете адреса на видеото от YouTube, vbox7 или VideoClip.bg", "");
			if(link != null && link.trim() != ''){
				if(link.match(yt_pattern)){
					var x = link.match(yt_pattern);
					surroundText('[youtube=' + x[x.length-1] + ']', '', $('forum-textarea'));
				}
				else if(link.match(vb_pattern)){
					var x = link.match(vb_pattern)
					surroundText('[vbox7=' +  x[x.length-1] + ']', '', $('forum-textarea'));
				}
				else if(link.match(vc_pattern)){
					var x = link.match(vc_pattern)
					surroundText('[videoclip=' +  x[x.length-1] + ']', '', $('forum-textarea'));
				}
			}
	});
	
	}

//		Event.observe($('btn-link'), 'click', function(){ 
//
//			var link = prompt("въведете линк", ""); 
//			var txt = prompt("въведете текст на линка", ""); 
//
//			// Добавяне на http:// 
//			if(link.substring(0, 7) != 'http://')
//				link = 'http://' + link;
//
//			if(link != null && link.trim() != '') 
//			  if (txt != null && txt.trim() != '')
//				surroundText('[url=' + link + ']' + txt + '[/url]', '', $('forum-textarea')); 
//			  else
//			    surroundText('[url]' + link + '[/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(
				ajax_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(
				ajax_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>';}
				});			
			
		});
	});
*/	
//quote fix
var tee = 1;
$A(document.getElementsByClassName('quote-unhide')).each(function(quote){

	var quote_id   = quote.id.substr(8);
	var quote_text = document.getElementById('hidden_'+quote_id);
	
	quote.id      = 'showquo_'+tee;
	quote_text.id = 'hidden_'+tee;
	
	tee++;
	});
	// 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(
					ajax_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(
					ajax_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(
					ajax_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(
				ajax_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(
					ajax_url, 
					{
						method: 'post', 
						parameters: pars, 
						onComplete: function(){ postbox.hide();}
					});	
			}
			
		});
	});

	if($('forum-lock-btn'))
		Event.observe($('forum-lock-btn'), 'click', function(){
			temp = this.rel.split('-');
			if(temp[2] == 'unl')
			var lock = 'Да отключа темата?';
			else
			var lock = 'Да заключа/отключа темата?';
			if(confirm(lock))
			{
				var pars = 'action=locktopic&topic_id=' + temp[1];
				var myAjax = new Ajax.Request(
					ajax_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(
					ajax_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(
					ajax_url, 
					{
						method: 'post', 
						parameters: pars, 
						onComplete: function(){ window.location = 'forum.php'; }
					});	
			}
			
	});
	
	
	if($('forum-sticky-btn'))
		Event.observe($('forum-sticky-btn'), 'click', function(){ 
			if(confirm('Да сложа или махна темата като стики?'))
			{
				temp = this.rel.split('-'); 
				
				var pars = 'action=sticky&topic_id=' + temp[1];
				var myAjax = new Ajax.Request(
					ajax_url, 
					{
						method: 'post', 
						parameters: pars, 
						onComplete: function(){ window.location.reload(); }
					});	
			}
			
	});
	

	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(
				ajax_url, 
				{
					method: 'post', 
					parameters: pars, 
					onComplete: function(){ window.location.reload(); }
				});	

			
		});
	
	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(
					ajax_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(
					ajax_url, 
					{
						method: 'post', 
						parameters: pars, 
						onComplete: function(){ window.location.reload(); }
					});	
			}
		});
	});
	
	$A(document.getElementsByClassName('forum-ban-btn')).each(function(obj){ 
		Event.observe(obj, 'click', function(){ 
			var bantype = prompt("Задай тип на бан\n(1 = Глобален 2 = Форумен)", "");
			if(bantype != null && bantype.trim() != ''){
				temp = this.rel.split('-'); 
				var pars = 'action=ban&bantype='+bantype+'&post_id=' + temp[1];
				var myAjax = new Ajax.Request(
					ajax_url, 
					{
						method: 'post', 
						parameters: pars, 
						onComplete: function(originalRequest){ 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(
					ajax_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';
			}			
		});
	
	$A(document.getElementsByClassName('f-hidebtn')).each(function(obj){ 
		
		Event.observe(obj, 'click', function(){ 

			temp = this.id.split('-');
			if($('expandsection' + temp[1]).style.display == '')
				$('expandsection' + temp[1]).style.display = 'block';

			if($('expandsection' + temp[1]).style.display == 'block')
			{
				this.src = 'img/hide_off.png';
				$('expandsection' + temp[1]).style.display = 'none';
			}else{
				this.src = 'img/hide_on.png';
				$('expandsection' + temp[1]).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 = '../img/emo/' + emoid + '.gif';
		this.className = 'allemos';
	}else{
		this.src = '../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(
		ajax_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(
		ajax_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=' + Base64.encode($('forum-textarea').value) + section + topictitle;
	var myAjax = new Ajax.Request(
		ajax_url, 
		{
			method: 'post', 
			parameters: pars, 
			onComplete: function(originalRequest){ Modalbox.hide(); window.location.reload();}
		});	
}

function forumCoolVote(type, topic)
{
var parss = 'action=getcoolrating';
if( (type == 1 || type == 2) && topic) parss += '&vote='+type+'&topic_id='+topic;

new Ajax.Updater('forumVoteBox', ajax_url,
{
	method: 'post',
	parameters: parss
});

}

function forumTrack(topic) {
if(!topic) return false;

$('forumTrackBox').hide();

var myAjax = new Ajax.Request(
ajax_url, 
{
	method: 'post', 
	parameters: 'action=startfollowing&topic_id='+topic, 
	onComplete: function(originalRequest){ alert(originalRequest.responseText); }
});
}
