//CUBE UI Component Common API JavaScript

//Global variable definition
var TmCube_BrowserType = "";
var TmCube_Href = null;


//Function definition
/**
 * Get Browser type.
 * @Return  One of the list below.
 *             IE - Internet Explorer
 *             NS - NetScape
 *             Unknown - Unknown browser
 */
function TmCube_getBrowserType()
{
    if (!TmCube_BrowserType)
    {
        if (navigator.appName.toUpperCase().match(/MICROSOFT INTERNET EXPLORER/) != null)
        {
            TmCube_BrowserType = "IE";
        }
        else if(navigator.appName.toUpperCase().match(/NETSCAPE/) != null)
        {
            TmCube_BrowserType = "NS";
        }
        else
        {
            TmCube_BrowserType = "Unknown";
        }
    }
    return TmCube_BrowserType;
}

/**
 * Get target form control element of a event object.
 * @param event Event object, This object should pass from event handler
 * @return The target control. 
 */
function TmCube_getTarget(event)
{
    switch (TmCube_getBrowserType())
    {
    case "IE":
        return event.srcElement;
    case "NS":
        return event.target;
    default:
        return null;
    }
}

/**
 * Get component object by its sub control. If the control has no id attribute, check its ancestor nodes to find out id.
 * Then get the object with the eval funtion.
 * @param target A sub control of the component, typically retrieve from TmCube_getTarget function.
 * @return The component object which is generated by ui conversion (Menu : CUBE Component/Convert to CCGI PAGE).
 */
function TmCube_getComponent(target)
{
    for (;target && !target.id;target = target.parentNode);
    if (!target)
    {
        return null;
    }
    var controlId = target.id;
    if (controlId)
    {
        var index = controlId.indexOf("__");
        if (index != -1)
        {
            return eval("TmCube_" + controlId.slice(0, index));
        }
    }
    return null;
}

/**
 * Get component object by prefix.
 * Then get the object with the eval funtion.
 * @param prefix The prefix Strip from compnent inner control's id.
 * @return The component object which is generated by ui conversion (Menu : CUBE Component/Convert to CCGI PAGE).
 */
function TmCube_getComponentByPrefix(prefix)
{
    return eval("TmCube_" + prefix);
}

/**
 * Get component prefix by its sub control.
 * @param target A sub control of the component, typically retrieve from TmCube_getTarget function.
 * @return The component object which is generated by ui conversion (Menu : CUBE Component/Convert to CCGI PAGE).
 */
function TmCube_getPrefix(target)
{
    var controlId = target.id;
    if (controlId)
    {
        var index = controlId.indexOf("__");
        if (index != -1)
        {
            return controlId.slice(0, index);
        }
    }
    return null;
}
/**
 * Get real id of a sub control inner UI comopnent.The original id was changed by ui conversion.
 * In the javascript of UI comopnent, control id should not be hard code. This function is
 * to help retrieve the id.
 * @param control A control in the same component, return from TmCube_getTarget() function.
 * @param id The original id of the control
 * @return The real id represent the control.
 */
function TmCube_getRelativeID(control,  id)
{
    var controlId = control.getAttribute("id");
    if (controlId)
    {
        var index = controlId.indexOf("__");
        if (index != -1)
        {
            id = controlId.slice(0, index) + "__" + id;
        }
    }
    else
    {
        alert("no control id");
    }
    return id;
}

/**
 * Get original id of a element inner component.
 * @param target Element inner component, who must have id defined.
 * @return original id.
 */
function TmCube_getControlName(target)
{
    var controlId = target.id;
    if (controlId)
    {
        var index = controlId.indexOf("__");
        if (index != -1)
        {
            return controlId.slice(index + 2);
        }
    }
    return null;
}

/**
 * Get element with prefix and original id.
 * @param prefix Prefix of a component instance. may be it's name or type.
 * @return The element.
 */
 function TmCube_getElement(prefix, id)
 {
     return document.getElementById(prefix + "__" + id);
 }

/**
 * This function will be called on load time. It's always append to body "onload" attribute.
 */
function TmCube_uiInitial()
{
	alert(uicompList);
    if (uicompList)
    {
        for(var i=0; i<uicompList.length; i++)
        {
            if (uicompList[i].onload)
            {
                uicompList[i].onload();
            }
        }
    }
}

/**
 * This function is to disable a set of control objects. 
 * @param ... variable arguments. Each one is a instance of form control in the page.
 */
function TmCube_disable()
{
    for (var i=0; i<arguments.length; i++)
    {
        arguments[i].disabled = true;
    }
}

/**
 * This function is to enable a set of control objects. 
 * @param ... variable arguments. Each one is a instance of form control in the page.
 */
function TmCube_enable()
{
    for (var i=0; i<arguments.length; i++)
    {
        arguments[i].disabled = false;
    }
}

/**
 * To determine a key event is a input evnt. It will be treated as a input event that  user press any key except alt, control.
 * Pressing "ctrl + v" is also a input event.
 */
function TmCube_isInputting(evt)
{									  
    if (evt.altKey || (evt.ctrlKey && evt.keyCode != 86))
    {
        return false;
    }
    return true;
}

/**
 * Set a relation of two controls. if the objDepended is disabled, or un-checked. srcObj is disabled.
 */
function TmCube_setUIDependent(srcObj, objDepended)
{									  
    if (objDepended && srcObj)
    {
        if (objDepended.disabled) 
            srcObj.disabled = true;
        else 
            if (objDepended.checked) 
                srcObj.disabled = false;
            else 
                srcObj.disabled = true;
    }
}

/**
 * Check whether string "str" is a valid email address containing "@" and
 * other legal characters.
 */
function TmCube_checkEmailAddress(str)
{
    var at = -1;
    for (var i=0; i<str.length; i++)
    {
        var c = str.charAt(i);
        if("@"==c)
            at = i;
    }
    if((-1==at)||(0==at)||(str.length-1==at))
        return false;
    else
        return (TmCube_checkHostName(str.slice(at+1)));
}
/**
 * Check whether string "str" is a hostname composed of legal characters.
 */
function TmCube_checkHostName(str)
{
    for (var i=0; i<str.length; i++)
    {
        var c = str.charAt(i);
        if((c!=".")&&(c!="-")&&((c<"0")||(c>"9"))
            &&((c<"A")||(c>"Z"))&&((c<"a")||(c>"z")))
            return false;
    }
    return true;
}

/**
 * This function removes the leading and ending space(' '), tab('\t') or carriage 
 * return('\n') of str. If the input string is null, return value is also null.
 * @param s input string.
 * @return the stripped string.
 */
function TmCube_trimString(s)
{
  if (s)
  {
    return s.replace(/^\s*/, '').replace(/\s*$/, '');
  }
  return s;
}

/**
 * Convert url to suit environment. 
 * @param url The source url of the original.
 * @return new url that environment  relatived.
 */
function TmCube_getNormalURL(url)
{
    if (TmCube_Href)
    {
        return TmCube_Href.getNormalURL(url);
    }
    TmCube_Href = new TmCube_HrefObject(window.location);
    return TmCube_Href.getNormalURL(url);
}


/**
 * Convert url to suit environment.  The url should be CCGI relevant url.
 * @param url The source url of the original. the url seems like "File:<path>" , "Cmd:<command>" or "URL:<url>".
 * @return new url that environment  relatived.
 */
function TmCube_getCCGIURL(url)
{
    if (TmCube_Href)
    {
        return TmCube_Href.getCCGIURL(url);
    }
    TmCube_Href = new TmCube_HrefObject(window.location);
    return TmCube_Href.getCCGIURL(url);
}

/**
 * Href convertor object. The object is handled by TmCube_Href.
 * The object provide two functions to convert url to suit CCGI or other environment.
 */
function TmCube_HrefObject(href)
{
    this.href = href.toString();
    this.type = ".";
    var reg = /^http/i;
    if (!reg.test(this.href))
    {
        return;
    }
    reg = /\/CCGIServlet\?/;
    if (!reg.test(this.href))
    {
        return;
    }
    this.startPos = this.href.indexOf("&Page=");
    if (this.startPos == -1)
    {
        this.startPos = this.href.indexOf("&File=");
    }
    if (this.startPos == -1)
    {
        return;
    }
    this.startPos++;
    this.endPos = this.href.indexOf("&", this.startPos);
    this.type = "CCGI";
}

/**
 * TmCube_HrefObject.getNormalURL()
 */
TmCube_HrefObject.prototype.getNormalURL = function (file)
{
    if (this.type == ".")
    {
        return file;
    }
    /* if the file starts with "http://" or "https://" or "file://" or "ftp://" or "c:" ,
        return it directly.
     */
    if (/^http:\/\//.test(file) || /^https:\/\//.test(file) ||
        /^ftp:\/\//.test(file) || /^file:\/\//.test(file) ||
        /^[a-zA-Z]:/.test(file))
    {
        return file;
    }
    if (this.endPos == -1)
    {
        return this.href.slice(0, this.startPos) + "File=" + file;
    }
    return this.href.slice(0, this.startPos) + "File=" + file + this.href.slice(this.endPos);
}

/**
 * TmCube_HrefObject.getCCGIURL()
 */
TmCube_HrefObject.prototype.getCCGIURL = function (file)
{
    if (this.type == ".")
    {
        return file;
    }
    if (this.endPos == -1)
    {
        return this.href.slice(0, this.startPos) + "Page=" + file;
    }
    return this.href.slice(0, this.startPos) + "Page=" + file + this.href.slice(this.endPos);
}


/**
 * Rewrite url attributes user specified. This function converts the url to CCGI url if necessary.
 * @param element An element. This function will rewrite url attributes of it and its children.
 * @param tagSet An array contains tag name and attribute pairs. The odd sequence numbered element 
 *        in the array is the tag name(ignore case). The even sequence is attribute. For example: 
 *              TmCube_resolveURLAttributes(element, new Array("td", "background"));
 *         The statement will rewrite all the "background" attribute of "td".
 */
function TmCube_resolveURLAttributes(element, tagSet)
{
	if (!element  || element.nodeType !=1) //1 means ELEMENT_NODE.
	{
		return;
	}
	for (var i=0; i<tagSet.length/2; i++)
	{
		var reg = new RegExp("^" + tagSet[2*i] + "$", "i");
        if (reg.test(element.tagName))
		{
			var file = element.getAttribute(tagSet[2*i+1]);
			if (file)
			{
				element.setAttribute(tagSet[2*i+1], TmCube_getNormalURL(file));
			}
		}
	}
	if (element.childNodes)
	{
		var children = element.childNodes;
		for (var i=0; i<children.length; i++)
		{
			var child = children[i];
			TmCube_resolveURLAttributes(child, tagSet);
		}
	}
}

/**
 * Sometimes we must limit the user input in text field to follow a special format. For example,
 * AC format is XX-XXXX-XXXXX-XXXXX-XXXXX-XXXXX-XXXXX, where "X" can be 'A'-'Z' and '0'-'9'.
 * The TmCube_MaskedInput class is used to support this kind of masked input. There are four 
 * reserved characters in the mask:
 * N - Match numbers
 * C - Match letters
 * A - Match numbers and letters
 * ? - Match any characters
 * Any other character is treated as normal characters. For example, the mask for AC is
 * "AA-AAAA-AAAAA-AAAAA-AAAAA-AAAAA-AAAAA".
 * @param mask  The mask.
 */
function TmCube_MaskedInput(mask)
{
    this.mask = mask;
}

/**
 * A private method of TmCube_MaskedInput, to convert mask into regular expression.
 * @param ptn  The pattern (mask) to be converted
 * @return     Regular expression
 */
TmCube_MaskedInput.prototype.toRegExp = function (ptn)
{
    ptn = ptn.replace(/([-\/\[\]()\*\+\$\{\}])/g, '\\$1');
    ptn = ptn.replace(/N/g, '\\d');
    ptn = ptn.replace(/C/g, '[A-Za-z]');
    ptn = ptn.replace(/A/g, '\\w');
    ptn = ptn.replace(/\?/g, '.');
    return ptn;
}

/**
 * A private method of TmCube_MaskedInput, to auto complete the normal characters in the mask.
 * @param obj  The input object
 */
TmCube_MaskedInput.prototype.autoComplete = function (obj)
{
    var size = obj.value.length;
    while (true)
    {
        if (this.mask.length<=size)
        {
            break;
        }
        else
        {
            switch (this.mask.charAt(size))
            {
                case 'N':
                case 'C':
                case 'A':
                case '?':
                    return;
                default:
                    obj.value += this.mask.charAt(size);
            }
            size++;
        }
    }
	return;
}

/**
 * A private method of TmCube_MaskedInput, to match the input value against the mask.
 * @param value  The input value
 * @return       Matched string, all the unmatched characters will be removed.
 */
TmCube_MaskedInput.prototype.getMatch = function (value) 
{
    var size = value.length;
    if (0 == size)
    {
        return "";
    }
    var reg = new RegExp('^' + this.toRegExp(this.mask.substr(0, size)) + '$');
    if (value.match(reg))
    {
        return value;
    }
    else
    {
        return this.getMatch(value.substr(0, size-1), this.mask);
    }
}

/**
 * A public method of TmCube_MaskedInput, to match the input and auto-complete normal
 * characters in the mask.
 * @param obj  The input object
 * @param evt  The event object
 */
TmCube_MaskedInput.prototype.editMask = function (obj, evt) 
{
    var matchedValue = this.getMatch(obj.value, this.mask);
    if (obj.value != matchedValue) 
	{
	    obj.value = matchedValue;
	}
	
	var keyCode = 0;
    if(document.all)
    {
        keyCode = evt.keyCode;
    }
    else
    {
        keyCode = evt.which;
    } 
	if(keyCode != 8 && keyCode != 0 && keyCode!= 9)
	{
	    this.autoComplete(obj);
	}
}

/**
 * A public method of TmCube_MaskedInput, to auto-complete the leading normal characters.
 * @param obj  The input object
 * @param evt  The event object
 */
TmCube_MaskedInput.prototype.autoCompleteLeadingChars = function (obj, evt)
{
    var keyCode = 0;
    if(document.all)
    {
        keyCode = evt.keyCode;
    }
    else
    {
        keyCode = evt.which;
    }
    if(obj.value.length == 0 && keyCode != 8 && keyCode != 0 && keyCode!= 9) 
    {
        this.autoComplete(obj);
	}
}

/**
 * Match the input against a specified mask. Call this function in "onkeyup" and "onblur"
 * event handlers. There are four reserved characters in the mask:
 * N - Match numbers
 * C - Match letters
 * A - Match numbers and letters
 * ? - Match any characters
 * Any other character is treated as normal characters. For example, the mask for AC is
 * "AA-AAAA-AAAAA-AAAAA-AAAAA-AAAAA-AAAAA". Note that only the following reserved characters 
 * in regular expression are supported in mask: -, /, [, ], (, ), *, +, $, {, }
 * @param obj  The input object.
 * @param mask The mask.
 * @param evt  The event object.
 */
function TmCube_editMask(obj, mask, evt)
{
    var maskInput = new TmCube_MaskedInput(mask);
    return maskInput.editMask(obj, evt);
}

/**
 * Auto-complete the leading characters according to the mask.
 * Call this function in "onkeydown" event handler only when the mask contains leading normal 
 * characters like "-" (the mask is not begun with "N", "C", "A" or "?").
 * @param obj  The input object.
 * @param mask The mask.
 * @param evt  The event object.
 */
function TmCube_autoCompleteLeadingChars(obj, mask, evt)
{
    var maskInput = new TmCube_MaskedInput(mask);
    return maskInput.autoCompleteLeadingChars(obj, evt);
}


/**
 * Open a status window. Closing the status window will refresh the parent window. This function is intended to be 
 * an onclick handler of a button which will perform an time consumed action.
 * @param page The destination page to be open in a window.
 * @param width Optional width of new window. 
 * @param height Optional height of new window. 
 * @param top Optional top of new window. If not specified, the window is in the middle of window.
 * @param left Optional left of new window. if not specified, the window is in the center of window.
 * @return none.
 */
function TmCube_callWindow(page, width, height, top, left)
{
	if (page)
	{
		var url = TmCube_getCCGIURL(page);
		var feature = "status=no,toolbar=no, menubar=no, location=no,dependent=yes,alwaysRaised=true, resizable=no";
		width = width || 410;
		height = height || 240;
		feature += ",width="+ width;
		feature += ",height=" + height ;
		if (top)
			feature += ",top=" + top;
		else
			feature += ",top=" + getSuitableTop(height);
		if (left)
			feature += ",left=" + left;
		else
			feature += ",left=" + getSuitableLeft(width);
		var popup = window.open(url,  "popup",  feature);
		window.popupWindow = popup;
		if (!window.name) window.name = "_temp_parent";
	}
	else
	{
		throw "Destination page is null";
	}
}

/**
 * Get original page information from CCGI URL. 
 * @param CCGI URL.
 * @return String following "Page=", or return URL if it is not CCGI.
 */
function TmCube_getOriginalFromCCGIURL(url)
{
	var pagePos = url.indexOf("Page=");
	var result = url;
	if (pagePos >0)
 	{
		pagePos += "Page=".length;
		endPos = url.indexOf("&", pagePos);
		//Because %3A is not recognized by CUBE servlet. so unescape it.
		result = unescape((endPos > 0)? url.slice(pagePos, endPos) : url.slice(pagePos));
	}
	return result;
}

/**
 * Submit form in current page and refresh parent window. This function serves for onunload  handler of a statusis window.
 * To status window, it needs refresh the parent window after it closed and submit some value to web side. Therefore, the 
 * function will access the first form of the document, change its target and action attributes to point to parent page and then 
 * submit it. So to status window page developer, he/she needs not to fill the attributes of the form.
 * @return none.
 */
function TmCube_submitForm()
{
	/* To avoid permission denied error, add try catch block. */
	try
	{
		if (window.top && window.top.opener && !window.top.opener.closed && window.top.opener.popupWindow && document.forms.length >=1)
		{
			var theForm = document.forms[0];
			if (theForm.CCGI_Form_NextPage)
			{
				if (window.top.opener.name) theForm.target = window.top.opener.name; 
				theForm.CCGI_Form_NextPage.value = TmCube_getOriginalFromCCGIURL(window.top.opener.location.href);
				theForm.submit();
			}
		}
	}
	catch (exp)
	{
		return;
	}
}


/**
 * Calculate left offset to center popup window.
 * @param width The width of the window.
 * @return Left offset
 */
function getSuitableLeft(width)
{
	width = new Number(width);
	if (width != Number.NaN && width != Number.NEGATIVE_INFINITY && width != Number.POSITIVE_INFINITY)
	{
		width = width.valueOf();		
	}
	else
	{
		width = 410;
	}
	return (screen.width - width)/2;
}

/**
 * Calculate top offset to center popup window.
 * @param height The width of the window.
 * @return top offset
 */
function getSuitableTop(height)
{
	height = new Number(height);
	if (height != Number.NaN && height != Number.NEGATIVE_INFINITY && height != Number.POSITIVE_INFINITY)
	{
		height = height.valueOf();		
	}
	else
	{
		height = 240;
	}
	return (screen.height - height)/2;
}

/**
 * Popup a window.
 * @param page Destination page to be opened. The function auto convert it to CCGI URL.
 *                       It can be start with "file:", "cmd:", "url:" ("Page=...") or  none of them ("File=").
 * @param width Width of popup window
 * @param height Height of popup window
 * @return None
 */
function TmCube_popupWindow(page, width, height)
{
	if (/^file:/.test(page) || /^cmd:/.test(page) || /^url:/.test(page))
	{
		page = TmCube_getCCGIURL(page);
	}
	else
	{
		page = TmCube_getNormalURL(page);
	}
	
	width = width || 410;
	height  = height || 240;
	var feature = "status=no,toolbar=no, menubar=no, location=no,dependent=yes,alwaysRaised=true, resizable=no";
	feature += ",width="+ width;
	feature += ",height=" + height ;
	feature += ",top=" + getSuitableTop(height);
	feature += ",left=" + getSuitableLeft(width);
	window.open (page,  "_blank", feature);
}

/**
 * Refresh status window. The function is suitable for "meta" element. See the sample
 * <meta http-equiv="refresh" content="4;url=javascript:TmCube_refreshWindow()" />
 * @return null
 */
function TmCube_refreshWindow()
{
	window.onunload = null;
	window.location.href = window.location.href;
}

/**
 * Record status (enabled or disabled) of UI component inner controls. This function should be 
 * called in loading time (onload handler).
 * @param compObj Component object.
 * @param ... The control names.
 */
function TmCube_recordStatus(compObj)
{
	var len = arguments.length;
	if (len > 1)
	{
		compObj.innerControls = new Array(len -1);
		for (var i=0; i< len - 1; i++)
		{
			var pair = new Object();
			pair.name = arguments[i+1];
			var element = TmCube_getElement(compObj.name, pair.name);
			if (element)
			{
				pair.disabled = element.disabled;
			}
			compObj.innerControls[i] = pair;
		}
	}
}

/**
 * Restore status of UI component inner controls. This function should be called in reset handler.
 * @param compObj Component object.
 * @return none.
 */
function TmCube_restoreStatus(compObj)
{
	if (compObj.innerControls)
	{
		for (var i=0; i<compObj.innerControls.length; i++)
		{
			var pair = compObj.innerControls[i];
			var element = TmCube_getElement(compObj.name, pair.name);
			if (element)
			{
			    element.disabled = pair.disabled;
			}
		}
	}
}

/**
 * Reset all component status. This function restore multi component status in one function.
 * If multiply component is in same form, user can call this function instead of concatenation of  
 * onreset handler of components.
 * @ param ... The component name's list. Note the parameter is string type.
 */
function TmCube_resetComponents()
{
	for (var i=0; i<arguments.length; i++)
	{
		var compObj = TmCube_getComponentByPrefix(arguments[i]);
		if (compObj)
		{
			TmCube_restoreStatus(compObj);
		}
	}
}