
String.prototype.trim = function() { return this.replace(/^\s+|\s+$/, ''); }

function setStyleById(id, style, value) {
	obj = document.getElementById(id);
	if (obj != null)
		obj.style[style] = value;
}

function togglebox_open(i) {
	setStyleById('closebox_' +i, 'display', 'none');
	setStyleById('openbox_'  +i, 'display', 'block');
}

function togglebox_close(i) {
	setStyleById('closebox_'+i, 'display', 'block');
	setStyleById('openbox_' +i, 'display', 'none');
}

function AjaxLoader(addr, post, outid) {
	try { var loader = new XMLHttpRequest(); }
	catch (err) { var loader = new ActiveXObject('Microsoft.XMLHTTP'); }
	loader.outputdiv = document.getElementById(outid);
	loader.onreadystatechange = function () {
		if (loader.readyState == 1)
			loader.outputdiv.innerHTML = '<br><br><center>Aguarde...<br><img src="/img/ajax.gif" width="101" height="15"></center><br><br>';
		else if (loader.readyState == 4)
			if (x=loader.responseText.match(/^ok\=(\d+)$/)) {
				if (x[1] == "0")
					location.href="/manager";
				else
					location.href="/manager?show="+x[1];
			}
			else
				loader.outputdiv.innerHTML = loader.responseText;
	};
	loader.open('POST', addr, true);
	loader.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	loader.send(post);
	return false;
}

function friendRequestCallback() {
	var divid;
	var friendRequests = document.getElementsByTagName('div');
	for (var i = 0; i < friendRequests.length; i++)
		if (divid = friendRequests[i].id)
			if (divid = divid.match(/^friendRequestBox(\d+)$/))
				if (friendRequests[i].style.display != 'none')
					if (document.getElementById('friendRequestCheck'+divid[1]) == null) return;
	location.href = '/home';
}

function AjaxFriendRequest(addr, uid) {
	if (!uid.match(/^\d+$/)) return false;
	try { var FRLoader = new XMLHttpRequest(); }
	catch (err) { var FRLoader = new ActiveXObject('Microsoft.XMLHTTP'); }
	document.getElementById('friendRequest'+uid).innerHTML = '<br><br><center>Aguarde...<br><img src="/img/ajax.gif" width="101" height="15"></center><br><br>';
	eval("FRLoader.onreadystatechange = function () { if (FRLoader"+uid+".readyState == 4) friendRequestCallback(document.getElementById('friendRequestBox"+uid+"').style.display='none'); };");
	eval("var FRLoader"+uid+" = FRLoader;");
	FRLoader.open('POST', addr, true);
	FRLoader.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	FRLoader.send('uid='+uid);
	return false;
}

function acceptFriend(uid) { AjaxFriendRequest('/acceptfriend.ajax', uid); }
function declineFriend(uid) { AjaxFriendRequest('/declinefriend.ajax', uid); }

function selectAllFriendRequests() {
	var friendRequests = document.getElementsByTagName('input');
	for (var i = 0; i < friendRequests.length; i++)
		if (friendRequests[i].name.match(/^friendRequestCheck\d+$/)) friendRequests[i].checked = true;
}

function acceptAllSelectedFriendRequests() {
	var friendRequests = document.getElementsByTagName('input');
	for (var i = friendRequests.length -1; i >= 0; i--) {
		if (friendRequests[i].checked) {
			var friendRequestCheck = friendRequests[i].name.match(/^friendRequestCheck(\d+)$/);
			if (friendRequestCheck) acceptFriend(friendRequestCheck[1]);
		}
	}
}

function declineAllSelectedFriendRequests() {
	var friendRequests = document.getElementsByTagName('input');
	for (var i = friendRequests.length -1; i >= 0; i--) {
		if (friendRequests[i].checked) {
			var friendRequestCheck = friendRequests[i].name.match(/^friendRequestCheck(\d+)$/);
			if (friendRequestCheck) declineFriend(friendRequestCheck[1]);
		}
	}
}

function AjaxTestimonialRequest(addr, uid, time) {
	if (!uid.match(/^\d+$/)) return false;
	if (!time.match(/^\d+$/)) return false;
	try { var TRLoader = new XMLHttpRequest(); }
	catch (err) { var TRLoader = new ActiveXObject('Microsoft.XMLHTTP'); }
	document.getElementById('testimonialRequest'+uid+'_'+time).innerHTML = '<br><br><center>Aguarde...<br><img src="/img/ajax.gif" width="101" height="15"></center><br><br>';
	eval("TRLoader.onreadystatechange = function () { if (TRLoader"+uid+"_"+time+".readyState == 4) document.getElementById('testimonialRequestBox"+uid+"_"+time+"').style.display='none'; };");
	eval("var TRLoader"+uid+"_"+time+" = TRLoader;");
	TRLoader.open('POST', addr, true);
	TRLoader.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	TRLoader.send('uid='+uid+'&time='+time);
	return false;
}
function acceptTestimonial(uid, time) { AjaxTestimonialRequest('/accepttestimonial.ajax', uid, time); }
function declineTestimonial(uid, time) { AjaxTestimonialRequest('/declinetestimonial.ajax', uid, time); }

function selectAllTestimonialRequests() {
	var testimonialRequests = document.getElementsByTagName('input');
	for (var i = 0; i < testimonialRequests.length; i++)
		if (testimonialRequests[i].name.match(/^testimonialRequestCheck\d+_\d+$/)) testimonialRequests[i].checked = true;
}

function acceptAllSelectedTestimonialRequests() {
	var testimonialRequests = document.getElementsByTagName('input');
	for (var i = testimonialRequests.length -1; i >= 0; i--) {
		if (testimonialRequests[i].checked) {
			var testimonialRequestCheck = testimonialRequests[i].name.match(/^testimonialRequestCheck(\d+)_(\d+)$/);
			if (testimonialRequestCheck) acceptTestimonial(testimonialRequestCheck[1], testimonialRequestCheck[2]);
		}
	}
}

function declineAllSelectedTestimonialRequests() {
	var testimonialRequests = document.getElementsByTagName('input');
	for (var i = testimonialRequests.length -1; i >= 0; i--) {
		if (testimonialRequests[i].checked) {
			var testimonialRequestCheck = testimonialRequests[i].name.match(/^testimonialRequestCheck(\d+)_(\d+)$/);
			if (testimonialRequestCheck) declineTestimonial(testimonialRequestCheck[1], testimonialRequestCheck[2]);
		}
	}
}

function AjaxAddCredential(form) {
	AjaxLoader('/addcred.ajax', 'login='+encodeURIComponent(form.login.value)+'&passwd='+encodeURIComponent(form.passwd.value), 'ajaxOutput');
	return false;
}

function removeCredential(id) {
	AjaxLoader('/delcred.ajax', 'id='+encodeURIComponent(id), 'credInfo'+id);
}

var countdown = [];
var viewtime;
var loaded_for = 0;

var current_popup = null;

function exTimeDisplay(delta) {
	ddelta = Math.floor(delta / 86400);
	delta %= 86400;
	hdelta = Math.floor(delta / 3600);
	delta %= 3600;
	mdelta = Math.floor(delta / 60);
	sdelta = (delta % 60);
	delta = (sdelta == 0 ? "" : (sdelta == 1 ? " e 1 segundo" : " e "+sdelta+" segundos"));
	if (delta == "")
		delta = (mdelta == 0 ? "" : (mdelta == 1 ? " e 1 minuto" : " e "+mdelta+" minutos"));
	else
		delta = (mdelta == 0 ? "" : (mdelta == 1 ? ", 1 minuto" : ", "+mdelta+" minutos"))+delta;
	if (delta == "")
		delta = (hdelta == 0 ? "" : (hdelta == 1 ? " e 1 hora" : " e "+hdelta+" horas"));
	else
		delta = (hdelta == 0 ? "" : (hdelta == 1 ? ", 1 hora" : ", "+hdelta+" horas"))+delta;
	if (delta == "")
		delta = (ddelta == 0 ? "" : (ddelta == 1 ? " e 1 dia" : " e "+ddelta+" dias"));
	else
		delta = (ddelta == 0 ? "" : (ddelta == 1 ? ", 1 dia" : ", "+ddelta+" dias"))+delta;
	if (delta == "")
		delta = "Expirou (reautenticará dentro dos próximos 5 minutos)";
	else
		delta = delta.substr(2).trim();
	return delta;
}

function updateCountdown() {
	if (viewtime != null) viewtime.innerHTML = exTimeDisplay(++loaded_for);
	for (var i in countdown)
		countdown[i][0].innerHTML = exTimeDisplay(--countdown[i][1]);
}

function main() {
	viewtime = document.getElementById('viewtime');
	var divs = document.getElementsByTagName('div');
	for (var i = 0; i < divs.length; i++)
		if (divs[i].id.match(/^countdown_/))
			countdown.push([divs[i], parseInt(divs[i].innerHTML)]);
	setInterval("updateCountdown();", 1000);
	updateCountdown();
	var loadtime = document.getElementById('loadtime');
	if (loadtime != null)
		loadtime.innerHTML = ''+((new Date).valueOf()/1000 - load_starttime);
}

function SWFObject(swf, id, width, height, version, bgColor, quality, unused1, unused2, unused3) {
	this.params = [];
	this.variables = [];
	this.attributes = [];
	this.installedVer = getSWFInstalledVersion();
	if (swf)     this.setAttribute("swf", swf);
	if (id)      this.setAttribute("id", id);
	             this.setAttribute("width",  width  ? width  : '300');
	             this.setAttribute("height", height ? height : '300');
	if (version) this.setAttribute("version", new SWFVersion(version.toString().split(".")));
	if(bgColor)  this.addParam("bgcolor", bgColor);
	             this.addParam("quality", quality ? quality : 'high');
}

SWFObject.prototype.getAttribute = function (a) { return this.attributes[a]; };
SWFObject.prototype.setAttribute = function (a, b) {this.attributes[a] = b; };
SWFObject.prototype.addParam = function (a, b) { this.params[a] = b; };
SWFObject.prototype.getParams = function () { return this.params; };
SWFObject.prototype.addVariable = function (a, b) { this.variables[a] = b };
SWFObject.prototype.getVariables = function () { return this.variables };
SWFObject.prototype.getVariablesString = function () { var a=[], b, c = this.getVariables(); for(b in c) a[a.length] = b+"="+encodeURIComponent(c[b]); return a.join("&"); };
SWFObject.prototype.getSWFHTML = function () {
	var a = "";
	if(navigator.plugins && navigator.mimeTypes && navigator.mimeTypes.length) {
		a  = '<embed type="application/x-shockwave-flash" src="'+this.getAttribute("swf")+'" width="'+this.getAttribute("width")+'" height="'+this.getAttribute("height")+'" style="'+this.getAttribute("style")+'"';
		a += ' id="'+this.getAttribute("id")+'" name="'+this.getAttribute("id")+'" ';
		var b = this.getParams();
		for (var c in b) a += [c]+'="'+b[c]+'" ';
		var b = this.getVariablesString();
		if(b.length > 0) a += 'flashvars="'+b+'"';
		a += "/>";
	}
	else {
		a  = '<object id="'+this.getAttribute("id")+'" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="'+this.getAttribute("width")+'" height="'+this.getAttribute("height")+'" style="'+this.getAttribute("style")+'">';
		a += '<param name="movie" value="'+this.getAttribute("swf")+'" />';
		var b = this.getParams();
		for(var c in b) a+='<param name="'+c+'" value="'+b[c]+'" />';
		var b = this.getVariablesString();
		if(b.length > 0) a += '<param name="flashvars" value="'+b+'" />';
		a += "</object>";
	}
	return a;
}

SWFObject.prototype.write = function (obj) {
	if (this.installedVer.support(this.getAttribute("version"))) {
		var obj = (typeof obj == 'string') ? document.getElementById(obj) : obj;
		if (obj) {
			obj.innerHTML = this.getSWFHTML();
			return true;
		}
	}
	return false;
}

SWFObject.prototype._setAttribute = SWFObject.prototype.setAttribute;
SWFObject.prototype._addParam = SWFObject.prototype.addParam;
SWFObject.prototype._write = SWFObject.prototype.write;
_SWFObject = SWFObject;

function getSWFInstalledVersion() {
	if (navigator.plugins && navigator.mimeTypes.length) {
		var obj = navigator.plugins["Shockwave Flash"];
		if (obj && obj.description)
			return new SWFVersion(obj.description.replace(/([a-zA-Z]|\s)+/,"").replace(/(\s+r|\s+b[0-9]+)/,".").split("."));
	}
	else if (navigator.userAgent && navigator.userAgent.indexOf("Windows CE") >= 0) {
		var obj = true, ver = 3;
		while(obj) {
			try {
				obj = new ActiveXObject("ShockwaveFlash.ShockwaveFlash."+ver);
				ver++;
			}	catch(e) {
				return new SWFVersion([ver, 0, 0]);
			}
		}
	}
	else {
		try {
			obj = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7")
		}
		catch (e) {
			try {
				obj = new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");
				tmp = new SWFVersion([6, 0, 21]);
				obj.AllowScriptAccess = "always";
			} catch (e) {
				if(tmp.major == 6) return tmp;
			}
			try {
				obj = new ActiveXObject("ShockwaveFlash.ShockwaveFlash");
			}
			catch (e) { }
		}
		if(obj != null)
			return  new SWFVersion(obj.GetVariable("$version").split(" ")[1].split(","));
	}
	return new SWFVersion([0, 0, 0]);
}

function SWFVersion(arr) {
	this.major = arr[0] ? parseInt(arr[0]) : 0;
	this.minor = arr[1] ? parseInt(arr[1]) : 0;
	this.rev   = arr[2] ? parseInt(arr[2]) : 0;
}

SWFVersion.prototype.support = function (that) {
	if (this.major  < that.major) return false;
	if (this.major  > that.major) return true;
	if (this.minor  < that.minor) return false;
	if (this.minor  > that.minor) return true;
	if (this.rev    < that.rev)   return false;
	return true;
}

function popupbox_update(obj) {
}

function adjustpopup() {
	var graylayer = document.getElementById('graylayer');
	graylayer.style.left     = document.body.scrollLeft + 'px';
	graylayer.style.top      = document.body.scrollTop  + 'px';
	current_popup.style.left = (document.body.scrollLeft + (document.body.clientWidth  - current_popup.clientWidth )/2)+'px';
	current_popup.style.top  = (document.body.scrollTop  + (document.body.clientHeight - current_popup.clientHeight)/2)+'px';
}

function popupbox_open(obj) {
	current_popup = obj = document.getElementById(obj);
	var graylayer = document.getElementById('graylayer');
	obj.style.display    = graylayer.style.display  = 'block';
	obj.style.left       = (document.body.scrollLeft + (document.body.clientWidth  - obj.clientWidth )/2)+'px';
	obj.style.top        = (document.body.scrollTop  + (document.body.clientHeight - obj.clientHeight)/2)+'px';
	graylayer.style.left = document.body.scrollLeft + 'px';
	graylayer.style.top  = document.body.scrollTop  + 'px';
	window.onscroll = window.onresize = adjustpopup;
}

function popupbox_close(obj) {
	var graylayer = document.getElementById('graylayer');
	obj = (typeof obj == 'string') ? document.getElementById(obj) : obj;
	graylayer.style.display = obj.style.display  = 'none';
	window.onscroll = window.onresize = null;
}

function updateCharCount(textarea, counter, maxcount) {
	textarea = document.getElementById(textarea);
	counter  = document.getElementById(counter);
	count    = textarea.value.length;
	delta    = maxcount - count;
	if (delta > 0)
		counter.innerHTML = 'Você pode digitar mais <b>'+delta+'</b> caracteres.';
	else
		counter.innerHTML = '<font color="red">Você excedeu o limite em <b>'+Math.abs(delta)+'</b> caracteres.</font>';
}


function AjaxSendScrap(uid, qsid) {
	if (!uid.match(/^\d+$/)) return false;
}

function quickscrap_open(i) {
	setStyleById('closebox_'  +i, 'display', 'none');
	// setStyleById('captchabox_'+i, 'display', 'none');
	setStyleById('ajaxbox_'   +i, 'display', 'none');
	setStyleById('openbox_'   +i, 'display', 'block');
	setStyleById('scrapbox_'  +i, 'display', 'block');
}

function quickscrap_close(i) {
	setStyleById('closebox_'+i, 'display', 'block');
	setStyleById('openbox_' +i, 'display', 'none');
}

function quickScrapCallback(SCLoader, qsid) {
	result = SCLoader.responseText.split('\r\n');
	if (result[0] == 'ok') {
		if (qsid == 0) location.href = location.href;
		else return quickscrap_close(qsid);
	}
	if (result[0] == 'error') {
		ajaxbox = document.getElementById('ajaxbox_'   +qsid);
		ajaxbox.innerHTML = '<br><br><center><font color="red">'+result[1]+'</font><br><br><span class="btnboxl"><a href="javascript:quickscrap_open('+qsid+');">Voltar</a></span><span class="btnboxr"><img src="/img/b.gif" height="1" width="5"></span></center><br><br>';
	}
	if (result[0] == 'captcha') {
		quickscrap_open(qsid);
		captchabox = document.getElementById('captchabox_'+qsid);
		captchabox.style.display = 'block';
		captchabox.style.width = '600px';
		captchabox.innerHTML = '<br><center>Por favor digite o texto na imagem para prosseguir:<br><img src="'+result[1]+'"><br><input type="text" id="captcha_'+qsid+'" value=""></center><br><br>';
		captcha    = document.getElementById('captcha_'+qsid);
		if (captcha) captcha.focus();
	}
}

function quickScrap(uid, qsid) {
	textarea   = document.getElementById('quickscrap_'+qsid);
	if (textarea.value.length > 1024) return alert('Você não pode enviar este recado porque excedeu o limite de 1024 caracteres.');
	scrapbox   = document.getElementById('scrapbox_'  +qsid);
	ajaxbox    = document.getElementById('ajaxbox_'   +qsid);
	captchabox = document.getElementById('captchabox_'+qsid);
	captcha    = document.getElementById('captcha_'+qsid);
	ajaxbox.innerHTML = '<br><br><center>Aguarde...<br><img src="/img/ajax.gif" width="101" height="15"></center><br><br>';
	scrapbox.style.display = 'none';
	ajaxbox.style.width = '600px';
	ajaxbox.style.display  = 'block';
	try { var SCLoader = new XMLHttpRequest(); }
	catch (err) { var SCLoader = new ActiveXObject('Microsoft.XMLHTTP'); }
	eval("SCLoader.onreadystatechange = function () { if (SCLoader"+qsid+".readyState == 4) quickScrapCallback(SCLoader"+qsid+", "+qsid+"); };");
	eval("var SCLoader"+qsid+" = SCLoader;");
	post  = 'uid=' + uid;
	post += '&text=' + encodeURIComponent(textarea.value);
	if (captchabox.style.display == 'block')
		post += '&captcha=' + encodeURIComponent(captcha.value);
	SCLoader.open('POST', '/dispatchscrap.ajax', true);
	SCLoader.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	SCLoader.send(post);
}

function scrapsSelectAll(select) {
	var scraps = document.getElementsByTagName('input');
	for (var i = 0; i < scraps.length; i++)
		if (scraps[i].name.match(/^scrapCheck\d+$/)) scraps[i].checked = select;
}

function scrapsDeleteSelected() {
	if (!confirm('Deseja realmente deletar todos os recados selecionados?')) return;
	var sharedform = document.getElementById('sharedform');
	var cryptids   = document.createElement('input');
	cryptids.name = 'cryptids';
	cryptids.value = '';
	sharedform.action = 'deletescraps';
	sharedform.appendChild(cryptids);

	var scraps = document.getElementsByTagName('input');
	for (var i = 0; i < scraps.length; i++)
		if (scraps[i].name.match(/^scrapCheck\d+$/))
			if(scraps[i].checked) cryptids.value += scraps[i].value;

	sharedform.submit();
}

function scrapsDeleteSingle(cryptid) {
	var sharedform = document.getElementById('sharedform');
	var cryptids   = document.createElement('input');
	cryptids.name = 'cryptids';
	cryptids.value = cryptid;
	sharedform.action = 'deletescraps';
	sharedform.appendChild(cryptids);
	sharedform.submit();
}

function buyshopitem(entry) {
	if (!confirm('Deseja realmente comprar este item?')) return;
	var buyform = document.getElementById('buyform');
	buyform.buyitemid.value = entry;
	buyform.submit();
}

function buyscript(entry) {
	if (!confirm('Deseja realmente comprar este item?')) return;
	var scriptform = document.getElementById('scriptform');
	scriptform.script.value = entry;
	scriptform.submit();
}

function vote(entry, halt) {
    if (halt) {
        alert('Você já votou neste site hoje e não pode votar novamente.');
    } else {
    	var voteform = document.getElementById('voteform');
    	voteform.votesite.value = entry;
    	voteform.submit();
    	setTimeout('location.reload()', 10000);
    }
}

function hearthstone(guid) {
	var teleform = document.getElementById('teleform');
	teleform.guid.value = guid;
	teleform.submit();
}


function commentout(entry) {
	var commentBox = document.getElementById('commentBox'+entry);

    if (commentBox.value.length < 2) alert('Seu comentário deve conter no mínimo 2 letras.');
    else {
    	var sharedform = document.getElementById('sharedform');
    	sharedform.action = location.href;

    	var comment = document.createElement('input');
    	comment.name = 'comment';
    	comment.value = commentBox.value;
    	sharedform.appendChild(comment);

    	var blogentry = document.createElement('input');
    	blogentry.name = 'entry';
    	blogentry.value = entry;
    	sharedform.appendChild(blogentry);

    	sharedform.submit();
    }
}

function commentlimit(entry) {
	var commentBox   = document.getElementById('commentBox'+entry);
	var commentCount = document.getElementById('commentCount'+entry);
    if (commentBox.value.length > 200)
	    commentBox.value = commentBox.value.substring(0, 200);
    commentCount.innerHTML = 200 - commentBox.value.length;
}
