// function addLoadEvent(func) {
//     var oldonload = window.onload;
//     if (typeof window.onload != 'function') {
//         window.onload = func;
//     } else {
//         window.onload = function() {
//             if (oldonload) {
//                 oldonload();
//             }
//             func();
//         }
//     }
// }

/*-  Queue up functions to fire onload/onresize
----------------------------------------------------------------------*/
/*
	Text sizing
*/
// addLoadEvent(buildTextSizer);
// addLoadEvent(function() {
// 	if (readCookie("text-size")) {
// 		textIt(readCookie("text-size"));
// 	} else {
// 		textIt("txt-medium");
// 	}
// });

/*
	"Current Issue" tabs
*/
// addLoadEvent(buildCurrentIssueTabs);

/*
	Expand/collapse search navigation
*/
addLoadEvent(buildSearchNavigation);
/*
	IE fix for non-anchor hovers (top navigation, cover archive, etc.)
*/
// if (document.all) {
// 	addLoadEvent(function() {
// 		ieHover(cssQuery("#navigation li"));
// 		ieHover(cssQuery("#restaurant-menu table tr"));
// 		ieHover(cssQuery("#cover-archive ul li.cover"));
// 	});
// }

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


/*
	Implement "smart" navigation hiding
*/
// addLoadEvent(widthMonitor);
// addResizeEvent(widthMonitor);

/*
	Column height patch
*/
// addLoadEvent(sectionColumnFix);

/*
	"Splash" feature tabs
*/
// addLoadEvent(initSplashFeature);



/*
	"The Find" navigation processing
*/
// addLoadEvent(theFindNav);

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



/*-  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;
// }


/*-  Text sizing
----------------------------------------------------------------------*/
/*
	Build controls text sizing
*/
// function buildTextSizer() {
// 	if (document.getElementsByTagName) {
// 		var trigger = document.getElementsByTagName("body")[0];
// 		if (findWord("text-sizer", trigger.className) && document.createElement && document.getElementById) {
// 			if (document.getElementById("article-content")) {
// 				var container = document.getElementById("article-content");
// 			} else {
// 				var container = document.getElementById("content-primary");
// 			}
// 
// 			if (container) {
// 				// Build elements
// 				var slugs = new Array("small", "medium", "large");
// 				var controlContainer = document.createElement("div");
// 				var topList = document.createElement("ul");
// 				var innerList = document.createElement("ul");
// 				var listItem = document.createElement("li");
// 				var span = document.createElement("span");
// 				var labelText = document.createTextNode("Text Size:")
// 
// 				// Loop over the text size "slugs", and build a link for each one
// 				for (var i = 0; i < slugs.length; i++) {
// 					var text = document.createTextNode("A");
// 					var anchor = document.createElement("a");
// 					var item = document.createElement("li");
// 
// 					anchor.appendChild(text);
// 					anchor.setAttribute("href", "javascript:textIt('txt-" + slugs[i] + "');");
// 					anchor.setAttribute("title", "Make the story text " + slugs[i] + ".");
// 					item.appendChild(anchor);
// 					item.setAttribute("id", "txt-" + slugs[i]);
// 
// 					innerList.appendChild(item);
// 				}
// 
// 				// Assemble everything, and insert it into the document
// 				span.className = "label";
// 				span.appendChild(labelText);
// 				listItem.appendChild(span);
// 				listItem.appendChild(innerList);
// 				topList.appendChild(listItem);
// 				controlContainer.setAttribute("id", "text-size");
// 				controlContainer.appendChild(topList);
// 				container.insertBefore(controlContainer, container.childNodes[0]);
// 			}
// 		}
// 	}
// }
// 

/*
	Text sizer function
*/
// function textIt(str) {
// 	var wrap = document.getElementById("wrap");
// 	var textSize = document.getElementById("text-size");
// 	if (wrap && textSize) {
// 		wrap.className = str;
// 
// 		var listItems = textSize.getElementsByTagName("li");
// 		for (var i = 0; i < listItems.length; i++) {
// 			listItems[i].className = "";	// IE5/Mac won't respect .removeAttribute("class"), for some reason.
// 			if (listItems[i].getAttribute("id") == str) {
// 				listItems[i].className = safeAppend(listItems[i].className, "current");
// 				setCookie("text-size", str, 365)
// 			}
// 		}
// 	}
// }



// //////////////////////////////////////////////////////////////
/*-  Expand/collapse functionality for search navigation
----------------------------------------------------------------------*/
function buildSearchNavigation() {
	var searchNav = document.getElementById("search-results-navigation");
	if (searchNav && document.getElementsByTagName) {
		var lists = searchNav.getElementsByTagName("ul");
		for (var i = 0; i < lists.length; i++) {
			if (findWord("search-nav", lists[i].className)) {

				// 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 = "off";
						}

						// Build the widget link
						var widget = document.createElement("a");
						var linkText = document.createTextNode("Expand/collapse this item");
						widget.appendChild(linkText);
						widget.setAttribute("href", "#");
						widget.className = "widget";
						widget.onclick = function() {
							toggleSearch(this);
							return false;
						}

						// Insert the widget link into the <li> (before all other items)
						items[j].insertBefore(widget, items[j].childNodes[0]);
					}
				}
			}

			// Do we need to build show more/fewer links into this list?
			if (findWord("show-more", lists[i].className)) {
				var children = lists[i].childNodes;
				var count = 1;
				var flag = 0;

				for (var k = 0; k < children.length; k++) {
					if (children[k].nodeType == 1 && children[k].tagName.toLowerCase() == "li") {
						if (count > 8) {
							children[k].className = (children[k].className.length > 0) ? safeAppend("gone", children[k].className) : "gone";
							flag++;
						}

						if (!findWord("info", children[k].className)) {
							count++;
						}
					}
				}

				if (flag > 0) {
					var listItem = document.createElement("li");
					var showLink = document.createElement("a");
					var linkText = document.createTextNode("Show more");
					showLink.appendChild(linkText);
					showLink.setAttribute("href", "#");
					showLink.onclick = function() {
						showLinks(this);
						return false;
					}

					listItem.appendChild(showLink);
					listItem.className = "show";
					lists[i].appendChild(listItem);
				}
			}
		}
	}
}

function showLinks(el) {
	var parent = getParent(el, "ul");
	var children = parent.childNodes;

	for (var i = 0; i < children.length; i++) {
		if (children[i].nodeType == 1 && children[i].tagName.toLowerCase() == "li" && findWord("gone", children[i].className)) {
			children[i].className = replaceWord("gone", "", parent.className);
		}
	}

	el.innerHTML = "Show fewer";
	el.onclick = function() {
		hideLinks(this);
		return false;
	}
}

function hideLinks(el) {
	var parent = getParent(el, "ul");
	var children = parent.childNodes;
	var count = 1;

	for (var i = 0; i < children.length; i++) {
		if (children[i].nodeType == 1 && children[i].tagName.toLowerCase() == "li") {
			if (count > 8) {
				if (children[i].className != "show") {
					children[i].className = (children[i].className.length > 0) ? safeAppend("gone", children[i].className) : "gone";
				}
			}

			if (!findWord("info", children[i].className)) {
				count++;
			}
		}
	}

	el.innerHTML = "Show more";
	el.onclick = function() {
		showLinks(this);
		return false;
	}
}

function toggleSearch(el) {
	var parent = getParent(el, "li");
	if (parent) {
		if (parent.className == "off") {
			parent.className = "on";	// Fix for IE/Win
		} else if (parent.className == "on" || parent.className == "default") {
			parent.className = "off";	// Fix for IE/Win
		} else {
			if (findWord("off", parent.className)) {
				parent.className = replaceWord("off", "on", parent.className);
			} else {
				parent.className = (parent.className.length > 0) ? safeAppend("on", parent.className) : "on";
			}
		}
	}
}





/*-  Splash feature show/hide functionality
----------------------------------------------------------------------*/
// function initSplashFeature() {
// 	var imgPath = "../images/2/";
// 	var ext = "gif";
// 
// 	// Which tab are we showing by default? The first tab shows at 8, the second at 12, and the third at 4.
// 	var time = new Date();
// 	var hour = time.getHours();
// 	hour = (hour > 12) ? hour - 12 : hour;
// 
// 	var def = 0; // Let's default to the first tab.
// //	if (hour == 12 || hour < 4) {
// //		def = 1; // This is the second tab.
// //	} else if (hour >= 4 && hour < 8) {
// //		def = 2; // This is the third tab.
// //	}
// 
// 	// Now, let's build the tabs.
// 	if (document.getElementById && document.getElementsByTagName) {
// 		var container = document.getElementById("splash-features");
// 		var features = cssQuery("div#splash-features div.feature");
// 
// 		if (container && features) {
// 			// Build the navigation tabs
// 			var list = document.createElement("ul");
// 			list.setAttribute("id", "splash-feature-nav");
// 
// 			for (var i = 0; i < features.length; i++) {
// 				var thisId = features[i].getAttribute("id");
// 
// 				var item = document.createElement("li");
// 				var anchor = document.createElement("a");
// 				var img = document.createElement("img");
// 
// 				img.setAttribute("src", imgPath + "feat-" + thisId + "." + ext);
// 				img.setAttribute("alt", "");
// 				anchor.setAttribute("href", "javascript:showFeature('" + thisId + "');");
// 				anchor.onclick = function() {
// 					tagSiblings(getParent(this, "ul"), "li", "closed");
// 					toggleNav(this, "li");
// 				}
// 
// 				anchor.appendChild(img);
// 				item.appendChild(anchor);
// 				list.appendChild(item);
// 
// 				if (i == def) {
// 					toggleNav(anchor, "li");
// 					item.className = "open";
// 					showFeature(thisId);
// 				} else {
// 					item.className = "closed";
// 				}
// 			}
// 
// 			container.appendChild(list);
// 		}
// 	}
// }
// 
// function showFeature(id) {
// 	var features = cssQuery("div#splash-features div.feature");
// 
// 	for (var i = 0; i < features.length; i++) {
// 		var thisId = features[i].getAttribute("id");
// 		if (thisId == id) {
// 			features[i].className = "feature";
// 		} else {
// 			features[i].className = "feature off";
// 		}
// 	}
// }
// 
// function tagSiblings(parent, type, className) {
// 	var targets = parent.getElementsByTagName(type);
// 	if (targets) {
// 		for (var i = 0; i < targets.length; i++) {
// 			targets[i].className = className;
// 		}
// 	}
// }
// 
// function toggleNav(el, target) {
// 	var parent = getParent(el, target);
// 
// 	if (parent) {
// 		parent.className = (findWord("closed", parent.className)) ? "open" : "closed";
// 	}
// }



/*-  Monitor the width of the page
----------------------------------------------------------------------*/
// function widthMonitor() {
// 	if (document.getElementById && document.getElementsByTagName) {
// 		var body = document.getElementsByTagName("body")[0];
// 		if (!findWord("fixed", body.className)) {
// 			var docWidth = getBrowserWidth();
// 			var nav = document.getElementById("navigation");
// 
// 			if (docWidth > 990) {
// 				nav.className = "full";
// 			} else if (docWidth <= 990 && docWidth > 903) {
// 				nav.className = "medium";
// 			} else if (docWidth <= 903 && docWidth > 800) {
// 				nav.className = "mini";
// 			} else if (docWidth <= 800) {
// 				nav.className = "micro";
// 			}
// 			/*
// 			var diagnostic = document.getElementById("text-size");
// 			diagnostic.innerHTML = docWidth;
// 			*/
// 		}
// 	}
// }




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

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

/*
	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);
}

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


/*
	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"), "");
		}
	}
}

/*
	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;
// }


/*
	Get Browser Width
*/
function getBrowserWidth() {
	if (window.innerWidth) {
		return window.innerWidth;
	} else if (document.documentElement && document.documentElement.clientWidth != 0) {
		return document.documentElement.clientWidth;
	} else if (document.body) {
		return document.body.clientWidth;
	}
	return 0;
}


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


/*
	Add Resize Event
*/
function addResizeEvent(func) {
	var oldresize = window.onresize;
	if (typeof window.onresize != 'function') {
		window.onresize = func;
	} else {
		window.onresize = function() {
			oldresize();
			func();
		}
	}
}


/*
	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;
}

/*
	Trim function
*/
function trim(str) {
	return str.replace(/^\s*|\s*$/g,"");
}
/*-  Show a send to phone element
----------------------------------------------------------------------*/
// function show_send_to_phone(id) {
//     var nyml_id = id;
//     var element_name = "send_to_phone_" + nyml_id;
//         var element = document.getElementById(element_name);
// 
//     if (element == null) {
//         return;
//     }
// 
//     // if this is visible, hide it
//     if(element.style && element.style.display == 'block') {
//         element.style.display = 'none';
//         // reset global var that stores open send-to-phone box name
//         visible_send_to_phone_name = 'undefined';
//         return;
//     }
// 
//     // make this box visible
//     if(element.style && element.style.display != undefined) {
// 
//         // if there is another send-phone is open - close it (this uses a
//         // global variable that is set elsewhere (search results template, for
//         // example)
//         if (visible_send_to_phone_name != 'undefined') {
// 
//                 var open_box = document.getElementById(visible_send_to_phone_name);
//             if(open_box.style && open_box.style.display == 'block') {
//                 open_box.style.display = 'none';
//             }
//         }
// 
//         element.style.display = 'block';
//         // update global var that stores open send-to-phone box name
//         visible_send_to_phone_name = element_name;
//     }
// }

/*-  Show a sent to phone element
----------------------------------------------------------------------*/
// function show_sent_to_phone(id) {
//     var nyml_id = id;
//     var element_name = "sent_to_phone_" + nyml_id;
//         var element = document.getElementById(element_name);
// 
//     if (element == null) {
//         return;
//     }
// 
//     // if this is visible, hide it
//     if(element.style && element.style.display == 'block') {
//         element.style.display = 'none';
//         // reset global var that stores open send-to-phone box name
//         visible_send_to_phone_name = 'undefined';
//         return;
//     }
// 
//     // make this box visible
//     if(element.style && element.style.display != undefined) {
// 
//         // if there is another send-to-phone open - close it (this uses a
//         // global variable that is set elsewhere (search results template, for
//         // example)
//         if (visible_send_to_phone_name != 'undefined') {
// 
//                 var open_box = document.getElementById(visible_send_to_phone_name);
//             if(open_box.style && open_box.style.display == 'block') {
//                 open_box.style.display = 'none';
//             }
//         }
// 
//         element.style.display = 'block';
//         // update global var that stores open send-to-phone box name
//         visible_send_to_phone_name = element_name;
//     }
// }
// 

/*-  Send to phone using form values
----------------------------------------------------------------------*/
// function send_to_phone(id, slug) {
//     var nyml_id = id;
//     // kill the html page in the slug, and leve the directory only
//     slug = slug.replace(/\/\w+\.html$/,'');
//     // now erase anything before the last slash to leave us with dir name only
//     slug = slug.replace(/^.*\//,'');
//     var form_name = "text_message_" + nyml_id;
// 
//     // do not do anything unless terms have been accepted
//     if (document.forms[form_name].elements['terms'].checked == false) {
//         alert("You must accept Terms and Conditions");
//         return;
//     }
// 
//     // verify phone format (simple)
//     if ( document.forms[form_name].elements['areacode'].value.length < 3) {
//         alert('Area code must be at least 3 digits long');
//         return;
//     }
//     if ( document.forms[form_name].elements['prefix'].value.length < 3) {
//         alert('Prefix must be at least 3 digits long');
//         return;
//     }
//     if ( document.forms[form_name].elements['suffix'].value.length < 4) {
//         alert('Suffix must be at least 4 digits long');
//         return;
//     }
// 
//     if ( document.forms[form_name].elements['areacode'].value.match(/\D/) ) {
//         alert('Area code must be numeric');
//         return;
//     }
//     if ( document.forms[form_name].elements['prefix'].value.match(/\D/) ) {
//         alert('Prefix must be numeric');
//         return;
//     }
//     if ( document.forms[form_name].elements['suffix'].value.match(/\D/) ) {
//         alert('Suffix must be numeric');
//         return;
//     }
// 
//     var phone_to_send_to
//         = document.forms[form_name].elements['areacode'].value
//         + document.forms[form_name].elements['prefix'].value
//         + document.forms[form_name].elements['suffix'].value;
// 
//     var target_url
//         = 'http://juicewireless.com/nymag/txt_mobile.php?client=nymag&m0='
//         + phone_to_send_to
//         + '&slug=' + escape(slug);
// 
//     window.location = '/search/send_to_phone.cgi?t=' + escape(target_url);
// 
//     show_sent_to_phone(id);
// }
// 
// 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");
// 	if (!name) {
// 		name = "Friend";
// 	}
// 	return name;
// }
