/*******************************************************************************************
 * disclosureNav
 * Written by Craig Francis
 * Create a navigation bar which can expand to show additional links in the selected section
 *******************************************************************************************/

	var nav = new function() {

		//--------------------------------------------------
		// Old browsers

			if (!document.getElementById || !document.getElementsByTagName) {
				return;
			}

		//--------------------------------------------------
		// Initialisation

			this.init = function() {

				//--------------------------------------------------
				// Debug

					console.log('nav.js: Initialisation');

				//--------------------------------------------------
				// Defaults

					nav.moving = false;
					nav.navCurrent = null;
					nav.timer = null;
					nav.openingSpeedDist = 20;
					nav.openingSpeedRate = 3;
					nav.defaultNavItemCookie = 'defaultNavItem';

				//--------------------------------------------------
				// Get a reference to the wrapper

					nav.holder = document.getElementById('s_cat_browse');

					if (!nav.holder) {
						nav.reset('Missing element "pageNavigation"');
						return;
					}

				//--------------------------------------------------
				// Setup the sections

					nav.navRefs = [];
					nav.headingImagesOff = [];
					nav.headingImagesOn = [];
					nav.headingRefs = nav.holder.getElementsByTagName('h3');

					for (var k = (nav.headingRefs.length - 1); k >= 0; k--) {

						headingHolder = getParent(nav.headingRefs[k], 'div');
						headingNav = headingHolder.getElementsByTagName('ul');
						headingImg = nav.headingRefs[k].getElementsByTagName('img');

						if (!headingHolder) {

							console.log('nav.js: Skip heading "' + k + '", with no parent [div]');

						} else if (!headingNav || headingNav.length != 1) {

							console.log('nav.js: Skip heading "' + k + '", with missing sibling [ul]');

						} else if (!headingImg || headingImg.length != 1) {

							console.log('nav.js: Skip heading "' + k + '", with missing heading [img]');

						} else {

							//--------------------------------------------------
							// Setup

								nav.navRefs[k] = headingNav[0];

								nav.setup(k);

							//--------------------------------------------------
							// Heading image

								//--------------------------------------------------
								// Create image

									var img = createElement('img');
									img.alt = headingImg[0].alt;
									img.src = headingImg[0].src.replace(/\.([a-z]+)$/, 'On.$1');

								//--------------------------------------------------
								// Set width and height, if possible - Saf returns 0

									var width = parseInt(headingImg[0].width);
									var height = parseInt(headingImg[0].height);

									if (width > 0 && height > 0) {
										img.width = headingImg[0].width;
										img.height = headingImg[0].height;
									}

								//--------------------------------------------------
								// Hide by default

									cssjs('add', img, 'hidden');

								//--------------------------------------------------
								// Add to DOM

									headingImg[0].parentNode.insertBefore(img, headingImg[0].nextSibling);

								//--------------------------------------------------
								// Remember references

									nav.headingImagesOff[k] = headingImg[0];
									nav.headingImagesOn[k] = img;

						}

					}

				//--------------------------------------------------
				// Number of navs

					nav.navCount = nav.navRefs.length;

				//--------------------------------------------------
				// Default shown

					var defaultNavItem = this.readCookie(nav.defaultNavItemCookie);

					if (nav.navRefs[defaultNavItem]) {
						nav.selectSection(defaultNavItem, false);
					}

			}

		//--------------------------------------------------
		// Select section

			this.setup = function(id) {

				//--------------------------------------------------
				// Add more link

					var moreLink = createElement('li');

					var moreLinkA = createElement('a');
					moreLinkA.appendChild(document.createTextNode('more...'));
					moreLinkA.href = '#';

					moreLink.appendChild(moreLinkA);

					cssjs('add', moreLink, 'default');

					nav.navRefs[id].appendChild(moreLink);

				//--------------------------------------------------
				// Setup actions

					moreLink.sectionId = id;
					moreLink.onclick = nav.selectSectionClick;

					nav.headingRefs[id].sectionId = id;
					nav.headingRefs[id].onclick = nav.selectSectionClick;

					nav.headingRefs[id].onkeyup = nav.selectSectionClick;
					nav.headingRefs[id].tabIndex = 0;

				//--------------------------------------------------
				// Fix the height - so when the other links are
				// shown, they don't have an immediate effect

					nav.navRefs[id].style.height = (nav.navRefs[id].offsetHeight) + 'px';

				//--------------------------------------------------
				// Debug

					console.log('nav.js: Processed heading "' + id + '"');

			}

		//--------------------------------------------------
		// Select section

			this.selectSectionClick = function() {
				return nav.selectSection(this.sectionId, true);
			}

			this.selectSection = function(id, animate) {

				//--------------------------------------------------
				// Moving?

					if (nav.moving) {
						console.log('nav.js: Already moving');
						return;
					}

					nav.moving = true;

				//--------------------------------------------------
				// If this one is already open

					if (id == nav.navCurrent) {
						console.log('nav.js: Section "' + id + '" already open');
						nav.moving = false;
						return;
					}

				//--------------------------------------------------
				// Debug

					console.log('nav.js: Open section "' + id + '"');

				//--------------------------------------------------
				// Save

					nav.createCookie(nav.defaultNavItemCookie, id, 30);

				//--------------------------------------------------
				// Get the new height of the navigation bar's

					nav.heightsCurrent = [];
					nav.heightsEnd = [];
					nav.closingCount = 0;

					for (var k = (nav.navCount - 1); k >= 0; k--) {

						//--------------------------------------------------
						// Current

							var currentHeight = nav.navRefs[k].offsetHeight;
							var newHeight = 0;

						//--------------------------------------------------
						// Child list items

							var lis = nav.navRefs[k].getElementsByTagName('li');
							var liLength = lis.length;

						//--------------------------------------------------
						// If this is first run, kill the "more" link

							if (nav.navCurrent === null) {
								liLength -= 1;
								lis[liLength].parentNode.removeChild(lis[liLength]);
							}

						//--------------------------------------------------
						// Get the height of the li's - keeping in mind
						// that each li can have a different height.

							for (var j = 0; j < liLength; j++) {

								if (k == id || j < 3) {
									newHeight += lis[j].offsetHeight;
								}

								if (nav.navCurrent === null) {
									cssjs('add', lis[j], 'shown');
								}

							}

						//--------------------------------------------------
						// Remember values, and tally the number of sections
						// which will be closing in this action

							if (animate) {

								nav.heightsCurrent[k] = currentHeight;
								nav.heightsEnd[k] = newHeight;

								if (newHeight < currentHeight) {
									nav.closingCount++;
								}

							} else {

								nav.navRefs[k].style.height = newHeight + 'px';

							}

					}

				//--------------------------------------------------
				// Toggle the heading graphic

					if (nav.navCurrent !== null) {
						cssjs('remove', nav.headingImagesOff[nav.navCurrent], 'hidden');
						cssjs('add', nav.headingImagesOn[nav.navCurrent], 'hidden');
					}

					cssjs('add', nav.headingImagesOff[id], 'hidden');
					cssjs('remove', nav.headingImagesOn[id], 'hidden');

				//--------------------------------------------------
				// Remember which is being opened

					nav.navCurrent = id;

				//--------------------------------------------------
				// Animation

					if (animate) {
						nav.timer = setInterval(nav.animate, nav.openingSpeedRate);
					} else {
						nav.moving = false;
					}

				//--------------------------------------------------
				// Stop link action

					return false;

			}

		//--------------------------------------------------
		// Animation

			this.animate = function() {

				//--------------------------------------------------
				// Start

					done = true;

				//--------------------------------------------------
				// Opening section

					var k = nav.navCurrent;
					var newHeight = nav.heightsCurrent[k];
					var endHeight = nav.heightsEnd[k];

					if (newHeight < endHeight) {

						newHeight += nav.openingSpeedDist;

						if (newHeight > endHeight) {
							newHeight = endHeight;
						}

						nav.heightsCurrent[k] = newHeight;
						nav.navRefs[k].style.height = newHeight + 'px';

						done = false;

					}

				//--------------------------------------------------
				// Closing sections

					for (var k = (nav.navCount - 1); k >= 0; k--) {
						if (k != nav.navCurrent) {

							var newHeight = nav.heightsCurrent[k];
							var endHeight = nav.heightsEnd[k];

							if (newHeight > endHeight) {

								newHeight -= (nav.openingSpeedDist / nav.closingCount);

								if (newHeight < endHeight) {
									newHeight = endHeight;
								}

								nav.heightsCurrent[k] = newHeight;
								nav.navRefs[k].style.height = newHeight + 'px';

								done = false;

							}

						}
					}

				//--------------------------------------------------
				// End

					if (done) {
						clearInterval(nav.timer);
						nav.moving = false;
					}

			}

		//--------------------------------------------------
		// Cookies - http://www.quirksmode.org/js/cookies.html

			this.createCookie = function(name,value,days) {
				if (days) {
					var date = new Date();
					date.setTime(date.getTime()+(days*24*60*60*1000));
					var expires = "; expires="+date.toGMTString();
				}
				else var expires = "";
				document.cookie = name+"="+value+expires+"; path=/";
			}

			this.readCookie = function(name) {
				var nameEQ = name + "=";
				var ca = document.cookie.split(';');
				for(var i=0;i < ca.length;i++) {
					var c = ca[i];
					while (c.charAt(0)==' ') c = c.substring(1,c.length);
					if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
				}
				return null;
			}

		//--------------------------------------------------
		// Reset

			this.reset = function(error) {

				console.log('nav.js: Error - ' + error);

				var body = document.getElementsByTagName('body');
				if (body && body[0]) {
					cssjs('remove', body[0], 'jsEnabled');
				}

			}

		//--------------------------------------------------
		// On page load

			addLoadEvent(function() {
				nav.init();
			});

	}
