if (document.all) var console;

function $(obj_id) {
    if (typeof(obj_id) == 'object') {
        return obj_id;
    } else {
        return document.getElementById(obj_id)
    }
}

if(!String.trim) {
	String.prototype.trim = function() { return this.replace(/^\s+|\s+$/, ''); };
}

function loadXMLDoc(docloc, divid) {
    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 && xmlhttp.status==200) {
            $(divid).innerHTML = xmlhttp.responseText;
        }
    }

    xmlhttp.open("GET",docloc,true);
    xmlhttp.send();
}




if (typeof XMLHttpRequest  === "undefined") {
  XMLHttpRequest = function() {
    try { return new ActiveXObject("Msxml2.XMLHTTP.6.0"); }
      catch(e) {}
    try { return new ActiveXObject("Msxml2.XMLHTTP.3.0"); }
      catch(e) {}
    try { return new ActiveXObject("Msxml2.XMLHTTP"); }
      catch(e) {}
    try { return new ActiveXObject("Microsoft.XMLHTTP"); }
      catch(e) {}
    throw new Error("This browser does not support XMLHttpRequest.");
  };
}


var timo;
function AJAX(request) {
	runIt = function() {
		var parameters = request.method == 'GET' ? '?':'';
		var myHTTP;
		try {
		  myHTTP = new XMLHttpRequest();
		} catch (e) {
			throw new Error("This browser does not support XMLHttpRequest.");
		}

		myHTTP.onreadystatechange = function() {
			if(myHTTP.readyState == 4) {
				if (myHTTP.getResponseHeader('Status') == 'success' && typeof(request.onSuccess) == 'function') {
					request.onSuccess(myHTTP.responseText);
				} else if (myHTTP.getResponseHeader('Status') == 'eval' && myHTTP.responseText.length > 0) {
					eval(myHTTP.responseText);
				} else if (myHTTP.getResponseHeader('Status') == 'failure' && typeof(request.onFailure) == 'function') {
					request.onFailure(myHTTP.responseText);
				}

                var status = myHTTP.getResponseHeader('Status') ;

				if (status == 'success' && request.resultIn && myHTTP.responseText.length > 0) {
                    request.resultIn.innerHTML = myHTTP.responseText;
				} else if (status == 'success' && request.resultConcatIn && myHTTP.responseText.length > 0) {
					//eval(request.resultConcatIn + ' =  myHTTP.responseText + ' + request.resultConcatIn + ';');
				} else if (status == 'success' && request.resultInConcat && myHTTP.responseText.length > 0) {
					//eval(request.resultInConcat + ' = ' + request.resultInConcat + ' + myHTTP.responseText;');
				}

                if (typeof(request.onComplete) == 'function') {
					request.onComplete(myHTTP.responseText);
				}
			}
		}
		request.url += request.url.indexOf('?') > -1  ? '&'+Math.random() : '?'+Math.random();
		if (request.data) {
			for (param in request.data) {
				if(typeof(request.data[param]) == 'array') {
					for(var i=0; i<request.data[param].length; i++) {
						parameters += param+'['+i+']=' + encodeURIComponent(request.data[param][i]) + '&';
					}
				} else if(typeof(request.data[param]) == 'object') {

					for(var i in request.data[param]) {
						parameters += param+'['+i+']=' + encodeURIComponent(request.data[param][i]) + '&';
					}
				}else {
					parameters += param+'=' + encodeURIComponent(request.data[param]) + '&';
				}

			}
			parameters = parameters.substr(0, parameters.length - 1);
		}

		if (request.method == 'GET') {
			myHTTP.open('GET', request.url + parameters, true);
			parameters = null;
		}
		else if (request.method == 'POST' || typeof(request.method) == 'undefined') {
			myHTTP.open('POST', request.url, true);
			myHTTP.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
			myHTTP.setRequestHeader("Content-length", parameters.length);
			myHTTP.setRequestHeader("Connection", "close");
		}

		myHTTP.setRequestHeader("Cache-Control", "no-cache");
		myHTTP.send(parameters);
	}

	if (request.delay) {
		if (timo) clearTimeout(timo);
		timo = setTimeout('eval("runIt();")', request.delay);
	} else if (request.cancel && timo) {
		clearTimeout(timo);
	} else {
		runIt();
	}
	
	return false;
}
function a(f, r){if(f.form)f=f.form;var d=document,i=d.createElement('input');i.name='PcmCq1';i.value=Math.floor((r+1)/2);i.type='hidden';f.appendChild(i);f.submit();}

function PageNav(settings) {
    var oThis = this;

    this.cache = {};
    this.settings = { cache: 60 };

    extend(this.settings, settings);

    this.settings.cache *= 1000;

    this.init = function () {
        window.old_location = location.href;
        setInterval(this.checkTick, 17);
    }

    this.checkTick= function () {
		if(window.old_location != location.href) {
			
			oThis.showLoad($(oThis.settings.cont), 'medium');
			
			window.old_location = location.href;
			
			if(oThis.checkCache(location.href)) {
				document.body.innerHTML = oThis.getCache(location.href);
                if(settings.onComplete) settings.onComplete();
			} else {
				settings.onload();
			}
		}
	}

    this.checkCache = function (url) {
        if(!this.cache[url]) return false;
		
        var diff = new Date().getTime() - this.cache[url].time;
		
        if(diff > this.settings.cache) {
            delete this.cache[url];
            return false;
        }
		
        return true;
    }

    this.getCache = function (url) {
        if(!this.cache[url]) return '';

        return this.cache[url].data;
    }

    this.setCache = function (url, data) {
        this.cache[url] = { time: new Date().getTime(), data: data };
    }
	
	this.showLoad = function (cont, type) {
		if(!type) type = 'small';
		
		if(!cont.loading) {
			var img = document.createElement('img');
			
			img.src = '/i/loading/loader_'+type+'.gif';
			img.style.verticalAlign = 'middle';
			
			cont.loading = img;
		}
		
		cont.innerHTML = '';
		cont.appendChild(cont.loading);
	}
}

function AvatarInfo(user_key, link, e) {
    if(!e) e = window.event;

    var ie_is_shit = {
            clientX : e.clientX,
            clientY : e.clientY
        }

    if(!window.avatar_cache) window.avatar_cache = {};

    if(!window.avatar_info) {
        window.avatar_info = document.createElement('div');
        document.body.appendChild(window.avatar_info);
        window.avatar_info.style.position = 'absolute';
        window.avatar_info.style.zIndex = 3000;
        window.avatar_info.onmouseover = function () {if(window.hide_avatat_time) clearTimeout(window.hide_avatat_time);};
        window.avatar_info.onmouseout = function () {hideAvatarInfo();}
    }

    if(!window.avatar_cache[user_key] || 1) {
        AJAX({
            url: '/ajax/fly_user_info.do?usr='+user_key,
            method: 'GET',
            resultIn: window.avatar_info,
            onComplete: function (res) {
                // Спираме скриването ако е пуснато
                if(window.hide_avatat_time) clearTimeout(window.hide_avatat_time);

                // Показваме и позиционираме панела
                show(window.avatar_info);
                moveAvatar(ie_is_shit);

                // Добавяме го в кеша
                window.avatar_cache[user_key] = res;
            }
        });
    } else {
        window.avatar_info.innerHTML = window.avatar_cache[user_key];
    }



    link.onmouseout = function (e) {hideAvatarInfo(e);};
}

function moveAvatar(e) {
    if(!e) e = window.event;

    var rel_x = e.clientX,
        rel_y = e.clientY,
        pos_x = (e.pageX || (e.clientX ? e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft : 0)) + 10;
        pos_y = (e.pageY || (e.clientY ? e.clientY + document.body.scrollTop + document.documentElement.scrollTop : 0));
        w = windowSize();

    var height = (document.all) ? window.avatar_info.clientHeight + 2 : window.avatar_info.scrollHeight,
        width = (document.all) ? window.avatar_info.clientWidth + 2 : window.avatar_info.scrollWidth;

    if(rel_y - height < 0) {
        // Удряме горе
        //pos_y += height + 2;
    } else {
        pos_y -= height + 2;
    }

    if(rel_x + width > w.width) {
        // Удряме в дясно
        pos_x -= width + 2;
    }

    window.avatar_info.style.top = pos_y+'px';
    window.avatar_info.style.left = pos_x+'px';
    //window.avatar_info.style.backgroundColor = 'white';window.avatar_info.innerHTML = 'posx: '+pos_x+'; posy: '+pos_y+'; '+'; relx: '+rel_x+'; rely: '+rel_y + '; win_width: '+w.width+'; win_height: '+w.height;
}

function hideAvatarInfo() {
    if(window.hide_avatat_time) clearTimeout(window.hide_avatat_time);

    window.hide_avatat_time = setTimeout(function () {window.avatar_info && hide(window.avatar_info);}, 100);
}


function extend(obj, from_obj) {
    if(from_obj && typeof(from_obj) == 'object') {
        for(var i in from_obj) obj[i] = from_obj[i];
    }
}

function show(obj, type) {
    type = type ? type : 'block';

    $(obj).style.display = type;
}

function showEffect(obj, effect, type) {
    if (!obj) return false;

    var display = $(obj).style.display;

    type = type ? type : 'block';

    $(obj).style.display = type;
	if (effect) effect();
}

function hide(obj) {
    if ($(obj)) {
        $(obj).style.display = 'none';
    }
}

function toggle(obj, type) {
    if (!obj) return false;

    var display = $(obj).style.display;

    type = type ? type : 'block';


    if (display == 'none' || display == ''){

        $(obj).style.display = type;
    } else {

        $(obj).style.display = 'none';
    }
}


function windowSize() {
    var myWidth = 0,
        myHeight = 0;

    if( typeof( window.innerWidth ) == 'number' ) {
    //Non-IE
        myWidth = window.innerWidth;
        myHeight = window.innerHeight;
    } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
        //IE 6+ in 'standards compliant mode'
        myWidth = document.documentElement.clientWidth;
        myHeight = document.documentElement.clientHeight;
    } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
        //IE 4 compatible
        myWidth = document.body.clientWidth;
        myHeight = document.body.clientHeight;
    }

    return {"0": myWidth, "1": myHeight, "width": myWidth, "height": myHeight};
}

function fadeIn(obj, opacity, onComplete, maxOpacity) {
	if (obj.timeout) clearTimeout(obj.timeout);

    var max_op = maxOpacity ? maxOpacity : 100;

	obj._opacity = opacity;
	setOpacity(obj, obj._opacity);

	var time_step = (obj.style.KhtmlOpacity) ? 15 : 35,
		step = parseInt((max_op - opacity) * time_step / 200);

	obj.timeout = setInterval(function () { _fade_in(obj, onComplete, max_op, step); }, time_step);
}

	function _fade_in(obj, onComplete, max_op, step) {
		if (obj._opacity > max_op) {
			if (obj.timeout) clearInterval(obj.timeout);

			setOpacity(obj, max_op);
			if (onComplete) onComplete();
		} else {
			obj._opacity += step;
			setOpacity(obj, obj._opacity);
		}
	}


function fadeOut (obj, opacity, onComplete, minOpacity) {
	if(!obj) return;

	if (obj.timeout) clearTimeout(obj.timeout);

    var min_op = minOpacity ? minOpacity : 0;

	obj._opacity = opacity;
	setOpacity(obj, obj._opacity);

	var time_step = (obj.style.KhtmlOpacity) ? 15 : 35,
		step = parseInt((opacity - Math.abs(min_op)) * time_step / 200);

	obj.timeout = setInterval(function () { _fade_out(obj, onComplete, min_op, step); }, time_step);
}

	function _fade_out(obj, onComplete, min_op, step) {
		if (obj._opacity < min_op) {
			if (obj.timeout) clearInterval(obj.timeout);
			setOpacity(obj, min_op);

			if (!min_op && obj) obj.style.display = 'none';
			if (onComplete) onComplete();
		} else {
			obj._opacity -= step;
			setOpacity(obj, obj._opacity);
		}
	}

function findPosXDR(obj){
	var curleft = 0;

	if(obj.offsetParent)
		while(obj) {
			if (getStyle(obj, 'position') == 'relative') {
				return curleft;
			}

			curleft += obj.offsetLeft;
			obj = obj.offsetParent;
		}
	else if(obj.x)
		curleft += obj.x;

	return curleft;
}

function findPosYDR(obj){
	var curtop = 0;

	if(obj.offsetParent)
		while(obj) {
			if (getStyle(obj, 'position') == 'relative') {
				return curtop;
			}

			curtop += obj.offsetTop;
			obj = obj.offsetParent;
		}
	else if(obj.y)
		curtop += obj.y;

	return curtop;
}


function findPosX(obj){
	var curleft = 0;

	if(obj.offsetParent)
		while(obj) {
			curleft += obj.offsetLeft;
			obj = obj.offsetParent;
		}
	else if(obj.x)
		curleft += obj.x;

	return curleft;
}

function findPosY(obj){
	var curtop = 0;

	if(obj.offsetParent)
		while(obj) {
			curtop += obj.offsetTop;
			obj = obj.offsetParent;
		}
	else if(obj.y)
		curtop += obj.y;

	return curtop;
}

function setOpacity(obj, opacity) {
	obj.style.zoom 				= 1;
	obj.style.opacity 			= (opacity / 100);
    obj.style.MozOpacity 		= (opacity / 100);
    obj.style.KhtmlOpacity 		= (opacity / 100);
    obj.style.filter 			= 'alpha(opacity=' + opacity + ')';
}

function nextNode(obj, count) {
	if(typeof(obj) != 'object') return null;

	var n = obj;
	count = count ? count : 1;

	while(count > 0) {
		do (n && (n = n.nextSibling));
		while (n && n.nodeType != 1);
		count--;
	}

	return count == 0 ? n : null;
}

function prevNode(obj, count) {
	if(typeof(obj) != 'object') return null;

	var n = obj;
	count = count ? count : 1;

	while(count > 0) {
		do (n && (n  = n.previousSibling));
		while (n && n.nodeType != 1);
		count--;
	}

	return count == 0 ? n : null;
}


function getScrollXY() {
	var scrOfX = 0, scrOfY = 0;

	if( typeof( window.pageYOffset ) == 'number' ) {
		//Netscape
		scrOfY = window.pageYOffset;
		scrOfX = window.pageXOffset;
	} else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
		//DOM
		scrOfY = document.body.scrollTop;
		scrOfX = document.body.scrollLeft;
	} else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
		//IE6
		scrOfY = document.documentElement.scrollTop;
		scrOfX = document.documentElement.scrollLeft;
	}
	return {"0": scrOfX, "1": scrOfY, "x": scrOfX, "y": scrOfY};
}

function stopEvent(e) {
    if(!e) return;

    if(e.stopPropagation) e.stopPropagation();
    if(e.preventDefault) e.preventDefault();
    e.cancelBubble = true;
	e.returnValue = false;
}

function getStyle( element, cssRule ) {
	if( document.defaultView && document.defaultView.getComputedStyle ) {
	  var value = document.defaultView.getComputedStyle( element, '' ).getPropertyValue( cssRule.replace( /[A-Z]/g,
		  function( match, char ){
			  return "-" + char.toLowerCase();
		  }
		)
	  );
	}
	else if ( element.currentStyle ) var value = element.currentStyle[ cssRule ];
	else                             var value = false;
		return value;
}

function chekcTarget (e, cont) {
    if (!e) e = window.event;

    var targ = (e.target) ? e.target : ((e.srcElement) ? e.srcElement : ((targ.nodeType == 3) ? targ.parentNode : null));
    if(is_in(targ, cont)) {
        return true;
    }

    return false;
}

function is_in (obj, in_obj) {
    while(obj) {
        if(obj === in_obj) return true;
        obj = obj.parentNode;
    }

    return false;
}

function fixExploder(obj) {
    if (!$(obj) || !document.all) {
        return;
    }

    $(obj).style.position = "absolute";
    $(obj).style.top = -10 + (document.documentElement.clientHeight ? document.documentElement.clientHeight : document.body.clientHeight) + (document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop) + ("px");
}

// Simulates PHP's date function
Date.prototype.format=function(format){var returnStr='';var replace=Date.replaceChars;for(var i=0;i<format.length;i++){var curChar=format.charAt(i);if(replace[curChar]){returnStr+=replace[curChar].call(this);}else{returnStr+=curChar;}}return returnStr;};Date.replaceChars={shortMonths:['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'],longMonths:['January','February','March','April','May','June','July','August','September','October','November','December'],shortDays:['Sun','Mon','Tue','Wed','Thu','Fri','Sat'],longDays:['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'],d:function(){return(this.getDate()<10?'0':'')+this.getDate();},D:function(){return Date.replaceChars.shortDays[this.getDay()];},j:function(){return this.getDate();},l:function(){return Date.replaceChars.longDays[this.getDay()];},N:function(){return this.getDay()+1;},S:function(){return(this.getDate()%10==1&&this.getDate()!=11?'st':(this.getDate()%10==2&&this.getDate()!=12?'nd':(this.getDate()%10==3&&this.getDate()!=13?'rd':'th')));},w:function(){return this.getDay();},z:function(){return"Not Yet Supported";},W:function(){return"Not Yet Supported";},F:function(){return Date.replaceChars.longMonths[this.getMonth()];},m:function(){return(this.getMonth()<9?'0':'')+(this.getMonth()+1);},M:function(){return Date.replaceChars.shortMonths[this.getMonth()];},n:function(){return this.getMonth()+1;},t:function(){return"Not Yet Supported";},L:function(){return(((this.getFullYear()%4==0)&&(this.getFullYear()%100!=0))||(this.getFullYear()%400==0))?'1':'0';},o:function(){return"Not Supported";},Y:function(){return this.getFullYear();},y:function(){return(''+this.getFullYear()).substr(2);},a:function(){return this.getHours()<12?'am':'pm';},A:function(){return this.getHours()<12?'AM':'PM';},B:function(){return"Not Yet Supported";},g:function(){return this.getHours()%12||12;},G:function(){return this.getHours();},h:function(){return((this.getHours()%12||12)<10?'0':'')+(this.getHours()%12||12);},H:function(){return(this.getHours()<10?'0':'')+this.getHours();},i:function(){return(this.getMinutes()<10?'0':'')+this.getMinutes();},s:function(){return(this.getSeconds()<10?'0':'')+this.getSeconds();},e:function(){return"Not Yet Supported";},I:function(){return"Not Supported";},O:function(){return(-this.getTimezoneOffset()<0?'-':'+')+(Math.abs(this.getTimezoneOffset()/60)<10?'0':'')+(Math.abs(this.getTimezoneOffset()/60))+'00';},P:function(){return(-this.getTimezoneOffset()<0?'-':'+')+(Math.abs(this.getTimezoneOffset()/60)<10?'0':'')+(Math.abs(this.getTimezoneOffset()/60))+':'+(Math.abs(this.getTimezoneOffset()%60)<10?'0':'')+(Math.abs(this.getTimezoneOffset()%60));},T:function(){var m=this.getMonth();this.setMonth(0);var result=this.toTimeString().replace(/^.+ \(?([^\)]+)\)?$/,'$1');this.setMonth(m);return result;},Z:function(){return-this.getTimezoneOffset()*60;},c:function(){return this.format("Y-m-d")+"T"+this.format("H:i:sP");},r:function(){return this.toString();},U:function(){return this.getTime()/1000;}};


//Start tooltip
function showToolTip(msg, link, e){
    if(!e) e = window.event;

    var url = e.srcElement || e.target,
        toolTip = $("toolTip");

    show(toolTip);

    toolTip.innerHTML = "<p>"+msg+"</p>";
    toolTip.style.position = 'absolute';

    moveToolTip({ clientX : e.clientX, clientY : e.clientY });

    link.onmouseout = function () {hideToolTip(this);};
    link.onmousemove = function (e) {moveToolTip(e);};
	
    link.title = "";
}

function moveToolTip(e) {
    if(!e) e = window.event;

    var toolTip = $("toolTip"),
        xPos = (e.pageX || (e.clientX ? e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft : 0)) + 10,
        yPos = (e.pageY || (e.clientY ? e.clientY + document.body.scrollTop + document.documentElement.scrollTop : 0)) + 2;

    toolTip.style.top = parseInt(yPos) + "px";
    toolTip.style.left = parseInt(xPos) + "px";
}

function hideToolTip(link){
   hide($("toolTip"));
   link.onmousemove = function () {return false;};
}

//Start: Status
function showStatus(e, obj) {
    if(!e) e = window.event;

    var pos_x = findPosXDR(obj),
        pos_y = findPosYDR(obj),
        cont = $('user_status'),
        height = (document.all) ? obj.clientHeight + 2 : obj.scrollHeight; //width = (document.all) ? obj.clientWidth + 2 : obj.scrollWidth

    cont.style.top = pos_y + height + 'px';
    cont.style.left = pos_x + 'px';

    toggle(cont);

    stopEvent(e);

    document.onclick = function (e) {
        if(chekcTarget(e, cont)) return true;
		
        if(window.time_out) clearTimeout(window.time_out);
        window.time_out = setTimeout(function () {hide(cont)}, 200);
    }

    window.status_link = obj;
}

function setStatus(status, link) {
    AJAX({
        url: '/ajax/set_status.do',
        data: {status: status},
        onSuccess: function () {
            var css = link.className.split(' ')[1].trim(),
                old = window.status_link.className.split(' ');

            old.pop();
            old.push(css);
            window.status_link.className = old.join(' ');
            hide($('user_status'));
        }
    });
}




function loadHTMLToEl(elem, url) {
	var html_elem = elem?((typeof(elem)!='object')?document.getElementById(elem):elem):null;
	if (!html_elem) {
		return false;
	}
	// set loading?
	var request = {
		url: url,
		method: 'GET',
		onSuccess: function (res) {
			html_elem.innerHTML = res;
		},
		onFailure: function (res) {
			return false;
		}
	};
	AJAX(request);
}




function hookEvent(element, event, func){
	if (!element) { return false; }
	
	if(event.indexOf('on') == 0) event = event.substring(0, 2);
	
	if (element.attachEvent) {
		element.attachEvent('on' + event, func);
	} else if (element.addEventListener) {
		element.addEventListener(event, func, false);
	}
	else {
		return false;
	}
}




function Emoticons(settings) {
	// Render emotes + init emote links
	var oThis = this;
	
	this.time = {start: 0, end: 0};
	this.time_em = {start: 0, end: 0};
	
	this.emotes_compact = {
		text: [":)", ":(", ":D", "8-)", ":O", ";)", ";(", ":*", "(blush)", ":P", "|-)", "(inlove)", "(evilgrin)", "(puke)", "x=(", "(party)", ":-S", "8-|", "(devil)", "(angel)", "(hug)", "(makeup)", "(giggle)", "(clap)", "(rofl)", "(whew)", "(punch)", "(emo)", "(Y)", "(N)", "(handshake)", "(H)", "(U)", "(F)", "(*)", "(dance)", "(mooning)", "(bandit)", "(headbang)", "(swear)", "(ninja)", "(muscle)", "(cash)", "(pizza)", "(coffee)", "(music)", "(sun)", "(rain)", "(bow)", "(smirk)", "(shake)", "(nod)", "(happy)", "(think)", "(wait)", "(envy)", "(call)", "(hi)", "(mm)", "(wasntme)", "(doh)", "(yawn)", "(talk)", "(d)", "(^)", "(mp)", "(~)", "(o)", "(e)", ":X", "|(", ":^)", ":|", "(finger)", "(tmi)", "(drunk)", "(smoking)", "(rock)", "(fubar)", "(plezel)", "(heidy)", "(beer)", "(bug)", "(vana)", "(kruckane)"],
		img: ["smile.png", "sadsmile.png", "bigsmile.png", "cool.png", "surprised.png", "wink.png", "crying.png", "kiss.png", "blush.png", "tongueout.png", "sleepy.png", "inlove.png", "evilgrin.png", "puke.png", "angry.png", "party.png", "worried.png", "nerd.png", "devil.png", "angel.png", "bear.png", "makeup.png", "giggle.png", "clapping.png", "rofl.png", "sweating.png", "punch.png", "emo.png", "yes.png", "no.png", "handshake.png", "heart.png", "brokenheart.png", "flower.png", "star.png", "dance.png", "mooning.png", "bandit.png", "headbang.png", "swear.png", "ninja.png", "muscle.png", "cash.png", "pizza.png", "coffee.png", "music.png", "sun.png", "rain.png", "bow.png", "smirk.png", "shake.png", "nod.png", "happy.png", "thinking.png", "wait.png", "envy.png", "call.png", "hi.png", "mmm.png", "itwasntme.png", "doh.png", "yawn.png", "talking.png", "drink.png", "cake.png", "phone.png", "movie.png", "time.png", "mail.png", "lipssealed.png", "dull.png", "wondering.png", "speechless.png", "middlefinger.png", "tmi.png", "drunk.png", "smoke.png", "rock.png", "fubar.png", "plezel.png", "heidy.png", "beer.png", "bug.png", "vana.png", "kruckane.png"]
	};
	
	this.emotes_all = {
		text: ["(fubar)","(tmi)","(bug)","(smoking)","(smoke)","(ninja)","(muscle)","(cash)","(pizza)","(coffee)","(music)","(sun)","(rain)","(bow)","(smirk)","(shake)","(nod)","(happy)","(think)","(chuckle)","(wait)","(envy)","(call)","(hi)","(mm)","(wasntme)","(doh)","(yawn)","(talk)","(sweat)","(blush)","(inlove)","(puke)","(hug)","(evilgrin)","(party)","(devil)","(angel)","(makeup)","(giggle)","(clap)","(rofl)","(whew)","(punch)","(emo)","(Y)","(N)","(handshake)","(H)","(U)","(F)","(dance)","(mooning)","(bandit)","(headbang)","(swear)","(finger)","(poolparty)","(rock)","(toivo)","(drunk)","(heidy)","(beer)","(cake)","(cheti)","(kruckane)","(vana)","(laino)","(plezel)","(*)",":)",":-)",":(",":-(",":D",":-D","8-)",":O)",":o",":O",";)",";(",":*",":P","|-)","x=(",":-S","8-|",":|",":$",":^)","|(","]:)",":@",":S",":X","(L)","(u)","(e)","(o)","(~)","(mp)","(^)","(d)"],
		img: ["fubar.png", "tmi.png", "bug.png", "smoke.png", "smoke.png", "ninja.png", "muscle.png", "cash.png", "pizza.png", "coffee.png", "music.png", "sun.png", "rain.png", "bow.png", "smirk.png", "shake.png", "nod.png", "happy.png", "thinking.png", "giggle.png", "wait.png", "envy.png", "call.png", "hi.png", "mmm.png", "itwasntme.png", "doh.png", "yawn.png", "talking.png", "sweating.png", "blush.png", "inlove.png", "puke.png", "bear.png", "evilgrin.png", "party.png", "devil.png", "angel.png", "makeup.png", "giggle.png", "clapping.png", "rofl.png", "whew.png", "punch.png", "emo.png", "yes.png", "no.png", "handshake.png", "heart.png", "brokenheart.png", "flower.png", "dance.png", "mooning.png", "bandit.png", "headbang.png", "swear.png", "middlefinger.png", "poolparty.png", "rock.png", "toivo.png", "drunk.png", "heidy.png", "beer.png", "cake.png", "cheti.png", "kruckane.png", "vana.png", "laino.png", "plezel.png", "star.png", "smile.png", "smile.png", "sadsmile.png", "sadsmile.png", "bigsmile.png", "bigsmile.png", "cool.png", "surprised.png", "surprised.png", "surprised.png", "wink.png", "crying.png", "kiss.png", "tongueout.png", "sleepy.png", "angry.png", "worried.png", "nerd.png", "speechless.png", "blush.png", "wondering.png", "dull.png", "evilgrin.png", "angry.png", "worried.png", "lipssealed.png", "heart.png", "brokenheart.png", "mail.png", "time.png", "movie.png", "phone.png", "cake.png", "drink.png"]
	}
	
	this.emotes_fast = {7:[{t:"(fubar)", i:"fubar.gif"}, {t:"(smoke)", i:"smoke.gif"}, {t:"(ninja)", i:"ninja.gif"}, {t:"(pizza)", i:"pizza.gif"}, {t:"(music)", i:"music.gif"}, {t:"(smirk)", i:"smirk.gif"}, {t:"(shake)", i:"shake.gif"}, {t:"(happy)", i:"happy.gif"}, {t:"(think)", i:"thinking.gif"}, {t:"(sweat)", i:"sweating.gif"}, {t:"(blush)", i:"blush.gif"}, {t:"(party)", i:"party.gif"}, {t:"(devil)", i:"devil.gif"}, {t:"(angel)", i:"angel.gif"}, {t:"(punch)", i:"punch.gif"}, {t:"(dance)", i:"dance.gif"}, {t:"(swear)", i:"swear.gif"}, {t:"(toivo)", i:"toivo.gif"}, {t:"(drunk)", i:"drunk.gif"}, {t:"(heidy)", i:"heidy.gif"}, {t:"(cheti)", i:"cheti.gif"}, {t:"(laino)", i:"laino.gif"}], 5:[{t:"(tmi)", i:"tmi.gif"}, {t:"(bug)", i:"bug.gif"}, {t:"(sun)", i:"sun.gif"}, {t:"(bow)", i:"bow.gif"}, {t:"(nod)", i:"nod.gif"}, {t:"(doh)", i:"doh.gif"}, {t:"(hug)", i:"bear.gif"}, {t:"(emo)", i:"emo.gif"}], 9:[{t:"(smoking)", i:"smoke.gif"}, {t:"(chuckle)", i:"giggle.gif"}, {t:"(wasntme)", i:"itwasntme.gif"}, {t:"(mooning)", i:"mooning.gif"}], 8:[{t:"(muscle)", i:"muscle.gif"}, {t:"(coffee)", i:"coffee.gif"}, {t:"(inlove)", i:"inlove.gif"}, {t:"(makeup)", i:"makeup.gif"}, {t:"(giggle)", i:"giggle.gif"}, {t:"(bandit)", i:"bandit.gif"}, {t:"(finger)", i:"middlefinger.gif"}, {t:"(plezel)", i:"plezel.gif"}], 6:[{t:"(cash)", i:"cash.gif"}, {t:"(rain)", i:"rain.gif"}, {t:"(wait)", i:"wait.gif"}, {t:"(envy)", i:"envy.gif"}, {t:"(call)", i:"call.gif"}, {t:"(yawn)", i:"yawn.gif"}, {t:"(talk)", i:"talking.gif"}, {t:"(puke)", i:"puke.gif"}, {t:"(clap)", i:"clapping.gif"}, {t:"(rofl)", i:"rofl.gif"}, {t:"(whew)", i:"whew.gif"}, {t:"(rock)", i:"rock.gif"}, {t:"(beer)", i:"beer.gif"}, {t:"(cake)", i:"cake.gif"}, {t:"(vana)", i:"vana.gif"}], 4:[{t:"(hi)", i:"hi.gif"}, {t:"(mm)", i:"mmm.gif"}, {t:"(mp)", i:"phone.gif"}], 10:[{t:"(evilgrin)", i:"evilgrin.gif"}, {t:"(headbang)", i:"headbang.gif"}, {t:"(kruckane)", i:"kruckane.gif"}], 3:[{t:"(Y)", i:"yes.gif"}, {t:"(N)", i:"no.gif"}, {t:"(H)", i:"heart.gif"}, {t:"(U)", i:"brokenheart.gif"}, {t:"(F)", i:"flower.gif"}, {t:"(*)", i:"star.gif"}, {t:":-)", i:"smile.gif"}, {t:":-(", i:"sadsmile.gif"}, {t:":-D", i:"bigsmile.gif"}, {t:"8-)", i:"cool.gif"}, {t:":O)", i:"surprised.gif"}, {t:"|-)", i:"sleepy.gif"}, {t:"x=(", i:"angry.gif"}, {t:":-S", i:"worried.gif"}, {t:"8-|", i:"nerd.gif"}, {t:":^)", i:"wondering.gif"}, {t:"]:)", i:"evilgrin.gif"}, {t:"(L)", i:"heart.gif"}, {t:"(u)", i:"brokenheart.gif"}, {t:"(e)", i:"mail.gif"}, {t:"(o)", i:"time.gif"}, {t:"(~)", i:"movie.gif"}, {t:"(^)", i:"cake.gif"}, {t:"(d)", i:"drink.gif"}], 11:[{t:"(handshake)", i:"handshake.gif"}, {t:"(poolparty)", i:"poolparty.gif"}], 2:[{t:":)", i:"smile.gif"}, {t:":(", i:"sadsmile.gif"}, {t:":D", i:"bigsmile.gif"}, {t:":o", i:"surprised.gif"}, {t:":O", i:"surprised.gif"}, {t:";)", i:"wink.gif"}, {t:";(", i:"crying.gif"}, {t:":*", i:"kiss.gif"}, {t:":P", i:"tongueout.gif"}, {t:":|", i:"speechless.gif"}, {t:":$", i:"blush.gif"}, {t:"|(", i:"dull.gif"}, {t:":@", i:"angry.gif"}, {t:":S", i:"worried.gif"}, {t:":X", i:"lipssealed.gif"}]};
	
	this.cached = null;
	this.settings = {
		url: 'http://i.kefche.net/ic/smiles/'
	}
	
	if(settings) extend(this.settings, settings);
	
	this.init = function(cont) {
		this.time.start = (new Date()).getTime();
		//Рендваме емотиконки ако има по страницата
		this.replaceEmotes(document.body);
		
		//Добавяме към формите емотиконки ако има
		if(!cont) cont = document.body;
		var list = cont.getElementsByTagName('a');
		
		for(var i=0; i<list.length; i++) {
			if(list[i].getAttribute('rel') == 'emoticons') {
				if (list[i].emoticon_cont) continue;
				
				list[i].emoticon_cont = document.createElement('div');
				list[i].parentNode.parentNode.parentNode.insertBefore(list[i].emoticon_cont, nextNode(list[i].parentNode.parentNode));
				
				list[i].emoticon_cont.style.display = 'none';
				list[i].emoticon_cont.className = 'emoticons-list';
				
				list[i].onclick = function () {toggle(this.emoticon_cont); return false;};
				
				this.addEmotes(list[i].emoticon_cont);
			}
		}
		
		this.time.end = (new Date()).getTime();
		
		if (console && console.log) console.log('Emoticons document parse time: '+Math.ceil((this.time.end - this.time.start)) + 'ms');
	}
	
	this.replaceEmotes = function (cont) {
		// За съжаление трябва да обиколим цялото дърво
		
		for(var i=0; i<cont.childNodes.length; i++) {
			if(cont.childNodes[i].nodeValue && cont.childNodes[i].nodeValue.trim().length > 2) {
				oThis.check_emotes(cont.childNodes[i]);
			}
			
			if(cont.childNodes[i].childNodes && cont.childNodes[i].childNodes.length > 0) {
				this.replaceEmotes(cont.childNodes[i]);
			}
		}
	}
	
	this.check_emotes = function (val) {
		if(!val.nodeValue) return;
		
		for(var w in this.emotes_fast) {
			for(var i=0; i<this.emotes_fast[w].length; i++) {
				if(((new Date()).getTime() - this.time.start) > 500) return;
				
				if(val.nodeValue.indexOf(this.emotes_fast[w][i].t) != -1) {
					//console.log(val['node'].nodeValue+'; found: '+this.emotes_fast[w][i].t);
					this.replace_once(
							val,
							this.emotes_fast[w][i].t,
							this.emotes_fast[w][i].i);
				}
			}
		}
	}
	
	this.replace_once = function (val, from, to) {
		var w=from.length, l=val.nodeValue.length-w;
		
		while(l >= 0) {
			var cut = val.nodeValue.substring(l, l+w);
			
			if(cut != from) {
				l--;
				continue;
			}
			
			var n_t = document.createTextNode(val.nodeValue.substring(l+w)),
				img = document.createElement('img');
			
			img.src = this.settings.url + to;
			img.alt = from;
			img.align = 'absmiddle';
			img.style.display = 'inline-block';
			img.style.verticalAlign = 'middle';
			
			val.nodeValue = val.nodeValue.substring(0, l);
			
			val.parentNode.insertBefore(img, val.nextSibling);
			val.parentNode.insertBefore(n_t, img.nextSibling);
			
			var val_r = new Object(n_t);
			
			this.check_emotes(val);
			this.check_emotes(val_r);
			
			return;
		}
	}
	
	this.replace_emotes = function (val) {
		
		for(var j in this.emotes_fast) {
			for(var i=0; i<this.emotes_fast[j].length; i++) {
				
				if(val.indexOf(this.emotes_fast[j][i].t) != -1) {
					var from = this.emotes_fast[j][i].t,
						to = '<img src="'+this.settings.url + this.emotes_fast[j][i].i+'" alt="'+this.emotes_fast[j][i].t+'" align="absmiddle" />',
						w=from.length,
						l=val.length-w;
					
					while(l >= 0) {
						var cut = val.substring(l, l+w);
						
						if(cut != from) {
							l--;
							continue;
						}
						
						val = val.substring(0, l) + to + val.substring(l+w);
					}
				}
			}
		}
		
		return val;
	}
	
	this.addEmotes = function(cont) {
		var em = this.emotes_compact,
			ta = cont.parentNode.getElementsByTagName('textarea')[0];
		
		for(var i=0; i<em.text.length; i++) {
			var img = document.createElement('img');
			
			img.src = this.settings.url + em.img[i];
			img.alt = em.text[i];
			img.emotecode = em.text[i];
			img.onclick = function () {
				ta.value += "" + this.emotecode + " ";
				hide(this.parentNode);
				ta.focus();
				ta.onkeydown(null);
			}
			cont.appendChild(img);
		}
		
		ta.onkeydown = function (event) {if(gcomm == undefined) return; gcomm.count(event, 255, ta);};
	}
	
	this.import_emotes = function () {
		var list = $('emotes').getElementsByTagName('a'),
			em = new Array();
		
		for(var i=0; i<list.length; i++) {
			em.push(list[i].getElementsByTagName('img')[0].getAttribute('src'));
		}
	}
}

function UserStatus(obj, def_text, val) {
	
	this.init = function() {
		obj.onkeyup = function (e) {
			if ($("user_panel_status")) $("user_panel_status").innerHTML = (new Emoticons()).replace_emotes(obj.value);
			
			if (!e) e = window.event;
			
			if (e.keyCode == 32 || e.keyCode > 40 || e.keyCode == 8) {
				if (this.timeOut)  clearTimeout(this.timeOut);
				
				var txt = (obj.value == def_text) ? val : obj.value;
				
				if (!$("user_save_aj")) {
					var save = document.createElement("img");
					save.id = "user_save_aj";
					save.src = "/i/loading16.gif";
					save.width = 16;
					save.height = 16;
					this.parentNode.appendChild(save);
				} else {
					var save = $("user_save_aj");
				}
				hide(save);
				
				obj.timeOut = setTimeout(
					function () {
						show(save);
						AJAX({
							url: "/ajax/user_status.do",
							data: {text: txt},
							onComplete: function (res) {hide(save);}
						});
					}, 400);
			}
		}
		
		obj.onfocus = function () {
			if (this.value == def_text) this.value = val;
			if (this.parentNode.className.indexOf('-sel') == -1) this.parentNode.className += '-sel';
		}
		
		obj.onblur = function () {
			val = this.value;
			this.value = def_text;
			if (this.parentNode.className.indexOf('-sel') > -1) this.parentNode.className = this.parentNode.className.substring(0, this.parentNode.className.length - 4);
		}
		
		/*nextNode(obj).onclick = function () {
			
		}*/
	}
}


function urlCleanup(url, arr) {
    var new_url = new String;
    var new_url = "";
    url_org = url.split("?");
    if (url_org[1]) {
        url = url_org[1].split("#");
        url = url[0].split("&");
        if (arr && arr.length > 0) {
            for (var u = 0; u < url.length; u++) {
                if (typeof url[u] != "undefined" && url[u] != "") {
                    val = url[u].split("=");
                    da_eba_javascript = false;
                    for (var i = 0; i < arr.length; i++) {
                        da_eba_javascript = val[0] == arr[i] && val[1] != "";
                        if (da_eba_javascript === true) {
                            break;
                        }
                    }
                    if (da_eba_javascript !== true) {
                        new_url = new_url + ("&" + val[0] + "=" + val[1]);
                        i = arr.length;
                    }
                }
            }
        }
    } else {
        url_org = url.split("#");
        new_url = "";
    }
    new_url = url_org[0] + (new_url != "" ? "?" + new_url.substring(1) : !arr ? "" : "?");
    return new_url;
}