// ************************
// Constructor for Page
// ************************
function Page(title, href, path, section, head)
{
	this.title = title;
	this.href = href;
	this.path = path;
	this.section = section;
	this.head = head;
}

// ************************
// Constructor for Nav
// ************************
function Nav(anchor)
{
	this.state = "";
	this.pages = new Array();
	this.anchor = anchor;
	this.home = "<a href=\"index.html\">Home</a>";
	this.icon = " >> ";
}

Nav.prototype.addPage = function(title, href, path, section, head)
{
	this.pages[href] = new Page(title, href, path, section, head);
}

Nav.prototype.load = function()
{
	this.state = this.getCookie("navstate");
	if(!this.state)
	{
		this.state = "";
	}
	this.hitPage();
}

Nav.prototype.hitPage = function()
{
	var c = window.location.pathname;
	c = c.replace(/\\/g, "/");
	c = c.substring(c.lastIndexOf("/") +1);
	
	var p = this.state.substring(this.state.lastIndexOf(":") +1);
	
	var o = this.state.substring(0,this.state.lastIndexOf(p) -1);
	var o = o.substring(o.lastIndexOf(":") +1);

	var current = this.pages[c];
	var previous = this.pages[p];

	if(current == null)
	{
		this.setCookie("navstate","");
	}
	else
	{
		this.figureState(current, previous);
		this.setCookie("navstate", this.state);
		this.write();
	}
}

Nav.prototype.figureState = function(current, previous)
{
	if(previous != null && previous.section == current.section && previous.href != current.href)
	{
		if(current.head != "")
		{
			this.state = current.head + ":" + current.href;
		}
		else
		{
			this.state = current.href;
		}
	}
	else if (!previous || previous.section != current.section)
	{
		if(current.head == "")
		{
			this.state = current.href;
		}
		else
		{
			this.state = this.pages[current.head].href + ":" + current.href;
		}
	}
}

Nav.prototype.write = function()
{
	var content = this.home + this.icon;
	var p = this.state.split(":");
	
	for(var i=0; i<p.length; i++)
	{
		if(i<(p.length -1))
		{
			content += "<a href=\"" + this.pages[p[i]].path + this.pages[p[i]].href + "\">" + this.pages[p[i]].title + "</a>" + this.icon;
		}
		else
		{
			content += this.pages[p[i]].title;
		}
	}
	
	document.getElementById(this.anchor).innerHTML = content;
}

Nav.prototype.setCookie = function(name, value)
{
	document.cookie = name + "=" + value + ";path=/";
}
	
Nav.prototype.getCookie = function(name)
{
	var cookie = document.cookie;
	if( cookie.indexOf(name) > -1 ) {
		var start = cookie.indexOf(name) + name.length + 1;
		var end = cookie.indexOf(";",start);
		if(end < 0) {
			end = cookie.length;
		}
		var value = cookie.substring(start,end);
		
		return value;
	}
}

