/*-----------------------------------------------------------+
 | addLoadEvent: Add event handler to body when window loads |
 +-----------------------------------------------------------*/
function addLoadEvent(func) {
	var oldonload = window.onload;
	
	if (typeof window.onload != "function") {
		window.onload = func;
	} else {
		window.onload = function () {
			oldonload();
			func();
		}
	}
}

/*------------------------------------+
 | Functions to run when window loads |
 +------------------------------------*/
addLoadEvent(function () {
	if (document.getElementById && document.getElementsByTagName) {
		addCalendars();
		addSetDates();
		attachWindowOpeners();
		//initSwap();
	}
});


/*-----------------------------------------------------------------------+
 | attachWindowOpeners: Make all external/file links open in new windows |
 +-----------------------------------------------------------------------*/
function attachWindowOpeners() {
	var links = document.getElementsByTagName("a");
	
	for (var i = 0; i < links.length; i++) {
		var theLink = links[i];
		
		if (theLink.href.indexOf("reachillinois") <= -1 && theLink.href.indexOf("javascript") <= -1) {
			var url = theLink.href;
			
			links[i].onclick = function () {
				window.open(this.href);
				return false;
			}
		}
	}
}


/*---------------------------------------------+
 | initSwap: Initialize swapping functionality |
 +---------------------------------------------*/
function initSwap () {
	if (document.getElementById("swap")) {
		clearTextNodes("swap");
		var bin = document.getElementById("swap");
		var buttons = bin.getElementsByTagName("a");
		
		// Give buttons move() event handler
		for (var i = 0; i < buttons.length; i++) {
			if (buttons[i].className == "up" || buttons[i].className == "down") {
				buttons[i].href = "#";
				buttons[i].onclick = move;
			}
		}
	}
}

/*---------------------------------------------+
 | clearTextNodes: Remove text nodes from code |
 +---------------------------------------------*/
function clearTextNodes(container) {
	var bin = document.getElementById(container);
	for (var i = 0; i < bin.childNodes.length; i++) {
		if (bin.childNodes[i].nodeType == 3) {
			bin.removeChild(bin.childNodes[i]);
		}
	}
}

/*-------------------------------------------------+
 | move: Move element up or down in swapping range |
 +-------------------------------------------------*/
function move() {
	// Set vars for button, direction, bin, current, above, below row
	var item = this;
	var dir = item.className;
	var trunkID = "swap"
	
	// Find trunk
	var trunk = item.parentNode
	while (trunk.id != trunkID) { trunk = trunk.parentNode }
	
	// Find current position
	var posCur = item;
	while (posCur.parentNode.id != trunkID) { posCur = posCur.parentNode }
	
	var posUp = posCur.previousSibling;
	var posDown = posCur.nextSibling;
	var posNew;
	
	//alert("UP: " + posUp + "\nCUR: " + posCur + "\nDOWN: " + posDown);
	
	// Set new target position
	if (dir == "up" && posUp) {
		posNew = posUp;
	} else if (dir == "down" && posDown) {
		posNew = posCur;
		posCur = posDown;
	}
	
	// Swap positions only if both are active and current position is not top or bottom
	if (posNew != undefined) {
		// Swap
		trunk.insertBefore(posCur, posNew);
		
		updateOrder();
	}
	return false;
}

/*-----------------------------------+
 | updateOrder: Update swapped order |
 +-----------------------------------*/
function updateOrder() {
	// Get new order
	var newOrder = Sortable.serialize("swap");
	newOrder = newOrder.replace(/swap\[\]=/g, "")
	newOrder = newOrder.split("&");
	
	// Update sequence value
	document.getElementById("sequence").value = newOrder	
}


/*--------------------------------------+
 | addCalendars: enable calendar picker |
 +--------------------------------------*/
function addCalendars() {
	var pickers = document.getElementsByTagName("span");
	
	for (var i = 0; i < pickers.length; i++) {
		if (pickers[i].className.indexOf("date-picker") > -1) {
			// Create anchor to open calendar picker when clicked
			var anchor = document.createElement("a");
			anchor.href = "#";
			anchor.onclick = function () {
				// Separate vars (based on class names...first one is "date-picker")
				var fields = this.parentNode.className.split(" ");
				var y = fields[1];
				var m = fields[2];
				var d = fields[3];
				
				// Open new window in center of screen
				var posX = (screen.height - 200) / 2;
				var posY = (screen.width - 200) / 2;
				remote = window.open("/source/date-picker.asp?y=" + y + "&m=" + m + "&d=" + d, "", "scrollbars=yes,height=250,width=250,resizable=yes,left=" + posY + ",top=" + posX);
				remote.focus();
			}
			
			// Create calendar icon
			var cal = document.createElement("img");
			cal.alt = "Pick date from calendar"
			cal.src = "/images/icon-calendar.gif";
			cal.title = cal.alt
			
			// Wrap icon with anchor
			anchor.appendChild(cal);
			
			// Insert anchor & icon into page
			pickers[i].appendChild(anchor);
		}
	}
}


/*-------------------------------------------------------------+
 | addSetDates: Set date of parent window from calendar pop-up |
 +-------------------------------------------------------------*/
function addSetDates() {
	var cal = document.getElementById("cal");
	
	if (!cal) return false;
	
	// Get vars from query string (year, month, day)
	var query = window.location.search.substring(1);
	var vars = query.split("&");
	var dateFields = new Array;
	
	// Find fields in parent window
	for (var i = 0; i < vars.length; i++) {
		var pair = vars[i].split("=");
		if (window.opener)
			dateFields[i] = window.opener.document.getElementById(pair[1]);
	}
	
	// Get all anchors
	var links = document.getElementsByTagName("a");
	for (var i = 0; i < links.length; i++) {
		// Only work with anchors having date for ID
		if (/^\d*-\d*-\d*$/.test(links[i].id)) {
			links[i].onclick = function () {
				// Get parts of date
				dateParts = this.id.split("-");
				
				// Set appropriate option element in parent window to "selected"
				for (var j = 0; j < dateParts.length; j++) {
					//alert(dateFields[j].id);
					for (var k = 0; k < dateFields[j].length; k++) {
						//alert(dateFields[j].id + ": " + dateFields[j][k].value + " == " + dateParts[j]);
						dateFields[j][k].selected = false;
						if (dateFields[j][k].value == dateParts[j]) {
							dateFields[j][k].selected = true;
							var found = true;
						}
					}
					
					// If year chosen doesn't exist, create the option for it
					if (!found) {
						// Create new option / text node
						var newOpt = window.opener.document.createElement("option");
						newOpt.value = dateParts[j];
						newOpt.selected = "selected";
						var newTxt = window.opener.document.createTextNode(dateParts[j]);
						newOpt.appendChild(newTxt);
						
						// Insert new option in the appropriate numerical order
						var inserted = false;
						for (var k = 0; k < dateFields[j].length; k++) {
							if (parseInt(dateFields[j][k].value) > parseInt(dateParts[j])) {
								dateFields[j].insertBefore(newOpt, dateFields[j][k]);
								inserted = true;
								break;
							}
						}
						
						// Couldn't find a spot to insert. Append at the end
						if (!inserted) {
							alert("Inserting " + newOpt.value + " at the end...")
							dateFields[j].appendChild(newOpt);
						}
					}
				}
				
				window.close();
			}
		}
	}
}