﻿// Add a namespace to avoid conflicts
var addNamespace = function(ns) 
{
	var nsParts = ns.split(".");
	var root = window;
	for(var i=0; i< nsParts.length; i++) 
	{
		if(typeof root[nsParts[i]] == "undefined") 
		{
			root[nsParts[i]] = {};
		}
		root = root[nsParts[i]];
	}
};

// Extend functionalities
Object.extend = function(dest, source, replace) 
{
	for(var prop in source) 
	{
		if(replace == false && dest[prop] != null) continue; 
		dest[prop] = source[prop];
	}
	return dest;
};

// Define $ and Class declaration
Object.extend(window, 
{
	$: function() 
	{
		var elements = [];
		for(var i=0; i < arguments.length; i++) 
		{
			var e = arguments[i];
			if(typeof e == 'string') 
			{
				e = document.getElementById(e);
			}
			if(arguments.length == 1) 
			{
				return e;
			}
			elements.push(e);
		}
		return elements;
	},
	Class: 
	{
		create: function() 
		{
			return function() 
			{
				if(typeof this.initialize == "function") 
				{
					this.initialize.apply(this, arguments);
				}
			};
		}
	}
}, false);

var SysBrowserVersion = parseFloat(navigator.appVersion);
var SysBrowserAgent = "";

if (navigator.userAgent.indexOf(" MSIE ") >- 1) 
{
    SysBrowserAgent = "InternetExplorer";
    SysBrowserVersion = parseFloat(navigator.userAgent.match(/MSIE (\d+\.\d+)/)[1]);
} 
else if (navigator.userAgent.indexOf(" Firefox/") >- 1) 
{
    SysBrowserAgent = "Firefox";
    SysBrowserVersion = parseFloat(navigator.userAgent.match(/Firefox\/(\d+\.\d+)/)[1]);
} 
else if (navigator.userAgent.indexOf(" Safari/") >- 1) 
{
    SysBrowserAgent = "Safari";
    SysBrowserVersion = parseFloat(navigator.userAgent.match(/Safari\/(\d+\.\d+)/)[1]);
} 
else if (navigator.userAgent.indexOf("Opera/") >- 1)
    SysBrowserAgent = "Opera";
    
    
var $get = function(f, e) 
{
    if (!e) return document.getElementById(f);
    if (e.getElementById) return e.getElementById(f);
    var c = [], d = e.childNodes;
    for (var b = 0; b < d.length; b ++ ) 
    {
        var a = d[b];
        if (a.nodeType == 1) c[c.length] = a
    }
    while (c.length) 
    {
        a = c.shift();
        if (a.id == f) return a;
        d = a.childNodes;
        for (b = 0; b < d.length; b ++ ) 
        {
            a = d[b];
            if (a.nodeType == 1) c[c.length] = a
        }
    }
    return null
};   

function getChildNode(e, tagName)
{
    if (!e || !e.hasChildNodes()) return null;
    tagName = tagName.toUpperCase();
        
    var children = e.childNodes;
    for (var i = 0; i < children.length; i++) 
    {
        if (children[i].nodeName == tagName) return children[i];
        var child = getChildNode(children[i], tagName);
        if (child) return child;
    }
        
   return null;
}  

var $getByTagName = function(e, tagName) 
{
    var ele = (typeof e ==  "string") ? $get(e) : e; 
	tagName = tagName.toUpperCase();
    if (!ele) 
    {
        var results = document.getElementsByTagName(tagName);
        return (results.length > 0) ? results[0] : null;
    }
    else
    {
        return getChildNode(ele, tagName)
    }
};    

var $getNextSibling = function(e) 
{
    endBrother = e.nextSibling;
    
    while(endBrother.nodeType != 1)
    {
        endBrother = endBrother.nextSibling;
    }
    
    return endBrother;
}

var $getInnerText = function(e)
{
    return (SysBrowserAgent == "InternetExplorer") ? e.innerText : e.textContent;
}

// Add events to a Html element
// This gives an example of how to create static class functions
addNamespace("Web.UI.DomElement");

Object.extend(Web.UI.DomElement, 
{
	getCurrentStyle : function(a) 
	{
        var b = (a.ownerDocument ? a.ownerDocument: a.documentElement).defaultView;
        return b && a !== b && b.getComputedStyle ? b.getComputedStyle(a, null): a.style;
    },
    
    getClientDimension: function ()
    {
        var w;
        var h;
        
        if (self.innerHeight) // all except Explorer
        {
	        w = self.innerWidth;
	        h = self.innerHeight;
        }
        else if (document.documentElement && document.documentElement.clientHeight)	    // Explorer 6 Strict Mode
        {
	        w = document.documentElement.clientWidth;
	        h = document.documentElement.clientHeight;
        }
        else if (document.body) // other Explorers
        {
	        w = document.body.clientWidth;
	        h = document.body.clientHeight;
        }
        return {width:w, height:h};
    },
    
    getHtmlObject: function (ele)
    {
        return (typeof ele ==  "string") ? $get(ele) : ele; 
    },
    
    getParentNodeByTagName: function(elem, tag)
    {
        if (!elem) return null;
        var parent = elem.parentNode;
        tag = tag.toUpperCase();
        while(parent && parent.tagName != tag)
        {
            parent = parent.parentNode;
        }
        
        return parent;
    },
    
    getLocation : function(ele)
    {
        var el = Web.UI.DomElement.getHtmlObject(ele);		
        if (el == null || typeof(el) == "undefined") return null;
        
        if (SysBrowserAgent == "InternetExplorer")
        {
            if (el.self || el.nodeType === 9) return {x:0, y:0};
            var d = el.getClientRects();
            if (!d ||!d.length) return {x:0, y:0};
            var e = el.ownerDocument.parentWindow,
            g = e.screenLeft - top.screenLeft - top.document.documentElement.scrollLeft + 2,
            h = e.screenTop - top.screenTop - top.document.documentElement.scrollTop + 2,
            c = e.frameElement || null;
            if (c) 
            {
                var b = c.currentStyle;
                g += (c.frameBorder || 1) * 2 + (parseInt(b.paddingLeft) || 0) + (parseInt(b.borderLeftWidth) || 0) - el.ownerDocument.documentElement.scrollLeft;
                h += (c.frameBorder || 1) * 2 + (parseInt(b.paddingTop) || 0) + (parseInt(b.borderTopWidth) || 0) - el.ownerDocument.documentElement.scrollTop;
            }
            var f = d[0];
            return {x:f.left - g, y: f.top - h};
        }
        else
        {
            if (el.window && el.window === el || el.nodeType === 9)  return {x:0, y:0};
            var e = 0,
            f = 0,
            i = null,
            h = null,
            b = null;
            for (var a = el; a; i = a, (h = b, a = a.offsetParent)) 
            {
                var c = a.tagName;
                b = Web.UI.DomElement.getCurrentStyle(a);
                if ((a.offsetLeft || a.offsetTop) &&! (c === "BODY" && ( ! h || h.position !== "absolute"))) 
                {
                    e += a.offsetLeft;
                    f += a.offsetTop
                }
                if (i !== null && b) 
                {
                    if (c !== "TABLE" && c !== "TD" && c !== "HTML") 
                    {
                        e += parseInt(b.borderLeftWidth) || 0;
                        f += parseInt(b.borderTopWidth) || 0
                    }
                    if (c === "TABLE" && (b.position === "relative" || b.position === "absolute")) 
                    {
                        e += parseInt(b.marginLeft) || 0;
                        f += parseInt(b.marginTop) || 0
                    }
                }
            }
            b = Web.UI.DomElement.getCurrentStyle(el);
            var g = b ? b.position: null,
            j = g && g !== "static";
            if ( !g || g !== "absolute")
            for (var a = el.parentNode; a; a = a.parentNode) 
            {
                c = a.tagName;
                if (c !== "BODY" && c !== "HTML" && (a.scrollLeft || a.scrollTop)) 
                {
                    e -= a.scrollLeft || 0;
                    f -= a.scrollTop || 0;
                    b = Web.UI.DomElement.getCurrentStyle(a);
                    e += parseInt(b.borderLeftWidth) || 0;
                    f += parseInt(b.borderTopWidth) || 0
                }
            }
            return {x:e, y:f};
        }
    },
    
    getObjectWidth: function (ele)  	
    {
	    var el = Web.UI.DomElement.getHtmlObject(ele);		
	    if (el == null || typeof(el) == "undefined") return 0;
	    var result = 0;
	    
	    if (el.offsetWidth) 
		{
	        result = el.offsetWidth;
		} 
	    else if (el.clip && el.clip.width) 
		{
		    result = el.clip.width;
		} 
	    else if (el.style && el.style.pixelWidth) 
		{
		    result = el.style.pixelWidth;
		}
	    return parseInt(result);
	 },
	 
	 getObjectHeight: function(ele)  
     {
	    var el = Web.UI.DomElement.getHtmlObject(ele);		
	    if (el == null || typeof(el) == "undefined") return 0;
	    var result = 0;
	    if (el.offsetHeight) 
		{
		    result = el.offsetHeight;
		} 
	    else if (el.clip && el.clip.height) 
		{
		    result = el.clip.height;
		} 
	    else if (el.style && el.style.pixelHeight) 
		{
		    result = el.style.pixelHeight;
		}
	    return parseInt(result);
    },   
    
    getMaxObjectHeight: function(ele)
    {
	    var el = Web.UI.DomElement.getHtmlObject(ele);		
	    if (el == null || typeof(el) == "undefined") return 0;
	    var objPos = Web.UI.DomElement.getLocation(el);
	    if (objPos)
	    {
		    var clientDimension = Web.UI.DomElement.getClientDimension();
		    if (clientDimension)
		    {
			    var h = clientDimension.height - objPos.y;
			    return h;
		    }
		    else
			    return 0;
	    }
	    else
	    {
		    return 0;
	    }
    },  
    
    getMaxObjectWidth: function(ele)
    {
	    var el = Web.UI.DomElement.getHtmlObject(ele);		
	    if (el == null || typeof(el) == "undefined") return 0;
	    var objPos = Web.UI.DomElement.getLocation(el);
	    if (objPos)
	    {
		    var clientDimension = Web.UI.DomElement.getClientDimension();
		    if (clientDimension)
		    {
			    var h = clientDimension.width - objPos.x;
			    return h;
		    }
		    else
			    return 0;
	    }
	    else
	    {
		    return 0;
	    }
    },  
    
    getBounds: function(el)
    {
         var b = Web.UI.DomElement.getLocation(el);
         var w = Web.UI.DomElement.getObjectWidth(el);
         var h = Web.UI.DomElement.getObjectHeight(el);
         return {x: b.x, y: b.y, width: w, height: h};
    },
    
    setObjectHeight: function(ele, h)
    {
	    if (parseInt(h) <= 0) return;
	    var el = Web.UI.DomElement.getHtmlObject(ele);		
	    if (el == null) return false;

        var str = "" + h;
        if (str.indexOf("px") == -1) str += "px";
        
        // IE 6 syntax    
        el.style.height = str;
        
        // IE 7, Netscape syntax    
        el.setAttribute("height", str);
    },


    setObjectWidth: function(ele, w)
    {
       if (parseInt(w) <= 0) return;
       var el = Web.UI.DomElement.getHtmlObject(ele);		
       if (el == null) return false;
        
        var str = "" + w;
        
        if (str.indexOf("px") == -1) str += "px";
        
        // IE 6 syntax    
        el.style.width = str;
        
        // IE 7, Netscape syntax    
        el.setAttribute("width", str);
    },


    setMaxObjectHeight: function(ele)
    {
	    var el = Web.UI.DomElement.getHtmlObject(ele);		
	    if (el == null) return;
	    var h = Web.UI.DomElement.getMaxObjectHeight(el);
	    Web.UI.DomElement.setObjectHeight(el, h);
    },


    setMaxObjectWidth: function(ele, maxWidth)
    {
	    var objPos = Web.UI.DomElement.getLocation(ele);
	    if (objPos)
	    {
		    if (typeof(maxWidth) == "undefined")
		    {
			    var clientDimension = Web.UI.DomElement.getClientDimension();
			    if (clientDimension)
			    {
				    var w = clientDimension.width - objPos.x;
				    Web.UI.DomElement.setObjectWidth(ele, w);
			    }
		    }
		    else
		    {
			    var w = maxWidth - objPos.left;
			    Web.UI.DomElement.setObjectWidth(ele, w);
		    }
	    }
    },
    
    verticalCenter: function(ele)
    {
		var el = Web.UI.DomElement.getHtmlObject(ele);		
	    if (el == null) return;
		
		var h = Web.UI.DomElement.getObjectHeight(el);
		var clientSize = Web.UI.DomElement.getClientDimension();
		var marginTop = Math.max((clientSize.height - h)/2, 0);
		if (marginTop > 0)
		{
			el.style.marginTop = marginTop + "px";
		}
    },
    
    maximizeWindow: function( ) 
    {
        var offset = (navigator.userAgent.indexOf("Mac") != -1 || 
                  navigator.userAgent.indexOf("Gecko") != -1 || 
                  navigator.appName.indexOf("Netscape") != -1) ? 0 : 4;
        window.moveTo(-offset, -offset);
        window.resizeTo(screen.availWidth + (2 * offset), screen.availHeight + (2 * offset));
    },
    
    execAllChildNodes: function(node, execFunc)
    {
        if(node.nodeType == 1)
        {
            execFunc(node);
        }
            
        var children = node.childNodes;
        for(var i = 0;i < children.length;i++) scan(children.item(i), execFunc);
    },
    
    // Create a dynamic Iframe
    createDynamicIframe: function(parentNode, src, scroll, name)
    {
        var location = Web.UI.DomElement.getLocation(parentNode);
	    var startOfMarkerTop = location.y;
	    var startOfMarkerLeft = location.x;
    	
	    var frameHeight = document.body.clientHeight - startOfMarkerTop;	 		 								 	
	    var frameWidth   = document.body.clientWidth - startOfMarkerLeft;
    	
	    try 
	    { 
		    var tmpIF = document.createElement("iframe"); 
		    tmpIF.setAttribute("width",frameWidth); 
		    tmpIF.setAttribute("height",frameHeight); 
		    tmpIF.setAttribute("id",name); 
		    tmpIF.setAttribute("name",name); 
		    tmpIF.setAttribute("frameBorder","0"); 
		    tmpIF.setAttribute("hspace","0"); 
		    tmpIF.setAttribute("vspace","0"); 
		    tmpIF.setAttribute("marginheight","0"); 
		    tmpIF.setAttribute("marginwidth","0"); 
		    tmpIF.setAttribute("scrolling",scroll); 
		    // CSS styles 
		    tmpIF.style.width= frameWidth + 'px'; 
		    tmpIF.style.height= frameHeight + 'px'; 
		    tmpIF.style.margin='0px'; 
		    tmpIF.style.padding='0px'; 
		    tmpIF.style.border='0px'; 
		    // Replace the image with an IFRAME 
		    tmpIF.setAttribute("src", src); 
		    parentNode.innerHTML = ''; 
		    parentNode.appendChild(tmpIF); 
	    } 
	    catch(e) 
	    { 
		    // If createElement() failed, maybe innerHTML works 
		    if( typeof(parentNode.innerHTML)=="string" ) 
		    { 
			    parentNode.innerHTML = '<iframe id="adminFrame" src="' + src + ' style="OVERFLOW:visible"' +
							' marginWidth="5" marginHeight="5" height="' + frameHeight + '" frameBorder="0" scrolling="' +
							scroll + '" width="' + frameWidth + '"</iframe>';
		    }			
	    }

    },

    // Move an element directly on top of another element (and optionally
    // make it the same size)
    Cover: function(bottom, top, ignoreSize) 
    {
        var location = Web.UI.DomElement.getLocation(bottom);
        top.style.position = 'absolute';
        top.style.top = location.y + 'px';
        top.style.left = location.x + 'px';
        if (!ignoreSize) 
        {
            top.style.height = bottom.offsetHeight + 'px';
            top.style.width = bottom.offsetWidth + 'px';
        }
    }

    
}, true);	


String.__typeName = "String";
String.__class = true;

String.prototype.endsWith = function(a) 
{
   var re = new RegExp(a + "$");
   return (this.match(re) != null);
};

String.prototype.startsWith = function(a) 
{
    var re = new RegExp("^" + a);
    return (this.match(re) != null);
};

String.prototype.startsWithNoCase = function(a) 
{
    var re = new RegExp("^" + a, "i");
    return (this.match(re) != null);
};


String.prototype.trim = function() 
{
    return this.replace(/^\s+|\s+$/g, "");
};

String.prototype.trimEnd = function() 
{
    return this.replace(/\s+$/, "")
};

String.prototype.trimStart = function() 
{
    return this.replace(/^\s+/, "")
};

String.format = function() 
{
    return String._toFormattedString(false, arguments)
};

String.localeFormat = function() 
{
    return String._toFormattedString(true, arguments)
};

String._toFormattedString = function(l, j) 
{
    var c = "",
    e = j[0];
    for (var a = 0; true;) 
    {
        var f = e.indexOf("{", a),
        d = e.indexOf("}", a);
        if (f < 0 && d < 0) {
            c += e.slice(a);
            break
        }
        if (d > 0 && (d < f || f < 0)) {
            c += e.slice(a, d + 1);
            a = d + 2;
            continue
        }
        c += e.slice(a, f);
        a = f + 1;
        if (e.charAt(a) === "{") {
            c += "{";
            a ++ ;
            continue
        }
        if (d < 0)
            break;
        var h = e.substring(a, d),
        g = h.indexOf(":"),
        k = parseInt(g < 0 ? h: h.substring(0, g)) + 1,
        i = g < 0 ? "": h.substring(g + 1),
        b = j[k];
        if (typeof b === "undefined" || b === null)
            b = "";
        if (b.toFormattedString)
            c += b.toFormattedString(i);
        else if (l && b.localeFormat)
            c += b.localeFormat(i);
        else if (b.format)
            c += b.format(i);
        else c += b.toString();
        a = d + 1
    }
    return c
};

String.prototype.isNull = function ()
{
    return (this.trim().length == 0);	
};

String.prototype.isNotNull = function ()
{
    return (this.trim().length > 0);	
};

String.prototype.isEmail = function ()
{
    var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
	return (re.test(this.trim()));
};

String.prototype.isEmailOrNull = function ()
{
    if (this.trim().length == 0) return true;
    return this.isEmail();	
};

String.prototype.isInteger = function ()
{
    var re = /^([+-]?)(\d+)$/;
    return (re.test(this.trim()));
};

String.prototype.isIntegerOrNull = function ()
{
    if (this.trim().length == 0) return true;
    return this.isInteger();	
};

String.prototype.isNumber = function ()
{
    var re = /^([+-]?)(\d+\.?\d*|\.\d+|\d+)$/;
	return (re.test(this.trim()));
};

String.prototype.isNumberOrNull = function ()
{
    if (this.trim().length == 0) return true;
	return this.isNumber();
};

String.prototype.isMatch = function (p)
{
    var re = new RegExp(p);
	return (re.test(this.trim()));
};

String.prototype.isDate = function ()
{
	var re = /^\d{1,2}(\-|\/|\.)\d{1,2}\1\d{4}$/

	//check to see if in correct format
	if(!re.test(this))
		return false; //doesn't match pattern, bad date
	else 
	{
		var strSeparator = RegExp.$1;
		var arrayDate = this.split(strSeparator); 
		//create a lookup for months not equal to Feb.
		var arrayLookup = { '01' : 31,'03' : 31, 
                    '04' : 30,'05' : 31,
                    '06' : 30,'07' : 31,
                    '08' : 31,'09' : 30,
                    '10' : 31,'11' : 30,'12' : 31}
		var intDay = parseInt(arrayDate[0],10); 
		var intMonth = parseInt(arrayDate[1],10);
					
		if (intMonth > 12 || intDay > 31) return false;
		
		//check if month value and day value agree
		if(arrayLookup[arrayDate[1]] != null) 
		{
			if(intDay <= arrayLookup[arrayDate[1]] && intDay != 0)
				return true; //found in lookup table, good date
		}

		//check for February
		if (intMonth == 2) 
		{ 
			var intYear = parseInt(arrayDate[2]);
			if (intDay > 0 && intDay < 29) 
			{
				return true;
			}
			else if (intDay == 29) 
			{
				if ((intYear % 4 == 0) && (intYear % 100 != 0) || (intYear % 400 == 0)) 
				{
					// year div by 4 and ((not div by 100) or div by 400) ->ok
					return true;
				}   
			}
		}
	}  
	return false; //any other values, bad date
};

String.prototype.isDateOrNull = function ()
{
    if (this.trim().length == 0) return true;
    return this.isDate();	
};

RegExp.IsMatch = function(s, p)
{
    if (typeof(s) == "undefined" || typeof(p) == "undefined") return true;
	var re = new RegExp(p);
	return (s.match(re) != null);
};

addNamespace("Web.UI.Events");

Object.extend(Web.UI.Events, 
{
    getEvent: function(evt)
    {
    	return (evt) ? evt : ((window.event) ? event : null);
    },
    
    getEventSource: function(evt)
	{
		// Get the event
		evt = Web.UI.Events.getEvent(evt);
		if (!evt) return null;

		// Get the element generated the event
		var elem = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
		return elem;
	},
	
    addEvent: function(el, evType, f, capture) 
	{
		var o = Web.UI.DomElement.getHtmlObject(el);
		if(o == null) { return false; }
		if(o.addEventListener) 
		{
		    if (typeof capture == "undefined") capture = false;
			o.addEventListener(evType, f, capture);
			return true;
		} 
		else if (o.attachEvent) 
		{
			var r = o.attachEvent("on" + evType, f);
			return r;
		} 
		else 
		{
			try{ o["on" + evType] = f;} catch(e){}
		}
	},
	
	removeEvent: function(el, evType, f, capture) 
	{
		var o = Web.UI.DomElement.getHtmlObject(el);
		if(o == null) { return false; }
		if(o.removeEventListener) 
		{
		    if (typeof capture == "undefined") capture = false;
			o.removeEventListener(evType, f, capture);
			return true;
		} 
		else if (o.detachEvent) 
		{
			o.detachEvent("on" + evType, f);
		} 
		else 
		{
			try{ o["on" + evType] = function(){};} catch(e){}
		}
	},
	
	stopPropagation: function(evt) 
	{
	    evt = Web.UI.Events.getEvent(evt);
        if (evt.stopPropagation)
            evt.stopPropagation();
        else 
            evt.cancelBubble = true;
    },
    
    preventDefault: function(evt) 
    {
        evt = Web.UI.Events.getEvent(evt);
        if (evt.preventDefault)
            evt.preventDefault();
        else 
            evt.returnValue = false
    },
    
    addOnLoad: function(f)
    {
        if (window.onload) 
        {
            var oldfunc = window.onload;
            window.onload = function() 
            { 
                oldfunc(); 
                f(); 
            };
        }
        else 
        {
            window.onload = f;
        }
    },
    
    addOnResize:  function(f)
    {
        if (window.onresize) 
        {
            var oldfunc = window.onresize;
            window.onresize = function() 
            { 
                oldfunc(); 
                f(); 
            };
        }
        else 
        {
            window.onresize = f;
        }
    }
    
}, true);	

addNamespace("Web.UI.ValidationEvent");

Object.extend(Web.UI.ValidationEvent, 
{
    regularCheck: function(evt, regularExpression, prompt) 
	{
	    evt = Web.UI.Events.getEvent(evt);
		var elem = Web.UI.Events.getEventSource(evt);
		if (elem) 
		{
		    var charCode = (evt.charCode) ? evt.charCode : ((evt.which) ? evt.which : evt.keyCode);
			if (charCode < 32 ) return true;
			var ch = String.fromCharCode(charCode);
			var newValue = elem.value + ch;
			var re = new RegExp(regularExpression);
			if (newValue.match(re) == null)
			{
			    if (typeof(prompt) != 'undefined')
				{
				    alert(prompt);
				}
					
				return false;
			} 
			   
		return true;
		}
	},
	
	addTextChangedEvent: function(ele, validateFunc)
	{
		var el = Web.UI.DomElement.getHtmlObject(ele);		
		if(el == null) { return false; }
				
		var validType = validateFunc.substring(2, 100);
						
		var f =  function(evt)
		{
		    evt = Web.UI.Events.getEvent(evt);
			var evtSrc = Web.UI.Events.getEventSource(evt);
            
			if (evtSrc == null) 
			{
				return true;
			}
			
			var charCode = (evt.charCode) ? evt.charCode : ((evt.which) ? evt.which : evt.keyCode);
			
			if (charCode < 32 ) return true;
			var ch = String.fromCharCode(charCode);
			var newValue = evtSrc.value + ch;
			eval("result = newValue." + validateFunc + "();");
			
			if (!result)
			{
				alert("Invalid entry - Please enter a " + validType + ".");
				Web.UI.Events.preventDefault(evt);
				evtSrc.focus();
				return false;
			}
			
			return true;
		}
		
		Web.UI.Events.addEvent(el, "keypress", f);		
	}
	
}, true);	

// Class Web.UI.ValidationItem
addNamespace("Web.UI.ValidationItem");
Web.UI.ValidationItem = Class.create();

// This gives an example how to define member method of a class.
// These methods require a class instance. 
// This constrasts with static class functions
Object.extend(Web.UI.ValidationItem.prototype, 
{
	// Constructor
	initialize: function(id, validateFunc, message, regEx) 
	{
		this.id = id;
		this.ele = $(id);
		this.validateFunc = validateFunc;
		this.regEx = regEx;
		this.message = new String(message);
		},
	
	validate: function(alertError)
	{
		if (this.ele == null) 
		{
			alert("Element with id = " + this.id + " not found!");
			return false;
		}
		
		var value = this.ele.value;
		var strValue = new String(value);
		if (strValue.isNull() && this.validateFunc != "isNotNull")
		    return true;
		    
		var result = true;
		
		if (typeof (this.regEx) != "undefined")
		    eval("result = strValue." + this.validateFunc + "('" + this.regEx + "');");
		else    
		    eval("result = strValue." + this.validateFunc + "();");
				
		if (!result && this.message.length > 0 && alertError) alert(this.message);

		return result;
	}		
}, true);

addNamespace("Web.UI.Validation");
Web.UI.Validation = Class.create();
Object.extend(Web.UI.Validation.prototype, 
{
    initialize: function(divError) 
	{
	    this.divError = $(divError); // Where to output the errors
		this.collection = new Array();
	},

    // Valid validateFunc: isNotNull, isEmail, isInteger, isNumber, isDate, isMatch
	add: function(id, validateFunc, message, regEx)
	{
		var ClientValidation = new Web.UI.ValidationItem(id, validateFunc, message, regEx);
		this.collection[this.collection.length] = ClientValidation;
	},		
		

	validate: function()
	{
		var firstError = -1;
		var aErrors = (this.divError) ? new Array() : null;
		
		// if this.divError == null, we output errors in alerts
		// Otherwise, we put them in divError
		var alertError = (this.divError == null);
		
		for (i = 0; i < this.collection.length; i++)
		{
			if (this.collection[i].validate(alertError) == false) 
			{
				if (this.divError)
				{
					if (firstError == -1) firstError = i;

					// Add error message in the array of errors
					var errorMessage = this.collection[i].message;
					if (errorMessage.length > 0)
						aErrors[aErrors.length] = errorMessage;
				}
				else
				{
					// set the focus on the input that causes the problem and quit.
					if (this.collection[i].ele != null) this.collection[i].ele.focus();
					return false;
				}
			}
		}
		
		// If there are error messages then output them in the divError
		if (aErrors && aErrors.length > 0)
		{
		    this.divError.innerHTML = "";
			var ul = document.createElement("ul");
			this.divError.appendChild(ul);
			ul.className = "errorlist";
			
			for(i = 0; i < aErrors.length; i++) 
			{
				var li = document.createElement("li");
				ul.appendChild(li);
				li.innerHTML = aErrors[i];
			}			
		}

		// The first problematic input will get the focus		
		if (firstError > -1) 
		{
			this.collection[firstError].ele.focus();
			return false;
		}
		
		return true;
	}		
}, true);

addNamespace("Web.UI.DefaultButtonEvent");
Object.extend(Web.UI.DefaultButtonEvent, 
{
	add: function(ele, target)
	{
	    var ctrlSource = Web.UI.DomElement.getHtmlObject(ele);
	    var ctrlTarget = Web.UI.DomElement.getHtmlObject(target);
	    var submitViaEnter= function(evt) 
	    {
	        evt = Web.UI.Events.getEvent(evt);
			var evtSrc = Web.UI.Events.getEventSource(evt);
            
			if (evtSrc == null) 
			{
				return true;
			}
			
			var charCode = (evt.charCode) ? evt.charCode : ((evt.which) ? evt.which : evt.keyCode);
			
			if (charCode == 13 || charCode == 3) 
			{
				if (ctrlTarget.click)
				{
					// IE OK with this one
					return ctrlTarget.click();
				}
				else
				{
					// For Fire Fox
					var id = ctrlTarget.id;
					return Web.UI.DefaultButtonEvent.doPostBack(id, '');
				}
				
			}
			
	    };
	    
	    Web.UI.Events.addEvent(ctrlSource, "keypress", submitViaEnter);		
	},
		
	doPostBack: function (id, arg)
	{
		if (id.length == 0) return false;
		id = id.replace("_", "$");
		return __doPostBack(id, arg);
	}
}, true);	

addNamespace("Web.UI.Print");
Web.UI.Print = Class.create();
Object.extend(Web.UI.Print.prototype, 
{
	initialize: function(styleSheet) 
	{
		this.styleSheet = styleSheet;
	},		

	print: function(aDivs)
	{
		var attr = "toolbar=no,location=no,directories=no,menubar=yes,scrollbars=yes,width=800px,height=600px,left=10px,top=10px,resizable=1"; 
		var docprint = window.open("","",attr); 
		docprint.document.open(); 
		docprint.document.write('<html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" />'); 
		docprint.document.write('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-Strict.dtd">');
		docprint.document.write('<link href="' + this.styleSheet + '" type="text/css" rel="stylesheet" />');
		docprint.document.write('</head><body onload="self.print()">');          
	
		var aDivsToPrint = aDivs.split(",");
		
		for(var i = 0; i < aDivsToPrint.length; i++)
		{
			var contentToPrint = document.getElementById(aDivsToPrint[i]).innerHTML; 	
			docprint.document.write(contentToPrint);          
		}
				
		docprint.document.write('</body></html>'); 
		docprint.document.close(); 
		docprint.focus(); 
	}
	
}, true);

addNamespace("Web.UI.RoundCorner");

Object.extend(Web.UI.RoundCorner, 
{
	browserCheck: function()
	{
		if (!document.getElementById || !document.createElement)   return(false);
		
		var b = navigator.userAgent.toLowerCase();
		if (b.indexOf("msie 5") > 0 && b.indexOf("opera")== -1) return(false);
		
		return(true);
	},

	setRoundCorner: function(selector, outsideBackgroundColor, insideBackgroundColor, size)
	{
		var v = Web.UI.RoundCorner.getElementsBySelector(selector);
		for( var i = 0; i < v.length; i++)
		{
			v[i].style.padding = 0;
			Web.UI.RoundCorner.addTop(v[i], outsideBackgroundColor, insideBackgroundColor, size);
			Web.UI.RoundCorner.addBottom(v[i], outsideBackgroundColor, insideBackgroundColor, size);
		}
	},
	
	setRoundTop: function(selector, outsideBackgroundColor, insideBackgroundColor, size)
	{
		var v = Web.UI.RoundCorner.getElementsBySelector(selector);
		for (var i = 0; i < v.length; i++)
			Web.UI.RoundCorner.addTop(v[i], outsideBackgroundColor, insideBackgroundColor, size);
	},
	
	setRoundBottom: function(selector, outsideBackgroundColor, insideBackgroundColor, size)
	{
		var v = Web.UI.RoundCorner.getElementsBySelector(selector);
		for (var i = 0; i < v.length; i++)
			addBottom(v[i], outsideBackgroundColor, insideBackgroundColor, size);
	},	
	
	addTop: function(el, outsideBackgroundColor, insideBackgroundColor, size)
	{
		var d = document.createElement("b");
		var cn ="r";
		var lim = 4;
		if (size && size == "small")
		{ 
			cn ="rs"; 
			lim = 2;
		}
		
		d.className = "rtop";
		d.style.backgroundColor = outsideBackgroundColor;
		
		for(var i = 1; i <= lim; i++)
		{
			var x = document.createElement("b");
			x.className = cn + i;
			x.style.backgroundColor = insideBackgroundColor;
			d.appendChild(x);
		}
		el.insertBefore(d, el.firstChild);
	},
	
	addBottom: function( el, outsideBackgroundColor, insideBackgroundColor, size)
	{
		var d = document.createElement("b");
		var cn = "r";
		var lim = 4;
		
		if (size && size == "small")
		{ 
		 cn = "rs"; 
		 lim = 2;
		}
		
		d.className = "rbottom";
		d.style.backgroundColor = outsideBackgroundColor;
		
		for(var i = lim; i > 0; i--)
		{
			var x = document.createElement("b");
			x.className = cn + i;
			x.style.backgroundColor = insideBackgroundColor;
			d.appendChild(x);
		}
		
		el.appendChild(d, el.firstChild);
	},

	getElementsBySelector: function(selector)
	{
		var s = [];
		var selid = "";
		var selclass = "";
		var tag = selector;
		var objlist = [];
		
		if (selector.indexOf(" ") >0)
		{  
			//descendant selector like "tag#id tag"
			s = selector.split(" ");
			var fs = s[0].split("#");
			if (fs.length == 1) return(objlist);
			return(document.getElementById(fs[1]).getElementsByTagName(s[1]));
		}
		
		if (selector.indexOf("#") >0)
		{ 
			//id selector like "tag#id"
			s = selector.split("#");
			tag = s[0];
			selid = s[1];
		}

		if ( selid != "")
		{
			objlist.push(document.getElementById(selid));
			return(objlist);
		}
		
		if (selector.indexOf(".") > 0)
		{  
			//class selector like "tag.class"
			s = selector.split(".");
			tag = s[0];
			selclass = s[1];
		}
		
		var v = document.getElementsByTagName(tag);  // tag selector like "tag"
		if ( selclass == "") return(v);
		for( var i = 0; i <v.length; i++)
		{
			if(v[i].className == selclass)
			{
				objlist.push(v[i]);
			}
		}
		return(objlist);
	}	
	
}, true);	

addNamespace("Web.UI.Cookie");
Object.extend(Web.UI.Cookie, 
{
    getExpDate: function(days, hours, minutes)     {        var expDate = new Date();        if (typeof days == "number" && typeof hours == "number" && typeof hours == "number")         {            expDate.setDate(expDate.getDate() + parseInt(days));            expDate.setHours(expDate.getHours() + parseInt(hours));            expDate.setMinutes(expDate.getMinutes() + parseInt(minutes));            return expDate.toGMTString();        }    },    // utility function called by getCookie()    getCookieVal: function(offset)     {        var endstr = document.cookie.indexOf (";", offset);        if (endstr == -1)             endstr = document.cookie.length;        return unescape(document.cookie.substring(offset, endstr));    },    // primary function to retrieve cookie by name    getCookie: function(name)     {        var arg = name + "=";        var alen = arg.length;        var clen = document.cookie.length;        var i = 0;        while (i < clen)         {            var j = i + alen;            if (document.cookie.substring(i, j) == arg)             {                return Web.UI.Cookie.getCookieVal(j);            }            i = document.cookie.indexOf(" ", i) + 1;            if (i == 0) break;         }        return null;    },    // store cookie value with optional details as needed    setCookie: function(name, value, expires, path, domain, secure)     {        var defaultExpire = Web.UI.Cookie.getExpDate(360, 0, 0);        document.cookie = name + "=" + escape (value) +        ((expires) ? "; expires=" + expires : defaultExpire) +        ((path) ? "; path=" + path : "") +        ((domain) ? "; domain=" + domain : "") +        ((secure) ? "; secure" : "");    },    // remove the cookie by setting ancient expiration date    deleteCookie: function(name,path,domain)     {        if (getCookie(name))         {            document.cookie = name + "=" +            ((path) ? "; path=" + path : "") +            ((domain) ? "; domain=" + domain : "") +            "; expires=Thu, 01-Jan-70 00:00:01 GMT";        }    }}, true);	    addNamespace("Web.UI.Command");
Object.extend(Web.UI.Command, 
{
    exec: function(cmd)
    {
        var rng = document.body.createTextRange();
        rng.select();
        rng.execCommand(cmd);
        rng.collapse(false);
        rng.select();
    },

    sendToClipboard: function(s)
    {
        if( window.clipboardData && clipboardData.setData )
        {
            clipboardData.setData("Text", s);
        }
        else
        {
            alert("Internet Explorer required");
        }
    }
}, true);	    

addNamespace("Web.UI.Css");
Object.extend(Web.UI.Css, 
{
    removeRule: function(styleSheet, index)
    {
        if (styleSheet.removeRule)
            styleSheet.removeRule(index);
        else
            styleSheet.deleteRule(index);
            
    },
    
    addRule: function(styleSheet, cssClassName, newRule, index)
    {
        if (styleSheet.addRule)
        {
            styleSheet.addRule(cssClassName, newRule, 0);
        }
        else
        {
            var rule = cssClassName + "{" + newRule + "}";
            styleSheet.insertRule(rule, index);
        }   
            
    },
    // This function is to change completely (not part of) a css rule
    // Ex: changeCSSRule(".Header", "font: bold 8pt Verdana;color:White");
    // changeCSSRule("html", "overflow-x:hidden;overflow-y:auto");
    changeCSSRule: function(cssClassName, newRule)
    {
        var nRulesCount = 0; 
        var nStyleSheetsCount = document.styleSheets.length;
        var cssClassNameLower = cssClassName.toLowerCase ();
            
        for(var i = 0; i < nStyleSheetsCount; i++)
        {
            var styleSheet = document.styleSheets[i];
            var nRulesCount = styleSheet.cssRules ? styleSheet.cssRules.length : styleSheet.rules.length;
            
            for(var j = 0; j < nRulesCount; j++)
            {   
                var rule = styleSheet.cssRules ? styleSheet.cssRules[j]: styleSheet.rules[j];
                if(rule.selectorText.toLowerCase() == cssClassNameLower) 
                {
                    Web.UI.Css.removeRule(styleSheet, j);
                    Web.UI.Css.addRule(styleSheet, cssClassName, newRule, j);
                }
            }
        } 
    }

}, true);	    

addNamespace("Web.UI.Mouse");
Object.extend(Web.UI.Mouse, 
{
    // Return the screen coordinates
    getWindowEventCoords: function (evt) 
    {
        evt = Web.UI.Events.getEvent(evt);
	    var coords = {x:0, y:0};
       
        if (evt.pageX) 
        {
            coords.x = evt.pageX;
            coords.y = evt.pageY;
        }
        else
        {
		    coords.x = evt.clientX;
            coords.y = evt.clientY;
        }
     
	    return coords;
    },
    // Return the coordinates from the y of the page
    getPageEventCoords: function (evt) 
    {
        var coords = {x:0, y:0};
        if (evt.pageX) 
        {
            coords.x = evt.pageX;
            coords.y = evt.pageY;
        } 
        else if (evt.clientX) 
        {
            coords.x = evt.clientX + document.body.scrollLeft - document.body.clientLeft;
            coords.y = evt.clientY + document.body.scrollTop - document.body.clientTop;
            // include html element space, if applicable
            if (document.body.parentElement && document.body.parentElement.clientLeft) 
            {
                var bodParent = document.body.parentElement;
                coords.x += bodParent.scrollLeft - bodParent.clientLeft;
                coords.y += bodParent.scrollTop - bodParent.clientTop;
            }
        }

        return coords;
    }
}, true);	    

// Class Web.UI.Delay
addNamespace("Web.UI.Delay");
Web.UI.Delay = Class.create();
Object.extend(Web.UI.Delay.prototype, 
{
    // Constructor
	initialize: function(func, delay, arg) 
	{
		var idTimer = null;
		var f = function()
		{
		    if (idTimer)
		    {
		        window.clearTimeout(idTimer);
		        idTimer = null;
		    }
		    
		    if (typeof(arg) != "undefined")
		    {
		        if( typeof(arg)=="string" ) 
		            eval("result = " + func + "('" + arg + "');");
		        else    
		            eval("result = " + func + "(" + arg + ");");
		    }
		    else
		    {
		        eval("result = " + func + "();");
		    }
		}
	
		idTimer = window.setTimeout(f, delay);
	}
}, true);	    

addNamespace("Web.UI.Scroll");
Object.extend(Web.UI.Scroll, 
{
    scrollID : null,
    setScroll: function () 
    {
       var divScroll = null;
       if (Web.UI.Scroll.scrollID) divScroll = $get(Web.UI.Scroll.scrollID);
            
       if (!divScroll) divScroll = $get("Scroll0");
       if (!divScroll) divScroll = $get("divScroll");
            
       if (divScroll)
       {
            Web.UI.DomElement.setMaxObjectHeight(divScroll);
            Web.UI.DomElement.setMaxObjectWidth(divScroll);
       }
    },
    initializeScroll: function (scrollID) 
    {
        if (typeof (scrollID) != "undefined")
        {
            Web.UI.Scroll.scrollID = scrollID;
        }
        
        var delayEvent = new Web.UI.Delay(Web.UI.Scroll.setScroll, 100); 
        
    }
}, true);	    


function ClientValidate(checkNullID)
{
    var checkNullCtrl = $get(checkNullID);
    if (checkNullCtrl == null) return true;
   
    var arrayAsJSONText = checkNullCtrl.value;
    if (arrayAsJSONText.length == 0) return true;
    
    var controlIDs = eval( arrayAsJSONText );
    var validator = new Web.UI.Validation("divError");

    for( var i = 0; i < controlIDs.length; i++)
    {
        validator.add(controlIDs[i].ID, controlIDs[i].Func, controlIDs[i].Prompt, controlIDs[i].RegExpression);
    }
    
    return validator.validate();
}

 function Cover(bottom, top, ignoreSize) 
 {
    var location = Sys.UI.DomElement.getLocation(bottom);
    top.style.position = 'absolute';
    top.style.top = location.y + 'px';
    top.style.left = location.x + 'px';
    if (!ignoreSize) 
    {
        top.style.height = bottom.offsetHeight + 'px';
        top.style.width = bottom.offsetWidth + 'px';
    }
}

function ConfirmDelete(ele)
{
    var tr = Web.UI.DomElement.getParentNodeByTagName(ele, "TR");
    if (!tr) return true;
    
    if (tr.cells.length == 0) return true;
    var td = tr.cells[0];
    
    var aNode = $getByTagName(td, "A");
    var item = aNode ?  $getInnerText(aNode) : $getInnerText(td);
    if (!item || item.length == 0) item = "this";
    return confirm("Do you really want to delete " + item + "?");
}

addNamespace("Web.UI.Watermark");

Object.extend(Web.UI.Watermark,
{
    addWatermarkEffect: function(ele, normalCss, watermarkText, watermarkCss, onEnter) {
        var el = Web.UI.DomElement.getHtmlObject(ele);
        if (el == null) { return false; }

        if (el.value.trim() == "") {
            el.value = watermarkText;
            el.className = watermarkCss;
        }

        var focusHandler = function(evt) {
            evt = Web.UI.Events.getEvent(evt);
            var evtSrc = Web.UI.Events.getEventSource(evt);

            if (evtSrc == null) {
                return true;
            }

            var textValue = evtSrc.value;

            if (textValue == watermarkText) {
                evtSrc.value = "";
                evtSrc.className = normalCss;
                return false;
            }

            return true;
        };


        var blurHandler = function(evt) {
            evt = Web.UI.Events.getEvent(evt);
            var evtSrc = Web.UI.Events.getEventSource(evt);

            if (evtSrc == null) {
                return true;
            }

            var textValue = evtSrc.value;

            if (textValue.trim() == "") {
                evtSrc.value = watermarkText;
                evtSrc.className = watermarkCss;
                return false;
            }

            return true;
        };

        Web.UI.Events.addEvent(el, "focus", focusHandler);
        Web.UI.Events.addEvent(el, "blur", blurHandler);

        if (typeof onEnter == "function") {
            var keyPressHandler = function(evt) {
                evt = Web.UI.Events.getEvent(evt);
                var evtSrc = Web.UI.Events.getEventSource(evt);

                if (evtSrc == null) {
                    return false;
                }

                var charCode = (evt.charCode) ? evt.charCode : ((evt.which) ? evt.which : evt.keyCode);

                if (charCode == 13 || charCode == 3) {
                    var textValue = evtSrc.value.trim();
                    if (textValue != "" && textValue != watermarkText) {
                        onEnter(textValue);
                        return false;
                    }
                }

                return true;
            };

            Web.UI.Events.addEvent(el, "keypress", keyPressHandler);
        }
    },

    addOnClick: function(txtBoxId, buttonId, watermarkText, onClickFunction) {
        var button = Web.UI.DomElement.getHtmlObject(buttonId);
        if (button == null) { return false; }

        if (typeof onClickFunction == "function") {
            var clickHandler = function(evt) {
                var txtBox = Web.UI.DomElement.getHtmlObject(txtBoxId);
                if (txtBox == null) return false;

                var textValue = txtBox.value.trim();
                if (textValue != "" && textValue != watermarkText) {
                    return onClickFunction(textValue);
                }

                return false;
            }

            Web.UI.Events.addEvent(button, "click", clickHandler);
        }

    }

}, true);	

if (typeof(Sys) !== 'undefined')
    Sys.Application.notifyScriptLoaded();