var pods = new Array ();
pods['prime']=new pod ();

function alertbad (){
	if(navigator.appName=="Microsoft Internet Explorer"){
		alert('The Interactive Social Contract Does Not Work In Explorer.  PLease Try Firefox, Safari, or Opera.  Our Engineers are working on it.');
	}
}

var thehistory = new podhistory();
function podhistory (){
	this.visited = new Array ();
	this.states=0;
	this.thisstate=0;
	this.goforth = function (){
		if (this.thisstate < this.states){
			this.thisstate++;
			scrollto(this.visited[this.thisstate-1]);
			divtofront(this.visited[this.thisstate-1]);
		}
	}
	this.goback = function (){
		if (this.thisstate >0 ) {
			this.thisstate--;
			scrollto(this.visited[this.thisstate-1]);
			divtofront(this.visited[this.thisstate-1]);
		}
	}
	this.newstate = function (podID) {
		if (this.states != this.thisstate) {
			this.states=this.thisstate;
			this.visited[this.states]=podID;
			this.states++;
			this.thisstate++;			
	
		}else{
			this.visited[this.states]=podID;
			this.states++;
			this.thisstate++;
		} 
	}
}

function closeall(){      //close all open pods
	for (x in pods['prime'].children) {
		if (typeof pods['prime'].children[x] != 'undefined'){
		  killpod(x);
		}
	}	
	var thehistory = new podhistory();  //reset history
}

function highscores (){
	if (document.getElementById('highscores').style.display=='none'){
		document.getElementById('highscores').style.display='block';
		document.getElementById('gray').style.display='block';
		//TVsin('out');
	}else{
		document.getElementById('highscores').style.display='none';
		document.getElementById('gray').style.display='none';
		//TVsin('in');
	}	
}

function newdiv (newid){
	thediv=document.createElement('div');
	thediv.setAttribute('id',newid);
	holder=document.getElementById('podholder');
	holder.appendChild(thediv);		
}

function editpod (podid) {   //open up the editing filed
	if (document.getElementById(podid+"textbox").style.display=='none'){
		var podcontentdivid = podid+'content';
		var podeditdivid = podid+'edit';
		document.getElementById(podcontentdivid).style.display='none';
		document.getElementById(podeditdivid).style.display='block';	
	}
}

function handleedit (target,response) {	
	document.getElementById(target+'throbber').style.display='none';	//turn off throbber
	pods[target].podsloading--;											//subtract new throbber to que
	var changes = new Array ();
	changes= response.split('_');	
	document.getElementById(target+'titletext').innerHTML=unescape(changes[0]);
	document.getElementById(target+'bodytext').innerHTML=unescape(changes[1]);
	document.getElementById(target+'postertext').innerHTML=unescape(changes[2]);
}

function submiteditedlaw (submitorcancel, podid) {
	var podcontentdivid = podid+'content';
	var podeditdivid = podid+'edit';
	document.getElementById(podcontentdivid).style.display='block';   // close everything
	document.getElementById(podeditdivid).style.display='none';
	
	if (submitorcancel=='cancel'){
		//do nothing	
	}else{  //send update
		var editedtitle=podid+'edittitle';
		var editedtext=podid+'editbody';
		var editedposter=podid+'editsig';
	
		var newtitle=document.getElementById(editedtitle).value;		
		var newtext=document.getElementById(editedtext).value;
		var newposter=document.getElementById(editedposter).value;
		
		document.getElementById(podid+'throbber').style.display='block';	//turn on throbber
		pods[podid].podsloading++;											//add new throbber to que
		
		XHR(podid,'dbupdate.php?podid='+podid+'&title='+escape(newtitle)+'&body='+escape(newtext)+'&poster='+escape(newposter),handleedit);
	}
}

function hideshowurllink (id) {
	if (document.getElementById(id).style.display=='none'){
		document.getElementById(id).style.display='block';
	} else {
		document.getElementById(id).style.display='none';
	}	
}

function returnbookmark (thebookmark,serverdata,status,thetitle){
	//  if bookamrks isn't visible or the bookmark is not new reload the frame
	if (tvinout='in'){TVsin();}
	if ((window.frames.leftTV.document.title!='bookmarks')||(serverdata=='duplicate')){
			leftTV.location.href = 'bookmarks.php';
	}else if (serverdata=='create'){ 	// if the bookmark is new and bookamrks are open, update the html by hand (maybe we should)
		bookmarktext=window.frames.leftTV.document.getElementById('bookmarks');   
		bookmarktext.innerHTML='<hr><span onclick="parent.prepopento('+"'"+thebookmark+"'"+')">'+thetitle+'</span>'+bookmarktext.innerHTML;
	} 
	if (serverdata=='deleted'){
		bookmarktodie=window.frames.leftTV.document.getElementById(thebookmark+'bookmark');   
		bookmarktodie.parentNode.removeChild(bookmarktodie);
	}
}

function addbookmark (thebookmark,thetitle){
	XHR (thebookmark,'addbookmark.php?bookmark='+thebookmark,returnbookmark,thetitle)	
}

function removebookmark (thebookmark){
	XHR (thebookmark,'removebookmark.php?bookmark='+thebookmark,returnbookmark)	;
}
function confirmemail (bogus, addy){
	alert(addy);
}
function sendemail(addy) {
	XHR ('bogus','addemailaddress.php?email='+addy, confirmemail);
}

function cyclead (){
	if (document.getElementById('tvrightlogin').style.display=='block') {
		document.getElementById('tvrightlogin').style.display='none';
		document.getElementById('tvrightad').style.display='block';
	}else{
		document.getElementById('tvrightlogin').style.display='block';
		document.getElementById('tvrightad').style.display='none';	
	}
	setTimeout(cyclead,30000);
}

function scrollup (distance,thediv,up)  {   //scroll the law box
	var thisdiv = thediv+"scroller";     //"thisdiv" is the div name plus "scroller"  "thediv"  is the pod div  that is the name of the element in the array that has the scroll l,ocations

	dist=distance-(distance/3);
	var divtoscroll=document.getElementById(thisdiv);
	if (up=="up") {
		pods[thediv].scrollposition-=dist;
	}else{
		pods[thediv].scrollposition+=dist;
	}
	divtoscroll.style.top = pods[thediv].scrollposition+'px';
	thedivFF=thediv;  upFF=up;   //why can't you pass the functions vars back to the function?  Balls!
	if (dist >= 3) { 
		setTimeout("scrollup(dist,thedivFF,upFF);", 30);
	}

}

function findPos(objId) {     //quirksmode.org
	obj=document.getElementById(objId);
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		curleft = obj.offsetLeft
		curtop = obj.offsetTop
		while (obj = obj.offsetParent) {
			curleft += obj.offsetLeft
			curtop += obj.offsetTop
		}
	}
	return [curleft,curtop];
}



function f_scrollLeft() {
	return f_filterResults (
		window.pageXOffset ? window.pageXOffset : 0,
		document.documentElement ? document.documentElement.scrollLeft : 0,
		document.body ? document.body.scrollLeft : 0
	);
}
function f_scrollTop() {
	return f_filterResults (
		window.pageYOffset ? window.pageYOffset : 0,
		document.documentElement ? document.documentElement.scrollTop : 0,
		document.body ? document.body.scrollTop : 0
	);
}
function f_filterResults(n_win, n_docel, n_body) {
	var n_result = n_win ? n_win : 0;
	if (n_docel && (!n_result || (n_result > n_docel)))
		n_result = n_docel;
	return n_body && (!n_result || (n_result > n_body)) ? n_body : n_result;
}

{var desX=0;
var desY=0;
var curX=0;
var curY=0;
var curspeedX=0;
var curspeedY=0;
var scrolling='no';
//var speedX=0;
//var speedY=0;
}

function updatescroll (   ){    
	tspeedX=(desX-curX)/6;
	tspeedY=(desY-curY)/6;
	curspeedX=((tspeedX-curspeedX)/2)+curspeedX;
	curspeedY=((tspeedY-curspeedY)/2)+curspeedY;
	curX= f_scrollLeft ();
	curY= f_scrollTop ();
	if (scrolling == 'yes'){  //stupid firefox...
		window.scrollBy(curspeedX,curspeedY);
		setTimeout (updatescroll,20);
	}
//	if ((speedX <= 1) && (speedY <= 1) ){
//		scrolling='no';
//	}
}

function scrollto (thetarget,multiplier){
	if (typeof(multiplier)=='undefined'){multiplier=0;}
	curX= f_scrollLeft ();
	curY= f_scrollTop ();
	destination=findPos(thetarget);
	desX= destination[0]-(document.body.clientWidth/2)+50;   //center it in the screen
	desY= destination[1]-50;
	desX= curX + (desX - curX); 
	desY= curY + (desY - curY);
	if (scrolling=='no'){
		scrolling='yes';
		setTimeout (updatescroll,20);
	}	
				
}

var newz=1;
function tofront(divID) {
	newz++;
   	var thediv=document.getElementById(divID);
   	thediv.style.zIndex = newz;
   	thediv = thediv.parentNode;
	thediv.style.zIndex = newz;
}

function divtofront(divID)  {
   	findparents (divID,tofront);
   	tofront(divID);
   	findchildren (divID,tofront);
}

function handlevote (thelaw,serverdata,status){  //recieve new truth index and bonus points
		
	voteresult=serverdata.split('*');  							//separate the votes from your bonus pints (is this what xml is for?)	
	var votediv=thelaw+'popularity';  							//this is the name of the div with the vote number in the main pod
	var votelistdiv=thelaw+'listpopularity';  					//this is the name of the div with the vote number in the list pod
	var voteholder=voteresult[0];  								//the truth index
	var bonusholder=voteresult[1];								//your new bonus points
	document.getElementById(votediv).innerHTML=voteholder;		//update the big number
	document.getElementById(votelistdiv).innerHTML=voteholder;	//udate the number in the list
	document.getElementById('bonuspoints').innerHTML=bonusholder;   //update your bonus points

}


function vote (thelaw,good) {
	//name up & down img objects
	upimg=thelaw+"upon";										//name of the selected up vote's div
	downimg=thelaw+"downon"	;									//name of the selected up vote's div
	//assign votes and show feedback
	if (good) {
		XHR(thelaw,'addvotes.php?id='+thelaw+'&good='+good,handlevote);
		document.getElementById(upimg).style.display='block';   //highlight correct hand
		document.getElementById(downimg).style.display='none';	
	}else{
		XHR(thelaw,'addvotes.php?id='+thelaw+'&good='+good,handlevote);  
		document.getElementById(upimg).style.display='none';	//highlight correct hand
		document.getElementById(downimg).style.display='block';
	}
}

function killdiv (thediv){				//removes any div from the page
	if (typeof pods[thediv]!='undefined'){ 		//  doesn't break it's calling function if it got passed bad data
		thisdiv=document.getElementById(thediv);
		thisdiv=thisdiv.parentNode;
		thisdiv.parentNode.removeChild(thisdiv);
	}
}


function forgetpod (thepod) {
	var parent=pods[thepod].parent;  				    //who's the parent?
	var containerdiv = pods[parent].children[thepod];	//and what div# is it in?
	pods[parent].childcount--;							//there is one less child now, and .length cannot keep track of it.  grr!	
	pods[parent].divs[containerdiv]=undefined;			//empty it's parent div
	pods[parent].children[thepod]=undefined;			//parent forget it's name
	pods[thepod]=undefined;								//erase it
}

function killpod (thepod,scrollback) {				//  this does all the pod removal bookeeping, kill div actually removes the div		
	thisdiv=document.getElementById(thepod);
	findchildren(thepod, killdiv);
	findchildren(thepod, forgetpod);
	if (scrollback !='stay'){	
		if (pods[thepod].parent=='prime') {scrollto('primeX',1);}
		else {scrollto(pods[thepod].parent,0.2);}
	}
	
	killdiv (thepod);  // actually remove this pod from page	
	forgetpod(thepod); // remove it from the array
	
	// un highlight this law in the stub list...
	var thestubname = thepod+'stub';      	
	var thestub = document.getElementById(thestubname);
	thestub.style.color = '#000000';
	
	
}

function handledbinsert(target,serverdata,status){   //what happened with the db insert?
				//probably outgh to check to see if it was entered into the datbase properly too...
	var thetitlediv=target+'texttitle';  //empty the title
	document.getElementById(thetitlediv).value=' ';
	var thebodydiv=target+'textbody';	//empty the body
	document.getElementById(thebodydiv).value=' ';
	var thetextbox=target+"textbox";  	//hide the entry field
	document.getElementById(thetextbox).style.display = 'none';	
	var thescroller=target+'scroller';	//update the scroller with the new subs
	document.getElementById(thescroller).innerHTML=serverdata;
	
//	var thisparent=pods[target].parent;
		pods[target].podsloading--;
		document.getElementById(target+'throbber').style.display='none';	//turn on throbber


}

function insertnewlaw(action,theparent){  		//insert new law
	var thetitlediv=theparent+'texttitle';
	var thebodydiv=theparent+'textbody';
	var theposterdiv=theparent+'poster';
	if (action=="cancel"){  			 //did they just decide to close the insert area?  
		var thetextbox=theparent+"textbox";
		document.getElementById(thetextbox).style.display = 'none';	
		document.getElementById(thetitlediv).value="";
		document.getElementById(thebodydiv).value="";
	}else{  							// No, add law to database
		var thetitle=document.getElementById(thetitlediv).value;	//set php vars	
		var thebody=document.getElementById(thebodydiv).value;
		var theposter=document.getElementById(theposterdiv).value;
		if (thetitle!=""  &&  thetitle!=" "){						//send data
			document.getElementById(theparent+'throbber').style.display='block';	//turn on throbber
			pods[theparent].podsloading++;											//add new throbber to que
			XHR(theparent,'dbinsert.php?parent='+theparent+'&title='+escape(thetitle)+'&body='+escape(thebody)+'&poster='+escape(theposter),handledbinsert);
			var thetextbox=theparent+"textbox";  									//hide the entry field
			document.getElementById(thetextbox).style.display = 'none';					
		}
	}
}

function showentryfield (theparent){  // show the text input field for new laws
	var thetextbox=theparent+"textbox";
	document.getElementById(thetextbox).style.display = 'block';
}

function opento(somediv, serverdata, status, targets){  
	if ((targets[location]!=0)&&(serverdata!='open')){  			//is this the first pod?  no?  then insert the pod we've been given
		insertpod (somediv, serverdata);
	}
	var name = targets[targets[location]+1];	
	var parent = "prime";  						//this is the variable that we'll construct the correct pod's name into
	for (var x=1; x <= targets[location]; x++){   	//cycle therough the array making the right name
		parent=parent+"-"+targets[x];	
	}

	targets[location]++; //increment location in array 
	
	if ( typeof pods[parent+'-'+name]!='undefined'){   //is it already open?
		scrollto(parent+'-'+name,1);					//scrollto
		opento (parent+'-'+name,'open','bogus',targets);

	}else if (targets.length-1 >= targets[location]){
		prepinsertpod (parent,name,opento,targets);
	}
}


function prepopento (targetpod){
	thehistory.newstate(targetpod);
	if ( typeof pods[targetpod]!='undefined'){   //is it already open?
		scrollto(targetpod,1);					//scrollto and die	
	}else{										//opento it
		var podstoOpen=targetpod.split("-");
		podstoOpen[location]=0;
		opento ('bogus','bogus','bogus',podstoOpen);
	}
}

function insertpod (thediv,serverdata,status,opentoaddress) {   //put a new pod on the screen  & turn the throbber off
	divholder=thediv+'holder';
	newdiv(divholder);								  //new div
	var thisdiv=document.getElementById(divholder); //get it   //thediv is the same as thisdiv.  BTW.	
	thisdiv.innerHTML=serverdata;		   			//fill it with data
	
	if (thediv!='prime'){							//find the position of the outgoing div
		findthis = pods[thediv].parent + '_' + pods[thediv].parentdiv;	//what is the outgoing div named?
	} else {findthis = 'primeX';}
	var destination = findPos(findthis);						//where is the outgoing div?
	thisdiv.style.position='absolute';							//style the container div
	thisdiv.style.left=destination[0]+'px';
	thisdiv.style.top=destination[1]+'px';		
	//turn the throbber off
	var thisparent=pods[thediv].parent;
		
	if (thisparent!='god'){
		pods[thisparent].podsloading--;
		if (pods[thisparent].podsloading<=0){							//find the position of the outgoing div
			document.getElementById(pods[thediv].parent+'throbber').style.display='none';
		}
	}
	divtofront(thediv);						  	  //bring the pod forward
	//fadethat(thediv,'in');	
	scrollto(divholder,0.7);
	// this is an exception for when the site is loaded with an external pod reference
	
	
	if (typeof (opentoaddress) != 'undefined') {prepopento(opentoaddress);}
}

function pod() {
	this.parent="god";
	this.parentdiv=1;			//the div number that this pod lives in
	this.name="prime"
	this.minchildren=1;
	this.maxchildren=10;	
	this.children = new Array();//this is all of the child pods listed by name, containing their div
	this.divs = new Array ();	//this is all of the target divs, containing the name of the pod as their value 
	this.thisdiv=Math.floor(Math.random()*5)+1;				//this is the next div to stick a pod into
	this.childcount=0;
	this.scrollposition=0;
	this.x=0;
	this.y=0;
	this.fade=10;   		//broken fade vars
	this.inout='off';		//more
	this.podsloading=0;
	this.nextdiv = function() {
		this.thisdiv += 3;    
		if (this.thisdiv > this.maxchildren) {   // did we reach the end of the divs?
			this.thisdiv = this.minchildren + (this.thisdiv - this.maxchildren-1); 
		}

		if ( (this.maxchildren - (this.minchildren-1)) <= this.childcount ) {  //if we're out of divs kill whatever's in the newest div
			killpod(this.divs[this.thisdiv],'stay');
		}
	}
}

function prepinsertpod (parent, name, callback, passdata) {    
	var podID = parent+'-'+name;								//construct the name of the new pod we're making

	if (pods[podID] ) {divtofront(podID); scrollto (podID,0.5);  shemtov;}				//scrollto then break if pod is already open.

	pods[podID] = new pod();  									//make a new pod in the array o' pods

	//update the parent pod
	pods[parent].nextdiv();										//increment the div level on the parent
	pods[parent].children[podID] = pods[parent].thisdiv;		//this is the div that this pod is in
	thisdiv = pods[parent].thisdiv;								//this is the parent's div container for the new pod.  It's being put in a convenent variable here
	pods[parent].divs[thisdiv] = podID;							//put the new pod's name into the corresponding div #.
	pods[parent].childcount++;
	pods[parent].podsloading++;									//increment the load count (for the throbber)

	//initialize the new pod									//debug(	'podID='+podID+'  ||   pods[parent].children[podID]='+pods[parent].children[podID]);
	pods[podID].parent=parent;
	pods[podID].parentdiv=pods[parent].children[podID];			//the div that contains the new pod
	pods[podID].name=podID;
	
	//horrible multidirection hack here
	if (pods[podID].parentdiv>=6){
		pods[podID].minchildren=6;	
		pods[podID].maxchildren=10;							
		pods[podID].thisdiv+=5;
	}else{  //end horrible hack
		pods[podID].minchildren=1;	
		pods[podID].maxchildren=5;
	}	
	pods[podID].x=500;
	pods[podID].y=100;

	//turn on throbber
	document.getElementById(parent+'throbber').style.display='block';

	if (typeof(callback)=='undefined'){   	//the idea here is that there's an option to have another callback procedure, but have insertpod be the default one...
		XHR(podID,'pod.php?parent='+parent+'&name='+name+'&type='+pods[parent].thisdiv,insertpod);
	}else{										
		XHR(podID,'pod.php?parent='+parent+'&name='+name+'&type='+pods[parent].thisdiv,callback, passdata);
	}
	var thestubname = podID+'stub';      	// highlight pods as they are opened...
	var thestub = document.getElementById(thestubname);
	thestub.style.color = '#999999';
}

function findchildren (thediv, callback){  //finds all of the children of the given pod and executes the callback function
	for (var x in pods[thediv].children){
		if (typeof (pods[x]) != 'undefined'){  		//this hacktastic fix deals with the occasion when x=undefined.  why does this happen?  I do not know.
			findchildren (x, callback);   
			callback(x);
		}
	}
}

function findparents(podID, callback){
	if(pods[podID].parent!='god'){
		podID=pods[podID].parent;
		callback(podID);
		findparents(podID,callback);	
		//findchildren(podID,callback);  //this can only work if we keep track of what order the pods are opened.
	}
}


var tvin = -150;
var tvspeed = 50;
var tvinout ='in';

function TVsin(direction) {
	if ((direction == 'in')&&(tvinout=='out')){shemtov();}
	if ((direction == 'out')&&(tvinout=='in')){shemtov();}

	if ( ((tvin <= -20)&&(tvinout=='in'))  || ((tvin >= -175)&&(tvinout=='out')) ) {
		var ltv=document.getElementById('tvleft');
		var rtv=document.getElementById('tvright');
		if (tvinout=='in') {tvin+=Math.round(tvspeed);} else {tvin-=Math.round(tvspeed);}
		tvspeed=tvspeed/1.3;
		ltv.style.left=tvin+'px';
		rtv.style.right=tvin+'px';
		setTimeout(TVsin,50);	
	} else {
		if (tvinout=='in') {tvinout='out'} else {tvinout='in'}
		tvspeed=50;
	}
}

var ISCstarted=false;
function startisc(opentoID) {
	if (!ISCstarted){
		ISCstarted=true;
		TVsin();
		if (typeof opentoID=='undefined') {		//don't hide the instructions if they're not there
			document.getElementById('loader').style.display='none'; 
		}
		setinitiallocation();
		XHR('prime','pod.php?name=prime&type=0',insertpod,opentoID);	
	}
}

function debug (var1) {
	var debugoutput = document.getElementById('debugwindow');
	outputtext=var1;
	//debugoutput.innerHTML=debugoutput.innerHTML+'<br>'+outputtext;
}

function XHR(target,URL,donext,passdata){
   var AJAX = null;    	                           				// Initialize the AJAX variable.
   if (window.XMLHttpRequest) { AJAX=new XMLHttpRequest();} else {AJAX=new ActiveXObject("Microsoft.XMLHTTP");}
   AJAX.onreadystatechange = function() {                     	// When the browser has the request info..
      if ((AJAX.readyState==4) || (AJAX.readyState=="complete")) {	// see if the complete flag is set.	s
		donext(target,AJAX.responseText, AJAX.status,passdata);	//Run the selected callback function.  
	  }                                                       	// End Ajax readystate check.
   }
   AJAX.open("GET", URL, true);                                 // Open the url this object was set-up with.
   AJAX.send(null);   // Send the request.
}

