var req=new Array;
var The_ID=new Array;

Object.size = function(obj) {
    var size = 0, key;
    for (key in obj) {
        if (obj.hasOwnProperty(key)) size++;
    }
    return size;
};

function $(objID) {
	return document.getElementById(objID);
}

function initXMLHTTPRequest()
{
	var xRequest=null;
	if(window.XMLHttpRequest) {
		xRequest=new XMLHttpRequest();
	}
	else if(window.ActiveXObject) {
		xRequest=new ActiveXObject("Microsoft.XMLHTTP");
	}
	return xRequest;
}

window.onload = function(){ var elem = $('s'); elem.focus(); }

function State() {
	this.term;
	this.sites = new Object;
	this.go = start;
	this.get = grab;
	this.prep = prepare;
	this.sorter = sort_results;
	this.disp = display;
	this.results = new Object;
	this.cats = new Object;
	this.results[''] = new Object;
	this.sOrder = 1;
	this.sCol = "date";
	this.cat = select_cat;
	this.count = 0;
	this.selCat = "";
	this.maxResults = 40;
	this.pg = 1;
	this.category = '';
	this.check = check_status;
	this.abort = ajaxTimeout;
	this.done = 0;
    this.strings = new Object;
    this.stringSearch;
    this.filters = new Array;
	this.filter = Applyfilter;
	this.removefilter = Removefilter;
	
	function start(sTerm) {
		$('q').innerHTML = '';
		$('q').innerHTML = sTerm;
		this.term = sTerm;
		this.results = new Array;
		this.cats = new Array;
		this.count = 0;
		this.selCat = "";
		this.done = 0;
		this.get("process");
        this.strings.include = "";
        this.strings.exclude = "";
        this.strings.words = this.term.split(" ");
        for (var x in this.strings.words) {
            var _2 = this.strings.words[x].substr(0, 1);
            if (_2 == "+") {
                this.strings.include += " " + this.strings.words[x].substr(1) + ".*";
            } else {
                if (_2 == "-") {
                    this.strings.exclude += "|" + this.strings.words[x].substr(1);
                }
            }
        }
        this.strings.include = this.strings.include.substr(1);
        this.strings.exclude = this.strings.exclude.substr(1);
        this.strings.include = this.strings.include ? new RegExp(this.strings.include, "gi") : "";
        this.strings.exclude = this.strings.exclude ? new RegExp(this.strings.exclude, "gim") : "";
        this.stringSearch = this.term.replace(new RegExp("\\+|\\-", "g"), "").replace(this.strings.exclude, "");
        this.strings.highlight = new RegExp("(" + this.stringSearch.replace(new RegExp("\\s", "g"), "|") + ")", "gi");
		for(var s in this.sites) {
			if($(s)) {
				$(s).className = "idle";
				$(s).id = 's' + $(s).id;
			}
			this.sites[s].state = 0;
			this.get(s, "r_area");
		}
	}
	
	function grab(sID, anyID) {
		req.push(initXMLHTTPRequest());
		The_ID.push(anyID);
		var i=parseInt(req.length)-1;
		if(req[i]) {
			if(sID == "process") req[i].open("POST","/includes/process.php?q=" + this.term + "&remove=" + (anyID == true ? "1" : "0"),true);
			else req[i].open("POST","/includes/engine.php?site=" + sID + "&term=" + this.term,true);
			req[i].onreadystatechange=function () {
				if(sID != "process") {
				if(!state.results['']) state.results[''] = [];
				for(i=0; i<req.length;i++)
					{
						if(req[i]) {
							var data=null;
							if(req[i].readyState==4 && req[i].status==200) {
								data=req[i].responseText;
								try {
									if(data.indexOf("[BB]") > -1 ){
										var splits=data.split("[BB]");
										var torrents=new Array;
										for(sp=0;sp<splits.length;sp=sp+1){
											var att=splits[sp].split("|");
											if(att[3] && att[7] && (att[4]>0) && att[5]<10000 && att[6]<10000) {
												if(!state.cats[att[1]]) { state.cats[att[1]] = []; state.cats[att[1]].data = []; }
												state.cats[att[1]].data.push({sid:att[7],date:att[0],cat:att[1],url:att[2],name:att[3],size:att[4],seeds:att[5],leechs:att[6]});
												state.results[''].push({sid:att[7],date:att[0],cat:att[1],url:att[2],name:att[3],size:att[4],seeds:att[5],leechs:att[6]});
												state.count++;
											}
										}
										state.sites[sID].state = 1;
									} else {
										if(state.sites[sID]) state.sites[sID].state = 2;
									}
								} catch(err) { state.sites[sID].state = 2; state.check(); }
								state.prep();
								The_ID.splice(i,1);
								req.splice(i,1);
							}
						}
					}
				}
			};
			req[i].send(null);
			//var xhrTimeout=setTimeout("state.abort();",5000);
		}
	}
	
	function ajaxTimeout(sid){
		for(v in this.sites) {
			if(this.sites[v].state!=1) this.sites[v].state = 2;
		}
		this.check();
	}

	function prepare() {
		this.done++;
		this.sorter('');
	}
	
	function select_cat(scat) {
		this.category = scat;
		if(scat) $('c').innerHTML = "&nbsp;in&nbsp;<b>" + scat + "</b>"; else $('c').innerHTML = "";
		this.sorter('');
	}
	
	function sort_results(sortCol) {
		if($("s" + this.sCol)) {
			$("s" + this.sCol).className = "";
			if(sortCol) {
				this.sOrder = this.sCol == sortCol ? this.sOrder == 1 ? -1 : 1 : 1;
				this.sCol = sortCol;
			}
			$("s" + this.sCol).className = this.sOrder == 1 ? "sd" : "su";
			this.filters.length?this.filters.sort(rs):this.category?this.cats[this.category].data.sort(rs):this.results[this.category].sort(rs);
			if(this.category) this.disp(this.category);
			else this.disp('');
		}
	}
	
	function check_status() {
		for(var e in this.sites) {
			if(this.sites[e].state == 1) {
				if(e && $('s' + e)) {
					var eng = $('s' + e);
					eng.id = e;
					eng.className = "done";
				}
			}
			else if(this.sites[e].state == 2) {
				if(e && $('s' + e)) {
					var eng = $('s' + e);
					eng.id = e;
					eng.className = "not";
				}
			}
		}
	}
	
    function Applyfilter() {
        if ($("txtfilter").value!="") {
            var ftxt = $("txtfilter").value;
            var frep = this.stringSearch + " " + ftxt;
            this.strings.highlight = new RegExp("(" + frep.replace(new RegExp("\\s", "g"), "|") + ")", "gi");
            var fsrch = new RegExp(ftxt.replace(new RegExp("\\s", "g"), ".*"), "gi");
            //var _9 = this.categories[this.category].results;
			this.filters = [];
			this.category = '';
			var fres = this.results[this.category];
            for (var x in fres) {
                var _b = fres[x].name.toString();
                if (fsrch && _b.match(fsrch)) {
                    this.filters[this.filters.length] = fres[x];
                }
            }
            $("tFil").innerHTML = "Real-time Filter: <font color=\"#060\">Active</font>";
			if(!this.filters.length) $("txtfilter").style.borderColor = "red";
			else $("txtfilter").style.borderColor = "#ccc";
            this.disp();
        } else 
	        this.removefilter();
    }
	
    function Removefilter() {
        $("tFil").innerHTML = "Real-time Filter: <font color=\"#990000\">Not Active</font>";
        this.strings.highlight = new RegExp("(" + this.stringSearch.replace(new RegExp("\\s", "g"), "|") + ")", "gi");
        $("txtfilter").value = "";
		$("txtfilter").style.borderColor = "#ccc";
		this.filters = [];
        this.disp(this.category,this.pg);
    }

	function display(category,page) {
		if($('results').style.display=="none") toggleSlide('results');	
		if(page) this.pg = page; else this.pg = 1;
		if(category) this.category = category; else this.category = '';
		var passID = $("r_area");
		var html='';
		passID.innerHTML = '';
		var siteID = '';
		$('p_area1').innerHTML = "";$('p_area2').innerHTML = "";

		var resArray = this.filters.length ? this.filters : this.category ? this.cats[this.category].data : this.results[this.category];
		resultStart = this.maxResults * (this.pg - 1);
        resultStop = (this.maxResults * this.pg) > resArray.length ? resArray.length : this.maxResults * this.pg;
		resArray = resArray.slice(resultStart, resultStop);
		var cnt = 0;
		for (var t in resArray) {
				var torrent = resArray[t];
				if(torrent.name) {
					html += drawResults(torrent,cnt);
					cnt++;
				}
		} 
		passID.innerHTML=passID.innerHTML+html;
		$('counter').innerHTML = "Displaying " + (resultStart + 1) + " - " + resultStop + " of " + (this.filters.length?this.filters.length:this.category?this.cats[this.category].data.length:this.count);
		
		$('c_area').innerHTML = '';
		if(!this.filters.length) {
			if(!$('catList')) {
				var ul = document.createElement("ul");
				ul.className = "head";
				ul.id = "catList";
				$('c_area').appendChild(ul);
			}
			if($('catList')) {
				var ul = $('catList');
				ul.innerHTML = '<li' + (category == "" ? ' class=\'active\'' : '') + '><span onclick="state.cat(\'\')">All (' + this.count + ')</span></li>';
				for(var c in this.cats) {
					ul.innerHTML += "<li" + (c == category ? " class='active'" : "") + "><span id=\"" + c + "\" onclick=\"state.cat('" + c + "')\">" + c.substring(0,7) + " (" + this.cats[c].data.length + ")</span>";
				}
			}
		}
		
		if(this.category) var pgs = Math.ceil(this.cats[this.category].data.length / this.maxResults);
		else if(this.filters.length) var pgs = Math.ceil(this.filters.length / this.maxResults);
		else var pgs = Math.ceil(this.count / this.maxResults);
		if (pgs > 1) {
			var _14 = "<ul><li class=\"pages\">Pages:</li>";
			for (var x = 1; x <= pgs; x++) {
				_14 += "<li" + (x == this.pg ? " class='active'" : "") + "><a" + (x == this.pg ? " class='active'" : "") + " onclick=\"javascript:state.disp('" + this.category + "','" + x + "')\" href=\"#top\">" + x + "</a></li>";
			}
			_14 += "</ul>";
			$('p_area1').innerHTML = _14;
			$('p_area2').innerHTML = _14;
		} else {
			$('p_area1').innerHTML = "";
			$('p_area2').innerHTML = "";
		}
		this.check();
		
		if(this.count == 0) {
			if(this.done==Object.size(this.sites)) this.get("process", true); //fade('results',true);
			html = "<li style=\"width:880px;\"><span style=\"display:block; width:880px; text-align:center; font-size:16px; font-weight:bold; height:80px; padding-top:25px;\">No results matched your keyword(s).</span></li>";
			passID.innerHTML=passID.innerHTML+html;
			
		}
	}
}

function drawResults(torrent,count) {
	var html = '';
	var url = torrent.url
	html += "<ul id='" + count + "'" + (count%2==0 ? " class='tNode'" : " class='ttNode'") + " onclick= window.open('" + url.replace("$a$", "&nbsp;") + "'); openDet('"+count+"'); >"; //window.open('" + url.replace("$a$", "&nbsp;") + "')
	html += "<li style=\"width:106px;\"><span style=\"font-size:11px;\"><b>" + convert_date(torrent.date) + "</b></span></li>";
	//html += "<li style=\"width:26px;\"></li>";
	html += "<li style=\"width:466px;\"><p class=\"res\" id=\"" + torrent.sid + "\"></p><span>" + torrent.name.replace(state.strings.highlight, "<span class=\"f\">$1</span>") + "</span></li>"; //" + (torrent.sid=="kick"?"<span style=\"float:right;margin-right:5px;\"><p class=\"res\" id=\"comments\"></p></span>":"") + "
	html += "<li style=\"width:81px;\"><span>" + get_size(torrent.size) + "</span></li>";
	html += "<li style=\"width:71px;\"><span class=\"seeds\">" + (torrent.seeds==0?"<font style=\"font-weight:normal\" color=\"darkred\">" + torrent.seeds + "</font>":torrent.seeds) + "</span></li>";
	html += "<li style=\"width:71px;\"><span class=\"leechs\">" + (torrent.leechs==0?"<font style=\"font-weight:normal\" color=\"darkred\">" + torrent.leechs + "</font>":torrent.leechs) + "</span></li>";
	html += "<li style=\"width:66px;\"><span id='h" + get_health(torrent.seeds,torrent.leechs) + "'><!-- --></span></li>";
	html += "</ul>";
	return html;
}

function openDet(eID) {
	//modal.panel(eID, document.getElementById(eID).className);
	document.getElementById(eID).className = "taNode";
	//smoothScroll(eID);
	//document.body.style.overflow = "hidden";
	return true;
}

function showIcon(site) {
	var init = $("s" + site);
	init.id = site;
	init.innerHTML = '';
}

function IsNumeric(strString)
{
	if(!/\D/.test(strString)) return true;
	else if(/^\d+\.\d+$/.test(strString)) return true;
	else return false;
}

function rs(a, b) {
	var col = state.sCol.toString().toLowerCase();
    var x = a[col];
    var y = b[col];
    if (IsNumeric(x)) {
        return (y - x) * state.sOrder;
    } else {
        return ((x < y) ? -1 : (x > y) ? 1 : 0) * state.sOrder;
    }
}

function get_health(m, n) {
    if (m > 0 && n > 0) {
        var out = Math.round((m / n) * 10) / 10;
        out = out >= 1.1 ? 10 : out;
        out = out == 1 ? 10 : out;
        out = out == 0.9 ? 9 : out;
        out = out == 0.8 ? 8 : out;
        out = out == 0.7 ? 9 : out;
        out = out == 0.6 ? 7 : out;
        out = out == 0.5 ? 6 : out;
        out = out <= 0.4 ? 5 : out;
        return out;
    } else {
        return 1;
    }
}

function get_size(sz) {
    var ot = new Array("Byte", "KB", "MB", "GB", "TB");
    for (val in ot) {
		if (sz > 1024) {
			sz = sz / 1024;
        }
		else
	        break;
    }
    return Math.round(sz * 100) / 100 + " " + ot[val];
}

function convert_date(_2f) {
    if (_2f <= 0) {
        return "-";
    }
    var _30 = new Date;
    dif = Math.round(_30 / 1000) - _2f;
    years = Math.floor(dif / 31535999);
    months = Math.floor(dif / 2591999);
    days = Math.floor(dif / 86399);
    hours = Math.floor(dif / 3599);
	minutes = Math.floor(dif / 59);
    if (years < 1) {
        if (months < 1) {
            if (days < 1) {
                if (hours < 1) {
                    stime = minutes + " " + (minutes == 1 ? "minute" : "minutes") + " ago";
                } else {
                    stime = hours + " " + (hours == 1 ? "hour" : "hours") + " ago";
                }
            } else {
                stime = days + " " + (days == 1 ? "day" : "days") + " ago";
            }
        } else {
            stime = months + " " + (months == 1 ? "month" : "months") + " ago";
        }
    } else {
        stime = years + " " + (years == 1 ? "year" : "years") + " ago";
    }
    return stime;
}

var state = new State();
//,torbit:{name:"TorrentBit"},ahashare:{name:"AhaShare"},btjunk:{name:"BtJunkie"},sumo:{name:"SumoTorrents"},td:{name:"TorrentDownloads"},alive:{name:"AliveTorrents"},nova:{name:"MiniNova"}

function start_search() {
	if($('home')) { 
		if($('home').style.display=="block") {
			fade('home');
		} else {
			if($('e_area').style.display=="none") doSlide('e_area');
			//$('results').style.opacity = 1;
			//$('results').style.filter = 'alpha(opacity = 100)';
			state.go($('s').value);
		}
	} else {
		if($('e_area').style.display=="none") doSlide('e_area');
		$('results').style.opacity = 1;
		$('results').style.filter = 'alpha(opacity = 100)';
		state.go($('s').value);
	}
}

var TimeToFade = 700.0;

function fade(eid,n){

	
	if($('s').value == '')
		return;

	var element = $(eid);

	if(element == null)
		return;

	if(element.FadeState == null){
		element.FadeState = 2;
	}

	if(element.FadeState == 1 || element.FadeState == -1){
		element.FadeState = element.FadeState == 1 ? -1 : 1;
		element.FadeTimeLeft = TimeToFade - element.FadeTimeLeft;
	}else{
		element.FadeState = element.FadeState == 2 ? -1 : 1;
		element.FadeTimeLeft = TimeToFade;
		setTimeout("animateFade(" + new Date().getTime() + ",'" + eid + "'," + n + ")", 33);
	}
	element.FadeState = null;
}

function animateFade(lastTick, eid, n){

	var curTick = new Date().getTime();
	var elapsedTicks = curTick - lastTick;
	
	var element = $(eid);
	
	if(element.FadeTimeLeft <= elapsedTicks){
	
		element.style.opacity = element.FadeState == 1 ? '1' : '0';
		element.style.filter = 'alpha(opacity = ' + (element.FadeState == 1 ? '100' : '0') + ')';
		element.FadeState = element.FadeState == 1 ? 2 : -2;
		return;
	}
	
	element.FadeTimeLeft -= elapsedTicks;
	var newOpVal = element.FadeTimeLeft/TimeToFade;
	if(element.FadeState == 1)
		newOpVal = 1 - newOpVal;
	
	if(newOpVal < 0.05 && eid != "results") {
		$('results').style.display = "block";
		element.style.display = "none";
		doSlide('e_area');
		setTimeout("state.go('" + $('s').value + "')", 1000);
	}
	
	element.style.opacity = newOpVal;
	element.style.filter = 'alpha(opacity = ' + (newOpVal*100) + ')';
	setTimeout("animateFade(" + curTick	+ ",'" + eid + "')", 33);
}

function doSlide(id){
	timeToSlide = 8; // milliseconds
	obj = $(id);
	if(obj.style.display == "none"){
	   obj.style.visibility = "hidden";
	   obj.style.display = "block";
	   height = obj.offsetHeight-16;
	   obj.style.height="0px";
	   obj.style.visibility = "visible";
	   slideDown(obj,0,height,Math.ceil(height/timeToSlide));
	}
}
 
function slideDown(obj,offset,full,px){
	if(offset < full){
	   obj.style.height = offset+"px";
	  offset=offset+px;
	   setTimeout((function(){slideDown(obj,offset,full,px);}),1);
	} else {
	   obj.style.height = full+"px";
	}
}