﻿// UI.js
// extends DOM/UI functionality with additional helper methods

// common Util object; include this line in each library class
var Util = Util ? Util : {};
Util.UI = {};


// CreateElementWithText
//
// Description
// creates a DOM Element of the specified name and sets it's textual content
//
// Args
// name [string] : the name of the DOM Element to create ("P", "DIV", etc.)
// text [string] (optional) : the textual content of the element

Util.UI.CreateElementWithText = function(name, text)
{
  text = text || "";
  var elem = document.createElement(name);
  elem.appendChild(document.createTextNode(text));
  return elem;
};

Util.UI.GetSrcElement = function(e)
{
	var src;
	e = e || window.event;

	if (e.target) src = e.target;
	else if (e.srcElement) src = e.srcElement;
	
	if (src.nodeType == 3) // defeat Safari bug
		src = src.parentNode;
	
	return src;
};


// FindPositionX
//
// Description
// returns the x coordinate for an element
//
// Args
// e [object] : the object for discovering an X coordinate
Util.UI.FindPositionX = function(obj)
{
	
	var curleft = 0;
	if (obj.offsetParent)
	{
		while (obj.offsetParent)
		{
			curleft += obj.offsetLeft
			obj = obj.offsetParent;
		}
	}
	else if (obj.x)
		curleft += obj.x;
	return curleft;
}

// FindPositionY
//
// Description
// returns the y coordinate for an element
//
// Args
// e [object] : the object for discovering an Y coordinate
Util.UI.FindPositionY = function(obj)
{
	var curtop = 0;
	if (obj.offsetParent)
	{
		while (obj.offsetParent)
		{
			curtop += obj.offsetTop
			obj = obj.offsetParent;
		}
	}
	else if (obj.y)
		curtop += obj.y;
	return curtop;
}

	
// CopyContents
//
// Description
// Perfroms a deep clone for all child objects of objTemplateSource

Util.UI.CopyContents = function(objDest, objTemplateSource)
{
	for (var i=0; i<objTemplateSource.childNodes.length; i++)
			objDest.appendChild(objTemplateSource.childNodes[i].cloneNode(true));
}

// OnEnterKeyPress
//
// Description
// When the enter key is pressed on this element execute function actionPointer
Util.UI.OnEnterKeyPress = function(keyEvent, actionPointer)
{
	var key = false;
	var result = true;

	if(keyEvent.keyCode)
		key = keyEvent.keyCode;

	if(key == 13)
	{
		actionPointer();
		result = false;
	}
	
	return result;
}

// Hide
//
// Description
// Hide an element. Handles invalid ids silently.
Util.UI.Hide = function(id)
{
	var el = document.getElementById(id);				
	if (el)
		el.style.display = "none";
}

// Show
//
// Description
// Show an element. Handles invalid ids silently.
Util.UI.Show = function(id)
{
	var el = document.getElementById(id);				
	if (el)
		el.style.display = "";
}