var HTTPReq = new Object;

HTTPReq.create = function () {
    var xtr;
    var ex;

    if (typeof(XMLHttpRequest) != "undefined") {
        xtr = new XMLHttpRequest();
    } else {
        try {
            xtr = new ActiveXObject("Msxml2.XMLHTTP.4.0");
        } catch (ex) {
            try {
                xtr = new ActiveXObject("Msxml2.XMLHTTP");
            } catch (ex) {
            }
        }
    }

    // let me explain this.  Opera 8 does XMLHttpRequest, but not setRequestHeader.
    // no problem, we thought:  we'll test for setRequestHeader and if it's not present
    // then fall back to the old behavior (treat it as not working).  BUT --- IE6 won't
    // let you even test for setRequestHeader without throwing an exception (you need
    // to call .open on the .xtr first or something)
    try {
        if (xtr && ! xtr.setRequestHeader)
            xtr = null;
    } catch (ex) { }

    return xtr;
};

// opts:
// url, onError, onData, method (GET or POST), data
// url: where to get/post to
// onError: callback on error
// onData: callback on data received
// method: HTTP method, GET by default
// data: what to send to the server (urlencoded)
HTTPReq.getJSON = function (opts) {
    var req = HTTPReq.create();
    if (! req) {
        if (opts.onError) opts.onError("noxmlhttprequest");
        return;
    }

    var state_callback = function () {
        if (req.readyState != 4) return;

        if (req.status != 200) {
            if (opts.onError) opts.onError(req.status ? "status: " + req.status : "no data");
            return;
        }

        var resObj;
        var e;
        try {
            eval("resObj = " + req.responseText + ";");
        } catch (e) {
        }

        if (e || ! resObj) {
            if (opts.onError)
                opts.onError("Error parsing response: \"" + req.responseText + "\"");

            return;
        }

        if (opts.onData)
            opts.onData(resObj);
    };

    req.onreadystatechange = state_callback;

    var method = opts.method || "GET";
    var data = opts.data || null;

    var url = opts.url;
    if (opts.method == "GET" && opts.data) {
        url += url.match(/\?/) ? "&" : "?";
        url += opts.data
    }

    url += url.match(/\?/) ? "&" : "?";
    url += "_rand=" + Math.random();

    req.open(method, url, true);

    // we should send null unless we're in a POST
    var to_send = null;

    if (method.toUpperCase() == "POST") {
        req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        to_send = data;
    }

    req.send(to_send);
};

HTTPReq.formEncoded = function (vars) {
    var enc = [];
    var e;
    for (var key in vars) {
        try {
            if (!vars.hasOwnProperty(key))
                continue;
            enc.push(encodeURIComponent(key) + "=" + encodeURIComponent(vars[key]));
        } catch( e ) {}
    }
    return enc.join("&");

};

HTTPReq.getJSON2 = function (opts) {
    var req = HTTPReq.create();
    if (! req) {
        if (opts.onError) opts.onError("noxmlhttprequest");
        return;
    }

    var state_callback = function () {
        if (req.readyState != 4) return;

        if (req.status != 200) {
            if (opts.onError) opts.onError(req.status ? "status: " + req.status : "no data");
            return;
        }

        if (opts.onData)
            opts.onData(req.responseText);
    };

    req.onreadystatechange = state_callback;

    var method = opts.method || "GET";
    var data = opts.data || null;


    var url = opts.url;
    if (opts.method == "GET" && opts.data) {
        url += url.match(/\?/) ? "&" : "?";
        url += opts.data
    }

    url += url.match(/\?/) ? "&" : "?";
    url += "_rand=" + Math.random();
	url = "http://topbloger.ru"+url;
    req.open(method, url, true);

    if (method.toUpperCase() == "POST")
      req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

    req.send(data);
};

// LJ Thread Unfolder
//================================
//	INIT
//================================

var forsubs = 0;
var cur_thread = 0;
var is_ie = 0;
var buttons_count = 0;
var buttons_array = new Array();
var buttons_all = 0;//значит сейчас все открыты по умолчанию

var unfoldisover = 0;

if  (navigator.appName == "Microsoft Internet Explorer"){
	is_ie = 1;
}

add_unfolders(document);

///////////////////////////////
//================================
//	WORKHORSES
//================================

function add_unfolders(elem) {
	get_itemid_regexp = /thread=(\d+)/;
	var allReplies;
	allReplies = elem.getElementsByTagName("a");
	for (var i = 0; i < allReplies.length; i++) {
		thisOne = allReplies.item(i);
		if(!thisOne.href){
			continue;
		}
		params =  get_itemid_regexp.exec(thisOne.href);
		if(params){
			
			if((thisOne.innerHTML == 'link' || thisOne.innerHTML == 'Parent')
			|| (mycookie!='' && (thisOne.innerHTML == text_link || thisOne.innerHTML == link_parent))
			){
				if(cur_thread!=0){//po cur_thread opredelim, 4to ne podderevo				
					threads_done[params[1]] = 1; 
				}
				continue;
			}
			if((document.getElementById('ljcmt'+params[1]) && thisOne.innerHTML == 'Thread')
			|| (mycookie!='' && (document.getElementById('ljcmt'+params[1]) && thisOne.innerHTML == link_thread))
			){
					if (thisOne.nextSibling && thisOne.nextSibling.nextSibling && (thisOne.nextSibling.nextSibling.innerHTML == '<img src="/App_Themes/Basic/i/load.gif" border="0"> Unfold' || thisOne.nextSibling.nextSibling.innerHTML == '<img src="/App_Themes/Basic/i/load.gif" border="0"> done' || thisOne.nextSibling.nextSibling.innerHTML == '<img src="/App_Themes/Basic/i/load.gif" border="0"> clicked')){
						continue;
					}
													
					if(!thisOne.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.firstChild.firstChild.firstChild.firstChild || thisOne.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.firstChild.firstChild.firstChild.firstChild.width>5){
						continue;
					}
					
					if(!singleposts){//начальный этап
					//alert(thisOne.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.nextSibling.nextSibling.nextSibling.nextSibling.nextSibling.nextSibling.firstChild.firstChild.firstChild.firstChild.firstChild.width);//ширина третьего комментария
					    if(!thisOne.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.nextSibling.nextSibling.nextSibling//нет второго коммента
					    || !thisOne.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.nextSibling.nextSibling.nextSibling.nextSibling.nextSibling//нет третьего коммента
					    || !thisOne.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.nextSibling.nextSibling.nextSibling.nextSibling.nextSibling.nextSibling.firstChild
					    || !thisOne.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.nextSibling.nextSibling.nextSibling.nextSibling.nextSibling.nextSibling.firstChild.firstChild
					    || !thisOne.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.nextSibling.nextSibling.nextSibling.nextSibling.nextSibling.nextSibling.firstChild.firstChild.firstChild
					    || !thisOne.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.nextSibling.nextSibling.nextSibling.nextSibling.nextSibling.nextSibling.firstChild.firstChild.firstChild.firstChild
					    || thisOne.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.parentNode.nextSibling.nextSibling.nextSibling.nextSibling.nextSibling.nextSibling.firstChild.firstChild.firstChild.firstChild.firstChild.width==0){
					        //это из-за того что первый ответ всегда разворачивается
					        continue;
					    }
					}
			   		t = document.createTextNode(' - ');
					thisOne.parentNode.insertBefore(t, thisOne.nextSibling);

					a = document.createElement('a');
					//linktxt = document.createTextNode('Unfold')
					a.href = 'javascript:void(0)';
					
					if (forsubs || thisOne.previousSibling) // 'All' mode
						a.setAttribute('attall', 1);
					a.setAttribute('thread_href', thisOne.href);
					a.setAttribute('thread_id', params[1]);
                    
					//a.setAttribute('onclick', "unfold_thread(this);return false;")
					//a.appendChild(linktxt)
					t.parentNode.insertBefore(a, t.nextSibling);
					if(!threads_done[params[1]]){//mu takogo id ewe ne gruzili...
						a.innerHTML = '<img src="/App_Themes/Basic/i/load.gif" border="0"> Unfold';
						if(cur_thread==0){//po cur_thread opredelim, 4to ne podderevo
							addtodo(params[1],thisOne.href,a);
						}else{//podderevo , pometum, 4to mu ego ne delaem avtomatom
							threads_done[params[1]] = 1;
						}
						DOM.addEventListener(a, "click", unfold_thread);
					}else{
						a.innerHTML = '<img src="/App_Themes/Basic/i/load.gif" border="0"> done';
						if(a.getAttribute){
							DOM.addClassName(a, "unfold_thread");
						}
						DOM.addEventListener(a, "click", unfold_thread);
					}
				//}else{
				//	continue;
				//}
			//}else if(!document.getElementById('ljcmt'+params[1]) && !thisOne.previousSibling){
			}else if(!thisOne.previousSibling){
					//for singles posts;
					a = document.createElement('a');
					
					//linktxt = document.createTextNode('Unfold');
					//a.setAttribute('onclick', "unfold_thread(this);return false;")
					//a.appendChild(linktxt)
					
					a.href = 'javascript:void(0)';
					
					if (forsubs || thisOne.previousSibling) // 'All' mode
						a.setAttribute('attall', 1);
					a.setAttribute('thread_href', thisOne.href);
					a.setAttribute('thread_id', params[1]);

					threads_objs[params[1]] = a;
					if(singleposts){//if we have posts that we dont know at stage1 and stage2
						
						if(!threads_done[params[1]]){//mu takogo id ewe ne gruzili...
							a.innerHTML = '<img src="/App_Themes/Basic/i/load.gif" border="0"> Unfold';
							addtodo(params[1],thisOne.href,a);//меняет _todo
							DOM.addEventListener(a, "click", unfold_thread);
							t = document.createTextNode(' - ');
							thisOne.parentNode.insertBefore(t, thisOne.nextSibling);
							t.parentNode.insertBefore(a, t.nextSibling);
						}
					}
					///aliluya!
			}
		}
	}
	forsubs = 1;
}

function add_unfolders2(elem) { //for single posts = 2nd step
	get_itemid_regexp = /thread=(\d+)/;
	var allReplies;
	allReplies = elem.getElementsByTagName("a");
	for (var i = 0; i < allReplies.length; i++) {
		thisOne = allReplies.item(i);
		if(!thisOne.href){
			continue;
		}
		params =  get_itemid_regexp.exec(thisOne.href);
		if(params){
			if((thisOne.innerHTML == 'link' || thisOne.innerHTML == 'Parent')
			|| (mycookie!='' && (thisOne.innerHTML == text_link || thisOne.innerHTML == link_parent))
			){
				continue;
			}
			if(!thisOne.previousSibling){ // - yslovie na single-post
					if (thisOne.nextSibling && thisOne.nextSibling.nextSibling && (thisOne.nextSibling.nextSibling.innerHTML == '<img src="/App_Themes/Basic/i/load.gif" border="0"> Unfold' || thisOne.nextSibling.nextSibling.innerHTML == '<img src="/App_Themes/Basic/i/load.gif" border="0"> done' || thisOne.nextSibling.nextSibling.innerHTML == '<img src="/App_Themes/Basic/i/load.gif" border="0"> clicked')){
						continue;
					}
					
			   		t = document.createTextNode(' - ');
					thisOne.parentNode.insertBefore(t, thisOne.nextSibling);

					a = document.createElement('a');
					//linktxt = document.createTextNode('Unfold')
					a.href = 'javascript:void(0)';
					
					if (forsubs || thisOne.previousSibling) // 'All' mode
						a.setAttribute('attall', 1);
					a.setAttribute('thread_href', thisOne.href);
					a.setAttribute('thread_id', params[1]);

					
					if(!threads_done[params[1]]){//mu takogo id ewe ne gruzili...
						a.innerHTML = '<img src="/App_Themes/Basic/i/load.gif" border="0"> Unfold';
						if(current>_max){//po cur_thread opredelim, 4to ne podderevo
							addtodo(params[1],thisOne.href,a);//меняет _todo
						}else{//podderevo , pometum, 4to mu ego ne delaem avtomatom
							threads_done[params[1]] = 1;
						}
						DOM.addEventListener(a, "click", unfold_thread);
					}else{
						a.innerHTML = '<img src="/App_Themes/Basic/i/load.gif" border="0"> done';
						if(a.getAttribute){
							DOM.addClassName(a, "unfold_thread");
						}
						DOM.addEventListener(a, "click", unfold_thread);
					}
					t.parentNode.insertBefore(a, t.nextSibling);
				//}else{
				//	continue;
				//}
			}
		}
	}
	setMaxToDo();
}

function unfold_thread(arr) {
	//if(!is_ie){
	//	elem = arr['obj'];
	//}else{
		elem = threads_objs[arr['id']];
	//}
	if(!elem){
		elem = this;
	}
	if(!elem.getAttribute){
		alert('Sorry! IE hasnt supported with this function!');
		return false;
	}
	if(working) return false;
	working = 1;
	//save it
	threads_done[elem.getAttribute('thread_id')]=1;
	DOM.addClassName(elem, "unfold_thread");
	//this.style.cursor = 'default'
	if(elem.blur){
	    elem.blur();
	    //DOM.blur(elem);
	}
	elem.innerHTML = '<img src="/App_Themes/Basic/i/load.gif" border="0"> clicked';

	var url = "/livejournal2.aspx";
	
 	var params = HTTPReq.formEncoded ({
 			"thread_href": elem.getAttribute("thread_href"),
            "journal": Site.currentJournal,
            "mycookie": mycookie
    });
	function parse_result(result){
		working = 0;
		
		var dummy = document.createElement('DIV');
		dummy.style.display = 'none';
		document.body.appendChild(dummy);

		// the same one lives in new doc
		if (elem.getAttribute && elem.getAttribute('attall')){
			if(document.getElementById('ljcmt'+elem.getAttribute('thread_id'))){
				document.getElementById('ljcmt'+elem.getAttribute('thread_id')).id += '_old'
			}
		}
		
		dummy.innerHTML = result;
		reply = document.getElementById('ljcmt'+elem.getAttribute("thread_id"));

		cur_thread = elem.getAttribute('thread_id');
		
		//removed
		if(singleposts){//когда работаем с единичными постами надо развернуть УСЕ.
			add_unfolders(dummy);
		}
		
		// get cell
		td = elem;
		while (td && td.nodeName != 'TD'){
			td = td.parentNode;
		}
		if(!td){
			setTimeout("DoThread()", 300);
			return;
		}
		tbody = td.parentNode.parentNode;
		table = tbody.parentNode;
		my_padding = tbody.firstChild.firstChild.firstChild.width;
		
	if(my_padding < 2){
		//sdelaem dlya razvorotov
		control_ = document.createElement('td');
		control_.align = 'left';
		if(is_ie){
			control_.style.display = 'none';
		}
		a = document.createElement('a');
		a.alt=HideThreadText;
		a.title=HideThreadText;
		a.id='hide'+buttons_count;
		buttons_array[buttons_count] = 'hide'+buttons_count;
		img = document.createElement('img');
		img.src = '/App_Themes/Basic/i/close.jpeg';
		img.border='0';
		img.height='50';
		img.width='50';
		a.href = 'javascript:void(0)';
		
		DOM.addEventListener(control_, "click", COThread);
		a.appendChild(img);
		control_.appendChild(a);
	
		///////////////////////////////
		buttons_count++;
		
		if(reply && reply.firstChild && reply.firstChild.firstChild && reply.firstChild.firstChild.firstChild){
			reply.firstChild.firstChild.firstChild.appendChild(control_);
		}
	}

		if(table){
			// add comments there
			while(reply && reply.nodeName != 'HR'){
				next_one = reply.nextSibling;
				
					table.parentNode.insertBefore(reply, table);
					if (reply.nodeName == 'SPAN'){
						reply.firstChild.firstChild.firstChild.firstChild.firstChild.width += my_padding;
					}
					reply = next_one;
			}
		}
		// remove nesting comments			
			next_comment = 0;
			if(table.parentNode && table.parentNode.nextSibling){
				next_comment = table.parentNode.nextSibling;
				do{
					next_comment = next_comment.nextSibling;
				}while(next_comment && next_comment.nodeName != 'SPAN');
			}
			
			if(!my_padding) my_padding=1;
			while(next_comment && 
					next_comment.firstChild &&
					next_comment.firstChild.firstChild &&
					next_comment.firstChild.firstChild.firstChild &&
					next_comment.firstChild.firstChild.firstChild.firstChild &&
					next_comment.firstChild.firstChild.firstChild.firstChild.firstChild &&
					(next_comment.firstChild.firstChild.firstChild.firstChild.firstChild.width > my_padding)) {
				to_del = next_comment;
				do{
					next_comment = next_comment.nextSibling;
				}while(next_comment && next_comment.nodeName != 'SPAN');
				if (to_del.nodeName == 'SPAN'){
					to_del.parentNode.removeChild(to_del);
				}
			}
			document.body.removeChild(dummy);
			table.parentNode.removeChild(table);
			setTimeout("DoThread()", is_ie?300:0);
	}	
	HTTPReq.getJSON2({
       		"url": url,
            "method" : "GET",
            "data": params,
            "onData": parse_result,
            "onError": ContextualPopup.gotError
            });
}

function COThread(evn){
	var count = 0;
	
		my_padding = this.parentNode.parentNode.parentNode.firstChild.firstChild.firstChild.firstChild.width;
		if(!my_padding) my_padding=1;
		next_comment = this;
		do{
			next_comment = next_comment.parentNode;
		}while(next_comment && next_comment.nodeName != 'SPAN');
		
		if(next_comment){
	do{
		next_comment = next_comment.nextSibling;		
	}while(next_comment && next_comment.nodeName != 'SPAN');
		}
		//alert(next_comment.innerHTML);
	if(next_comment){
	if(next_comment.style.display == 'none'){
		changeto = 'block';		
	}else{
		changeto = 'none';		
	}
	while(next_comment && 
					next_comment.firstChild &&
					next_comment.firstChild.firstChild &&
					next_comment.firstChild.firstChild.firstChild &&
					next_comment.firstChild.firstChild.firstChild.firstChild &&
					next_comment.firstChild.firstChild.firstChild.firstChild.firstChild &&
					(next_comment.firstChild.firstChild.firstChild.firstChild.firstChild.width > my_padding)) {
		next_comment.style.display = changeto;
		do{
			next_comment = next_comment.nextSibling;
		}while(next_comment && next_comment.nodeName != 'SPAN');
		count++;
	}
	if(count>0){
		if(changeto == 'none'){
			this.firstChild.firstChild.src='/App_Themes/Basic/i/open.jpeg';
		}else{
			this.firstChild.firstChild.src='/App_Themes/Basic/i/close.jpeg';			
		}		
	}
	}
}

//когда передаем элемент A 
function COThread2(evn){
	var count = 0;
		my_padding=1;
		next_comment = evn.parentNode.parentNode.parentNode.parentNode;;
		do{
			next_comment = next_comment.parentNode;
		}while(next_comment && next_comment.nodeName != 'SPAN');
		
		if(next_comment){
	do{
		next_comment = next_comment.nextSibling;		
	}while(next_comment && next_comment.nodeName != 'SPAN');
		}
		//alert(next_comment.innerHTML);
	if(next_comment){
	if(buttons_all == 0){
		changeto = 'block';		
	}else{
		changeto = 'none';		
	}
	while(next_comment && 
					next_comment.firstChild &&
					next_comment.firstChild.firstChild &&
					next_comment.firstChild.firstChild.firstChild &&
					next_comment.firstChild.firstChild.firstChild.firstChild &&
					next_comment.firstChild.firstChild.firstChild.firstChild.firstChild &&
					(next_comment.firstChild.firstChild.firstChild.firstChild.firstChild.width > my_padding)) {
		next_comment.style.display = changeto;
		do{
			next_comment = next_comment.nextSibling;
		}while(next_comment && next_comment.nodeName != 'SPAN');
		count++;
	}
	if(count>0){
		if(changeto == 'none'){
			evn.firstChild.src='http://topbloger.ru/App_Themes/Basic/i/open.jpeg';
		}else{
			evn.firstChild.src='http://topbloger.ru/App_Themes/Basic/i/close.jpeg';			
		}		
	}
	}
}