var	gears = [];
var modx = {
	debug:false,
	ready:false,
	tree:'',
	cycler:[1],
	documentObject:'',
	animating:false,
	documentIdentifier:1,
	transitionSpeed:750,
	showredtable:true,
	cache:[],
	fancybox:{
		gallery:{
			margin:0,
			padding:6,
			showNavArrows:true,
			cyclic:true,
			titlePosition:'inside',
			transitionIn:'elastic',
			transitionOut:'elastic',
			easingIn:'easeInSine',
			easingOut:'easeOutQuart',
			speedIn:300,
			speedOut:700,
			overlayOpacity:.75
		}
	},
	content:[
		{
			container:"Content",
			tv:"content",
			title:""
		},
		{
			container:"Extras",
			tv:"extras",
			title:"<h2 class=\"gearTitle\">&nbsp;</h2>"
		}
	],
	loadPage:function(id) {
		// Used to display new page content, complete with page transitions

		// if the website content has not loaded and parsed, don't do anything yet
		if(!this.ready) return false;

		// set/reset some properties
		if(this.animating || this.documentIdentifier == id) return;
		this.documentObject = '';

		// first get document we are loading
		this.documentObject = this.getDocument(id)

		// check document type, if reference then load refereced document
		if(this.documentObject.type == 'reference') {
			if(this.documentIdentifier != this.documentObject.content) {
				this.documentObject = this.getDocument(this.documentObject.content);
			} else {
				return;
			}
		}

		// if a page is returned, load it
		// first though, set top of page anchor and snap to it
		var topAnchor = this.getDocument(this.documentObject.id).alias;
		if(topAnchor.length < 1) {
			topAnchor = "docid"+this.documentObject.id;
		}
		topAnchor.replace(/ /g,"_");
		$("body a.top_of_page").attr("id",topAnchor);
		window.location.hash = "#"+topAnchor;

		$("#siteBox .navBar ul li").removeClass("active");
		if(this.documentObject !== false) {
			this.loadingPage = this.documentObject.id;
			// figure out which cycler to use (next/prev buttons)
			if(this.childof(this.documentObject.id,2)) {
				modx.cycler = modx.parseTree(2);
			} else {
				modx.cycler = modx.parseTree(1);
			}

			// perform transitions and replace content containers
			for(var i in this.content) {
				$("#"+this.content[i].container).fadeOut(this.transitionSpeed/2,function(){
					$(this).empty();
					for(var j in modx.content) {
						if(modx.content[j].container == $(this)[0].id) {
							var content = '';
							if(modx.content[j].title.length > 0) {
								// add content area titles
								content = modx.content[j].title+"\n";
							}
							content += modx.documentObject[modx.content[j].tv]+"\n";
							for(var property in modx.documentObject) {
								content = content.replace('[*'+property+'*]',modx.documentObject[property]);
							}
							$(this).append(content);
							$("#"+this.id+" a").each(modx.makeLinks);
							$("#"+this.id+" .gallery a").fancybox(modx.fancybox.gallery);
						}
					}

					$(this).fadeIn(modx.transitionSpeed/2);
				});
			}

			// decide whether to show or hide redtable
			if(this.showredtable == true && this.documentObject.showredtable == 0) {
				$(".cpTable").fadeOut(this.transitionSpeed);
				this.showredtable = false;
			} else if(this.showredtable == false && this.documentObject.showredtable == 1) {
				$(".cpTable").fadeIn(this.transitionSpeed);
				this.showredtable = true;
			}

			// prepare header for sliding
			var slider = document.createElement('div');
			slider.setAttribute("class","slider");
			var sliderImages = [this.getDocument().header,"design/images/slides/transition.jpg",this.documentObject.header];
			for(var i in sliderImages) {
				var slide = new Image();
				slide.src = sliderImages[i];
				$(slider).append(slide);
			}
			$("#backStage").append(slider);
			$("#backStage").css("background-image",'url("'+this.documentObject.header+'")');
			this.documentIdentifier = this.loadingPage;
			this.animating = true;

			// animate sliding headers
			$(slider).animate({left:"-2600"},{duration:this.transitionSpeed,complete: function() {
				modx.animating = false;
				$(this).remove();
			}});
			$("#L"+this.documentIdentifier).addClass("active");
			if(this.documentObject.parent > 1) {
				$("#L"+this.documentObject.parent).addClass("active");
			}

		} else {
			// if no page returned then display an error message
			alert("[FATAL ERROR] This link tried to load a non-existent page. Bad document id: " + id);
		}
	},
	childof:function(id,section) {
		if(modx.findDocument(id,"id",modx.getDocument(section).children) == false) {
			return false;
		} else {
			return true;
		}
	},
	makeLinks:function(event) {
		var linkURL = this.href.substring(this.href.lastIndexOf("/")+1)
		if(isNaN(linkURL)) {
			var modLink = modx.findDocument(linkURL);
		} else {
			var modLink = modx.getDocument(linkURL);
		}
		if(modLink == false) {
			return false;
		} else {
			this.href = "javascript:modx.loadPage("+modLink.id+")";
			return true;
		}
	},
	nextPage:function() {
		// determines and then loads next page in the cycler set
		if(!this.ready) return false;
		var loadDoc = this.getIndex();
		if(++loadDoc > this.cycler.length - 1) loadDoc = 0;
		this.loadPage(this.cycler[loadDoc]);
	},
	prevPage:function() {
		// determines and then loads previous page in the cycler set
		if(!this.ready) return false;
		var loadDoc = this.getIndex();
		// check if the document in the cycler is a weblink, if so
		// skip that document and go to the next (prev prev in other words)
		if(this.getDocument(this.cycler[loadDoc-1]).type == 'reference') {
			if(--loadDoc < 0) loadDoc = this.cycler.length - 1;
		}
		if(--loadDoc < 0) loadDoc = this.cycler.length - 1;
		//alert("Index: "+loadDoc+"\nDocument: "+this.cycler[loadDoc]);
		this.loadPage(this.cycler[loadDoc]);
	},
	getIndex:function(id) {
		// returns the array index value for the requested document
		// as it exists in the cycler array, defaults to current document
		if(!id) id = this.documentIdentifier;
		var index = 0;
		for(var i in this.cycler) {
			if(id == this.cycler[i]) break;
			++index;
		}
		return index;
	},
	getCollection:function(id) {
		// returns an array of the children belonging to the parent of id
		// and its index within that array. This is used to get sibling
		// documents and determine the requested documents position to them
		// defaults to current document
		if(!id) id = this.documentIdentifier;
		var collection = this.getDocument(this.getParent(id)).children;
		var index = 0;
		for(var i in collection) {
			if(collection[i].id == id) break;
			++index;
		}
		return {collection:collection,index:index};
	},
	goHome:function() {
		// loads home page
		this.loadPage(this.siteStart);
	},
	getDocument:function() {
		// retrieve a document and then return it. This will also
		// return the documents children as well
		if(!this.ready) return false;

		// determine if id is set
		if(arguments.length > 0) {
			var id = arguments[0];
		} else {
			var id = this.documentIdentifier;
		}

		return this.findDocument(id,"id");
	},
	findDocument:function(val,property,section) {
		if(!this.ready) return false;
/*
			First determine if arguments were passed. This is necessary
			because the findDocument function is recursive and travels
			down the document tree until it finds the correct document
			and returns it.

			The initial call to findDocument is often void of parameters,
			other than the seach value but could be used with parameters to determine
			if a particular document belongs to a specific section of
			the document tree as it will either return false or the
			document referenced by id. Make sure that the second argument is the


			Example:
				var myPage = modx.findDocument("contactus","alias",modx.getDocument(10).children);

			If the above example returns false, then document id 50 is not
			a child or grandchild etc of document 10

			findDocument used to be getDocument but was expanded to find documents
			using parameters other than purely document id. findDocument allows
			searching of any document property.
*/

		if(arguments.length > 1) {
			var property = arguments[1];
		} else {
			var property = "alias";
		}

		// determine section to use.
		if(arguments.length > 2) {
			var section = arguments[2];
		} else {
			var section = this.tree;
		}

		// now for the core of the document search
		for(var i in section) {
			if(modx.debug) {
				if(!confirm("Searching for " + property + " = " + val + " in document tree\n\n" + "testing document id[" + section[i].id + "]: " + property + " = " + section[i][property])) {
					//modx.debug = !modx.debug;
				}
			}
			// we've found the matching document, lets return it
			if(section[i][property] == val) return section[i];
			// we have not found the matching document and now must
			// search the children of the current test document
			if(section[i].children != "") {
				var result = this.findDocument(val,property,section[i].children);
				if(result !== false) return result;
			}
		}
		return false;
	},
	getChildren:function(id) {
		// similar to getDocument but only returns children
		if(!id)	id = this.documentIdentifier;
		var doc = this.getDocument(id);
		if(doc) {
			for(var i in doc.children) {
				doc.children[i].children = '';
			}
			return doc.children;
		} else {
			return false;
		}
	},
	getParent:function(id) {
		// each document contains a property which references
		// its parent but it does not contain the parent document
		// this function returns the parent document in whole
		if(!this.ready) return false;
		if(id < 1) return undefined;
		var doc = this.getDocument(id);
		return doc.parent;
	},
	firstChild:function(id) {
		// returns the first child of id if it has one
		var collection = this.getDocument(id).children;
		if(!collection) {
			return false;
		} else {
			return collection[0].id;
		}
	},
	lastChild:function(id) {
		// returns the last child of id if it has one
		var collection = this.getDocument(id).children;
		if(!collection) {
			return false;
		} else {
			return collection[collection.length - 1].id;
		}
	},
	parseTree:function(startId) {
		// returns a one dimensional array which is nothing more
		// that a complete listing of documents contained within startId
		// if no startId is supplied then the list will contain all
		// documents. This is useful for image preloading among other things
		var documentList = [];
		if(!startId) {
			var collection = this.tree;
		} else {
			var collection = this.getDocument(startId).children;
		}
		for(var i in collection) {
			if(collection[i].type != 'reference') {
				documentList.push(collection[i].id);
			}
			if(collection[i].children != "") {
				documentList = documentList.concat(this.parseTree(collection[i].id));
			}
		}
		return documentList;
	}
};

function loadContent(contentURI) {
	// retrieve content data file from server
	$.getJSON(contentURI, function(sitedata){
		// once data file is returned, set some properties
		modx.tree = sitedata;
		modx.goHome();
		modx.ready = true;
		// setup page cycler order
		modx.cycler = modx.parseTree(1);
		// init gear nav
		initGear();
		// setup fancybox on any home page galleries
		$("#siteBox .contentBox .gallery a").fancybox(modx.fancybox.gallery);
		// now we need to preload header images
		var documentList = modx.parseTree();
		for(var i in documentList) {
			var docImage = new Image();
			docImage.src = modx.getDocument(documentList[i]).header;
			modx.cache.push(docImage);
		}

		// parse links to use javascript page loader
		$("#siteShell a").each(modx.makeLinks);
		$("#frontStage .arrowLeft").attr("href","javascript:modx.prevPage();");
		$("#frontStage .arrowRight").attr("href","javascript:modx.nextPage();");

		// if bookmarked page, load it
		if(window.location.hash.length > 0) {
			var bookmark = modx.findDocument(window.location.hash.replace("#",""));
			modx.loadPage(bookmark.id);
		}
	});
};

function initGear() {
	// reverse order starting with 23 down to 0
	gears.push('"100,36,107,38,114,12,108,11,100,36" rel="23"');
	gears.push('"114,41,119,44,133,21,127,18,114,41" rel="22"');
	gears.push('"130,54,149,35,145,30,125,49,130,54" rel="21"');
	gears.push('"134,60,138,66,162,53,158,47,134,60" rel="20"');
	gears.push('"141,72,143,79,169,73,167,66,141,72" rel="19"');
	gears.push('"143,93,170,93,170,87,143,87,143,93" rel="18"');
	gears.push('"140,107,166,114,169,108,142,101,140,107" rel="17"');
	gears.push('"134,120,157,133,161,127,138,114,134,120" rel="16"');
	gears.push('"125,130,130,125,148,144,143,149,125,130" rel="15"');
	gears.push('"113,139,126,161,133,157,119,134,113,139" rel="14"');
	gears.push('"100,143,106,140,114,167,107,168,100,143" rel="13"');
	gears.push('"86,170,93,170,93,143,86,143,86,170" rel="12"');
	gears.push('"79,142,72,168,65,167,72,141,79,142" rel="11"');
	gears.push('"52,161,66,138,60,135,46,157,52,161" rel="10"');
	gears.push('"35,149,54,130,49,126,30,144,35,149" rel="9"');
	gears.push('"22,133,18,128,41,114,45,120,22,133" rel="8"');
	gears.push('"36,100,11,108,13,114,38,108,36,100" rel="7"');
	gears.push('"9,87,35,87,35,93,9,93,9,87" rel="6"');
	gears.push('"38,73,36,79,10,72,12,65,38,73" rel="5"');
	gears.push('"41,66,44,61,21,46,17,52,41,66" rel="4"');
	gears.push('"49,54,53,49,34,30,30,35,49,54" rel="3"');
	gears.push('"46,22,51,18,65,41,59,45,46,22" rel="2"');
	gears.push('"72,11,79,36,72,38,65,13,72,11" rel="1"');
	gears.push('"86,9,86,35,93,35,93,9,86,9" rel="0"');
	var areas = "";
	for(var i in modx.cycler) {
		var doc = modx.getDocument(modx.cycler[i]);
		if(doc.type == 'reference') {
			continue;
		} else {
			areas += '<area shape="poly" href="javascript:modx.loadPage('+doc.id+');" coords='+gears.pop()+' title="'+doc.pagetitle+'">';
		}
	}
	var map = '<img usemap="#gears" src="design/images/glass_pane.gif" alt=""><map name="gears">'+areas+'</map>';
	$("#gearBox .interface").append(map);
	$("#gearBox .interface map area").mouseover(function(){
		$("#Extras .gearTitle").empty().append($(this).attr("title"));
		$("#gearBox .backdrop").css("background-image","url(design/images/gears/"+$(this).attr("rel")+".png)").fadeIn(500);
	});
	$("#gearBox .interface map area").mouseout(function(){
		$("#Extras .gearTitle").empty().append("&nbsp;");
		$("#gearBox .backdrop").fadeOut(100);
	});
}

$(window).resize(function(){
	if($(window).width() < 1300) {
		document.getElementById('siteShell').style.overflow = 'hidden';
	} else {
		document.getElementById('siteShell').style.overflow = 'visible';
	}
});

var contentURL = 'index.php?id=49';
//var contentURL = document.domain+'/new/modx_content';
//alert(contentURL);
loadContent(contentURL);


