
if(!window.Event) {    // for ie6 shh
    Event = new Object();
}

//if(typeof console === 'undefined') {
if( !window.console || !console.log ) {
	console = new Object(); 
	console.log = '';
	console.fakey = true;
}


function brLog(e) {
	if(!e)	errstr = String("+ERROR ");
	else {
		if(e.type) errstr = String("+ERROR " + e.type);
		else errstr = String("+log  \t" + e.toString() );
	}

	if(HIGHALERT) {
		alert(errstr);
	}

	window.status = errstr;

	if(console)
		if(!console.fakey)
			console.log(errstr);

	return;
}

function makeAjaxRequest(url, htmleid, eventhandler, cached) {
	var ajaxObject = new Object();

	var xmlhttp = null;
	if (window.XMLHttpRequest) {
		xmlhttp = new XMLHttpRequest();
	} else if (window.ActiveXObject) {
		//var xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
		xmlhttp = new ActiveXObject('MSXML2.XMLHTTP.3.0');
	}
	ajaxObject.modifybox = htmleid;
	ajaxObject.xmlhttp = xmlhttp;
	brLog('initilized for box: '+htmleid);

	xmlhttp.onreadystatechange = function() {
		if(xmlhttp.readyState == 4) {
			if(xmlhttp.status == 200) {
				eventhandler(ajaxObject);
			} else {
				/*fmc*/
				if(xmlhttp.status)
					brLog( 'unexpected XMLobj HTTP result: '+xmlhttp.status );
					//document.body.innerHTML = xmlhttp.responseText;
			}
		}
//		if(xmlhttp.responseText)
//			console.log('NEW_CODE_RESPONSE_BODY:'+xmlhttp.responseText);
	}

	if(url) {
		if(cached)
			url = '/talkback/cache/cachedRequest.php?u='+escape(url);

		xmlhttp.open('GET', url, true );
//		alert(url);
//		xmlhttp.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
		xmlhttp.send("");
		brLog( 'NEWAPI send() executed for ['+url+']');
	}
	else
		brLog( 'XML load exception.');
}




function ajaxRequestCallback( ajaxRequest ) {

	if(!ajaxRequest.modifybox) {
		brLog('no destination HTML element named.  aborting.');
		return;
	}

	// save the parent
	var oldNode = document.getElementById(ajaxRequest.modifybox);
	var attachNode = oldNode.parentNode;
	
	var tmpID = oldNode.getAttribute('id');
	var tmpListsrc = oldNode.getAttribute('listsrc');
	var tmpListclass = oldNode.getAttribute('class');
	
	var XMLdoc = ajaxRequest.xmlhttp.responseXML;	// if ! null then xml doc, otherwise, test for JSON, otherwise, just display......?
	var TXTdoc = ajaxRequest.xmlhttp.responseText;  // would like to trim/massage this first
	var JSONdoc = false;
	if(TXTdoc) {
		if(TXTdoc[0] == "{") {
			JSONdoc = eval('(' + ajaxRequest.xmlhttp.responseText + ')');
		}
	}

	var newNode = null;

	if (XMLdoc) {
		brLog(ajaxRequest.modifybox+' parsed as XML');
		newNode = loadDOMfromTwitterXML(XMLdoc);
		//newNode = traverse(XMLdoc);
		if(!newNode)
			brLog(ajaxRequest.modifybox+' failed XML matching');
	}

	if(!newNode) {
		if (JSONdoc) {
			brLog(ajaxRequest.modifybox+' parsed as JSON');
			newNode = loadDOMfromTwitterJSON(JSONdoc);
		}
	}

	if(!newNode) {
		if(TXTdoc) {
			brLog(ajaxRequest.modifybox+' displayed as TEXT');
			newNode	= document.createElement('P');
			newNode.appendChild( document.createTextNode( 'text: '+TXTdoc.toString() ) );
		}
	}

	if(newNode && newNode.nodeType == 1 ) { /* just HTML elements, pls */
		newNode.setAttribute('id', tmpID);
		newNode.setAttribute('listsrc', tmpListsrc);
		newNode.setAttribute('class', tmpListclass);
		attachNode.removeChild(oldNode);
	}
	else {
		msg	= document.createTextNode('error: could not translate the remote document');
		newNode	= document.createElement('P');
		newNode.appendChild(msg);
	}
	
	attachNode.appendChild(newNode);
	return;
}




function hyperlinks(text) {

	if(typeof text != 'string')
		return text;

	text = text.replace(/\s(http\:\/\/[a-z][a-zA-Z0-9\/\*\-\?\.\&\%\$]*)\s/ig," <a href=\"$1\" class=\"twitter-link\">$1</a>");
	text = text.replace(/\s([a-zA-Z]\+\:\/\/[a-z][a-z0-9\_\.\-]*[a-z]{2,6}[a-zA-Z0-9\/\*\-\?\&\%]*)([\s|\.|\,])/ig," <a href=\"$1\" class=\"twitter-link\">$1</a>$2");
	// match www.something.domain/path/file.extension?some=variable&another=asf%
	text = text.replace(/\s(www\.[a-z][a-z0-9\_\.\-]*[a-z]{2,6}[a-zA-Z0-9\/\*\-\?\&\%]*)([\s|\.|\,])/ig," <a href=\"http://$1\" class=\"twitter-link\">$1</a>$2");      

	return text;
}

function twitter_users(text) {

//	if(typeof text != 'string')
//		return text;

    text = text.replace(/([^a-zA-Z0-9]?)\@{1}(\w*)([^a-zA-Z0-9]?)\s/ig, "$1<a href=\"http://twitter.com/$2\" class=\"twitter-user\">\@$2</a>$3 ");
    return text;
}

function drop_us_a_line(obj) {
document.writeln("\x3C\x61\x20\x68\x72\x65\x66\x3D\x22\x6D\x61\x69\x6C\x74\x6F\x3A\x69\x6E\x66\x6F\x40\x62\x69\x74\x72\x6F\x6F\x74\x73\x2E\x63\x6F\x6D\x22\x3E\x69\x6E\x66\x6F\x40\x62\x69\x74\x72\x6F\x6F\x74\x73\x2E\x63\x6F\x6D\x3C\x2F\x61\x3E");
}

function rmailto(obj) {
//	if( obj.getAttribute("href").length < 2) {
		obj.setAttribute( );
//	}
}


function loadTweetsToTag( tweetFeedURL, tweetListContainer ) {

	if( typeof tweetListContainer != 'string' ) {
		tweetListContainer = tweetListContainer.getAttribute('id');
	}

	brLog( 'loading tweet: ' + tweetFeedURL + ' to box: ' + tweetListContainer );
	document.getElementById( tweetListContainer ).appendChild( document.createTextNode('(loading)') );

	makeAjaxRequest( tweetFeedURL, tweetListContainer, ajaxRequestCallback, true );	// ( file URL, htmlElementtoreplace, callback func, cached? bool )
}


function traverse(tree, startObj) {

	if(!startObj) startObj = document.createElement('UL');
	
	addToTree( tree, startObj );

	return	startObj;

}

function addToTree(tree, _lastNode ) {

	if(tree.hasChildNodes()) {

		var _addNode = document.createElement('UL');
		var _li = document.createElement('LI');
		var _b = document.createElement('B');
		var _p = document.createElement('P');
	
		var t_nodeName = document.createTextNode( tree.nodeName );		// name
//		var t_nodeText = document.createTextNode( '<a href="linkme.html">aaaaaaaa</a><br>');		// text
		var t_nodeInner = _p.innerHTML = tree.textContent;		// innerHTML NOT IDEAL, but it works.....
	
		_b.appendChild(t_nodeName);			        	
		_li.appendChild(_b);			        	
//		_li.appendChild(t_nodeText);			        	
		_li.appendChild(_p);			        	
		_addNode.appendChild(_li);			        	
	
		var nodes=tree.childNodes.length;
		for(var i=0; i<nodes; i++)
				addToTree( tree.childNodes[i], _addNode );
	
		_lastNode.appendChild(_addNode);
	}
	else
		return _lastNode;
              
}


function loadDOMfromTwitterJSON(jsondoc) {
	var tmpNode = document.createElement('B')
	tmpNode.appendChild(document.createTextNode('this is incomplete.') );
	
	return tmpNode;


// old code.... inaccessible for now

	//brLog(ajaxRequest.xmlhttp.responseText);


	// response doc parsing, assuming successful json compile
	if(JSONdoc['@attributes']) {
		if(JSONdoc['@attributes']['update'] == true) {
			updateTwitter( ajaxRequest.modifybox.getAttribute('listsrc') );
		}
	}

			
	if ( JSONdoc.item ) {

		//loadDOMfromJSON().....

		// remove ourselves
		attachNode.removeChild(ajaxRequest.modifybox);

		
		var itemCount = JSONdoc.item.length;
		
		
		for (var i = 0; i < itemCount; i++) {
			var li = document.createElement("LI");
			li.className = "twitter-item";
			
				var profilePic = document.createElement("A");
				profilePic.href = "http://www.twitter.com/" + JSONdoc.item[i].user;
				
					var img = document.createElement("IMG");
					img.src = JSONdoc.item[i].avatar;
				
				profilePic.appendChild(img);
				
			li.appendChild(profilePic);
			
			var message = hyperlinks(JSONdoc.item[i].description);
			message = twitter_users(message);
			
			li.innerHTML += message;
			
				var br = document.createElement("BR");
			
			li.appendChild(br);
				
				var a = document.createElement("A");
				a.href = JSONdoc.item[i].url;
				a.className = "twitter-link";
				a.innerHTML = "# posted " + JSONdoc.item[i].date;
			
			li.appendChild(a);

			
			newNode.appendChild(li);
		}
	}

}



function loadDOMfromTwitterXML(xmldoc) {

	var entries = xmldoc.getElementsByTagName('entry');
	var items = xmldoc.getElementsByTagName('item');

	if(entries.length>0)
		return processTwitterEntries(entries);
	
	else if(items.length>0)
		return processTwitterItems(items);

	var tmpNode = document.createElement('UL');
	var tmpItem = document.createElement('LI');

	tmpItem.appendChild(document.createTextNode('Sorry, no entries or items at this time... :-( '));
	tmpNode.appendChild(tmpItem);
	
	return tmpNode;	

	return null;
}


function processTwitterEntries(entries) {

	if(entries.length<1)
		return null;

	var tmpNode = document.createElement('UL');

	for(i=0;i<entries.length;i++) {
		
		var eTitle = entries[i].getElementsByTagName('title')[0].textContent;
		if(!eTitle) eTitle = entries[i].getElementsByTagName('title')[0].text;
		
		var eData = entries[i].getElementsByTagName('content')[0].textContent;
		if(!eData) eData = entries[i].getElementsByTagName('content')[0].text;

		var eAuthor = entries[i].getElementsByTagName('author')[0].getElementsByTagName('name')[0].textContent;
		if(!eAuthor) eAuthor = entries[i].getElementsByTagName('author')[0].getElementsByTagName('name')[0].text;

		var eAuthorLink = entries[i].getElementsByTagName('author')[0].getElementsByTagName('uri')[0].textContent;
		if(!eAuthorLink) eAuthorLink = entries[i].getElementsByTagName('author')[0].getElementsByTagName('uri')[0].text;

		var eAvatar = null;
		// test for:
		// <link type="image/png" href="http://a3.twimg.com/profile_images/1257098617/giochigratisonline_normal.png" rel="image"/>

		var j=0,testnode; 
		while( testnode = entries[i].getElementsByTagName('link')[j++] ) {
			if(testnode.attributes.getNamedItem("rel").nodeValue == 'image' ) {
				eAvatar = testnode.attributes.getNamedItem("href").nodeValue;
				break;
			}
		}

		var itemNode = document.createElement('LI');

		var authorNode = document.createElement('A');
		authorNode.setAttribute('href', eAuthorLink);
		authorNode.setAttribute('class', 'noclass');
/*
		var avatarNode = document.createElement('IMG');  // will only load after it's actually been appended to the doc, resulting in img loading boxes
		avatarNode.setAttribute('src', eAvatar);
		avatarNode.setAttribute('width', 48);
		avatarNode.setAttribute('height', 48);
*/
		var avatarNode = new Image();  /* built-in preloading */
		avatarNode.src = eAvatar;
		avatarNode.width = 48;
		avatarNode.height = 48;

		authorNode.appendChild(document.createTextNode(eAuthor));
		authorNode.appendChild(avatarNode);

		var contentNode = document.createTextNode( ' '+eTitle+' ' ); // everything in life needs a good buffer

		itemNode.appendChild( authorNode );
		itemNode.appendChild( contentNode );

		tmpNode.appendChild(itemNode);
	}

	return tmpNode;
}

function processTwitterItems(items) {

	if(items.length<1)
		return null;

	var topNode = document.createElement('UL').appendChild(
						document.createElement('UL'));

	for(i=0;i<items.length;i++) {
		
		var eTitle = items[i].getElementsByTagName('title')[0].textContent;
		if(!eTitle) eTitle = items[i].getElementsByTagName('title')[0].text;
		
		var eAuthor = 'bitroots';
		var eAuthorLink = 'http://twitter.com/bitroots';
		var eAvatar = 'http://a1.twimg.com/profile_images/1275011784/logo_sq_normal.png';

// still testing....
//		eTitle = getWholeText( items[i].getElementsByTagName('title')[0] );
//		var eContent = getWholeText( items[i].getElementsByTagName('description')[0] );
// too slow......

		var itemNode = document.createElement('LI');

		var authorNode = document.createElement('A');
		authorNode.setAttribute('href', eAuthorLink);
		authorNode.setAttribute('class', 'noclass');
/*
		var avatarNode = document.createElement('IMG');  // will only load after it's actually been appended to the doc, resulting in img loading boxes
		avatarNode.setAttribute('src', eAvatar);
		avatarNode.setAttribute('width', 48);
		avatarNode.setAttribute('height', 48);
*/

		var avatarNode = new Image();  /* built-in preloading */
		avatarNode.src = eAvatar;
		avatarNode.width = 48;
		avatarNode.height = 48;

//		authorNode.appendChild(document.createTextNode(eAuthor));
//		authorNode.appendChild(avatarNode);

		var contentNode = document.createTextNode( ' '+eTitle+' ' ); // everything in life needs a good buffer

		itemNode.appendChild( authorNode );
		itemNode.appendChild( contentNode );

		topNode.appendChild(itemNode);
	}


	
	return topNode;
}


function getWholeText(obj) {

	var foundText = null;
	
	foundText = traverseForText( obj );
	
	return foundText;


}



function traverseForText(tree) {

	var _text = new String();

	if(tree.nodeType == 3) {
		_text = tree.data;
	}

	if(tree.hasChildNodes()) {

		var _addText = new String();
		var nodes=tree.childNodes.length;
		

		for(var i=0; i<nodes; i++)
				_addText += traverseForText( tree.childNodes[i] );
						
		if(_addText != '')
			_text += _addText;
	}

	return _text;
              
}



function liberateform(formobj) {

	var k = Math.random() * Number.MAX_VALUE;
	var d = k/parseInt(k.toString()[0]);

	var sk = document.createElement('INPUT');
	sk.setAttribute('name', 'lfSK');
	sk.setAttribute('type', 'hidden');
	sk.setAttribute('value', k);

	var sd = document.createElement('INPUT');
	sd.setAttribute('name', 'lfSD');
	sd.setAttribute('type', 'hidden');
	sd.setAttribute('value', d);

	formobj.action = "http://bitroots.com/forms/";
	formobj.method = 'POST';
	formobj.encoding = 'application/x-www-form-urlencoded';	// generic for forms (default)
//	formobj.encoding = 'multipart/form-data';					// for uploading files


	// function will work on the formobj and return void;

	var subElems = formobj.childNodes;
	for(j=0;j<subElems.length;j++) {
		if (subElems[j].nodeType != 1)
			continue;
		var pt=subElems[j].getAttribute('pretext');
		if(pt){
			subElems[j].value = pt;
			subElems[j].onfocus = function() {
				if(this.value == this.getAttribute('pretext'))
					this.value = '';							
			};
			subElems[j].onblur = function() {
				if(this.value == '')
					this.value = this.getAttribute('pretext');							
			};
		}
	}
					
	formobj.appendChild( sk );
	formobj.appendChild( sd );

	return;				
}
