// Ampco Javascript - Common Functions

// Author: Mike Sollanych
// Version: 3


// Clear the contents of a text field.
function clearContents(text_field) {
	text_field.value = "";
}

// Select the contents of a text field
function selectContents(text_field) {
	text_field.select();
}

// Go back in the browser window.
function goBack() {
	history.go(-1);
}

// Get Label for Element
// Returns false if no label is found.
function getLabelForElement (element_id) {
	var labels = document.getElementsByTagName("label");
	for (i=0;i<labels.length;i++) {
			
		var thisId = labels[i].getAttribute("for");
		
		if (thisId == element_id) {
			
			var labelcnodes = labels[i].childNodes;
			
			var label;
			
			for(var j = 0; j < labelcnodes.length; j++) {
				var curcnode = labelcnodes[j];
				
				// Only if it's got an undefined tagName, i.e. a text node, do we put it in the label.
				if (!curcnode.tagName) {
					var test = curcnode.nodeValue + "";
					if (trim(test.toLowerCase()) != "undefined") {
						label = (curcnode.nodeValue + " ");
					}
				}
			}
			
			return trim(label);
		}
	}
	
	return false;
}

// Trim
function trim(string) {
	return string.replace(/^\s+|\s+$/g, '');
}


// Return an XMLHttpRequest object for compliant browsers; we conveniently provide one when done
function getHTTPObject() { 
	var xmlhttp; 
	
	if (!xmlhttp && typeof XMLHttpRequest != 'undefined') { 
		try { 
			xmlhttp = new XMLHttpRequest(); 
		} 
		catch (e) { 
			xmlhttp = false; 
		} 
	} 
	
	return xmlhttp; 	
}	
var http = getHTTPObject();


// Cookie Codes stolen shamelessly from http://www.quirksmode.org/js/cookies.html
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=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++)
	{
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}

function URLencode(sStr) {
    return escape(sStr).
             replace(/\+/g, '%2B').
                replace(/\"/g,'%22').
                   replace(/\'/g, '%27').
                      replace(/\//g,'%2F');
}