// Ampco E-Docket Javascript - Common Functions

// Author: Mike Sollanych
// Version: 0.1


// Options:
// var continueTimeout = 10;


// Functions:

// 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();
}

// Check if a variable is defined
function isDefined(variable) {
	return (typeof(window[variable]) == "undefined")?  false : true;
}

// Go back in the browser window.
function goBack() {
	history.go(-1);
}

// Try the continue form on page load, if possible.
// This is always called when a page loads.
function tryContinue() {
	if (document.getElementById("continue_nonauto")) {
		// No need then...
		return;
	}
	else { 
		if (document.getElementById("continue_form")) {
			document.getElementById('continue_form').submit();
		}
	}
	
}

// DecrementTimeoutDisplay will decrement the timeout form
// This is more of a cosmetic feature so the user knows it will auto continue
function decrementTimeoutDisplay() {
	
	if (document.getElementById("continue_form")) {
		// Decrement the time remaining by one second
		continueTimeout -= 1000;
	
		// Put that into seconds
		var continueSeconds = continueTimeout / 1000;

		// update the display	
		document.getElementById("continue_form").continue_timeout.value = "Automatically continuing in " + continueSeconds + " seconds...";
	}
}

// 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, '');
}

// Toggle Box Visibility by Id
function toggleDivById(div_id) {
	
	var div = document.getElementById(div_id);
	if (!div) {
		alert ("Could not toggle " + div_id);
		return false;
	}
	
	if (div.style.display == "block") {
		// It is showing right now.
		Effect.BlindUp(div);
	}
	else {
		// It is hidden right now.
		div.style.display = "block";
	}

	// document.getElementById("debug_output").innerHTML = "<pre> " + print_r(div.style) + "</pre>";
	// current_style.display = current_style.display? "":"block";
	return true;
}

// Confirm Deletion
function confirmDelete(mode, id) {
	var confirmation = confirm("Are you sure you wish to delete this " + mode + " object? This action cannot be undone.");
	
	if (confirmation) {
		window.location="delete.php?mode=" + mode + "&id=" + id;
	}
}			

// Advanced Confirm Deletion
function advConfirmDelete(english, url, custom_msg) {
	
	message = "Are you sure you wish to delete this " + english + "? This action cannot be undone.";

	if (custom_msg.length > 0) message += "\n" + custom_msg;
	
	var confirmation = confirm(message);
	
	if (confirmation) {
		window.location = url;
	}
}

// Return an XMLHttpRequest object for compliant browsers; we conveniently provide one when done
function getHTTPObject() { 
	alert ("WARNING: Deprecated function in use!");
	return false;
}

/*
	var xmlhttp; 
	
	if (!xmlhttp && typeof XMLHttpRequest != 'undefined') { 
		try {
			xmlhttp = new XMLHttpRequest(); 
		} 
		catch (e) { 
			alert ("Warning: unable to create XMLHTTPRequest!");
			xmlhttp = false; 
		} 
	} 
	
	return xmlhttp; 	
}	*/

// 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 insertAtCursor(myField, myValue) {
	//IE support
	if (document.selection) {
		myField.focus();
		sel = document.selection.createRange();
		sel.text = myValue;
	}
	//MOZILLA/NETSCAPE support
	else if (myField.selectionStart || myField.selectionStart == '0') {
		var startPos = myField.selectionStart;
		var endPos = myField.selectionEnd;
		myField.value = myField.value.substring(0, startPos) + myValue + myField.value.substring(endPos, myField.value.length);
	} 
	else {
		myField.value += myValue;
	}
}
		
function insertTimeStamp(field_id) {
	var field = document.getElementById(field_id);
	
	var now = new Date();
	insertAtCursor(field, now);
}

// Emulated sleep function
function pause(numberMillis) {
	var now = new Date();
	var exitTime = now.getTime() + numberMillis;
	
	while (true) {
		now = new Date();
		if (now.getTime() > exitTime) {
			return;
		}
	}
}

function toggleRowHilight(row) {
	if (row.className.length < 1) row.className = "hilight";
	else row.className = "";
}



function URLencode(sStr) {
    return escape(sStr).
             replace(/\+/g, '%2B').
                replace(/\"/g,'%22').
                   replace(/\'/g, '%27').
                      replace(/\//g,'%2F');
}

function nl2br(text) {
	text = escape(text);
	return unescape(text.replace(/(%5Cr%5Cn)|(%5Cn%5Cr)|%5Cr|%5Cn/g,'<br />'));
}

function toggleFieldset(fieldset_id, checkbox, do_inverse) {
	
	if (!checkbox) var checked = false;
	else var checked = checkbox.checked;
	
	if (do_inverse) checked = !checked;
	
	// Get all the dis/enableable elements in the fieldset.
	var fieldset = document.getElementById(fieldset_id);
	
	if (!fieldset) {
		alert ("Could not toggle the field set - ID not set correctly.");
		return false;
	}
	
	var children = fieldset.childNodes;
	
	for(var i = 0; i < children.length; i++) {
		
		var thischild = children[i];
		var tagname = thischild.tagName;
		
		if (!tagname) continue;
		
		tagname = tagname.toLowerCase();
		
		switch (tagname) {
			case 'input':
			case 'select':
			case 'textarea':
				thischild.disabled = !checked;
			break;
			
			case 'legend':
				if (!checked) thischild.className = 'disabled';
				else thischild.className = '';
			break;
		}
	}
	
	return true;
}

function toggleInput(element_id, checkbox, do_inverse) {
	
	// Figure out whether we're enabling or disabling the element
	var checked = (!checkbox) ? false : checkbox.checked;
	if (do_inverse) checked = !checked;
	
	// Get element and change
	var element = $(element_id);
	element.disabled = checked;
	
	return true;
}


function clearSelectBox(select_box_id) {
	
	var select_box = document.getElementById(select_box_id);
	
	if (!select_box) return false;
					
	while (select_box.childNodes[0]) {
	    select_box.removeChild(select_box.childNodes[0]);
	}
	
	return true;
}

function print_r(input, _indent) {
	if(typeof(_indent) == 'string') {
		var indent = _indent + ' ';
		var paren_indent = _indent + ' ';
	} else {
		var indent = ' ';
		var paren_indent = '';
	}
	
	switch(typeof(input)) {
		case 'boolean':
			var output = (input ? 'true' : 'false') + "\n";
		break;
		case 'object':
			if ( input===null ) {
				var output = "null\n";
				break;
			}
	
			var output = ((input.reverse) ? 'Array' : 'Object') + " (\n";
			
			for(var i in input) {
				output += indent + "[" + i + "] => " + print_r(input[i], indent);
			}
			
			output += paren_indent + ")\n";
		break;
		case 'number':
		case 'string':
		default:
			var output = "" + input + "\n";
	}
	
	return output;
}

function popupBox(box_title, inner_content, id) {
	// Creates a popup box with close button. Can't be dragged yet, but maybe one day.
	
	var popupdiv = document.createElement("div");
	popupdiv.className = "box_popup";
	popupdiv.id = "popup_box_" + id;
	
	var titlediv = document.createElement("div");
	titlediv.className = "box_title";
	titlediv.appendChild(document.createTextNode(box_title));
	
	popupdiv.appendChild(titlediv);
	
	var contentdiv = document.createElement("p");
	contentdiv.innerHTML = inner_content; // DONT FROWN ON ME!!
	popupdiv.appendChild(contentdiv);
	
	var document_body = document.getElementById("body_element");
	document_body.appendChild(popupdiv);
	
	var controls = document.createElement("div");
	controls.className = "controls"
	popupdiv.appendChild(controls);
	
	var closebutton = document.createElement("a");
	closebutton.onclick = function() { destroyElement(popupdiv.id); }
	closebutton.appendChild(document.createTextNode("Close..."));
	controls.appendChild(closebutton);
}

function destroyElement(element_id) {
	// Removes an element and all its children from the dom tree
	
	thiselement = document.getElementById(element_id);
	
	if (!thiselement) return false;
	
	thiselement.parentNode.removeChild(thiselement);
	
	return true;
}

function changeTabOrder(fieldset_ids, tabindex_base) {
	// Changes the tab order of a group of (fieldsets, or whatever) 
	// to be in the order the fieldset element id names are specified.
	
	// tabindex_base is a number base used for the tab index. Give it a decently high, nonconflicting number.
	
	var mytabindex = tabindex_base + 1;

	for (var i = 0; i < fieldset_ids.length; i++) {
	
		// get the current fieldset
		var thisfs = document.getElementById(fieldset_ids[i]);
		
		if (!thisfs) continue;
		
		// Get input elements for this fieldset
		var children = thisfs.getElementsByTagName("*");
		
		if (children.length < 1) continue;
		
		for (var j = 0; j < children.length; j++) {
			// alert (children[j].tagName);
			
			if ((children[j].tagName.toLowerCase() == "input") || (children[j].tagName.toLowerCase() == "select") || (children[j].tagName.toLowerCase() == "textarea")) {
				children[j].tabIndex = mytabindex;
			}
			
			mytabindex++;
		}
	}
}

// POPUP WINDOW FUNCTIONS
function openChild(url, windowname, width, height) {
	var childWindow = open (url, windowname, 'toolbar=no,scrollbars=yes,menubar=no,width='+width+',height='+height);
	if (childWindow.opener == null) childWindow.opener = self;
	
	return childWindow;
}

function updateParent(assignArray, appendMode, appendSeperator) {
	for (var i in assignArray) {
		var target = opener.document.getElementById(i);
		var input = assignArray[i];
		
		if (appendMode && target.value.length > 0) target.value += appendSeperator + input;
		else target.value = input;
	}
	
    self.close();
    return false;
}

function refreshParent(closeme) {
	opener.location.reload();
	
	if (closeme) self.close();
	return true;
}

// ISO datetime function from http://www.java-scripts.net/javascripts/ISO-Date.phtml
function getisodatetime() {
	var today = new Date();
	var year  = today.getYear();
	if (year < 2000)    // Y2K Fix
		year = year + 1900;
		
	var month = today.getMonth() + 1;
	var day  = today.getDate();
	var hour = today.getHours();
	var minute = today.getMinutes();
	var second = today.getSeconds();
	
	
	if (month <= 9) month = "0" + month;
	if (day <= 9) day = "0" + day;
	if (hour <= 9) hour = "0" + hour;
	if (minute <= 9) minute = "0" + minute;
	if (second <= 9) second = "0" + second;
	datetime = year + "-" + month + "-" + day + " "	+ hour + ":" + minute + ":" + second;
	
	return datetime;
}