/*-  Variables
----------------------------------------------------------------------*/
var imgPath = "/fashion/fashionshows/images/2/";


/*-  Queue up functions to fire onload/onresize
----------------------------------------------------------------------*/
/*
	Expand/collapse search navigation
*/
addLoadEvent(function() {
	buildSearchNavigation("filter-categories")
});

/*
	Expand/collapse "albums"
*/
addLoadEvent(function() {
	buildAlbumNavigation("shared-albums")
});

/*
	Expand/collapse "new album" link
*/
addLoadEvent(initNewAlbumLink);

/*
	Add "remove text" handler to text fields
*/
addLoadEvent(initRemoveText);

/*
	Add striped rows to all tables with a class of "calendar"
*/
addLoadEvent(striped);

/*
	Add striped rows to all tables with a class of "calendarstriped" - for Fashion Calendar
*/
addLoadEvent(stripedcalendar);

/*
	Expand/collapse for "All Shows" module
*/
addLoadEvent(function() {
	allShowsExpand("all-shows");
});

/*
	Multiple Expand/collapse for "expand-collapse-list" class
*/
addLoadEvent(function() {
	classExpand("expand-collapse-list");
});

/*
	Expand/collapse for "My Fashion" module
*/
addLoadEvent(function() {
	myAlbums("my-albums");
});

/*
	IE fix for non-anchor hovers (top navigation, cover archive, etc.)
*/
if (document.all) {
	addLoadEvent(function() {
		/* ieHover(cssQuery("#navigation li")); */
		ieHover(cssQuery("#thumb-results li"));
		ieHover(cssQuery("#shortcuts li"));
		ieHover(cssQuery("#more-models li"));
	});
}

/*
	Collapsible comments
*/
addLoadEvent(function() {
	collapseComments("comments-trunc");
});

/*
	Fashion week '07 functionality
*/
var FashionWeek = {
	init : function() {
		addLoadEvent(function() {
			FashionWeek.expandCollapse("model-index", "h3", "li", "open", "closed", true);
			FashionWeek.slideshow("model-navigator", "thumbs", "ul", "open", "closed", "Next group \xbb", "h3");
			FashionWeek.slideshow("model-quotes", "", "blockquote", "open", "closed", "Next quote \xbb", "h3");
			FashionWeek.tabBuilder("most-popular", "h3", "tab", "tab-closed", "nav");
		});
	},

	/*
		Generic expand/collapse function
			Arg:		scope = (str) id of target container
					hook = (str) element that'll be clicked on
					parent = (str) element type that contains "hook" (NB: these can be the same)
					openClass = (str) class name for "open" state
					closedClass = (str) class name for "closed" state
					expandFirst = (bool, optional) set to true if the first parent should be set to open
	*/
	expandCollapse : function(scope, hook, parent, openClass, closedClass, expandFirst) {
		if (NYMag.isCompatible()) {
			var container = document.getElementById(scope);

			if (container) {
				var els = container.getElementsByTagName(hook);

				for (var i = 0; i < els.length; i++) {
					var parentEl = (hook == parent) ? hook : getParent(els[i], parent);
					var thisNode = els[i];

					parentEl.className = (expandFirst && i == 0) ? openClass : closedClass;
					els[i].parentEl = parentEl;
					els[i].openClass = openClass;
					els[i].closedClass = closedClass;

					thisNode.onclick = function() {
						var el = this.parentEl;
						el.className = (el.className == this.openClass) ? this.closedClass : this.openClass;
					};
				}
			}
		}
	},

	/*
		Generic tab constructor dealie
			Arg:		scope = (str) id of target container
					label = (str) elements to be used for tag labels
					tabClass = (str) class of the 'label' elements to be turned into tabs
					closedClass = (str) class name for "closed" state
					navClass = (str) class name for the list of nav items
					navBottom = (bool, optional) position the nav at the top (=false) or bottom (=true)
	*/
	tabBuilder : function(scope, label, tabClass, closedClass, navClass, navBottom) {
		if (NYMag.isCompatible()) {
			var container = document.getElementById(scope);

			if (container) {
				var tabs = [];
				var a = document.createElement("a");
				a.setAttribute("href", "#");

				var li = document.createElement("li");
				var ul = document.createElement("ul");
				ul.className = navClass;

				var els = container.getElementsByTagName(label);

				for (var i = 0; i < els.length; i++) {
					var parent = els[i].parentNode;

					if (parent.className == tabClass) {
						var slug = scope + "-tab-" + i;
						parent.setAttribute("id", slug);
						tabs.push(slug);

						var txt = document.createTextNode(getInnerText(els[i]));

						var item = li.cloneNode(false);
						var link = a.cloneNode(true);
						link.className = slug;

						// onclick handler
						link.onclick = function() {
							var key;
							var ul = getParent(this, "ul");
							var items = ul.childNodes;
							for (var i = 0; i < items.length; i++) {
								if (items[i].childNodes[0].className == this.className) {
									items[i].className = "current";
									key = i;
								} else {
									items[i].className = "";
								}
							}

							var content = getParent(this, "div");
							var divs = content.getElementsByTagName("div");
							for (var i = 0; i < divs.length; i++) {
								divs[i].className = (i == key) ? "tab" : "tab-closed";
							}
							return false;
						};

						link.appendChild(txt);
						item.appendChild(link);
						ul.appendChild(item);

						if (i != 0) {
							parent.className = closedClass;
						} else {
							item.className = "current";
						}
					}
				}

				if (tabs.length > 0) {
					var content = els[0].parentNode.parentNode;
					if (navBottom) {
						content.appendChild(ul);
					} else {
						content.insertBefore(ul, content.childNodes[0]);
					}
				}
			}
		}
	},

	/*-  Slideshow
			Arg:		id = (str) ID of model navigator
					cl = (str) class of slideshow elements (can be empty string)
					slideEls = (str) element type to be used as slides
					open = (str) class name for "open" state
					closed = (str) class name for "closed" state
					txt = (str) Text to show up in the "next" link
					headerEl = (str, optional) Element that houses the "title" for each slide
	*/
	slideshow : function(id, cl, slideEls, open, closed, txt, headerEl) {
		if (NYMag.isCompatible()) {
			var container = document.getElementById(id);
			if (container) {
				var nav = {
					cEls : container.getElementsByTagName(slideEls),
					aSlides : [],
					current : null,
					key : null,
					init : function() {
						var c = nav;
						if (cl.length > 0) {
							for (var i = 0; i < c.cEls.length; i++) {
								if (findWord(cl, c.cEls[i].className)) {
									c.aSlides.push(c.cEls[i]);
								}
							}
						} else {
							for (var i = 0; i < c.cEls.length; i++) {
								c.aSlides.push(c.cEls[i]);
							}
						}

						// If there's more than one slide, let's build the navigation.
						if (c.aSlides.length > 1) {
							c.key = NYMag.getRandom(0, c.aSlides.length - 1);

							for (var i = 0; i < c.aSlides.length; i++) {
								if (i == c.key) {
									c.aSlides[i].className = safeAppend(c.aSlides[i].className, open);
									c.showTitle(c.aSlides[i]);
								} else {
									c.aSlides[i].className = safeAppend(c.aSlides[i].className, closed);
								}
							}
							c.buildnav();
						}
					},
					buildnav : function() {
						var c = nav;
						var ul = document.createElement("ul");
						var li = document.createElement("li");
						var a = document.createElement("a");
						var tTxt = document.createTextNode(txt);

						a.href = "#";
						a.onclick = function() {
							c.nextSlide();
							return false;
						}

						a.appendChild(tTxt);
						li.appendChild(a);
						ul.appendChild(li);
						ul.className = "nav";
						container.appendChild(ul);
					},
					nextSlide : function() {
						var d = nav;
						var next = (d.key + 1 < d.aSlides.length) ? (d.key + 1) : 0;

						d.key = next;

						for (var i = 0; i < d.aSlides.length; i++) {
							if (i == next) {
								d.aSlides[i].className = replaceWord(closed, open, d.aSlides[i].className);
								d.showTitle(c.aSlides[i]);
							} else {
								d.aSlides[i].className = replaceWord(open, closed, d.aSlides[i].className);
							}
						}
					},
					showTitle : function(el) {
						var d = nav;

						if (el.getAttribute("title") && headerEl) {
							var title = document.createTextNode("" + el.getAttribute("title") + "");

							var headline = el.parentNode.getElementsByTagName(headerEl)[0];
							if (headline) {
								NYMag.removeChildren(headline);
							} else {
								var headline = document.createElement(headerEl);
								el.parentNode.insertBefore(headline, c.aSlides[0]);
							}

							headline.appendChild(title);
						}
					}
				}

				nav.init();
			}
		}
	}
}

FashionWeek.init();

/*-  Collapsible comments
		Arg:		id = ID of comments' containing DIV
----------------------------------------------------------------------*/
function collapseComments(id) {
	var previewLength = 11; // Number of words in each comment preview

	if (document.getElementById && document.getElementsByTagName) {
		var tmp;
		var content;

		var container = document.getElementById(id);
		if (container) {
			var items = container.getElementsByTagName("li");

			for (var i = 0; i < items.length; i++) {
				if (findWord(items[i].className, "comment")) {

					var divs = items[i].getElementsByTagName("div");
					for (var j = 0; j < divs.length; j++) {
						// Is this the comment's "content" div?
						if (divs[j].className == "content") {
							// Let's build the preview
							var str = getInnerText(divs[j]);

							// .replace() doesn't seem to work, so let's use .split();
							var clean = str.replace(/^\s+|\s+$/g, "");
							var simpleSplit = clean.split(" ");
							var tmp = "";
							for (var k = 0; k < previewLength; k++) {
								tmp += simpleSplit[k];
								if (k != (previewLength - 1)) {
									tmp += " ";
								}
							}

							if (tmp.length > 0) {
								// Create preview block + "expand" link
								var a = document.createElement("a");
								a.setAttribute("href", "#");

								var p = document.createElement("p");

								// Content link
								var closeLink = a.cloneNode(false);
								var close = p.cloneNode(false);
								close.className = "close";

								var closeTxt = document.createTextNode("Close");

								closeLink.onclick = function() {
									closeComment(this);
									return false;
								}

								closeLink.appendChild(closeTxt);
								close.appendChild(closeLink);
								divs[j].appendChild(close);

								// Preview text & link
								var prevLink = a.cloneNode(false);
								var preview = p.cloneNode(false);
								preview.className = "preview";

								var txt = document.createTextNode(tmp);
								var aTxt = document.createTextNode("...");

								prevLink.onclick = function() {
									expandComment(this);
									return false;
								}

								prevLink.appendChild(aTxt);
								preview.appendChild(txt);
								preview.appendChild(prevLink);

								divs[j].parentNode.insertBefore(preview, divs[j]);
							}
						}
					}

					items[i].className = safeAppend(items[i].className, "collapsed");
				}
			}
			
		}
	}
}

function closeComment(el) {
	var comment = getParent(el, "li");
	comment.className = "comment collapsed";
}

function expandComment(el) {
	var comment = getParent(el, "li");
	comment.className = "comment";
}


/*-  Expand/collapse for "expand-collapse-list" class
----------------------------------------------------------------------*/
function classExpand(classname) {
	var targetIDs = getIDsByClass(classname);
	if (targetIDs.length > 0) {
		for (i=0; i<targetIDs.length; i++) {
			var thisID = document.getElementById(targetIDs[i]);
		
			if (thisID) {
				var header = thisID.getElementsByTagName("h3")[0];
				var wrap = thisID.getElementsByTagName("div")[0];

				if (wrap && header) {
					wrap.className = "closed";

					var text = document.createTextNode(getInnerText(header));

					var a = document.createElement("a");
					a.setAttribute("href", "#");
					a.appendChild(text);
					a.onclick = function() {
						toggleNav(this, "div");
						return false;
					}

					while (header.hasChildNodes()) {
						header.removeChild(header.firstChild);
					}

					header.appendChild(a);
				}
			
			}
    	}
	}
}

/*  Function to return all element IDs that have class "theClass"   */
 
function getIDsByClass(theClass) {
	var myIDs = new Array();
	var j=0;
	//Populate the array with all the page tags
	var allPageTags=document.getElementsByTagName("*");
	//Cycle through the tags using a for loop
	for (i=0; i<allPageTags.length; i++) {
		//Pick out the tags with our class name
		if (allPageTags[i].className==theClass) {
		//Manipulate this in whatever way you want
			myIDs[j++] = allPageTags[i].getAttribute("id");
		}
	}
	return myIDs;
}




/*-  Expand/collapse for "All Shows" module
----------------------------------------------------------------------*/
function allShowsExpand(id) {
	if (document.getElementById && document.getElementsByTagName) {

		var allShows = document.getElementById(id);
		if (allShows) {
			var header = document.getElementsByTagName("h3")[0];
			var wrap = allShows.getElementsByTagName("div")[0];

			if (wrap && header) {
				wrap.className = "closed";

				var text = document.createTextNode(getInnerText(header));

				var a = document.createElement("a");
				a.setAttribute("href", "#");
				a.appendChild(text);
				a.onclick = function() {
					toggleNav(this, "div");
					return false;
				}

				while (header.hasChildNodes()) {
					header.removeChild(header.firstChild);
				}

				header.appendChild(a);
			}
		}

	}
}

addLoadEvent(function() {
	buildCalendarTabs("show-calendars", "calendar-nav");
});

function buildCalendarTabs(calendars, navId) {
	if (document.getElementById && document.getElementsByTagName && document.createElement) {
		var allCalendars = document.getElementById(calendars);
		var isIE5Mac = (document.all && !window.attachEvent) ? 1 : 0;

		if (allCalendars) {
			calendarTables = allCalendars.getElementsByTagName("table");

			if (calendarTables) {
				var list = document.createElement("ul");
				list.setAttribute("id", navId);

				// First, get today's date.
				var d = new Date();
				var txtMonth = new Array("January", "February", "March", "April", "May", "June", "July", "August", "September",  "October", "November", "December");
				var txtToday = txtMonth[d.getMonth()] + " " + d.getDate();
				var isToday = false;
				var todayKey = 0;

				// Now, let's figure out which (if any) of the tables are active.
				for (var i = 0; i < calendarTables.length; i++) {
					var caption = calendarTables[i].getElementsByTagName("caption")[0];
					var captionText = trim(getInnerText(caption));

					// Check to see whether or not this is today's date
					if (trim(captionText.split(", ")[1]) == txtToday) {
						calendarTables[i].className = "calendar";
						isToday = i;
					} else {
						calendarTables[i].className = "ineffable";
					}
				}

				// And finally, let's build the navigation.
				for (var i = 0; i < calendarTables.length; i++) {
					var caption = calendarTables[i].getElementsByTagName("caption")[0];
					var captionText = trim(getInnerText(caption));
					if (captionText.match(/^([A-Za-z]*), [A-Za-z]* (\d{1,2})/i)) {
						var day = RegExp.$1;
						var date = document.createTextNode(RegExp.$2);
						var acronymTxt = document.createTextNode(day.substring(0,3));

						var item = document.createElement("li");
						var anchor = document.createElement("a");
						var span = document.createElement("span");
						var acronym = document.createElement("acronym");
						var space = document.createTextNode(" ");

						acronym.setAttribute("title", day);
						acronym.appendChild(acronymTxt);

						if (isIE5Mac) {
							var br = document.createElement("br");
							anchor.appendChild(acronymTxt);
							anchor.appendChild(br);
							anchor.appendChild(date);
						} else {
							span.appendChild(acronym);
							span.appendChild(space);
							span.appendChild(date);
							anchor.appendChild(span);
						}

						anchor.href = "javascript:showCalendarTable(" + i + ", '" + calendars + "', '" + navId + "');";
						item.appendChild(anchor);

						if ((i + 1) == calendarTables.length) {
							item.className = "last";
						}

						list.appendChild(item);

						if (isToday && i == isToday) {
							while (caption.hasChildNodes()) {
								caption.removeChild(caption.firstChild);
							}

							var txtCaption = document.createTextNode("Today\u2019s events:");
							caption.appendChild(txtCaption);
						}
					}
				}

				allCalendars.appendChild(list);

				if (isToday) {
					showCalendarTable(isToday, calendars, navId);
				} else {
					showCalendarTable(0, calendars, navId);
				}
			}
		}
	}
}

function showCalendarTable(key, calendars, nav) {
	if (document.getElementById && document.getElementsByTagName && document.createElement) {
		var allCalendars = document.getElementById(calendars);
		var calendarNavItems = document.getElementById(nav).getElementsByTagName("li");

		if (allCalendars) {
			calendarTables = allCalendars.getElementsByTagName("table");
			for (var i = 0; i < calendarTables.length; i++) {
				calendarTables[i].className = (i == key) ? "calendar" : "ineffable";

				if (findWord("last", calendarNavItems[i].className)) {
					calendarNavItems[i].className = (i == key) ? "current last" : "last";
				} else {
					calendarNavItems[i].className = (i == key) ? "current" : "";
				}
			}
		}
	}
}




/*-  When a user clicks on a text field, any default text should
	be removed.
----------------------------------------------------------------------*/
function initRemoveText() {
	if (document.getElementsByTagName) {
		var inputs = document.getElementsByTagName("input");
		for (var i = 0; i < inputs.length; i++) {
			var this_input = inputs[i];
			if (this_input.getAttribute("type") == "text" && this_input.className.match("smart_focus")) {
				this_input.setAttribute("previous", this_input.value);

				this_input.onclick = function() {
					this.value = "";
				}

				this_input.onblur = function() {
					if (this.value.length == 0) {
						this.value = this.getAttribute("previous");
					}
					this.setAttribute("previous", this.value);
				}
			}
		}
	}
}


/*-  Expand/collapse for "Create New Album" link
----------------------------------------------------------------------*/
function initNewAlbumLink() {
	if (document.getElementById) {
		var createNew = document.getElementById("create-album");

		if (createNew && document.getElementsByTagName) {
			var links = createNew.getElementsByTagName("a");

			for (var i = 0; i < links.length; i++) {

				if (links[i].className == "main") {
					var parentItem = getParent(links[i], "li");

					if (parentItem) {
						// "Close" the parent <li>
						parentItem.className = "closed";

						// Insert the "close" button
						var inputs = parentItem.getElementsByTagName("input");
						var refNode = -1;

						for (var j = 0; j < inputs.length; j++) {
							if (inputs[j].getAttribute("type").toLowerCase() == "text") {
								var refNode = inputs[j];
							}
						}

						if (refNode != -1) {
							var img = document.createElement("img");
							img.setAttribute("src", imgPath + "btn-cancel.gif");

							var a = document.createElement("a");
							a.className = "cancel";
							a.setAttribute("href", "#");
							a.onclick = function() {
								toggleNav(this, "li");

								return false;
							}

							a.appendChild(img);

							insertAfter(refNode.parentNode, a, refNode);
						}

					}

					// Attach the event handler to the link
					links[i].onclick = function() {
						toggleNav(this, "li");

						return false;
					}
				}

			}
		}
	}
}


/*-  "My Albums" in-place editing
----------------------------------------------------------------------*/
function myAlbums(id) {
	if (document.getElementById && document.getElementsByTagName) {
		var albums = document.getElementById(id);
		if (albums) {
			var links = albums.getElementsByTagName("a");

			for (var i = 0; i < links.length; i++) {
				if (findWord("edit", links[i].className)) {
					switchEdit(links[i], "div");

					links[i].onclick = function() {
						switchEdit(this, "div");

						return false;
					}
				}
			}
		}
	}
}

function switchEdit(el, target) {
	var parent = getParent(el, target);

	switch (parent.className) {
		case "switch-off":
			parent.className = "switch-on"
			break;
		case "switch-on":
			parent.className = "switch-off"
			break;
		case "switch":
			parent.className = "switch-off"
			break;
	}
}

/*-  Expand/collapse functionality for search navigation
----------------------------------------------------------------------*/
function buildSearchNavigation(id) {
	var searchNav = document.getElementById(id);

	if (searchNav && document.getElementsByTagName) {
		// Process the lists, and set expand/collapse handlers on the appropriate links.
		var lists = searchNav.getElementsByTagName("ul");

		for (var i = 0; i < lists.length; i++) {
			// Collect all of the current list's <li> elements
			var items = lists[i].getElementsByTagName("li");
			for (var j = 0; j < items.length; j++) {

				// If a <li> has <ul>s beneath it, let's process it.
				if (items[j].getElementsByTagName("ul").length > 0) {

					// Unless the link has a class of "default", collapse it
					if (findWord("default", items[j].className)) {
						items[j].className = "open";
					} else {
						items[j].className = "closed";
					}

					// Attach a handler to the first child link
					var anchors = items[j].getElementsByTagName("a");

					if (anchors.length) {
						for (var k = 0; k < anchors.length; k++) {
							if (k == 0 || anchors[k].className == "close") {
								anchors[k].onclick = function() {
									closeSiblings(this, id);
									toggleNav(this, "li");

									return false;
								}
							}
						}
					}
				}

			}
		}

		// Insert "Close" links into the DIVs with a class of "additional"
		var divs = searchNav.getElementsByTagName("div");

		for (var i = 0; i < divs.length; i++) {
			if (findWord("additional", divs[i].className)) {
				var p = document.createElement("p");
				var a = document.createElement("a");
				var txt = document.createTextNode("Close");

				a.className = "close";
				a.setAttribute("href", "#");
				a.onclick = function() {
					toggleNav(this, "li");

					return false;
				}
				p.className = "close";

				a.appendChild(txt);
				p.appendChild(a);
				divs[i].appendChild(p);
			}
		}
	}
}

function closeSiblings(el, id) {
	if (document.getElementById && document.getElementsByTagName) {
		var cnt = 0;
		var focus = document.getElementById(id);
		var parent = el.parentNode;
		var ref = parent.parentNode;

		var divs = focus.getElementsByTagName("div");

		for (var i = 0; i < divs.length; i++) {
			if (findWord("additional", divs[i].className)) {
				var container = divs[i].parentNode;

				if (parent != container) {
					container.className = "closed";
				}
				cnt++;
			}
		}
	}
}

function toggleNav(el, target) {
	var parent = getParent(el, target);

	if (parent) {
		parent.className = (findWord("closed", parent.className)) ? "open" : "closed";
	}
}


/*-  Add stripes to all tables with a class of "calendar"
----------------------------------------------------------------------*/
function striped() {
	if (document.getElementsByTagName) {
		var calendars = cssQuery("table.calendar");

		if (calendars.length > 0) {
			for (var i = 0; i < calendars.length; i++) {
				var rows = calendars[i].getElementsByTagName("tbody")[0].getElementsByTagName("tr");
				for (var j = 0; j < rows.length; j++) {
					if ((j % 2) == 0) {
						rows[j].className = safeAppend(rows[j].className, "odd");
					}
				}
			}
		}
	}
}


/*-  Add stripes to all tables with a class of "events" - for schedule page
----------------------------------------------------------------------*/
function stripedcalendar() {
 if (document.getElementsByTagName) {
  var calendars = cssQuery("table.stripedcalendar");
 
  if (calendars.length > 0) {
   for (var i = 0; i < calendars.length; i++) {
    var rows = calendars[i].getElementsByTagName("tbody")[0].getElementsByTagName("tr");
    for (var j = 0; j < rows.length; j++) {
     if ((j % 2) == 0) {
      rows[j].className = safeAppend(rows[j].className, "odd");
     }
    }
   }
  }
 }
}

/*-  Utility functions
----------------------------------------------------------------------*/
function buildAlbumNavigation(id) {
	if (document.getElementById) {
		var albums = document.getElementById(id);

		if (albums) {
			// Let's insert "Cancel" links into all of the forms
			var ps = albums.getElementsByTagName("p");

			for (var i = 0; i < ps.length; i++) {
				if (ps[i].className == "submit") {
					var a = document.createElement("a");
					a.setAttribute("href", "#");
					a.onclick = function() {
						toggleNav(this.parentNode.parentNode); // Overly verbose, I know. Blah.
						return false;
					}

					var img = document.createElement("img");
					img.setAttribute("src", imgPath + "btn-cancel.gif");
					img.setAttribute("alt", "Cancel");

					var txt = document.createTextNode(" ");

					a.appendChild(img);

					ps[i].insertBefore(txt, ps[i].childNodes[0]);
					ps[i].insertBefore(a, txt);
				}
			}

			// Let's process the LIs to create our "[edit]" links
			var items = albums.getElementsByTagName("li");
			var cache = new Array();

			/*
				Loop through all LIs, and remember the ones with a class of "del"
			*/
			for (var i = 0; i < items.length; i++) {
				if (items[i].className == "del") {
					cache.push(items[i]);
				}
			}

			// Loop through the li.del elements, and prepend an "edit" link that fires toggleNav()
			for (var i = 0; i < cache.length; i++) {
				var parent = cache[i].parentNode;
				var ref = getParent(parent, "li");

				var newItem = document.createElement("li");
				var a = document.createElement("a");
				var txt1 = document.createTextNode("[");
				var txt2 = document.createTextNode("Edit");
				var txt3 = document.createTextNode("]");

				a.setAttribute("href", "#");
				a.onclick = function() {
					toggleNav(this.parentNode.parentNode); // Overly verbose, I know. Blah.
					return false;
				}

				a.appendChild(txt2);
				newItem.appendChild(txt1);
				newItem.appendChild(a);
				newItem.appendChild(txt3);

				parent.insertBefore(newItem, cache[i]);

				// "Close" the top-level LI
				ref.className = "closed";
			}
		}
	}
}


/*-  Utility functions
----------------------------------------------------------------------*/
/*
	Add Load Event
*/
function addLoadEvent(func) {
	var oldonload = window.onload;
	if (typeof window.onload != 'function') {
		window.onload = func;
	} else {
		window.onload = function() {
			oldonload();
			func();
		}
	}
}

/*
	IE Fix: Son of Suckerfish (modified for IE5/Mac friendliness)
*/
function ieHover(els) {
	for (var i=0; i < els.length; i++) {
		els[i].onmouseover = function() {
			this.className = safeAppend(this.className, "ie-hover");
		}

		els[i].onmouseout = function() {
			this.className = this.className.replace(new RegExp("( ?|^)ie-hover\\b"), "");
		}
	}
}

/*
	Smart string concatenation
*/
function safeAppend(target, str) {
	target += (target.length > 0 ? " ": "") + str;
	return target;
}

/*
	Get parent element
*/
function getParent(el, pTagName) {
	if (el == null) return null;
	else if (el.nodeType == 1 && el.tagName.toLowerCase() == pTagName.toLowerCase())	// Gecko bug, supposed to be uppercase
		return el;
	else
		return getParent(el.parentNode, pTagName);
}


/*
	Get Inner Text
*/
function getInnerText(el) {
	if (typeof el == "string") return el;
	if (typeof el == "undefined") { return el };
	if (el.innerText) return el.innerText;	//Not needed but it is faster
	var str = "";
	
	var cs = el.childNodes;
	var l = cs.length;
	for (var i = 0; i < l; i++) {
		switch (cs[i].nodeType) {
			case 1: //ELEMENT_NODE
				str += getInnerText(cs[i]);
				break;
			case 3:	//TEXT_NODE
				str += cs[i].nodeValue;
				break;
		}
	}
	return str;
}

/*
	Insert node after referenceNode in parent
*/
function insertAfter(parent, node, referenceNode) {
	parent.insertBefore(node, referenceNode.nextSibling);
}

/*
	Trim function
*/
function trim(str) {
	return str.replace(/^\s*|\s*$/g,"");
}

/*
	Find full word (needle) in a string (haystack)
*/
function findWord(needle, haystack) {
	return haystack.match(needle + "\\b");
}

/*
	Smart string concatenation
*/
function safeAppend(target, str) {
	target += (target.length > 0 ? " " : "") + str;
	return target;
}

/*
	Used to replace a word (oldNeedle) with a new word (newNeedle), as found in a string (haystack)
*/
function replaceWord(oldNeedle, newNeedle, haystack) {
	return haystack.replace(new RegExp(oldNeedle + "\\b", "g"), newNeedle);
}

/*
	Cookie functions
*/
// Set the cookie
function setCookie(name, value, days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = ";expires="+date.toGMTString();
	} else {
		expires = "";
	}
	document.cookie = name+"="+value+expires+";";
}

// Read the cookie
function readCookie(name) {
	var needle = name + "=";
	var cookieArray = document.cookie.split(';');
	for(var i=0;i < cookieArray.length;i++) {
		var pair = cookieArray[i];
		while (pair.charAt(0)==' ') {
			pair = pair.substring(1, pair.length);
		}
		if (pair.indexOf(needle) == 0) {
			return pair.substring(needle.length, pair.length);
		}
	}
	return null;
}


/*
	Membership-related functions
*/

function isLoggedInUser() {
	var session = readCookie("nymag_session");
	var session_state = readCookie("nymag_session_state");
	 return (session && session_state) ? true : false;
}

function getUserName() {
	var name = readCookie("nymag_session_user");
	return isLoggedInUser() ? unescape(readCookie("nymag_session_user")) : "";
}

function getUserId() {
	return isLoggedInUser() ? readCookie("nymag_session_user_id") : "";
}

function updateLoginMessage() {
	var logged_in = isLoggedInUser();

	var user_name = document.getElementById("user_name");
	if (user_name) user_name.innerHTML = getUserName();

	var logged_out_bar = document.getElementById("logged_out_bar");
	if (logged_out_bar) {
		logged_out_bar.style.display = logged_in ? "none" : "block";
	}

	var logged_in_bar = document.getElementById("logged_in_bar");
	if (logged_in_bar) {
		logged_in_bar.style.display = logged_in ? "block" : "none";
	}
}


/*
	NYMag object
*/
var NYMag = {
	isCompatible : function() {
		if (document.getElementById && document.getElementsByTagName && document.createElement) {
			return true;
		} else {
			return false;
		}
	},
	removeChildren : function(el) {
		if (el.hasChildNodes()) {
			while (el.firstChild) {
				el.removeChild(el.firstChild);
			}
		}
	},
	getRandom : function(iMin, iMax) {
		return (Math.round(Math.random() * (iMax - iMin))) + iMin;
	}
};
