/*This library is free software; you can redistribute it and/or

modify it under the terms of the GNU Lesser General Public

License as published by the Free Software Foundation; either

version 2.1 of the License, or (at your option) any later version.



This library is distributed in the hope that it will be useful,

but WITHOUT ANY WARRANTY; without even the implied warranty of

MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU

Lesser General Public License for more details.



You should have received a copy of the GNU Lesser General Public

License along with this library; if not, write to the Free Software

Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA*/





/*

*************PREFACE*************

iXtli is not all that difficult to understand

my basic method of handling things is by using a simple handler function to activate a main function



IE. would be my use of the exe function to inspect input data before it is passed to the makeRequest function. i find that using such and idealogy to branch code like a tree is most useful. so when looking at the functions in place you can place them into 3 main catagories.

 independant functions which act once on thier own and then cease. //note i`m thinking about cutting most of these out.

 system functions whom support each other and use each other

 and support functions like gebi() which as used many times by many functions

 

you might also notice that i dislike using global variables. thats just my thing. 

*/





//vaiable initialization

var EventLog="";//total log file of all status bar outputs

var stor=false;//all ajax data is loaded into this variable

var ajaxDisplay=true;//this tells the core to not display the contents of the ajax stream 

var pong=false;//xml_http object

var linky="";//current link

var count=0;//this prevents a loop of server errors when the script tries to go home

var check;//prevents looping from the URIsearch

var loc;//global variable for the page name to be used in error messages

var History = new Array;

var hisPos = 0;//

var Active;

//ajax engine

//special thanks to dem mozilla & apple dev niggas. they made ajax simple yo.

//and a huge thanks to the staff of devguru.com for providing and excellent reference guide for free

function makeRequest(url) {

		//stor=false;

				 

		if(count>=2){alert("FATAL ERROR UNABLE TO RETURN HOME"); return false;}

		//sets loc for error handling

		if(ajaxDisplay)send('output','<H2><P>LOADING NEW PAGE...</P></H2>');

		loc=url;

		//random session ID generator

		//this is to prevent the 304 cache error

		rand=Math.random();

		rand*=100000000000000000;

		rand=rand.toString(36);

		url+='?session='+rand;

		send('statBar','sessionID '+rand+' chosen');

		//prevents the system from interpeting a second click as a true variable. see below

    pong=false;

		//linky change 

		send('statBar',"Stage 1: Initialized");

		//firefox, opera, safari, netscape http request engine

    if (window.XMLHttpRequest) {

        pong = new XMLHttpRequest();

        if (pong.overrideMimeType) {

					 //mozilla workaround for responseXML

       		  pong.overrideMimeType("text/xml");      

						send('statBar',"Stage 2: XMLHttpRequest formation and MIME type override sucsessful.");

        		}

				send('statBar',"Stage 2: mozilla, safari, opera; XMLHttpRequest complete");

				//IE http request engine

    		} 

		else if (window.ActiveXObject) 

				 {

         try {

             pong = new ActiveXObject("Msxml2.XMLHTTP");

             } catch (e) {

             	    try {

                    pong = new ActiveXObject("Microsoft.XMLHTTP");

             } catch (e) {}

         }

        send('statBar',"Stage 2: Internet Explorer; ActiveXObject creation complete");

		}

		//total failure message

    if (!pong) {

				send('statBar',"Fatal Error. XMLHTTP not supported.");

				alert("ABORTED! borwser unable to create XMLHttp request");

				return false;

        }

				send('statBar',"Stage 3: Awaiting ready state change.");

        pong.onreadystatechange = alertContents;

        pong.open('GET', url, true);

        pong.send(null);

				//return pong.responseText;

		}

function send(toThing,dataStream)

{

toThing=gebi(toThing);

if(toThing==null||toThing==false)return null;

//there we go.

//these send the ajax output to any element on the page as specified

toThing.innerHTML=dataStream;

if(toThing.id!='size'&&toThing.id!='output')EventLog+='<hr />'+toThing.id+' : '+dataStream+';';

}

function alertContents() {

		//return signal processor

		send('statBar',"Stage 4: Ready state now " + pong.readyState +'/4');

		//verifies that the request came back "OK"

		if (pong.readyState==4) {

			 //http error handling

			 switch (pong.status)

			 {

			 	//successful message and action

				case 200: 

				var dataStream=pong.responseText;

				//puts the page into the frame

				if(ajaxDisplay)send('output',dataStream);

				stor=dataStream;

				ajaxDisplay=true;//this resets the value of the ajax display system to 'on'

				//resets count to make a successful load

				count=0;

				send('statBar',"Success!!");

				if(document.cookie)Bake('page',loc,false);

				History[parseInt(History.length)] = loc;

				hisPos++;

				loc=loc.split('.');

				linky=((location.protocol=='http:')?location.protocol+'//':null)+location.hostname+location.pathname+'?'+loc[0];

				break;



				case 400: alert("Failure!\n Error 400, Malformed Syntax."+ "\n"+ loc);

				send('statBar',"Error! returning home!");

				exe("home.xml",false);

				count++;

				break;



				case 401: alert("Failure!\n Error 401, Failed Authentication."+ "\n"+ loc);

				send('statBar',"Error! returning home!");

				exe("home.xml",false);

				count++;

				break;

			

				case 403: alert("Failure!\n Error 403, Forbidden."+ "\n"+ loc);

				send('statBar',"Error! returning home!");

				exe("./pages/home.xml",false);

				count++;

				break;			



				case 404: alert("Failure!\n Error 404, Page NonExistant."+ "\n"+ loc);

				send('statBar',"Error! returning home!");

				send('output','<p>THE PAGE DOESN`T EXIST. RETURNING HOME!</p>');

				his(0);

				count++;

				break;					

				//error should be fixed now

				case 304:

				send('statBar',"Page is cached already!?");

				break;					

				

				// handles all other errors

				default:

				send('statBar',"General Server Error, Unrecoverable.");

				send('output','<p><b>CRITICAL ERROR!</b></p>');

				count++;

        } 

			 }

			 

	 }



//linky updateing engine



function Page(){prompt('This is your current location.\nUse it to link back to this page.',linky)}

//initial page creator and textbox formetter

//(opening or closing, the name of the object to be opened or closed, the max width, the max height, expansion variable it's the name of the nested object here., 2nd expansion variable)



//Huge amount of problems with the appear() function

//it centers around the DOM and it's queerbag usage of dom levels

function appear(expan,force){

	 send('statBar',expan.id+' visibility toggled')

	 	 //Note. this line is a bit too specialized for my likeing, fix it later to remove the className clause

		 

	 if(expan.style.display=='')expan.style.display='block';

	 	 if(force==null){

		

	    if(expan.style.display=='none'){expan.style.display='block';return 0;}

			if(expan.style.display=='block'){expan.style.display='none';return 0;}

	 }

	 

	 if (force==false){expan.style.display='none'}

	 if (force==true){expan.style.display='block'}

	 }


function exe(page,js,noDisplay)
{
	 
		
				
	 if(noDisplay)ajaxDisplay=false;
	 
	 			send('statBar','file '+page+' load begin');

	 //primary engine
	if (page)
	 {
			makeRequest(page);
	 }
	 else
	 {
			send('output','<p>THE XHTML IS CALLING A NULL VALUE.\n In english, the link is bad :(</p>');
	 }
	 
}

   



//pre loading system.

//this checks to see if the link used already specifies a page to load or not

//if so it engages the execution engine

function preLoad() {

	  send('mode',navigator.appName);

	 var S = new Array;

	 S = window.location.search.split('&');

	 if (S[0]&&S[0]!=check)

	 		{

	 		exe(S[0].slice(1,S[0].length)+'.xml');

			return true;

			}

				 //if no search TEST COOKIE FOR VALUES

				 

				 //check dem cookies

	 check = S[0];

	 if(Taste('page')){

	 //check to make sure that the page you are already on is not the same as the page in the cookie

	 exe(Taste('page'));

	 return null;

	 }

if(S==false)exe('./pages/home.xml',false);

	 send('statBar','preLoad() complete');

	 }



	 //BOOYAH, this function OWNS

function gebi(thing){if(!document.getElementById(thing))return null;return thing=(typeof(thing)=='string')?document.getElementById(thing):thing}



//swaps images for rollovers.

function swap(pic,thing){thing.style.backgroundImage="url("+pic+")"}



function printLog(){

LogChild=window.open('./','Log','fullscreen=yes,scrollbars=yes');

LogChild.document.write('<html><h3>iXtli status dump file</h3>');

LogChild.document.write('<input sytle="width:65%;" value="line item debugger" id="lineDebug" /><input type="button" onclick="debug(gebi(lineDebug))" value="Debug"/>');

LogChild.document.write('<p>Cookie:<hr />'+document.cookie+'<hr /></p><p>');

LogChild.document.write(EventLog);

LogChild.document.write('</p></html>');

}





//------------------------------------------------------

//this function changes the style of the borders

function Border(thing)

{

i=0;

var bType=new Array('none','dotted','dashed','solid','double','groove','ridge','inset','outset');

for(z=0;z<bType.length;z++){

if(thing.style.borderStyle==bType[z]){

i=z;

break;

}

}

(i>=0&&i<8)?(i++):(i=0);

thing.style.borderStyle=bType[i];

Bake(thing.id+'BType',bType[i],false);

send('statBar',thing.id+':Border changed to '+bType[i]);

}



//this lovely little function increses or decreses the font size

function Font(thing,delta)

{

var fs=thing.style.fontSize;

fs=(thing.style.fontSize=='')?'1em':fs;

fs=parseFloat(fs);

fs+=delta;

thing.style.fontSize=fs+'em';

send('statBar',thing.id+':Font size now '+fs+'em');

}

//allows a hq and lq image layer.

function quality(level)

{

var css0=document.getElementsByTagName('LINK')[0];

if(level=='high')css0.href='./exile2.css';

if(level=='low')css0.href='./exile1.css';

if(level=='off')css0.href='./exile0.css';

css0=null;

send('statBar','Image quality now '+level);

}



//many thanks to elated.com for explaining how bullshit this shit is.

//NEEDS BETTER TESTING

function Bake(name,data,del)

{

escape(data);

//FIXED DATE DECLARATION

var now=new Date();now.setTime(now.getTime()-1);

var then=new Date();then.setYear(now.getFullYear()+1);

//END FIXED DATE DECLARATION

if(del){document.cookie=name+"=; expires="+now.toGMTString()}

else{document.cookie=name+"="+data+"; expires="+then.toGMTString()}

send('statBar','Cookie "'+name+'" has been baked with data '+data);

} 



//reads that value of a cookie, if no argument is given then it delivers the entire cookie file

	 function Taste(name)

	 {

	 send('statBar','Cookie '+name+' tasted');

	 var cookie=unescape(document.cookie);

	 if(!name)return cookie;

	 if(!cookie)return false;

	 I1=cookie.indexOf(name);

	 if(I1==-1)return null;

	 I2=cookie.indexOf(';',I1+1);

	 if(I2==-1)I2=cookie.length+1;

	 return cookie.substring(name.length+1+I1,I2);

	 }

	 

	 function debug(thing)

	 {

	 if(!thing){

	 executeString=prompt('iXtli line item debugger\nCheat Sheet\nTaste(name),gebi(id),exe(location)','');

	 if(executeString=='exit')return true;

	 eval(executeString);

	 debug(false);

	 }

	 eval(thing.value);

	 }

	 

	 

 //experimental bullshit-------------------------------------------------------------------

	 function parseCsv()

	 {

	 exe('collectionx.csv',false,true)

	 checker()

	 }

	 

function checker(cmd)

{

setTimeout('(stor)?(Parser()):(Checker());',250)

}

function Parser()

{

var csv=stor;

var con;

var enter=String.fromCharCode(10);

con+='<table border="1"><tr><td>';

for(i=0;i<csv.length;i++)

{

var cell=csv.charAt(i);

switch(cell)

{

case ',':  con+='</td><td>';break;

case enter: con+='</td></tr><tr><td>';break;

default :  con+=cell;break;

}//switch check

}//for loop

con+='</td></tr></table>';

send('output',con)



}//function





function his(value)

{



if((parseInt(History.length)-1)+value < 0)return false;

if(History[(parseInt(History.length)-1)+value]==null)return false;

exe(History[(parseInt(History.length)-1)+value])

}