/****************

My JavaScript.

learning is not stealing,
but stealing is.

*****************/

// These are from twitter
function relative_time(time_value) {
	var parsed_date = Date.parse(time_value);
	
	var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
	var delta = parseInt((relative_to.getTime() - parsed_date) / 1000);
	
	if(delta < 60) {
		return 'less than a minute ago';
	} else if(delta < 120) {
		return 'about a minute ago';
	} else if(delta < (45*60)) {
		return (parseInt(delta / 60)).toString() + ' minutes ago';
	} else if(delta < (90*60)) {
		return 'about an hour ago';
	} else if(delta < (24*60*60)) {
		return 'about ' + (parseInt(delta / 3600)).toString() + ' hours ago';
	} else if(delta < (48*60*60)) {
		return '1 day ago';
	} else {
	return (parseInt(delta / 86400)).toString() + ' days ago';
}
}

function twitterCallback(obj) {
	var id = obj[0].user.id;
	document.getElementById('my_twitter_status').innerHTML = obj[0].text;
	document.getElementById('my_twitter_status_time').innerHTML = relative_time(obj[0].created_at);
}

// Shows and hides the links on the right
function show(id) {
	el = document.getElementById(id);
	if (el.style.display == 'none') {
		el.style.display = 'inline';
		el = document.getElementById('more' + id);
		el.innerHTML = 'see less';
	} else {
		el.style.display = 'none';
		el = document.getElementById('more' + id);
		el.innerHTML = 'see more';
	}
}

// to make everything standards compliant... changes rel=external to target=blank
function externalLinks() {
	if (!document.getElementsByTagName) return;
	var anchors = document.getElementsByTagName("a");
	for (var i=0; i<anchors.length; i++) {
		var anchor = anchors[i];
		if (anchor.getAttribute('rel') && anchor.getAttribute('rel').toLowerCase().match('external'))
			anchor.target = "_blank";
	}
	// this is for the blogroll items so they open externally.  fuckin' javascript.
	var divs = document.getElementsByTagName("div");
	for (var i=0; i<divs.length; i++) {
		var div = divs[i];
		if (div.getAttribute('class') && div.getAttribute('class').toLowerCase().match('blogrollitem'))
			div.childNodes[0].target = "_blank";
	}
}

// can switch stylesheets on the fly
function setActiveStyleSheet(title) {
	var i, a, main;
	for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
		if(a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title")) {
			a.disabled = true;
			if(a.getAttribute("title") == title) a.disabled = false;
		}
	}
}

//the function to test to see if a name has been selected.
function checkNames() {
	// is name entered yet?
	if (document.add.author.value == "") {
		alert("Please enter name...");
		document.add.author.focus();
		return false;
	}
	// is comment there?
	if (document.add.comment.value == "" || document.add.comment.value == "comment") {
		alert("um... gonna add a comment?");
		document.add.comment.focus();
		return false;
	}
	// i now require an email address
	if (document.add.email.value == "") {
		alert("Sorry, I require a valid email address now\nIt will not be published!");
		document.add.email.focus();
		return false;
	}
	return true;
}

// Pops up a new window with the comments
function commentPopUp(theURL) {
	window.open(theURL,'comments', config='height=400, width=350, toolbar=no, menubar=no, scrollbars=yes, resizable=yes, location=no, directories=no, status=no'); 
}

// Everything below is for AJAX
// I know it's messy right now, but hell, it works :)

// Trims whitespace from the "left" side of a string
function LTrim (str) {
  str = this != window ? this : str;
  return str.replace(/^\s+/g, '').replace(/\s+$/g, '');
}

// AJAX!
function createRequestObject() {
    var ro;
    var browser = navigator.appName;
    if(browser == "Microsoft Internet Explorer"){
        ro = new ActiveXObject("Microsoft.XMLHTTP");
    }else{
        ro = new XMLHttpRequest();
    }
    return ro;
}
var http = createRequestObject();
var added = false;
var beginH = 0;

function sndReq(pid) {
	if (document.getElementById('a'+pid).innerHTML == 'Hide Comments') {
		//document.getElementById('a'+pid).innerHTML = 'Show Comments';
		//document.getElementById('c'+pid).innerHTML = '';
		//document.getElementById('c'+pid).style.display="none";
		globalPid = pid;
		reScroll(pid);
	} else {
		document.getElementById('a'+pid).innerHTML = 'Loading Comments<img src="/images/loading.gif" align="baseline" alt="" />';
		params = 'pid='+pid;
		http.onreadystatechange = handleResponse;
		http.open('POST', '/talkback/rpc.php');
		http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		http.setRequestHeader("Content-length", params.length);
		http.setRequestHeader("Connection", "close");
		http.send(params); 
		http.onreadystatechange = handleResponse;
	}
}

function submitForm(pid) {
	if(!checkNames())
		return false;
	document.add.submit.disabled = true;
	document.add.submit.value = "adding...";
	var author = document.add.author.value;
	var email = document.add.email.value;
	var url = document.add.url.value;
	var comment = document.add.comment.value;
	var rememberme = document.add.rememberme.value;
	params = 'method=add&pid='+pid+'&author='+author+'&email='+email+'&url='+url+'&rememberme='+rememberme+'&comment='+comment;
	added = true; // this lets handleResponse know we just added a comment
	http.open('POST', '/talkback/rpc.php');
	http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	http.setRequestHeader("Content-length", params.length);
	http.setRequestHeader("Connection", "close");
	http.send(params);
	http.onreadystatechange = handleResponse;
}

function handleResponse() {
	if((http.readyState == 4) || (http.readyState == 'complete')) {
		var response = LTrim(http.responseText);
		var pid = response.match(/^[0-9]+/i);
		document.getElementById('c'+pid).style.display = 'block';
		if (added != true)
			beginH = 0;
		else
			beginH = document.getElementById('c'+pid).offsetHeight;
		document.getElementById('c'+pid).style.height = beginH + 'px';
		document.getElementById('c'+pid).style.overflow = 'hidden';
		response = response.replace(/^[0-9]+/i, '');
		document.getElementById('c'+pid).innerHTML = response;
		globalPid = pid;
		unScroll();
	}
}

// These do the movement scroll up and down thingies.
var sDiv="";
var inPx = 0;
var currTime = 0;
var duration = 100;
function unScroll() {
	sDiv = document.getElementById('c'+globalPid);
	scrollH = sDiv.scrollHeight;
	unScrollRe(sDiv);
}
// this one is the recursive "unhide" function.  love js recursion.
function unScrollRe() { // keep in mind that this is only called by unScroll
	offsetH = sDiv.offsetHeight;
	if (offsetH < (scrollH-5)) { // base case for recursion
		currTime += 20; // Thanks to Robert Penner www.robertpenner.com for help with these equations!
		newCurrTime = currTime/duration;
		if ((newCurrTime) < 1) 
			newHeight = scrollH/2*newCurrTime*newCurrTime + beginH;
		else
			newHeight = -scrollH/2 * ((--newCurrTime)*(newCurrTime-2) - 1) + beginH;
		sDiv.style.height = (newHeight + "px");
		setTimeout("unScrollRe()","10");
	} else {
		sDiv.style.height="auto";
		sDiv.style.overflow="visible";
		document.getElementById('a'+globalPid).innerHTML = 'Hide Comments';
		externalLinks();
		newHeight = 10;
		currTime = 0;
	}
}
function reScroll() {
	sDiv2 = document.getElementById('c'+globalPid);
	scrollH = sDiv2.scrollHeight;
	reScrollRe();
}
function reScrollRe() { // keep in mind that this is only called by reScroll
	sDiv2.style.overflow="hidden";
	offsetH = sDiv2.offsetHeight;
	if (offsetH > 5) { // base case for recursion
		currTime += 20;
		newCurrTime = currTime/duration;
		if ((newCurrTime) < 1) 
			newHeight = -scrollH/2*newCurrTime*newCurrTime + scrollH;
		else
			newHeight = scrollH/2 * ((--newCurrTime)*(newCurrTime-2) - 1) + scrollH;
		sDiv2.style.height = (newHeight + "px");
		setTimeout("reScrollRe()","10");
	} else {
		document.getElementById('a'+globalPid).innerHTML = 'Show Comments';
		sDiv2.innerHTML = '';
		sDiv2.style.display="none";
		newHeight = 10;
		currTime = 0;
	}
}

