var fc = {} // Namespace

// Tags
fc.tagUrl = "/tags/?tag=";
fc.drawTags = function(search) {
	if (gebi("tagSearchButtonId")) gebi("tagSearchButtonId").style.display = "none";
	var container = gebi("tagListId"), html = "", i, re;
	if (container != null) {
		if (typeof this.tagList != "undefined") {
			if (search) re = new RegExp("^"+search, "i");
			for (i = 0; i < this.tagList.length; i++) {
				if (search) if (!re.test(this.tagList[i][1])) continue;
				html += '<a style="font-size:'+this.tagList[i][2]+'pt;" href="'+this.tagUrl+this.tagList[i][0]+'">'+this.tagList[i][1]+'</a>';
			}
			if (!html) html = "Список тегов пуст";
		} else html = "Список тегов пуст";
		container.innerHTML = html;
	}
}
fc.tagTimer = null;
fc.tagKeyUpHandler = function() {
	var val = gebi("tagSearchId").value;
	val = val.replace("'", "\\'");
	if (this.tagTimer != null) {
		clearTimeout(this.tagTimer);
		this.tagTimer = null;
	}
	this.tagTimer = setTimeout("fc.drawTags('"+val+"')", 300);
}

// Counters
fc.showCounters = function(o) {
	var show = gebi("showCountersId");
	var hide = gebi("hideCountersId");
	if (show && hide) {
		show.style.display = o ? "none" : "";
		hide.style.display = o ? "inline" : "none";
	}
	var spans = gebi("counters").getElementsByTagName("span");
	for (var i = 0; i < spans.length; i++) spans[i].style.visibility = o ? "visible" : "hidden";
}


// >>> За основу взят объект, написанный автором Sardar <Sardar@vingrad.ru>
var textAreaSelectionObjects = [];
function getTextAreaSelection(id) {
	if (typeof(textAreaSelectionObjects[id]) == "undefined") {
		textAreaSelectionObjects[id] = new textAreaSelectionHelper(id);
	}
	return textAreaSelectionObjects[id];
}
function textAreaSelectionHelper(id) {
    var obj = document.getElementById(id);
    this.target = obj;
    this.target.carretHandler = this;
    this.target.onchange = _textareaSaver;
    this.target.onclick = _textareaSaver;
    this.target.onkeyup = _textareaSaver;
    this.target.onfocus = _textareaSaver;
    if(!document.selection) this.target.onSelect = _textareaSaver;
    this.start=-1;
    this.end=-1;
    this.scroll=-1;
    this.iesel=null;
}
textAreaSelectionHelper.prototype = {
    getSelectedText : function() {
        return this.iesel? this.iesel.text: (this.start>=0&&this.end>this.start)? this.target.value.substring(this.start,this.end): "";
    },
    setSelectedText : function(text, secondtag) {
        if (this.iesel) {
            if (typeof(secondtag) == "string") {
                var l = this.iesel.text.length;
                this.iesel.text = text + this.iesel.text + secondtag;
                this.iesel.moveEnd("character", -secondtag.length);
                this.iesel.moveStart("character", -l);  
            } else {
                this.iesel.text = text;
            }
            this.iesel.select();
        } else if (this.start >= 0 && this.end >= this.start) {
            var left = this.target.value.substring(0, this.start);
            var right = this.target.value.substr(this.end);
            var scont = this.target.value.substring(this.start, this.end);
            if (typeof(secondtag) == "string") {
                this.target.value = left + text + scont + secondtag + right;
                this.end = this.target.selectionEnd=this.start+text.length+scont.length;
                this.start = this.target.selectionStart = this.start + text.length;    
            } else {
                this.target.value = left + text + right;
                this.end = this.target.selectionEnd = this.start + text.length;
                this.start = this.target.selectionStart = this.start + text.length;
            }
            this.target.scrollTop = this.scroll;
            this.target.focus();
        } else {
            this.target.value += text + ((typeof(secondtag) == "string") ? secondtag: "");
            if (this.scroll >= 0) this.target.scrollTop = this.scroll;
        }
    }
}
function _textareaSaver() {
    if(document.selection) {
        this.carretHandler.iesel = document.selection.createRange().duplicate();
    } else if(typeof(this.selectionStart) != "undefined") {
        this.carretHandler.start = this.selectionStart;
        this.carretHandler.end = this.selectionEnd;
        this.carretHandler.scroll = this.scrollTop;
    } else {
        this.carretHandler.start = this.carretHandler.end = -1;
    }
}

function setLink(id, url) {
	var url = prompt("Введите URL", (url ? url : "http://"));
	if (!url || url == "") return;
	if (checkURL(url)) {
		getTextAreaSelection(id).setSelectedText("[url="+url+"]", "[/url]");
	} else {
		alert("Ссылка в неверном формате");
		setLink(id, url);
	}
}
function setQuote(id) {
	var source = prompt("Автор цитаты", "");
	if (!source) source = false;
	getTextAreaSelection(id).setSelectedText("[quote" + (source ? "="+source : "") + "]", "[/quote]");
}

function setSyntax(id, button, evt) {
	var div;
	if (typeof id == "undefined") {
		if (div = gebi("syntaxId")) div.style.display = "none";
		return;
	}
	evt = evt || window.event;
	evt.cancelBubble = true;
	var typeArray = [
		["", "код"],
		["html","HTML"],
		["js","JavaScript"],
		["css","CSS"],
		["php","PHP"],
		["mysql","MySQL"],
		["xml", "XML"],
		["bash", "bash"],
		["diff", "diff"],
		["perl", "Perl"],
		["python", "Python"],
		["ruby", "Ruby"],
		["java", "Java"],
		["cpp", "C++"]
	];
	if (!gebi("syntaxId")) {
		div = document.createElement("div");
		div.id = "syntaxId";
		div.className = "syntaxList";
		div.style.display = "none";
		gebi("syntaxConteiner").appendChild(div);
	}
	div = gebi("syntaxId");
	div.innerHTML = "";
	for (var i = 0; i < typeArray.length; i++) {
		if (i == 0) div.innerHTML += "<a href=\"#\" onclick=\"return false;\">"+typeArray[i][1]+"<\/a><br\/><br\/>";
		else div.innerHTML += "<a onclick=\"getTextAreaSelection('" + id + "').setSelectedText('[syntax="+typeArray[i][0]+"]', '[/syntax]'); return false;\" href=\"#\">"+typeArray[i][1]+"<\/a><br\/>";
	}
	div.style.display = "";
}

// Comments
fc.wasReply = 0;
fc.writeComment = function(entityId, reply, article) {
	if (typeof article == 'undefined')
		article = 0;
	switch(article) {
		case 1:
			article = '/articles/?aid=';
		break;
		case 2:
			article = '/forum/?topicId=';
		break;
		default :
			article = '/news/?id=';
		break;
		
	}
	var container = gebi('reply_' + reply);
	if (container == null) return;
	try {
		gebi('reply_' + this.wasReply).innerHTML = '';
	} catch(e) {}
	var rnd = Math.floor(Math.random()*1000000);
	container.innerHTML = (reply ? '<div class="addComment" style="border:0;">' : '')+'<div style="padding-left:20px;" class="selectLinks">\
		<span onclick="getTextAreaSelection(\'bb'+rnd+'\').setSelectedText(\'\[b]\', \'[/b]\');" style="font-weight:bold;">жирный<\/span>\
		<span onclick="getTextAreaSelection(\'bb'+rnd+'\').setSelectedText(\'\[i]\', \'[/i]\');" style="font-style:italic;">курсив<\/span>\
		<span onclick="setLink(\'bb'+rnd+'\');" style="text-decoration:underline;">ссылка<\/span>\
		<span onclick="setQuote(\'bb'+rnd+'\');">„цитата“<\/span>\
		<span onclick="setSyntax(\'bb'+rnd+'\', this, event);" style="border-bottom:1px dotted #BFA75F;">код<\/span>\
		<span style="position:absolute;" id="syntaxConteiner">&nbsp;<\/span>\
	<\/div>\
	<div class="form" style="margin-left:20px;"><form method="post" action="'+article+entityId+'"><p>\
		<input type="hidden" name="foreparent_id" value="'+entityId+'" \/>\
		<input type="hidden" name="parent_id" value="'+(reply ? reply : '')+'" \/>\
		<textarea onkeydown="fc.areaHeight(this);" onkeyup="fc.areaHeight(this);" id="bb'+rnd+'" cols="20" rows="5" name="body"'+(reply ? '' :' style="border:0;"')+'><\/textarea>\
		<input type="submit" name="goaddc" value="Ответить" \/>\
	<\/p><\/form><\/div>' + (reply ? '<\/div>' : '');
	gebi('bb'+rnd).focus();
	getTextAreaSelection('bb'+rnd);
	this.wasReply = reply;
	return false;
}
fc.areaHeight = function(t) {
	var rows = t.value.split("\n").length;
	rows = rows <= 5 ? 5 : rows + 1;
	t.rows = rows;
}