
//--- Attach Events

//---- On event move list item
//---  Also add selected to the list items.
//---  Also, should the prev/next button still be shown?
window.dhtmlHistory.create({
		toJSON: JSON.encode,
		fromJSON: JSON.decode
});

window.addEvent("load", function() {
	window.dhtmlHistory.initialize();
	window.dhtmlHistory.addListener(onHistoryChange);
	
	attachEvents();
	
	toggleNextPrev();
	
	initListNav();
	
	//--- Doesn't seem to be getting called onload, shouldn't hurt to call this twice.
	onHistoryChange(window.location.hash.substr(1));
});

function onHistoryChange(newLocation, historyData) {
	if(newLocation == null || newLocation.length == 0) { return; }
	
	var historyItem = $$("a[href$=" + newLocation.substr(5) + "]")[0];
	
	loadItem(historyItem);
	
	toggleNextPrev(historyItem);
}


function attachEvents() {
	//--- Events for the listing on the left.
	$$("#list_nav a").forEach( function(item, index) {
		item.addEvent("click", function(ev) {
			loadItem(this);
			
			toggleNextPrev(this);
			
			window.dhtmlHistory.add("view:" + this.getProperty("href").substr(1));
			
			new Event(ev).stop();
		});
	});
	
	//--- The Previous and Next Buttons
	$$(".prev", ".next").addEvent("click", function(ev) {
		var moveToDD;
		if(this.hasClass("prev")) {
			//--- Get the previous item in the list
			moveToDD = getSelectedItem().getParent().getPrevious("dd");
		} else {
			//--- Get next item in the list.
			moveToDD = getSelectedItem().getParent().getNext("dd");	
		}
		
		if(!moveToDD || moveToDD.hasClass('disabled')) {
		    toggleNextPrev();
		    return;
		}
		
		loadItem(moveToDD.getFirst(), this.hasClass("prev"));
		
		//--- Should we still show the next or prev button?
		toggleNextPrev(moveToDD);
		
		window.dhtmlHistory.add("view:" + moveToDD.getFirst().getProperty("href").substr(1));
		
	});
	
	
}

/* Toggle the Nav open and closed */
function initListNav() {
	$$("#list_nav dt").addEvent("click", function() {
		showNavSubSection(this);
  });
	
	$$("#list_nav dt").each(
		function(item){
				hideNavSubSection.delay(500, null, item);
		}
	);
	
	toggleExpandedSection();
}

function toggleExpandedSection() {
		var sel = getSelectedItem();
		if(!sel) { return; }
		//--- Lets work from the DD element;
		var dd = sel.getParent();
		var dt = dd.getPrevious("dt");
		
		showNavSubSection(dt);
		
		if(!dt.hasClass("expanded")) {
				dt.addClass("expanded");
		}		
}

function showNavSubSection(el) {
		if(el.hasClass("expanded")) {
				return;				
		}
		
		$$("#list_nav dt").removeClass("expanded");
		
		//--- Called without a section does all the sections except the default expanded one.
		hideNavSubSection();
		
		
		el.addClass("expanded");
		
		while((el = el.getNext()) && el.get('tag') === "dd") {
				el
						.setStyles({"display":"block"})
						.set('morph', {duration: 'long', transition: 'bounce:out'})
						.morph({"opacity": [0, 1], "height" : [0, el.retrieve("startHeight")]});
		}	
		
}

function hideNavSubSection(el) {
		if(el === undefined) {
				$$("#list_nav dt").each( function(item){
								hideNavSubSection(item);
						}
				);
				return;
		}
		if(el.hasClass("expanded")){
				return;
		}
		
		while((el = el.getNext()) && el.get('tag') === "dd") {
				if(el.getStyle("opacity") === 0  || el.getSize().y <= 0) {
						continue;
				}
				
				el
						.store("startHeight", (el.retrieve("startHeight") == null) ? el.getSize().y - 3 : el.retrieve("startHeight"))
						.set('morph', {duration: 'short', transition: 'cubic:out', onComplete: function(el) { $(el).setStyle('display', 'none'); } })
						.morph({"opacity": [0], "height" : [0]});
		}	
}



/*
	Load a new panel from the list.
		lnk : the link in the nav list that we want to load content for.
		direction: true or false to indicate moving left or right.
			true = move right to left
			false = move left to right
*/
function loadItem(lnk, direction) {
	if(!lnk) return;
	
	//--- Get the panel to show (minus the hash)
	var target = lnk.getProperty("href").substr(1);
	
	//--- Get the List Item to show
	var liShow = $(target);
	
	//--- Get the list item to hide
	var liHide = getCurrentItem();
	
	//--- If nothing to show, bail.
	if(!liShow || liShow.id == liHide.id) return;
	
	//--- Get element width
	var liWidth = liHide.getSize().x
	
	var fromDirModifier = direction ? 1 : -1; //--- Start on the right if true, start on the left if false.
	var toDirModifier = fromDirModifier * -1; //--- The direction to send the item out is the opposite of where its coming from.
	
	//--- Position the one to show.
	liShow.setStyles({
		"left" : fromDirModifier*liWidth + "px",
		"display" : "block"
	 });
	
	liShow.addClass("current");
	liHide.removeClass("current");
	
	//--- Build animations for them.
	var inTween = new Fx.Tween(liShow, { "property" : "left", transition: "circ:in" });
	var outTween = new Fx.Tween(liHide, { "property" : "left", transition: "circ:out"  });
	
		//--- Start the animations to move the current off the screen and the new one on.
		outTween.start(liWidth*toDirModifier);
		inTween.start(0);
	
	//--- Mark list item as selected
	getSelectedItem().removeClass("selected");
	lnk.addClass("selected");
}

function getCurrentItem() {
	return $$("#list_content .current")[0];
}

function getSelectedItem() {
	var result = $$("#list_nav a.selected");
	if(result.length > 0)
		return result[0];
	return null;
}

function toggleNextPrev(item) {
	if(!item) item = getSelectedItem();
	if(!item) return;
	if(item.tagName == "A") item = item.getParent();
	
	if(!item.getPrevious("dd")) {
		//--- Hide 	Prev
		$$(".prev").addClass("disabled");
	} else {
		$$(".prev").removeClass("disabled");
	}
	
	if(!item.getNext("dd[class!=disabled]")) {
		//--- Hide Next
		$$(".next").addClass("disabled");
	} else {
		$$(".next").removeClass("disabled");	
	}
	
	toggleExpandedSection();
}



