// Cookies.lib.js
// Loaded by the echoHTMLHead php function.
function createCookie(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=/";
}

// readCookie
// Returns the data part of the requested named cookie from the document cookie string.
function readCookie(name) {
	var nameEQ = name + "=";
	// Make an array of all the cookies that are set for this domain and path
	// by splitting the document cookie on semi-colons.
	var cookieArray = document.cookie.split(';');
	// Go through all the cookies
	for(var i=0;i < cookieArray.length;i++) {
		var candidate = cookieArray[i];
		// Strip leading space of the current candidate
		while (candidate.charAt(0)==' ') candidate = candidate.substring(1, candidate.length);
		// If it's the one we are looking for, return it without its name.
		if (candidate.indexOf(nameEQ) == 0) return candidate.substring(nameEQ.length, candidate.length);
	}
	return null;
}

// cookieToForm
// Used (2010-06-11) to read cookie values into calculators including Manning Pipe Flow
function cookieToForm (cookieName, form) {
	var 
	cookie = readCookie(cookieName),
	cookieVars,
	cookieVarsLength,
	inputCounter = -1,
	selectCounter = -1,
	cookieVarSplit;
	if (cookie) {
		cookieVars = cookie.split(",");
		cookieVarsLength = cookieVars.length;
		for (var i = 0; i < cookieVarsLength; i++) {
			cookieVarSplit = cookieVars[i].split(":");
			switch (cookieVarSplit[0]) {
			case 'i':
				inputCounter++;
				form.getElementsByTagName("INPUT")[inputCounter].value = cookieVarSplit[1];
				break;
			case 's':
				selectCounter++;
				form.getElementsByTagName("SELECT")[selectCounter].value = cookieVarSplit[1];
				break;
			}
		}
	}
	return cookie;
}

function formToCookie (form, cookieName) {
	var 
	cookie = "",
	formElementsLength = form.elements.length,
	element;
	for (var i = 0; i < formElementsLength; i++) {
		element = form.elements[i]
		switch(element.tagName) {
		case 'INPUT':
			if (element.type == "text") {
				cookie += ',' + 'i:' + element.value;
			}
			break;
		case 'SELECT':
			cookie += ',' + 's:' + element.value;
			break;
		}
	}
	createCookie(cookieName, cookie.substring(1), 36000);
}
