// ************************************************************************<BR>
// DHTML functions for Miscellaneous uses.								   <BR>
// ************************************************************************<BR>
// <SCRIPT>

// Gets a param's value from within the given URL
function GetURLParam(url, param)
{
	if (url == "" || param == "")
		return "";
	
	// Find "param="	
	var pos = url.search("[?&]" + param + "=")
	if (pos < 0)
		return "";
		
	// Get the start and end positions
	var start = pos + param.length + 2;
	var end = url.indexOf("&", start)	
	if (end < 0)
	{
		end = url.indexOf("#", start)
		if (end < 0)
			end = url.length;
	}
	
	return unescape(url.substring(start, end));
}

// Adds "param=value" to the given URL.
function SetURLParam(url, param, value)
{
	if (url == "" || param == "")
		return url;

	// Find any existing "param=" occurrence
	var start = url.search("[?&]" + param + "=") + 1;
	if (start > 0)
	{
		// Go to the next item
		var end = url.indexOf("&", start) + 1;
		if (end == 0)
		{
			// If there were no more items, check if there's an anchor
			end = url.indexOf("#", start) + 1;
			if (end == 0)
				end = url.length;
		}
			
		// Remove the existing entry
		url = url.substr(0, start) + url.substr(end)		
	}

	// If the value is empty, return the current URL
	value = escape(value);
	if (value == "")
		return url;
	
	// Check if there's a "backURL=" and if so take it out (temporarily) so we can place it at the end
	var backURL = "";
	var backURLPos = url.indexOf("backURL=");
	if (backURLPos >= 0)
	{
		backURL = "&" + url.substr(backURLPos);
		url = url.substr(0, backURLPos);
	}

	// Check if there's an anchor (at the end) and if so take it out (temporarily)
	var anchor = "";
	var anchorPos = url.lastIndexOf("#");
	if (anchorPos >= 0)
	{
		anchor = url.substr(anchorPos);
		url = url.substr(0, anchorPos);
	}
			
	// Append ? to the URL if necessary
	if (url.indexOf("?") < 0)
		url += "?";
	else
	{
		// Add the trailing & (if necessary)
		var c = url.charAt(url.length - 1);
		if (c != "?" && c != "&")
			url += "&";
	}
	
	// Append the field, value, backURL, and anchor (if any)
	url += param + "=" + value + backURL + anchor;
	return url;
}

// Sets the given cookie's value (and makes it expire a year from now)
function SetCookie(cookieName, value) 
{
	var dateExp = new Date;
	dateExp.setTime(dateExp.getTime() + 365 * 24 * 60 * 60 * 1000);  // 1 year from now	

	document.cookie = cookieName + "=" + escape(value) + ";expires=" + dateExp.toGMTString() + ";";
}

// Retrieves the given cookie's value.  If it doesn't exist, it returns null.
function GetCookie(cookieName) 
{
	// Cookies are separated by semicolons
	var cookies = document.cookie.split(";");
	for (var i = 0; i < cookies.length; i++)
	{
		// A cookie's name/value pair is separated by an equal sign
		var cookie = cookies[i].split("=");
		if (cookieName == cookie[0]) 
			return unescape(cookie[1]);
	}
	
	return null;
}

// Deletes the given cookie (if it exists)
function DeleteCookie(cookieName) 
{
	if (GetCookie(cookieName)) 
		document.cookie = cookieName + "=; expires=Thu, 01-Jan-70 00:00:01 GMT;";
}

// Column Sorter object
function ColumnSorter(listName, previousSortBy, previousSortOrder)
{
	// Initialize the values relating to column sorting
	this.listName = listName;
	this.previousSortBy = previousSortBy;
	this.previousSortOrder = previousSortOrder;
}
	
// Reload the current page so that the given column(s) appear sorted (ascending or descending)
ColumnSorter.prototype.sortBy = function(columns)
{
	// If we were previously sorting ascending, sort descending (if it's the same column)
	if (this.previousSortBy == columns)
		this.previousSortOrder = (this.previousSortOrder == 'ASC' ? 'DESC' : 'ASC');
	else
		this.previousSortOrder = 'ASC';

	this.previousSortBy = columns;
	
	// Check if there's a form containing hidden fields with the proper names
	for (var i = 0; i < document.forms.length; i++)
	{
		var sortBy = document.forms[i][this.listName + "_sortBy"];
		var sortOrder = document.forms[i][this.listName + "_sortOrder"];
		if (sortBy && sortOrder)
		{
			sortBy.value = columns;
			sortOrder.value = this.previousSortOrder;
			
			document.forms[i].submit();
			return;
		}
	}
	
	var link = location.href
	link = SetURLParam(link, this.listName + "_sortBy", columns);
	link = SetURLParam(link, this.listName + "_sortOrder", this.previousSortOrder);
	
	// If using Netscape, generate a random number for the URL.  This ensure the page is refrehed.
	if (!document.all)
		link = SetURLParam(link, this.listName + "_sortID", Math.random());

	// Refresh this page with a different set of sortBy and sortOrder parameters
	location.replace(link);
}

// OptionHolder object
function OptionHolder(element)
{
	// Initialize the values relating to column sorting
	this.element = element;
	this.selected = 0;

	// Keep track of the index of the selected option in case the user picks a blank option
	for (var i = 0; i < element.options.length; i++)
	{
		if (element.options[i].selected)
		{
			this.selected = i;
			return;
		}
	}
}

// Ensures the user changed to a valid option, otherwise the option that
// was selected when the object was created is selected again.
OptionHolder.prototype.validateChange = function(submitIfValid)
{
	// If the user picked a blank option, select the original one
	if (GetSelectedValue(this.element) == "")
	{
		this.element.options[this.selected].selected = true;
		return false;
	}

	if (submitIfValid == true)
		return document.form.submit();
	return true;
}

// Returns a string containing the properties for the given object
function GetObjectProperties(obj)
{
	var properties = "";	
	objectName = obj + "";
	
	for (prop in obj)
		properties += (objectName + "." + prop + " = " + obj[prop] + "<br>\n");
	
	return properties;
}	

// Runs up the hierarchy of windows and searches for the given frame name.
function FindFrame(strFrameName)
{
	var frame = null;
	
	// Loop through every parent (padre) until the top is reached or we find the frame.
	for (var padre = parent; padre && !frame; padre = padre.parent)
	{
		for (var iFrame = 0; iFrame < padre.frames.length; iFrame++)
		{
			if (padre.frames(iFrame).name == strFrameName)
			{
				frame = padre.frames(iFrame);
				break;
			}
		}
			
		// If we reached the top, break out
		if (padre == top)
			break;
	}
	
	return frame;
}

// Returns the option currently selected for the given element.
function GetSelectedOption(element)
{
	if (element.options)
	{
		for (var i = 0; i < element.options.length; i++)
		{
			if (element.options[i].selected)
				return element.options[i];
		}
	}
	return null;
}	

// Returns the value of the option currently selected for the given element.
function GetSelectedValue(element)
{
	var option = GetSelectedOption(element);
	return (option == null ? "" : option.value);
}

// Removes all the options from the given drop-down.
function RemoveOptions(element)
{
	while (element.options.length > 0)
        element.options[0] = null;
}

// Parses the given HTML text filled with option tags and repopulates
// the given drop-down element with them.
function ReplaceOptions(element, optionsHTML)
{
	RemoveOptions(element);

	// Create an array of each item for the dropdown
	var options = optionsHTML.split("</option>");
    var selectIndex = 0;

	// Fill 'er up
	for (var i = 0; i < options.length - 1; i++)
	{
	    aValueText = options[i].split(">");

	    option = new Option;
	    option.text = aValueText[1];

	    // Extract the value
	    var firstQuote = aValueText[0].indexOf("'");
	    var lastQuote = aValueText[0].lastIndexOf("'");
	    if (firstQuote > 0 && lastQuote > firstQuote + 1)
	        option.value = aValueText[0].substring(firstQuote + 1, lastQuote);

	    // Check if it's selected
	    if (aValueText[0].indexOf('selected') > 0)
	        selectIndex = i;

	    element.options[element.options.length] = option;
	}

	element.options[selectIndex].selected = true;
}

// Finds a control by its id and returns its object.
function FindControl(id, doc) 
{ 
	var p, i, x;  
	if (!doc) 
		doc = document; 
	if ((p = id.indexOf("?")) > 0 && parent.frames.length) 
	{
		doc = parent.frames[id.substring(p + 1)].document; 
		id = id.substring(0, p);
	}
	if(!(x = doc[id]) && doc.all) 
		x = doc.all[id]; 
	for (i = 0; !x && i < doc.forms.length; i++) 
		x = doc.forms[i][id];
	for (i = 0; !x && doc.layers && i < doc.layers.length; i++) 
		x = findObj(id, doc.layers[i].document);
	if (!x && doc.getElementById) 
		x = doc.getElementById(id); 
	if (!x && doc.getElementsByName && doc.getElementsByName(id))
		x = doc.getElementsByName(id)[0]; 
	return x;
}

// Handler for the onkeypress event used to associate a text control to a button so that when the
// Enter key is pressed on the textbox, the button is clicked.  This is useful for forms with multiple
// submit buttons.
function onEnterKeyPressClickButton(textControl, event, buttonID)
{
	// Only worry about the Enter key
	if (!((event.keyCode && event.keyCode == 13) || (event.which && event.which == 13)))
		return true;
		
	var buttonToClick = FindControl(buttonID);
	if (buttonToClick)
	{			
		// Add two extra handlers in case the user presses Enter while the AutoComplete dropdown is visible on the IE browser.
		textControl.onkeyup = function() { if (window.buttonToClick && window.buttonToClick.click) window.buttonToClick.click(); };
		textControl.onpropertychange = function() { if (window.buttonToClick) window.buttonToClick = null; };
		window.buttonToClick = buttonToClick;
	}		
	else
		textControl.title = "Error: Button control '" + buttonID + "' does not exist!";
	return false;
}

// Handler for the onkeypress event used to associate a text control to another text control so that when the
// Enter key is pressed on the first textbox, the second one gains focus.
function onEnterKeyPressChangeFocus(textControl, event, textID)
{
	// Only worry about the Enter key
	if (!((event.keyCode && event.keyCode == 13) || (event.which && event.which == 13)))
		return true;
		
	var textBoxToFocus = FindControl(textID);
	if (textBoxToFocus)
		textBoxToFocus.focus();
	else
		textControl.title = "Error: TextBox control '" + textID + "' does not exist!";
	return false;
}
