var jkInclude = function(script)
{

	var path = jkiPath + 'javascript/' + script + '.js';
	var tag = new Element('script');
	tag.set('type','text/javascript');
	tag.set('src',path + '?noCache='+Math.floor(Math.random()*100001)); //TO DO: remove noCache when site is complete
	$$('head').grab(tag);

};

var isCmd = function(e)
{

	return	((e.meta && Browser.Platform.name == 'mac') ||
		(e.control && Browser.Platform.name == 'win'))
		? true : false;

};

var jkiStart = new Class
({

	options:
	{

		deBug: jkiDeBug,
		url: jkiPath

	},

	initialize: function(options)
	{

		this.setOptions(options);
		this.currentPage = '';
		this.lastPage = '';
		this.loadAnew;
		this.vars = {

			'parent' : 0,
			'navTreeId' : 0,
			'entryPointId': 0,
			'loadPage': 0,
			'pasteAction': false,
			'pasteNode': false,
			'pasteInput': false

		};
		if (this.options.deBug) this.getServerDeBug();
		this.getNonce();
		var hold = function(){

			this.sendOffset();
			if (this.options.deBug) this.sendRequest('','','deBugData');
			$('loading').fade('out');

		}.bind(this).delay(2000);

	},

	deBug: function(data)
	{

		if (!this.options.deBug) return false;
		if (!$type(data)) return false;
		if (!window.console) return false;
		console.log(data);

	},

	sendOffset: function()
	{

		var userTime = new Date();
		this.sendRequest('userTime', (userTime.getTimezoneOffset()/ 60)*-1, 'jsStart');

	},

	getServerDeBug: function()
	{

		if (!this.options.deBug) return false;
		var jkiRequest = new Request({

			method: 'get',
			url: this.options.url + 'deBugData.jki',
			onSuccess: function(returns)
			{

				this.deBug(JSON.decode(returns));

			}.bind(this)

		}).send();

	},

	getNonce: function()
	{

		var jkiRequest = new Request({

			method: 'post',
			url: this.options.url + 'jsonFeed/',
			onSuccess: function(returns)
			{

				this.setNonce(returns);

			}.bind(this)

		}).send('jkId=newRequest');


	},

	setNonce: function(returns)
	{

		var data = JSON.decode(returns);
		this.jkId = data.data[0];

	},

	nonce: function()
	{

		return this.jkId;

	},
	
	encodeData: function(data)
	{
		
		var string = JSON.encode(data);
		string = string.replace(/&/g,'jkiAMP;');
		string = string.replace(/\+/g,'jkiPLUS;');
		string = string.replace(/\.\.\./g,'jkiELPS;');
		return string;
		
	},

	sendRequest: function(com,items,api)
	{

		var jkiRequest = new Request({

			method: 'post',
			url: this.options.url+'jsonFeed/'+api+'/',
			onSuccess: function(returns){

				if (this.options.deBug) this.getServerDeBug();
				this.processReturn(JSON.decode(returns));

			}.bind(this)

		}).send('jkId='+this.nonce()+'&do='+com+'&data='+this.encodeData(items));

	},

	changePage: function(path,keepBody,cssPath)
	{

		document.removeEvents();
		this.lastPage = this.currentPage;
		this.currentPage = path;

		if (!keepBody)
		{
			
			document.getElements('*').removeEvents();
			this.loadAnew = true;
			$('loading').setStyle('display', 'block');
			this.sendRequest('changePage',{

					'path': path.replace(jkiPath,'/')

			},'changePage');

		} else {

			this.loadAnew = false;
			this.cssPath = cssPath;
			$(cssPath).fade('out');
			var hold = function(){
				this.sendRequest('changePage',{

					'path': path.replace(jkiPath,'/'),
					'cssPath': cssPath

				},'changePage');
			}.bind(this).delay(1000);

		}

	},

	checkHeadNode: function(node)
	{

		if (!node.hasAttribute('src')) return false;
		if (node.get('src').match(/jkiPath/)) return true;
		if (node.get('src').match(/mootools/)) return true;
		if (node.get('src').match(/jkiStart/)) return true;
		if (node.get('src').match(/AdminNav/) && !this.checkScript) return true;
		return false;

	},

	updatePage: function(data)
	{

		if (this.loadAnew)
		{

			var body = $$('body');
			body.set('html',data.html[1]);
			if (this.lastPage.match(/textEditor/)) adminNav = new jkiAdminNav();

		} else {

			var node = $(data.id[1]);
			node.set('html',data.html[1]);

			if ($type(data.html[2]) != false) $(data.id[2]).set('html',data.html[2]);

		}

		var head = document.getElement('head');
		var headNodes = head.getElements('*');

		headNodes.each(function (node){

			if (!this.checkHeadNode(node)) node.destroy();

		}.bind(this));

		for (i=0;i < data.data[0].tagName.length; i++)
		{

			var newEl = new Element(data.data[0].tagName[i]);

			for (j=0;j < data.data[0].attributes[i].length;j++)
				newEl.setProperty(data.data[0].attributes[i][j][0],data.data[0].attributes[i][j][1]);

			if (data.data[0].tagName[i] == 'title') document.title = data.data[0].content[i];
			newEl.inject(head);

		}

		(this.loadAnew) ? function () {$('loading').fade('out')}.bind(this).delay(1000) : $(this.cssPath).fade('in');

	},

	processReturn: function(data)
	{

		if ($type(data) != 'object') return false;
		switch(data.package)
		{

			case 'error':
				this.userPop(data);
				break;
				
			case 'changePage':
				this.updatePage(data);
				break;
				
			default:
				eval(data.package+'.newData(data)');
				break;

		}

	},

	userPop: function(data)
	{

		var box = $('userPop').clone(true,true);
		box.getElement('h1').set('text',data.heading);
		box.getElement('p').set('text',data.message);
		box.getElement('a').set('text',data.linkText).set('href',data.link);
		box.injectAfter($('wrapper'));
		box.setStyles({

			'display': 'block'

		});

		var size = box.getSize();
		var width = size.x;
		var height = size.y;
		var size = window.getSize();
		var posX = (size.x - width) / 2;
		var posY = (size.y - height) / 2;

		box.setStyles({
			
			'left' : posX,
			'top' : posY
			
		});

		if ($chk(data.close))
		{
			box.getElement('button').addEvent('click',function(){
				box.destroy();
			});

			var dragBox = new Drag(box,{handle: box.getElement('div.userPopHead')});

		} else {

			box.getElement('button').destroy();

		}
		
		this.box = box;

	},

	getURLVar: function (urlVarName)
	{
		var urlHalves = String(document.location).split('?');
		var urlVarValue = '';
		if(urlHalves[1])
		{
			//load all the name/value pairs into an array
			var urlVars = urlHalves[1].split('&');
			//loop over the list, and find the specified url variable
			for(i=0; i<=(urlVars.length); i++){
				if(urlVars[i]){
				//load the name/value pair into an array
				var urlVarPair = urlVars[i].split('=');
					if (urlVarPair[0] && urlVarPair[0] == urlVarName) {
					//I found a variable that matches, load it's value into the return variable
					urlVarValue = urlVarPair[1];
					}
				}
			}
		}

		return urlVarValue;
	}

});

jkiStart.implement(new Options);

/*End of Class*/
var jkiSession =  new jkiStart();