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_unfolders2(document);

///////////////////////////////
//================================
//	WORKHORSES
//================================

function add_unfolders2(elem) { //for single posts = 2nd step
	get_itemid_regexp = /thread=(\w+)/;
	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 == 'ссылка' 
			|| thisOne.innerHTML == 'Ответить'
			|| thisOne.innerHTML == 'с цитатой'){ 
				if(_todo>0)//in work
				{
					threads_done[params[1]]=1;
				}
				continue;
			}			
			if(document.getElementById('post_full_'+params[1])){ // - yslovie na single-post
					if (thisOne.nextSibling && thisOne.nextSibling.nextSibling && (thisOne.nextSibling.nextSibling.innerHTML == '<img src="http://topbloger.ru/App_Themes/Basic/i/load.gif" border="0"> Unfold' || thisOne.nextSibling.nextSibling.innerHTML == '<img src="http://topbloger.ru/App_Themes/Basic/i/load.gif" border="0"> done' || thisOne.nextSibling.nextSibling.innerHTML == '<img src="http://topbloger.ru/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]);

					//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="http://topbloger.ru/App_Themes/Basic/i/load.gif" border="0"> Unfold';
						addtodo(params[1],thisOne.href,a);
						addEventListener(a, "click", unfold_thread);
					}else{
						a.innerHTML = '<img src="http://topbloger.ru/App_Themes/Basic/i/load.gif" border="0"> done';
						addEventListener(a, "click", unfold_thread);
					}
				//}else{
				//	continue;
				//}
			}
		}
	}
	setMaxToDo();
}

 function addEventListener( e, eventName, func, useCapture ) {
        try {
            if( e.addEventListener )
                e.addEventListener( eventName, func, useCapture );
            else if( e.attachEvent )
                e.attachEvent( "on" + eventName, func );
            else
                e[ "on" + eventName ] = func;
        } catch( e ) {}
    }
    
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;
	//this.style.cursor = 'default'
	elem.blur()
	elem.innerHTML = '<img src="http://topbloger.ru/App_Themes/Basic/i/load.gif" border="0"> clicked';

	var url = "/mailru2.aspx";
 	var params = HTTPReq.formEncoded ({
 			"thread_href": elem.getAttribute("thread_href"),
            "mycookie": mycookie
    });
	function parse_result(result){
		working = 0;
		var dummy = document.createElement('DIV');
		dummy.style.display = 'none';
		document.body.appendChild(dummy);

		cur_thread = elem.getAttribute('thread_id');
		
		// the same one lives in new doc
			if(document.getElementById('t_'+cur_thread)){
				document.getElementById('t_'+cur_thread).id += '_old'
			}
		dummy.innerHTML = result;
		
		reply = document.getElementById('t_'+cur_thread);		
		//removing for threads:
		add_unfolders2(dummy);
		// get cell
		td = elem;
		while (td && td.nodeName != 'TD'){
			td = td.parentNode;
		}
		if(!td){
			setTimeout("DoThread()", 300);
			return;
		}
		
		tr = td;
		while(tr && tr.nodeName!="TR"){
			tr = tr.parentNode;
		}
		if(!tr){
			setTimeout("DoThread()", 300);
			return;
		}
		tr = tr.parentNode;
		while(tr && tr.nodeName!="TR"){
			tr = tr.parentNode;
		}
		table = tr;
		while(table && table.nodeName!="TABLE"){
			table = table.parentNode
		}
		temp = tr.firstChild;
		
		while(temp.nodeName!='TD'){
			temp = temp.nextSibling;
		}
		//
		my_padding = temp.firstChild.width;//otstup
		if(table){
			// add comments there
			while(reply && reply.nodeName != 'HR'){
				next_one = reply.nextSibling;
				//find the space
				if(reply.nodeName=="TABLE"){
					var replyots = reply.firstChild;
					while(replyots && replyots.nodeName!='TBODY'){
						replyots = replyots.nextSibling;
					}
					replyots = replyots.firstChild;
					while(replyots && replyots.nodeName!='TR'){
						replyots = replyots.nextSibling;
					}
						var otstup = temp.cloneNode(true);//copy
						replyots.insertBefore(otstup, replyots.firstChild);
						
					var comment = reply.cloneNode(true);//copy
					if (typeof(comment) != "undefined") {
						table.parentNode.insertBefore(comment, table);
					}
				}
				reply = next_one;//going next comment
			}			
		}
		
		
		
		// remove nesting comments			
			next_comment = 0;
			if(table.nextSibling){
				next_comment = table.nextSibling;
				do{
					next_comment = next_comment.nextSibling;
				}while(next_comment && next_comment.nodeName != 'TABLE');
			}
			if(!my_padding) my_padding=1;
			while(next_comment && 
					next_comment.firstChild && 
					((next_comment.firstChild.nextSibling &&
					next_comment.firstChild.nextSibling.firstChild &&
					next_comment.firstChild.nextSibling.firstChild.firstChild &&
					next_comment.firstChild.nextSibling.firstChild.firstChild.nextSibling &&
					next_comment.firstChild.nextSibling.firstChild.firstChild.nextSibling.firstChild &&
					next_comment.firstChild.nextSibling.firstChild.firstChild.nextSibling.firstChild.width > my_padding)) || 
					(next_comment.firstChild.firstChild &&
					next_comment.firstChild.firstChild.firstChild &&
					next_comment.firstChild.firstChild.firstChild.firstChild &&
					next_comment.firstChild.firstChild.firstChild.firstChild.width > my_padding))
			{
				to_del = next_comment;
				do{
					next_comment = next_comment.nextSibling;
				}while(next_comment && next_comment.nodeName != 'TABLE');
				if (to_del.nodeName == 'TABLE'){
					to_del.parentNode.removeChild(to_del);
				}
			}
			table.parentNode.removeChild(table);
			document.body.removeChild(dummy);
			
		
		setTimeout("DoThread()", is_ie?300:0);
	}	
	
	HTTPReq.getJSON2({
       		"url": url,
            "method" : "GET",
            "data": params,
            "onData": parse_result,
            "onError": gotError
            });
}

function gotError(){
	alert("Connection Error");
}
