    var $aa = {};
    
    var MLX_ValidEmailRegExp = /^([a-zA-Z0-9_\.\-\'\=])([a-zA-Z0-9_\.\-\'\=])*\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
    var MLX_ValidEmailCharacters = "letters, numbers, .'-_ or = (period, apostrophe, hyphen, underscore or equals sign)"
    function SE_ClickOnEnterKey(e, btn)
    {
        // causes a button press on enter key press
        // process only the Enter key
        if (!e) e = window.event;
        
        if (e.keyCode == 13)
        {
            // ingore the event if the source element is a textarea (where hitting the enter key produces a line break)
            if (!e.srcElement || (e.srcElement && e.srcElement.type != "textarea"))
            {
                // cancel the default submit
                SE_CancelEvent(e)
                // submit the form by programmatically clicking the specified button
                btn.click();
            }
            return false;
        }
        else
            return true;
    }
    
    function SE_CallOnEnterKey(e, callbackFunction)
    {
        // causes a button press on enter key press
        // process only the Enter key
        if (!e) e = window.event;
        
        if (e.keyCode == 13)
        {
            // ingore the event if the source element is a textarea (where hitting the enter key produces a line break)
            if (!e.srcElement || (e.srcElement && e.srcElement.type != "textarea"))
            {
                // cancel the default submit
                SE_CancelEvent(e)
                // submit the form by programmatically clicking the specified button
                callbackFunction();
            }
            return false;
        }
        else
            return true;
    }
    
    function SE_CancelEnterKey(e)
    {
        if (!e) e = window.event;
        if (e && e.keyCode == 13)
            return !SE_CancelEvent(e);
        else
            return false;
    }

    function SE_CancelEnterKeyOnly(e) {
        if (!e) e = window.event;
        if (e && e.keyCode == 13)
            return !SE_CancelEvent(e);
        else
            return true;
    }
    function SE_CancelEvent(e)
	{
		if (!e)
			e = window.event;
		if (e)
		{
			if (e.stopPropagation)
				e.stopPropagation();
			
			if (e.preventDefault)
				e.preventDefault();

			e.returnValue = false;
			e.cancelBubble = true;
		}
		return false; 
	}

    function SE_StopEvent(a)
    {
        if (typeof (a) == "undefined" || !a) {
        var a = window.event;
        }
        if (a && typeof (a) != "undefined") {
            a.cancelBubble = true;
            if (a.stopPropagation) {
                a.stopPropagation();
            }
        }
        return false; 
    }
	
	function SE_JSDelay(count)
	{
		// sort of a DoEvents for Js - it allows the browser or other client threads to catch up
		if (!count)
			count = 1000;
		var msieVersion = SE_MSIEVersion() ;
		if (!msieVersion || parseInt(msieVersion) < 7)
			count = Math.round(count * 1.3);			
		// just loop creating a bigger and bigger text string
		var delayText = "";
		for(var i=0; i<count; i++)
			delayText += "delay";
	}
	
	function SE_SelectDefault(ctl, defaultValue)
	{
        if (ctl && ctl.value != '')
        {
            if(ctl.value == defaultValue
                || ctl.value == '0' 
                || ctl.value == '0.0' 
                || ctl.value == '$0' 
                || ctl.value == '$0.00')
            {
                ctl.select();
            }
        }
    }
	
	function SE_UserAgent(userAgentText)
	{
		userAgentText = userAgentText.toLowerCase();
        var _userAgent = navigator.userAgent.toLowerCase();
		if (userAgentText == "msie")
			return (_userAgent.indexOf(userAgentText) != -1) && (_userAgent.indexOf('opera') == -1) ;
		else
			return _userAgent.indexOf(userAgentText) != -1;
	}
	
	function SE_MSIEVersion()
	{
		if (SE_UserAgent("msie"))
		{
			re = new RegExp(/MSIE (\d)/g)
			found = re.exec(navigator.userAgent);
			if (found.length > 1)
			{
				try
				{
					var ver = parseInt(found[0]);
					if (!isNaN(ver))
						return ver
					else
					{
						ver = parseInt(found[1]);
						if (!isNaN(ver))
							return ver
					}				
				}	
				catch(e){}
			}
		}
		return 0;
	}
	
	function SE_GetCookie(name)
	{
		return SE_GetDocumentCookie(document, name)
	}
	function SE_GetDocumentCookie(doc, name)
	{
		var cookieName = name + "=";
		var objCookie = doc.cookie;
		var cookieStart;
		var cookieEnd;
		if(objCookie.length > 0)
		{
			cookieStart = objCookie.indexOf(cookieName);
			if(cookieStart != -1)
			{
				cookieStart += cookieName.length;
				cookieEnd = objCookie.indexOf(";",cookieStart);
				if(cookieEnd == -1)
				{
					cookieEnd = objCookie.length;
				}
				return unescape(objCookie.substring(cookieStart,cookieEnd));
			}
		}
		return null;
	}
	
	function SE_SetCookie(name, value, expires)
	{
		document.cookie = name + "=" + escape(value) + "; path=/" + 
		((expires == null) ? "" : "; expires=" + expires.toGMTString());
	}
	
	function SE_SupportsCookies()
	{
	    SE_SetCookie('cookieTest', 'passed');
        return SE_GetCookie('cookieTest') == 'passed';
	}
	
	function SE_GetQueryArgs(s)
	{
		//returns name/value objects from a querystring
		var args = new Object()
		if(s.indexOf("?") == -1)
			var query = s;
		else
			var query = s.substring(s.indexOf("?")+1);
		var pairs = query.split("&");
		
		for(var i=0;i<pairs.length;i++)
		{
			var pos = pairs[i].indexOf("=");
			if (pos == -1) continue;
			var argname = pairs[i].substring(0,pos).toLowerCase();
			var value = pairs[i].substring(pos+1);
			args[argname] = unescape(value);
		}
		return args;
	}
	
	function SE_ExtractAttributeFromTag(tag, sText)
	{
	    reTest = new RegExp(tag + '=[\'"]?([^\'" ]*)[\'" ]', 'gi');
	    found = reTest.exec(sText);
		if (found && found.length > 1)
		{
		    return found[1];
	    }
	    return "";
	}
	function SE_StripDollarComma(test)
    {
        var s = "";
         if (test)
         {
            if (typeof(test) == "string")
                s = test;
            else if (typeof(test) == "object")
                s = test.value;
            if (s != "")
            { 
                re = new RegExp('[,\$]', 'gi');
                s = s.replace(re, "");
            }               
         }
         if (test && typeof(test) == "object")
            test.value = s;
         return s;
    }
	function SE_StripNonNumeric(test)
    {
         var s = "";
         if (test)
         {
            if (typeof(test) == "string")
                s = test;
            else if (typeof(test) == "object")
                s = test.value;
            if (s != "")
            { 
                re = new RegExp('[^0-9\.-]', 'gi');
                s = s.replace(re, "");
            }               
         }
         if (test && typeof(test) == "object")
            test.value = s;
         return s;
     }
     function SE_StripNonDigit(test) {
         var s = "";
         if (test) {
             if (typeof (test) == "string")
                 s = test;
             else if (typeof (test) == "object")
                 s = test.value;
             if (s != "") {
                 re = new RegExp('[^0-9]', 'gi');
                 s = s.replace(re, "");
             }
         }
         if (test && typeof (test) == "object")
             test.value = s;
         return s;
     }
	
	function SE_SetDropDown(dropDown, values)
	{
		var v = "[" + values.replace(",","],[") + "]";
		
		for(var i=0; i<dropDown.options.length; i++)
		{
			if(v.indexOf("[" + dropDown[i].value + "]")>-1)
			{
				dropDown[i].selected = true;
			}
		}
	}

    // This method is also duplicated in /common/Mobile/mobile.js, 
    // so if you fix a bug here please fix this file also
    function SE_LoadDropDownWithIntegers($dropDown, minValue, maxValue, selectedValue)
    {
   
        var pages = [];
        for(var iPage = 1; iPage <= maxValue; iPage++)
        {
            pages.push("<option>" + iPage.toString() + "</option>");
        }
        var options = pages.join('\
            ');
        $dropDown.html(options);
        $dropDown.val(selectedValue);
    }


	function SE_AppendEvent(origEvent, newMethod)
	{
		// we will actually format the tables in the onload event 			
		if (!origEvent)	
			origEvent = newMethod;
		else 
		{
			re = /function (\w*)/gi
			origname = re.exec(origEvent.toString())
			if (origname[1] && newMethod.toString().indexOf(origname[1]) == -1)
			{	
				var prev_onload = origEvent;
				origEvent = function() { prev_onload(); newMethod();}
			}
		};
		return origEvent;
	}	
	
	function SE_GetHttpText(url, returnHeaderName)
	{
		// synchronous request
		oHttpRequest = SE_GetXmlHttp();
		if (oHttpRequest)
		{
			oHttpRequest.open('GET', url, false);
			oHttpRequest.send(null);
			if (returnHeaderName)
				return oHttpRequest.getResponseHeader(returnHeaderName);
			else
				return oHttpRequest.responseText
		}
		return null;
	}
	
	function SE_LoadXML(txt)
	{
	    try //Internet Explorer
        {
            xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
            xmlDoc.async="false";
            xmlDoc.loadXML(txt);
            return xmlDoc; 
        }
        catch(e)
        {
            parser = new DOMParser();
            xmlDoc = parser.parseFromString(txt,"text/xml");
            return xmlDoc;
        }
    }
	
	function SE_PostHttpText(url, postData, returnHeaderName)
	{
		// synchronous request
		oHttpRequest = SE_GetXmlHttp();
		if (oHttpRequest)
		{
			oHttpRequest.open("POST", url, false);
			oHttpRequest.send(postData);
			
			if (returnHeaderName)
				return oHttpRequest.getResponseHeader(returnHeaderName);
			else
				return oHttpRequest.responseText
		}
		return null;
	}	
	
	function SE_AsyncHttpXml(serverURL, xml, callbackFunction)
	{
		var httpRequest = SE_GetXmlHttp();

		if(httpRequest != null)
		{
			try
			{
				httpRequest.open("POST", serverURL, true);
				httpRequest.setRequestHeader("Content-Type", "text/xml");
				if (callbackFunction)
				{
				    httpRequest.onreadystatechange = function(){
					    SE_WatchState(httpRequest, callbackFunction);
				    };
				}
				httpRequest.send(xml);
				return httpRequest;
			}
			catch(e)
			{
				return null;
			}
		}
		else
			return null;
	}
	
	function SE_AsyncHttp(serverURL, callbackFunction)
	{
		var httpRequest = SE_GetXmlHttp();

		if(httpRequest != null)
		{
			try
			{
				httpRequest.open("GET", serverURL, true);
				if (callbackFunction)
				{
				    httpRequest.onreadystatechange = function(){
					    SE_WatchState(httpRequest, callbackFunction);
				    };
				}
				httpRequest.send(null);
				return httpRequest;
			}
			catch(e)
			{
				return null;
			}
		}
		else
			return null;
	}
	
	function SE_WatchState(Response, callbackFunction)
	{
		if(Response.readyState == 4)
			callbackFunction(Response);
	} 
	
	function SE_GetXmlHttp()
	{
		var httpRequest = null;
	
		if (window.XMLHttpRequest)
			httpRequest = new XMLHttpRequest();
		else if (window.ActiveXObject)
			httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
		
		return httpRequest;
	}
	
	function SE_GetArgs(s)
	{
		//returns name/value objects from a querystring
		var args = new Object()
		if(s.indexOf("?") == -1)
			var query = s;
		else
			var query = s.substring(s.indexOf("?")+1);
		var pairs = query.split("&");

		for(var i=0;i<pairs.length;i++)
		{
			var pos = pairs[i].indexOf("=");
			if (pos == -1) continue;
			var argname = pairs[i].substring(0,pos).toLowerCase();
			var value = pairs[i].substring(pos+1);
			args[argname] = unescape(value);
		}
		args.count = pairs.length;
		return args;
	}
	
	function MLX_HandleCallback()
    {
        var args = SE_GetArgs(location.search);
        
        if (args["callback"] && args["callback"].length > 0)
        {
            var callbackMethod = args["callback"];
            
            if (opener && eval('opener.' + callbackMethod))
                eval('opener.' + callbackMethod + '(document)');
            else if (parent && eval('parent.' + callbackMethod))
                eval('parent.' + callbackMethod + '(document)');
        }
    }
	
	function SE_BuildQueryString(args, skipQ)
	{
		var queryString = "";
		var qm = "?";
		if (skipQ) qm = "";
		for(var arg in args)
		{
			if (arg != "count")
				queryString += (queryString == "" ? qm : "&") + arg + "=" + SE_URLEncode(args[arg]);
		}
		return queryString;
	}
	function SE_BuildQueryStringWithoutDups(oldQsArgs, newQsArgs) {
	    var qsOldArgs = SE_GetArgs(oldQsArgs);
	    var qsNewArgs = SE_GetArgs(newQsArgs);
	    for (var arg in qsNewArgs) {
	        if (!qsOldArgs[arg])
	            qsOldArgs[arg] = qsNewArgs[arg];
	    }
	    return SE_BuildQueryString(qsOldArgs);
	}
	
	function SE_URLEncode(plaintext)
	{
		return encodeURIComponent(plaintext);
	}
	
	function SE_FindChildNode(startNode, id, isLike)
	{
		if (startNode && startNode.childNodes)
		{
			var iCount = startNode.childNodes.length ;
			var childNode = null;
			for(var i=0; i<iCount; i++)
			{	
				thisNode = startNode.childNodes[i];
				if (thisNode.id && (thisNode.id.toUpperCase() == id.toUpperCase()))
					return thisNode;
				else if (isLike && thisNode.id && (thisNode.id.toUpperCase().indexOf(id.toUpperCase()) > -1))
					return thisNode;
				else
				{
					childNode = SE_FindChildNode(thisNode, id, isLike);
					if (childNode != null) 
					    return childNode;
				}
			}		
		} 
		return null;		
	}
	function SE_FindChildNodeByName(startNode, name)
	{
        var $startNode;
        
        if (startNode && typeof(startNode.documentElement) != 'undefined')
            $startNode = $(document);
        else
        {
            var origID = ""
            if (typeof(startNode.id) != 'undefined' && startNode.id != "")
                origID = startNode.id;
            if (origID == "")
                startNode.id = "mlx_findnode_" + MLX_UniqueString();
            $startNode = $("#" + startNode.id);
        }
        var $child = $startNode.find(name);
        if ($child.length > 0)
            return $child[0];
//		if (startNode && startNode.childNodes)
//		{
//			var iCount = startNode.childNodes.length ;
//			var childNode = null;
//			for(var i=0; i<iCount; i++)
//			{	
//				thisNode = startNode.childNodes[i];
//				if (
//				    (
//				        thisNode.nodeName && thisNode.nodeName.toUpperCase()  
//				        && (thisNode.nodeName.toUpperCase() == name.toUpperCase())
//				    )
//				    || 
//				    (
//				        thisNode.name && thisNode.name.toUpperCase()  
//				        && (thisNode.name.toUpperCase() == name.toUpperCase())
//				    )
//				)
//					return thisNode;
//				else
//				{
//					childNode = SE_FindChildNodeByName(thisNode, name);
//					if (childNode != null) return childNode;
//				}
//			}		
//		}
		return null;		
	}
	
	function SE_FindNextElement(currentNodeID, elementType)
	{
	    var elementNodes = new Array();
	    SE_FindAllNodes(document.documentElement, elementType, elementNodes);
	    var found = false;
	    
	    for (var i=0; i< elementNodes.length; i++)
	    {
	        if (found)
	            return elementNodes[i];
	        if (elementNodes[i].id == currentNodeID)
	            found = true;
	    }
	    
	}
	function SE_FindAllNodes(startNode, elementType, elementNodes, subType)
	{
	    if (startNode && startNode.childNodes)
		{
			var iCount = startNode.childNodes.length ;
			var childNode = null;
			for(var i=0; i<iCount; i++)
			{	
				thisNode = startNode.childNodes[i];
				if (thisNode.tagName 
				    && thisNode.tagName.toLowerCase() == elementType.toLowerCase()
				    && thisNode.style.display.toLowerCase() != "none"
				    && thisNode.type.toLowerCase() != "hidden"
				    && 
				    (
				        (!subType && thisNode.type.toLowerCase() != "radio")
				        || 
				        (subType && subType.toLowerCase() == 'radio' && thisNode.type.toLowerCase() == "radio")
				        || 
				        (subType && subType.toLowerCase() == 'checkbox' && thisNode.type.toLowerCase() == "checkbox")
				     )
				    )
				    elementNodes[elementNodes.length] = thisNode;
				SE_FindAllNodes(thisNode, elementType, elementNodes, subType);
			}
		}
	}
	
	function SE_FindChildNodeByValue(startNode, name, value)
	{
		if (startNode && startNode.childNodes)
		{
			var iCount = startNode.childNodes.length ;
			var childNode = null;
			for(var i=0; i<iCount; i++)
			{	
				thisNode = startNode.childNodes[i];
				if (thisNode.nodeName && thisNode.nodeName.toUpperCase() && (thisNode.nodeName.toUpperCase() == name.toUpperCase()))
				{
				    if (thisNode.value == value)
				        return thisNode;
				}
				else
				{
					childNode = SE_FindChildNodeByValue(thisNode, name, value);
					if (childNode != null) return childNode;
				}
			}		
		}
		return null;		
	}

	function SE_FindChildNodeByClass(startNode, className, fCloseMatch)
	{
		var fExactMatch = !fCloseMatch;
		if (startNode && startNode.childNodes)
		{
			var iCount = startNode.childNodes.length ;
			var childNode = null;
			for(var i=0; i<iCount; i++)
			{	
				thisNode = startNode.childNodes[i];
				if (thisNode.className && thisNode.className.toUpperCase &&
				        (
				            (fExactMatch && thisNode.className.toUpperCase() == className.toUpperCase())
				            || (!fExactMatch && thisNode.className.toUpperCase().indexOf(className.toUpperCase()) > -1)
				        )
				   )
					return thisNode;
				else
				{
					childNode = SE_FindChildNodeByClass(thisNode, className, fCloseMatch);
					if (childNode != null) return childNode;
				}
			}		
		} 
		return null;		
	}
	
	
	function SE_HideChildNode(startNode, id)
	{
	    SE_FindChildNode(startNode,id).style.display='none'
	}	
	function SE_ShowChildNode(startNode, id)
	{
	    SE_FindChildNode(startNode,id).style.display='block'
	}
	
	function MLX_RemoveChildNodes(parent)
	{
        while(parent.hasChildNodes()){
            parent.removeChild(parent.childNodes[0])
        }
    }  
    
    function MLX_FindParentNodeById(selectedElement, parentID)
    {
        var testElement = selectedElement;
        while (testElement)
        {
            if (testElement.id == parentID)
                return testElement;
            else
                testElement = testElement.parentNode;           
        }
        return null;
    }
    
    function MLX_GetBackgroundColor(element)
	{
        while (element)
        {
            if (element.currentStyle && element.currentStyle.backgroundColor != 'transparent')
                return element.currentStyle.backgroundColor;
            else
                element = element.parentNode;
        }
        return "white";
    }  
	
	
    function MLX_GetPreviousSibling(elem)
    {
        // cross browserver version of previsousibling
        var prevElem = elem.previousSibling;
        while (prevElem && prevElem.nodeName == '#text')
        {
            prevElem = prevElem.previousSibling;
        }
        return prevElem;
    }
			
	
	function SE_OpenWin(url, width, height, name, params)
	{
		return SE_OpenWin_base(url, width, height, name, params);	
	}
	
	function SE_OpenWin2(url, width, height, name, params)
	{
		SE_OpenWin_base(url, width, height, name, params)	
	}
	
	function SE_LN_OpenWin(url, width, height, name)
	{
		if(!width) width = 525;
		if(!height) height = 657;
		if (!name) name = "_blank";
		SE_OpenWin(url, width, height, name);
	}
	function SE_PrintWhenLoaded(delay)
	{
	    if (!delay)
	        delay = 1000;
	    if (document.readyState.indexOf("complete") != -1)
	        window.print();
	    else
	        setTimeout('SE_PrintWhenLoaded(' + delay + ')', delay);
	}
	
	function SE_OpenWin_base(url, width, height, name, params)
	{
		var sh = screen.availHeight;
		var sw = screen.availWidth;
		var options = "";
		if(!width) width = 525;
		if(!height) height = 657;
		if (!name) name = "_blank";
		if (params)
			options = params;
		else
			options =  'dependent=1,fullscreen=0,toolbar=0,status=0,menubar=0,scrollbars=1,resizable=1,directories=0,location=0,';
		options += 'width=' + width + ',height=' + height + ',top=' + (sh-height)/2 + ',left=' + (sw-width)/2;
		
		var win = window.open(url, name, options);
		if (!win)
			SE_PopupBlocked_Warning();
		else
			win.focus();	
		return win;	
	}
	
	function SE_PopupBlocked_Warning()
	{
		setTimeout("SE_OpenTooltip('A popup blocker prevented the page you requested from opening.')", 1000);
	}
	
	function SE_GetServerUrl()
	{
		return window.location.protocol + "//" + window.location.hostname 
	}
	
	function SE_CurrentFolderURL()
	{
	    return document.location.pathname.substring(0, document.location.pathname.lastIndexOf("/"))
	}
	
	function SE_PrepURL(url)
	{
		return url + (url.indexOf("?") > 0 ? (!url.match(/&$/) ? "&" : "") : "?");
	}
	
	function SE_WriteItemNum()
    {
        if (!document.itemNum || document.itemNum == "")
            document.itemNum = 1;
        document.write(document.itemNum);
        document.itemNum++;
    }
    
    function MLX_SetBodyHeightToContentHeight() 
    {
        document.body.style.height = 
            Math.max(document.documentElement.scrollHeight, document.body.scrollHeight) + "px";
    }
    
    function MLX_SetBodyWidthToContentWidth() 
    {
        var onlyChildIndex = -1;
        if (document.body && document.body.childNodes)
        {
            for(var i=0; i<document.body.childNodes.length; i++)
            {
                if (document.body.childNodes[i].tagName != "SCRIPT")
                {
                    if (onlyChildIndex == -1)
                        onlyChildIndex = i;
                    else
                    {
                        onlyChildIndex = -1;
                        break;
                    }
                }   
            }         
        }    
        if (onlyChildIndex != -1)
            document.body.style.width = 
                document.body.childNodes[onlyChildIndex].scrollWidth + "px";

        else
            document.body.style.width = 
                Math.max(document.documentElement.scrollWidth, document.body.scrollWidth) + "px";
    }
     
     function MLX_GetContentHeight(doc) 
     {
        if (!doc.body && doc.documentElement && doc.documentElement.scrollHeight)
            return doc.documentElement.scrollHeight;
        else if(doc.body.scrollHeight)
            return doc.body.scrollHeight;
        else
            return doc.documentElement.scrollHeight;
     }
    
    function SE_ResizeToFitBodyContent()
    {
        MLX_SetBodyHeightToContentHeight() ;
        MLX_SetBodyWidthToContentWidth() ;
        SE_ResizeToFitContent();
    }
    
    
    function SE_ResizeToFitContent(noRestriction)
    {
        if (document && document.body && document.body.offsetWidth)
        {
            var xHeight = Math.min(document.body.scrollHeight, .8 * screen.availHeight) - Math.max(MLX_GetClientHeight(), document.documentElement ? document.documentElement.offsetHeight : 0);
            var xWidth = Math.min(document.body.scrollWidth, .8 * screen.availWidth) - Math.max(MLX_GetClientWidth(), document.documentElement ? document.documentElement.offsetWidth : 0);
            if (noRestriction)
            {
                xHeight = document.body.scrollHeight - MLX_GetClientHeight();
                xWidth = document.body.scrollWidth - MLX_GetClientWidth();
            }
            window.resizeBy( xWidth,  xHeight);
            if (noRestriction)
            {
                xHeight = document.body.scrollHeight - MLX_GetClientHeight();
                xWidth = document.body.scrollWidth - MLX_GetClientWidth();
            }
            else
            {
                xHeight = Math.min(document.body.scrollHeight, .8 * screen.availHeight) - MLX_GetClientHeight();
                xWidth = Math.min(document.body.scrollWidth, .8 * screen.availWidth) - MLX_GetClientWidth();
            }
            window.resizeBy( xWidth,  xHeight);

        }
    }
    
    function MLX_ResizeImageElementToFit(originalImage, resizedImage, maxWidth, maxHeight)
    {
        if(originalImage.offsetWidth > maxWidth || originalImage.offsetHeight > maxHeight)
        {
            var ratioX = originalImage.offsetWidth/maxWidth;
            var ratioY = originalImage.offsetHeight/maxHeight;
            var ratio = ratioY > ratioX ? 1/ratioY : 1 / ratioX;
            resizedImage.width = parseInt(ratio * originalImage.offsetWidth);
            resizedImage.height = parseInt(ratio * originalImage.offsetHeight);
        }
        return resizedImage;
    }

	function SE_CenterElement(myElement)
	{
		if (myElement)
		{
			myElement.style.display = "";
			myElement.style.position = "absolute";
			myElement.style.left = (MLX_GetClientWidth()/2 - myElement.offsetWidth/2 + MLX_GetScrollLeft()) + "px";
			
			var top = MLX_GetClientHeight() / 2 - myElement.offsetHeight / 2 + MLX_GetScrollTop();
			if (top > 0)
			    myElement.style.top = top + "px";
		}
	}


	function SE_CenterElementOnElement(myElement, targetElement)
	{
		if (myElement && targetElement)
		{
			myElement.style.position = "absolute";
			myElement.style.left = (SE_GetObjectLeft(targetElement) + targetElement.offsetWidth/2 - myElement.offsetWidth/2) + "px";
			myElement.style.top = (SE_GetObjectTop(targetElement) + targetElement.offsetHeight/2 - myElement.offsetHeight/2) + "px";
		}
    }

    function SE_Toggle_LoadingCover($container, addCover, contentHTML, opacity)
    {
    
        var $coverDiv = $("#loadingDiv");
        if (addCover && !$coverDiv.is(":visible")) {
            if($coverDiv.length == 0)
                $coverDiv = $("<div id='loadingDiv' style='position:absolute;'></div>").appendTo($container);
            
            if ($container.css("position") == "absolute"
            || $container.css("position") == "relative") {
                $coverDiv.css("top", "0px");
                $coverDiv.css("left", "0px");
            }
            else {
                $coverDiv.css("top", $container.position().top + "px");
                $coverDiv.css("left", $container.position().left + "px");
            }
            $coverDiv.width($container.outerWidth(true));
            $coverDiv.height($container.outerHeight(true));

            if (!contentHTML) {
                var oImage = new Image();
                oImage.src = '/common/images/rotating_arrow.gif';
                contentHTML = "<img src='/common/images/rotating_arrow.gif' alt='Loading' /><br/>Loading...";
            }
            
            var $messageDiv = $("<div class='modalmessage'>" 
                + contentHTML + "</div>" ).appendTo($coverDiv);
            $messageDiv.css("top", Math.min(100, ($coverDiv.height() - $messageDiv.outerHeight(true)) / 2) + "px");
            $messageDiv.css("left", ($coverDiv.width() - $messageDiv.outerWidth(true)) / 2 + "px");      
            
            var $backgroundDiv = $("<div class='modalcover'><div>").appendTo($coverDiv);
            $backgroundDiv.width("100%");
            $backgroundDiv.height("100%");
            if (opacity)
                $backgroundDiv.css("opacity", opacity);
            
        }
        else
        {
           $coverDiv.remove();
        }
    }

    function MLX_Confirm($dialog, continueMethod, dialogClass)
    {
        $dialog.dialog({
            resizable: false,
            modal: true,
            dialogClass: dialogClass,
            width:400,
            buttons: {
                "Continue": function () {
                    $(this).dialog("close");
                    continueMethod();
                },
                Cancel: function () {
                    $(this).dialog("close");
                }
            }
        });       
    }

    $aa.modalDialog = function (url, title, dialogClass, width, height,  partial_page_selector)
    {
        // to add or change buttons:
        //  var mydialog = new $aa.modalDialog(summary_url, "Search Summary", "search_summary_modal", 300, 300, "#profile_summary" );     
        //  mydialog.addButtons( {"OK": function () {
        //        myDialog.$dialog.dialog("close");
        //    }});
        
        this.$dialog = $("<div></div>");
        this.$dialog.load(url);
        if (partial_page_selector)
        {
            $partial = this.$dialog.find(partial_page_selector)
            if ($partial.length > 0)
                this.$dialog.replaceWith($partial);
        }
        this.$dialog.dialog({
            title: title,
            resizable: true,
            modal: true,
            dialogClass: dialogClass,
            width: width
            }
        );  
        myDialog = this;
        this.addButtons = function(buttons)
        {   
            myDialog.$dialog.dialog("option", "buttons", buttons);       
        }
        this.addButtons( {"OK": function () {
            myDialog.$dialog.dialog("close");
        }});        

    }

    function MLX_ConfirmWithCancelLink($dialog, continueMethod, dialogClass, contineText, cancelText, cancelMethod)
    {
        var buttons = {}; 
        buttons[contineText] = function() { $(this).dialog("close"); continueMethod(); } 
        buttons[cancelText] = function() { $(this).dialog("close"); cancelMethod(); } 

        $dialog.dialog({
            resizable: false,
            modal: true,
            dialogClass: dialogClass,
            width:400,
            buttons: buttons
        });   
        
        var firstButton = $('.ui-dialog-buttonpane button:last');
        firstButton.css('border','0px').find('span.ui-button-text').css('text-decoration','underline');
    }
    
    function MLX_LoadingDialog(show, dialogStyle, html, timeout) {
    
        var $dialogDiv = $(".loading_dialog")
        if ($dialogDiv.length == 0)
            $dialogDiv = $("<div class=\"loading_dialog " + (dialogStyle ? dialogStyle : "") + "\"><div class=\"loading_dialog_content\" ></div></div>");
        if(timeout == null)
            timeout = 400;

        if (show)
        {
            if (html)
            {
                if ($dialogDiv.find(".loading_dialog_content").length > 0)
                    $dialogDiv.find(".loading_dialog_content").html(html);
                else
                    $dialogDiv.html(html);
            }
            else 
                $dialogDiv.html('\
                    <div class="loading_dialog_content" >\
                        <img src="/common/images/rotating_arrow.gif" style="vertical-align:middle;font-weight:bold;" /> Loading ...\
                    </div>');
            timeout = setTimeout(function () {
                $dialogDiv.dialog({draggable:false,resizable:false,height:100});
                $dialogDiv.parent().cl_shadow();
                $dialogDiv.parent().find(".ui-dialog-titlebar").hide();
            }, timeout);
        }
        else {
            $dialogDiv.dialog("destroy");
            clearTimeout(timeout);
            timeout = null;
        }
        return timeout;
    }	
	
	function MLX_IsClickInDiv(e, div)
	{
		if (!e) e = window.event;
		if (e && e.clientX)
	    {
		    var mousex = e.clientX + MLX_GetScrollLeft() ;
			var mousey = e.clientY + MLX_GetScrollTop() ;
    		return MLX_IsInDiv(mousex, mousey, div)
         }
	}
	function MLX_IsInDiv(x, y, div)
	{
		if (div)
	    {
		    var divLeft = SE_GetObjectLeft(div);
		    var divTop = SE_GetObjectTop(div);
		    
		    return (
			    (x < divLeft + div.offsetWidth)
			    && (x > divLeft)
			    && (y < divTop + div.offsetHeight)
			    && (y > divTop)
		    )	;
	    }
	    else
		    return true;
	}
	
	function MLX_SlideToFitOnScreen(divPopup, margin)
	{
		if (divPopup)
		{
			var _left = SE_GetObjectLeft(divPopup);
			var _clientHeight = MLX_GetClientHeight();
			if (!margin)
			    margin = 10;
			    
			var clientWidth = MLX_GetClientWidth();
			var rightOverlap = _left + divPopup.offsetWidth - MLX_GetScrollLeft() - clientWidth;
		    var leftExtraSpace = MLX_GetClientWidth() - divPopup.offsetWidth ;
		
		    if (rightOverlap > - margin )
		    {
			    // not enough room on right - is there room on the left?
			    if (leftExtraSpace > 0)
				    divPopup.style.left = Math.max(_left - rightOverlap - margin, 0) + "px";
			    else
			        divPopup.style.left = Math.max(MLX_GetScrollLeft() + margin, 0) + "px";
			}
			
			var _parentTop = SE_GetObjectTop(window.frameElement) - MLX_GetParentScrollTop();
			var _top = SE_GetObjectTop(divPopup) ;
			
			var clientHeight = MLX_GetClientHeight();
			var parentClientHeight = MLX_GetParentClientHeight();
			    
			if (clientHeight > parentClientHeight)
			   clientHeight = parentClientHeight;
			   
			var bottomOverlap = _top +  divPopup.offsetHeight + _parentTop - MLX_GetScrollTop() - clientHeight;
          
            var topExtraSpace = MLX_GetClientHeight() - divPopup.offsetHeight ;
			
		    if (bottomOverlap > - margin )
		    {
			    // not enough room on right - is there room on the left?
			    if (topExtraSpace > 0)
			    {
				    if (_top - bottomOverlap - margin > 0)
				        divPopup.style.top = (_top - bottomOverlap - margin, 0) + "px";
				    else
				    {
				        var needToScroll = (_top - bottomOverlap - margin);
				        divPopup.style.top = "0px";
				        parent.scrollBy(0, -needToScroll);
				    }
				}
			    else
			        divPopup.style.top = Math.max(MLX_GetScrollTop()) +"px";
			}				
		 }
	}	
	
	var SE_PopupCenterOn = null;
	var SE_PopupTimeout = null;
	var SE_TooltipStart
	function SE_OpenTooltip(msg, divTip, centerOnElement, parentElement, startAfter, closeAfter)
	{
		if (centerOnElement)
		    SE_PopupCenterOn = centerOnElement;
		else
		    centerOnElement = SE_PopupCenterOn;		    
		if (parentElement)
	    {
	         parentElement.onmouseout=SE_CloseTooltip;
             parentElement.onmousedown=SE_CloseTooltip;
             parentElement.onkeydown=SE_CloseTooltip;
	    }
		if (startAfter)
		{
		    SE_PopupTimeout = setTimeout("SE_OpenTooltip('" + msg + "', null, null, null, null," + (closeAfter ? closeAfter : "null") + ")", startAfter);
		    return;
		}
		if (!divTip)
		    divTip = document.getElementById('divMessage');
		
		if (!divTip)
		{
			
			divTip = document.createElement("div");
			if (centerOnElement && centerOnElement.parentNode) 
			    centerOnElement.parentNode.appendChild(divTip);
			else if (document.body)
			    document.body.appendChild(divTip);
		    divTip.id = "divMessage";
		}
		
		
		divTip.style.position = "absolute";
		divTip.style.backgroundColor = "#FFFFCC";			
		divTip.style.filter = "alpha(opacity=90)";
		divTip.style.opacity = ".90";
		divTip.style.mozopacity = ".95";
		divTip.style.zIndex = "99999";
		divTip.style.border = "1px #444444 solid";
		divTip.style.padding = "2px";
		divTip.style.padding = "10px";
		divTip.style.whitespace = "nowrap";
		if (msg && msg != "")
		    divTip.innerHTML = msg;
		divTip.style.width = "170px";
		divTip.style.display = "block";
		if (centerOnElement)
		    SE_CenterElementOnElement(divTip, centerOnElement)
		else
		    SE_CenterElement(divTip);
		if (closeAfter)
		    setTimeout("SE_CloseTooltip()", closeAfter);
		SE_TooltipStart = new Date();
		return divTip;
	}
	
	function SE_CloseTooltip(divTip)
	{  
	    var now = new Date();
	    if (SE_TooltipStart && now.getTime() > (SE_TooltipStart.getTime() + 1000))
	    {
	        if (!divTip)
	            divTip = document.getElementById('divMessage')
	        if (divTip && divTip.parentNode)
	        {    
	            divTip.parentNode.onmouseout=null;
                divTip.parentNode.onmousedown=null;
                divTip.parentNode.onkeydown=null;
	            divTip.parentNode.removeChild(divTip);
	        }  
	        SE_PopupCenterOn = null;
	        if (SE_PopupTimeout)
	            clearTimeout(SE_PopupTimeout);
	        SE_PopupTimeout = null;
	    }
	}
	
	function SE_OpenBubbleTooltip(msg, nearElement, thisID, myHeight)
	{
		var isDontShow = SE_GetCookie(thisID);
		if (!isDontShow || isDontShow == "")
		{		
		    if (!myHeight)
		        myHeight = "118"
    		
		    var ttDiv = document.createElement("DIV")
		    ttDiv.id = thisID;
		    ttDiv.style.position = "absolute";
		    ttDiv.style.left = SE_GetObjectLeft(nearElement) + "px";
		    ttDiv.style.top = (SE_GetObjectTop(nearElement) - 30) + "px";
		    ttDiv.style.zIndex = 9999;
		    document.body.appendChild(ttDiv);
    		
            var imgLeft = new Image();
            imgLeft.src = "/image/tour/shortbubbleleft_leftflag.gif";
            imgLeft.style.width = "29px";
            imgLeft.style.height = myHeight + "px";
            imgLeft.style.position = "relative";
            ttDiv.appendChild(imgLeft);
            
            var content = document.createElement("span");
            content.style.borderTop = "black 1px solid";
            content.style.borderBottom = "black 1px solid";
            content.style.borderLeft = "none";
            content.style.borderRight = "none";
            content.className = "tooltip";
            content.innerHTML = msg;
            content.style.height = myHeight + "px";
            content.style.position = "relative";
            content.style.top = "-2px";
            content.style.padding = "15px";
            ttDiv.appendChild(content);
            
            var imgRight = new Image();
            imgRight.src = "/image/tour/shortbubbleright.gif";
            imgRight.style.width = "22px"; 
            imgRight.style.height = myHeight;
            imgRight.style.position = "relative";
            
            ttDiv.appendChild(imgRight);
            
            var closeFunction = "SE_CloseBubbleTooltip('" + ttDiv.id + "')";
            var ttDontShow = document.createElement("DIV");
            ttDontShow.style.left = "0px";
            ttDontShow.style.bottom = "10px"
            ttDontShow.style.position = "absolute";
            ttDontShow.innerHTML = "<input type=checkbox id=donotshow onclick=" + closeFunction + ">Do not show this again";
		    content.appendChild(ttDontShow);
            
            var ttDivClose = document.createElement("DIV");
            ttDivClose.style.bottom = "10px";
            ttDivClose.style.right = "20px"
            ttDivClose.style.position = "absolute";
            ttDivClose.innerHTML = "<a href=javascript:" + closeFunction + ">close</a>";
		    content.appendChild(ttDivClose);
		}
	}
	
	function SE_OpenBubbleTooltipBottom(msg, nearElement, thisID, myWidth)
	{
		var isDontShow = SE_GetCookie(thisID);
		if (!isDontShow || isDontShow == "")
		{
		    if (!myWidth)
		        myWidth = 300;

		    var ttDiv = document.createElement("DIV")
		    ttDiv.id = thisID;
		    ttDiv.style.position = "absolute";
		    ttDiv.style.zIndex = 9999;
		    ttDiv.style.width = myWidth + "px";
		    document.body.appendChild(ttDiv);
    		
            var imgTop = new Image();
            imgTop.src = "/image/tour/widebubbletop.gif";
            imgTop.style.height = "22px";
            imgTop.style.width = myWidth + "px";
            imgTop.style.position = "relative";
            ttDiv.appendChild(imgTop);
            
            var content = document.createElement("div");
            content.style.borderLeft = "black 1px solid";
            content.style.borderRight = "black 1px solid";
            content.style.borderTop = "none";
            content.style.borderBottom = "none";
            content.className = "tooltip";
            content.innerHTML = msg;
            content.style.width = (myWidth - 32) + "px";
            content.style.position = "relative";
            content.style.paddingLeft = "15px";
            content.style.paddingRight = "15px";
            content.style.paddingBottom = "45px";
            ttDiv.appendChild(content);
            
            var imgBottom= new Image();
            imgBottom.src = "/image/tour/widebubblebottomflag.gif";
            imgBottom.style.width = myWidth + "px"; 
            imgBottom.style.position = "relative";
            
            ttDiv.appendChild(imgBottom);
            
            var closeFunction = "SE_CloseBubbleTooltip('" + ttDiv.id + "')";
            var ttDontShow = document.createElement("DIV");
            ttDontShow.style.left = "10px";
            ttDontShow.style.bottom = "0px"
            ttDontShow.style.position = "absolute";
            ttDontShow.innerHTML = "<input type=\"checkbox\" id=\"donotshow\" onclick=\"" + closeFunction + "\"/>Do not show this again";
		    ttDontShow.style.zIndex = 9999;
		    content.appendChild(ttDontShow);
            
            var ttDivClose = document.createElement("DIV");
            ttDivClose.style.bottom = "0px";
            ttDivClose.style.right = "20px"
            ttDivClose.style.position = "absolute";
            ttDivClose.innerHTML = "<a href=\"javascript:" + closeFunction + "\">close</a>";
		    ttDivClose.style.zIndex = 9999;
		    content.appendChild(ttDivClose);
		    
		    ttDiv.style.left = (SE_GetObjectLeft(nearElement) + nearElement.offsetWidth - 70)/2 + "px";
		    ttDiv.style.top = (SE_GetObjectTop(nearElement) - ttDiv.offsetHeight) + "px";
		    
		}
	}
	
	function SE_CloseBubbleTooltip(thisID)
	{
	    var node = document.getElementById(thisID);
	    if (node)
	    {
	        var dontShow  = SE_FindChildNode(node,"donotshow");
    	    
	        if (dontShow)
	        {	  
		        if(dontShow.checked)
		        {
	                var expireTime = new Date();
	                expireTime.setTime(expireTime.getTime() + (1000 * 60 * 60 * 24 * 365));
	                setCookie(thisID,'DoNotShow', expireTime); 
	            }
	            else
	                setCookie(thisID,'DoNotShow');
	        }	    
	        node.parentNode.removeChild(node);
	    }
	}
	
	function MLX_IsVisible(obj)
	{    
	    if (obj == document) 
	        return true  ;   
	    if (!obj) 
	        return false;    
	    if (!obj.parentNode) 
	        return false;    
	    if (obj.style) 
	    {        
	        if (obj.style.display == 'none') 
	            return false;
	        if (obj.style.visibility == 'hidden') 
	            return false;
	     }     
	     //Try the computed style in a standard way    
	     if (window.getComputedStyle) 
	     {
	         var style = window.getComputedStyle(obj, "");
	         if (style.display == 'none') 
	            return false;
	         if (style.visibility == 'hidden') 
	            return false;
	     }     
	     //Or get the computed style using IE's silly proprietary way    
	     var style = obj.currentStyle;    
	     if (style) 
	     {        
	        if (style['display'] == 'none') 
	            return false;        
	        if (style['visibility'] == 'hidden') 
	            return false;
	      }     
	      return MLX_IsVisible(obj.parentNode);
	}
	
	function SE_SetFieldFocus(fieldID, goNow)
	{       
	    var focusField = document.getElementById(fieldID);
        if (focusField && focusField.focus)
        {
            if (goNow)
            {
                try {focusField.focus();}
                catch (e){}
            }
            else
	            setTimeout("SE_SetFieldFocus('" + fieldID + "', true)", 100); 
	    }  
	}
	
	
	function SE_SetSelectionRange(input, selectionStart, selectionEnd) 
	{
		if (input.setSelectionRange) 
		{
			input.focus();
			input.setSelectionRange(selectionStart, selectionEnd);
		}
		else if (input.createTextRange && input.type.toLowerCase() == 'text') 
		{
			var range = input.createTextRange();
			range.collapse(true);
			range.moveEnd('character', selectionEnd);
			range.moveStart('character', selectionStart);
			range.select();
		}
		else if (input.createRange ) 
		{
			var range = input.createRange();
			range.collapse(true);
			range.moveEnd('character', selectionEnd);
			range.moveStart('character', selectionStart);
			range.select();
		}
	}
	
	function SE_SetRepeaterRadioButton(nameregex, current)
    {
       var re = new RegExp(nameregex, "gi");
       for(i = 0; i < document.forms[0].elements.length; i++)
       {
          var elm = document.forms[0].elements[i]
          if (elm.type.toLowerCase() == 'radio')
          {
             if (elm.id.match(re))
                elm.checked = false;    
          }
       }
       current.checked = true;
    }


	
	function SE_SetCaretToEnd (input) 
	{
		SE_SetSelectionRange(input, input.value.length, input.value.length);
	}
	function SE_SetCaretToBegin (input) 
	{
		SE_SetSelectionRange(input, 0, 0);
	}
	function SE_SetCaretToPosition (input, start) 
	{
		SE_SetSelectionRange(input, start, 0);
	}
	
	function SE_GetCaretPosition(element)
	{
	    // believe it or not, this hack is the best way I could find to do this
	    if (element.selection.type != "Control")
	    {
	        var range = element.selection.createRange().duplicate();
	        range.collapse();
	        // we start with cursor at the beginning of the range 
	        // the move the start way to the left (it will stop at the beginning)
	        range.moveStart('character', -1000000);
	        // so the remaining text is the text before the start of the range
	        return range.text.length;
	    }
	    else
	        return -1;
	}
	
	function SE_CopyToClipBoard(elemId) 
    {
        var elem = document.getElementById(elemId);
        if (elem)
        {
            var holdText = document.createElement("TEXTAREA");
            holdText.innerText = elem.innerText;
            Copied = holdText.createTextRange();
            Copied.execCommand("Copy");
        }
    }

	
	
	function SE_GetSelectedValue(obj)
	{
		if (obj && obj.selectedIndex != -1)
		    return obj.options[obj.selectedIndex].value;
	    else
	        return "";
	}
	function SE_GetSelectedText(obj)
	{
		if (obj && obj.selectedIndex != -1)
		    return obj.options[obj.selectedIndex].text;
		else
		    return "";
	}
	function SE_SetSelectedValue(obj, selectedValue)
	{
		var fNotSelected = true;
		for (i=0; i< obj.options.length; i++)
		{
			obj.options[i].selected = false
		}
		for (i=0; i< obj.options.length; i++)
		{
			if (obj.options[i].value == selectedValue)
			{
				obj.options[i].selected = true;
				fNotSelected = false
				break;
			}
		}
		if (fNotSelected)
		{
		    obj.selectedIndex =-1
		    return "";
		}
		else
		    return obj.options[obj.selectedIndex].value;
	}
	
	function SE_GetSelectedValues(obj)
	{
	    
	    if (obj.options && (obj.options.length > 1)  || (obj.options[0] && obj.options[0].value != ""))
	    {
	        var ret = new Array();
	        for (var i=0; i< obj.options.length; i++)
	        {
	            if (obj.options[i].selected)
	                ret[ret.length] = obj.options[i].value;
	        }
	        return ret;
	    }
	}
	
	/*
	If you have multiple functions being called with a delay on a page, then do not use MLX_SetTimeout.  Instead create as many
	MLX_TimeoutManager instances as you need.  If you do use MLX_SetTimeout, it should really only be called once for a given 
	page's scope since the function relies on global variables.
	*/
	var _MLX_TimeoutRetried = 0;
	var _MLX_MaxTimeoutTries = 10;
	function MLX_SetTimeout(functionName, delay, isNotFirst)
	{
	   // replacement for setTimeout that waits for the function to exist before trying to run it
	   functionName = functionName.replace("()", "");
	   if (isNotFirst)
	        _MLX_TimeoutRetried++
	   else
	        _MLX_TimeoutRetried = 0;
	   
	   if (MLX_TraceInstanceExists())
	   {
	       _MLX_TraceInstance.addFunc("MLX_SetTimeout");
	       _MLX_TraceInstance.addArg("functionName", functionName);
	       _MLX_TraceInstance.addArg("isNotFirst", isNotFirst);
	       _MLX_TraceInstance.addInfo("_MLX_TimeoutRetried = " + _MLX_TimeoutRetried);
	   }
	   
	   if (_MLX_TimeoutRetried > _MLX_MaxTimeoutTries)
	        return;
	        
	   var func = null;
	   try {func = eval(functionName)}
	   catch(e){}
	   
	   if (typeof(func) == 'function' || (functionName.indexOf(".") != -1 && typeof(func) == 'object'))
	        setTimeout( functionName + '()', delay)
	   else
	        setTimeout("MLX_SetTimeout('" + functionName + "'," + delay + ", true)", delay);
	}
	
	// this method differs from MLX_SetTimeout in that it waits for a function to be ready
	// and then when it is it calls a different one (functionToCall).
	function MLX_WaitForFunction(functionName, delay, functionToCall, count)
	{
	   var MAX_COUNT = 60;
	   
	   functionName = functionName.replace("()", "");
	   functionToCall = functionToCall.replace("()", "");
	   
	   if(!count)
	     count = 0;
	     
	   count++;
	   
	   if (count > MAX_COUNT)
	     return;
	        
	   var func = null;
	   try {func = eval(functionName)}
	   catch(e){}
	   
	   if (typeof(func) == 'function' || (functionName.indexOf(".") != -1 && typeof(func) == 'object'))
	        setTimeout( functionToCall + '()', delay)
	   else
	   {	        
	        var method = "MLX_WaitForFunction('@functionName', @delay, '@functionToCall', @count)";
	        
	        method = method.replace("@functionName", functionName);
	        method = method.replace("@delay", delay);
	        method = method.replace("@functionToCall", functionToCall);
	        method = method.replace("@count", count);
	        
	        setTimeout(method, delay);
	   }
	}
	
    function MLX_TimeoutManager(myID, functionName)
    {
        //public fields
        this.id = myID;
        this.functionName = functionName;
        this.timeoutRetried = 0;
        this.maxTimeoutTries = 20;                
        this.requiredElements = new Array();    //Will test for the existence of these elements before calling the function
        
        //public functions
        this.setTimeout = function(delay, isNotFirst)
        {
            this.functionName = this.functionName.replace("()", "");
            if (isNotFirst)
                this.timeoutRetried++
            else
                this.timeoutRetried = 0;
	   
            if (this.timeoutRetried > this.maxTimeoutTries)
                return;
	   
	        //Trace info
            if (MLX_TraceInstanceExists())
            {
                _MLX_TraceInstance.addFunc(this.id + ".setTimeout");
                _MLX_TraceInstance.addArg("isNotFirst", isNotFirst);
                _MLX_TraceInstance.addInfo("timeoutRetried = " + this.timeoutRetried);
            }
	               
            delay += (this.timeoutRetried) * 100;
            if (this.isReady())
            {
                setTimeout(this.functionName + '()', delay)
            }
            else
                setTimeout(this.id + ".setTimeout(" + delay + ", true)", delay);
        }
        
        this.isReady = function()
        {
            var func = null, el = null;
            try {func = eval(this.functionName)}
            catch(e){}
	   
            if (func
                &&
                (
                    typeof(func) == 'function' 
                    || 
                    (this.functionName.indexOf(".") != -1 && typeof(func) == 'object')
                ))
            {
                // Check if the required elements exist also
                for (var i = 0; i < this.requiredElements.length; i++)
                {
                    try {el = eval(this.requiredElements[i])}
                    catch(e){}
                    
                    if (typeof(el) == 'undefined' || !el)
                        return false;
                }
                
                //Trace info
                if (MLX_TraceInstanceExists())
                {
                    _MLX_TraceInstance.addFunc(this.id + ".setTimeout");
                    _MLX_TraceInstance.addInfo("<i>" + this.functionName + "</i> is ready");
                    _MLX_TraceInstance.addInfo("typeof(func) = " + typeof(func));
                }
                
                return true;
            }
            
            return false;
        }
    }
	
	function MLX_Trace()
	{
	    this.text = "";
	    this.addFunc = function(val){this.text += "<br/><span style=\"font-weight:bold;color:red;\">" + val + "</span><br/>";}
	    this.addArg = function(name, val){this.text += "<span style=\"color:red;padding-left:2em\">arg: " + name + " = " + val + "</span><br/>";}
	    this.addInfo = function(val){this.text += "<span style=\"padding-left:4em\">" + val + "</span><br/>";}
	}
	
	// The global object _MLX_TraceInstance SHOULD be instantiated by the containing page to avoid possible re-instantiations that
	// could occur from an included script.
	function MLX_TraceInstanceExists()
	{
	    return typeof(_MLX_TraceInstance) == "object";
	}
	
	function SE_GetOpenerDoc(myOpener)
	{
		var docOpener = null;
		try
		{
			if (myOpener)
				docOpener = myOpener.document;
			else
				docOpener = window.opener.document;
		}
		catch(e)
		{}
		return docOpener;
	}
	
    function SE_IsArray(obj) 
    {
       try
       {
            if(obj && obj.constructor)
                return (obj.constructor.toString().indexOf("Array") != -1);
       }
       catch(e)       {

       }
       return false;
    }
    function SE_GetObjectTop(refobj) 
	{
		var y = 0;
		if (refobj)
		{
			if (refobj.offsetTop)
				y = refobj.offsetTop;
			var obj = refobj.offsetParent;
			while (obj != null) {
				y += obj.offsetTop;
				obj = obj.offsetParent;
			}
		}
		return y;
	}
	
	function SE_GetObjectLeft(refobj) 
	{
		var x = 0;
		if (refobj)
		{		
			if (refobj.offsetLeft)
				x = refobj.offsetLeft;
		    var obj = refobj.offsetParent;
		    while (obj != null) 
		    {
			    x += obj.offsetLeft;
			    obj = obj.offsetParent;
		    }
		}
		return x;
	}

    function MLX_IsMSIE(version)
    {
        return $.browser.msie && parseInt($.browser.version) == version;
    }
       
   // the following browser independent functions for getting dimensions are from 
   // http://www.softcomplex.com/docs/get_window_size_and_scrollbar_position.html
   function MLX_GetClientWidth() 
   {
        return MLX_ChooseBestValue (
	        window.innerWidth ? window.innerWidth : 0,
	        document.documentElement ? document.documentElement.clientWidth : 0,
	        document.body ? document.body.clientWidth : 0
        );
    }
    function MLX_GetClientHeight() 
    {
        return MLX_ChooseBestValue (
		    window.innerHeight ? window.innerHeight : 0,
		    document.documentElement ? document.documentElement.clientHeight : 0,
		    document.body ? document.body.clientHeight : 0
	    );
    }
    function MLX_GetParentClientHeight() 
    {
        return MLX_ChooseBestValue (
		    parent.window.innerHeight ? parent.window.innerHeight : 0,
		    parent.window.document.documentElement ? parent.window.document.documentElement.clientHeight : 0,
		    parent.window.document.body ? parent.window.document.body.clientHeight : 0
	    );
    }
    function MLX_GetScrollLeft() 
    {
	    return MLX_ChooseBestValue (
		    window.pageXOffset ? window.pageXOffset : 0,
		    document.documentElement ? document.documentElement.scrollLeft : 0,
		    document.body ? document.body.scrollLeft : 0
	    );
    }
    function MLX_GetScrollTop() 
    {
	    return MLX_ChooseBestValue (
		    window.pageYOffset ? window.pageYOffset : 0,
		    document.documentElement ? document.documentElement.scrollTop : 0,
		    document.body ? document.body.scrollTop : 0
	    );
    }
    
    function MLX_SetScrollTop(scrollTop) 
    {
	    if(typeof(window.pageYOffset) != 'undefined')
	        window.pageYOffset = scrollTop;
	    else if (document.documentElement && typeof(document.documentElement.scrollTop) != 'undefined')
		    document.documentElement.scrollTop = scrollTop;
		else if(document.body && typeof(document.body.scrollTop) != 'undefined')
	        document.body.scrollTop = scrollTop
    }
    
    function MLX_GetParentScrollTop() 
    {
	    if (parent)
	    {
	        return MLX_ChooseBestValue (
		        parent.window.pageYOffset ? parent.window.pageYOffset : 0,
		        parent.window.document.documentElement ? parent.window.document.documentElement.scrollTop : 0,
		        parent.window.document.body ? parent.window.document.body.scrollTop : 0
	        );
	    }
	    else
	        return 0;
	}

	function MLX_GetScrollBarWidth() {
	    var div = $('<div style="width:50px;height:50px;overflow:hidden;position:absolute;top:-200px;left:-200px;"><div style="height:100px;"></div>');
	    // Append our div, do our calculation and then remove it 
	    $('body').append(div);
	    var w1 = $('div', div).innerWidth();
	    div.css('overflow-y', 'scroll');
	    var w2 = $('div', div).innerWidth();
	    $(div).remove();
	    return (w1 - w2);
	}
    
    function MLX_ChooseBestValue(fromWindow, fromDocumentElement, fromBody) 
    {
	    // goes through values from the
	    // window, document, and body objects 
	    // and returns the smallest non-zero value or zero
	    var result = fromWindow ? fromWindow : 0;
	    if (fromDocumentElement && (!result || (result > fromDocumentElement)))
		    result = fromDocumentElement;
	    return fromBody && (!result || (result > fromBody)) ? fromBody : result;
    }
    
    function MLX_ConvertToBool(input)
    {
        switch (typeof(input))
        {
            case "boolean":
                return input;
            case "string":
                if (input == "yes" || input == "y" || input == "true" || input == "1")
                    return true;
                else
                    return false;
            case "undefined":
                return false;
        }
    }

   
    function MLX_Timer(name)
    {
        this.name = name;
        this.timeoutID = 0;
        this.startTime  = null;
        this.timeDiff = MLX_TimerDiff;
        this.start = MLX_TimerStart;
        this.stop = MLX_TimerStop;
        this.reset = MLX_TimerReset;
        this.message = "";
        this.addMessage = function(msg){this.message += msg + " " + this.timeDiff()  + "\n";};
    }

    function MLX_TimerDiff() 
    {
       if(this.timeoutID) {
          clearTimeout(this.timeoutID);
          this.timeoutID  = 0;
       }

       if(!this.startTime)
          this.startTime   = new Date();
       var tDate = new Date();
       var tDiff = tDate.getTime() - this.startTime.getTime();

       return tDate.setTime(tDiff);

    }

    function MLX_TimerStart() {
       this.startTime   = new Date();
       this.message = "";
    }

    function MLX_TimerStop() {
       if(this.timeoutID) 
       {
          clearTimeout(this.timeoutID);
          this.timeoutID  = 0;
       }
       this.startTime = null;
    }

    function MLX_TimerReset() 
    {
       this.startTime = null;
    }
    
    // more of a "drowsy" than sleep.
    // this keeps the js at the same line but delays until a method or object exists
    // or until a predetermined number of attempts 
    // at which point the code will continue and presumably throw an error
    // use this method only when necessary as it involved multiple server calls
    function MLX_Sleep(delayBetweenTries) {
        SE_GetHttpText('/Common/Utilities/sleep.aspx?delay=' + delayBetweenTries);
       
    }
    function MLX_SleepUntil(objectName, delayBetweenTries, maxTries)
    {
        
        for (var i=0; i<maxTries; i++)
        {
            try {testObject = eval(objectName);}
            catch(e){}
            if (typeof(testObject) == 'undefined'  || testObject == null)
                SE_GetHttpText('/Common/Utilities/sleep.aspx?delay=' + delayBetweenTries);
            else
                break;
        }
    }
    
    function MLX_IsDebug(debugTerm)
    {
     
        var args = SE_GetArgs(window.location.search)        
        if (!args["debug"] && top)
           args = SE_GetArgs(top.location.search)
           
	    if (args["debug"] && debugTerm )
	        return args["debug"] == debugTerm;
	    else if (args["debug"])
            return true;
        else
            return false;
    }
    
    function MLX_Debug_Alert(msg, debugTerm)
    {
        if (MLX_IsDebug(debugTerm))
            alert(msg)
    }
    
    function MLX_Debug_Eval(functionCall, debugTerm)
    {
         if (MLX_IsDebug(debugTerm))
        {
    	    eval(functionCall);
        }
    }

    function MLX_Debug_ShowCallStack() {
        var f = MLX_Debug_ShowCallStack;
        var result = "Call stack:\n";
var i=0
while ((f = f.caller) !== null && i< 20) {
    i++;
    
            var sFunctionName = f.toString().match(/^function (\w+)\(/)
            sFunctionName = (sFunctionName) ? sFunctionName[1] : 'anonymous function';
            result += sFunctionName;
            result += MLX_Debug_GetArguments(f.toString().substring(0,20), f.arguments);
            result += "\n";

        }
        alert(result);
    }

    function MLX_Debug_GetArguments(sFunction, a) {
        var i = sFunction.indexOf(' ');
        var ii = sFunction.indexOf('(');
        var iii = sFunction.indexOf(')');
        var aArgs = sFunction.substr(ii + 1, iii - ii - 1).split(',')
        var sArgs = '';
        for (var i = 0; i < a.length; i++) {
            var q = ('string' == typeof a[i]) ? '"' : '';
            sArgs += ((i > 0) ? ', ' : '') + (typeof a[i]) + ' ' + aArgs[i] + ':' + q + a[i] + q + '';
        }
        return '(' + sArgs + ')';
    }

    function MLX_UniqueString() {
        return ((new Date()).valueOf()).toString();
    }

    
    function MLX_GetIDRoot(fullID, lastIDPart)
    {
        var idx = fullID.indexOf(lastIDPart);
        if (idx > 0)    //idx=0 indicates the fullID and lastIDPart are the same, so there is no root
        {
            return fullID.substring(0, idx);
        }
        else
            return "";
    }
    
    function MLX_Util_ValidateURLLocation(urlToTest, callbackFunction)
    {
        var testerURL = "/Common/Utilities/CheckURL.aspx?url=" + encodeURIComponent(urlToTest);
        return SE_AsyncHttp(testerURL, callbackFunction);
    }

    function Post_ObjectToURL(url, resp) {
        var ifr = document.createElement('iframe');
        ifr.setAttribute("id", "ifr");
        ifr.setAttribute("width", "0px");
        document.body.appendChild(ifr);

        var _frm = document.createElement("form");
        _frm.id = "MLX_Post_ToURL_Form";
        _frm.method = "POST";
        _frm.action = url;
        _frm.target = "_posturl";
        ifr.appendChild(_frm);

        for(var property in resp)
        {
	        var $hidValue = $("<input type='hidden' id='" + property + "', name='" + property + "', value='" + resp[property] + "'/>");
	        $hidValue.appendTo(_frm)
        }
        _frm.submit();
    }

    function Post_ToURL(formId, url, inputNames, inputValues, windowname, width, height) {
        var ifr = document.createElement('iframe');
        ifr.setAttribute("id", "ifr");
        ifr.setAttribute("width", "0px");
        document.body.appendChild(ifr);
        
        var _frm = document.createElement("form");
        _frm.id = "MLX_Post_ToURL_Form";
        _frm.method = "POST";
        _frm.action = url;
        _frm.target = "ifr";
        ifr.appendChild(_frm);
        
        if (inputNames
         && inputValues
         && inputNames.length > 0
         && inputValues.length > 0) {
            var el;
            for (var i = 0; i < inputNames.length && i < inputValues.length; i++) {
                if (inputNames[i]) {
                    //alert(inputNames[i] + " = " + inputValues[i]);
                    el = document.createElement("input");
                    el.id = inputNames[i];
                    el.name = inputNames[i];
                    el.type = "hidden";
                    el.value = inputValues[i];
                    _frm.appendChild(el);
                }
            }
        }

        _frm.submit();
    }
    
    //
    // This is a generic version of SE_Post_ToURL from Common\Utilities\checkboxhandler.js
    //
    function MLX_Post_ToURL(formId, url, inputNames, inputValues, windowname, width, height) {
        if ((windowname) && (windowname != ""))
			SE_LN_OpenWin("", width, height, windowname);
		var _frm = document.getElementById(formId);
        var isNewForm = false;
		if (!_frm)
		{
			isNewForm = true;
			_frm = document.createElement("form");
			_frm.id = "MLX_Post_ToURL_Form";
			document.body.appendChild(_frm);
		}
		_frm.method = "POST";
		_frm.action = url;
		if ((windowname) && (windowname != ""))
			_frm.target = windowname;
    
        if (inputNames
         && inputValues 
         && inputNames.length > 0 
         && inputValues.length > 0)
        {
            var el;
            for (var i = 0; i < inputNames.length && i < inputValues.length; i++)
            {
                if (inputNames[i])
                {
                    el = document.createElement("input");
                    el.id = inputNames[i];
                    el.name = inputNames[i];
                    el.type = "hidden";
                    el.value = inputValues[i];
                    _frm.appendChild(el);
                }
            }
        }

		_frm.submit();
}

    function MLX_ShowSlowPageStatus(msgConfirm, msgStatus, dotDelay)
    {
        var delay = (dotDelay && dotDelay > 100) ? dotDelay : 1000;
        if(!msgConfirm || msgConfirm == "" || confirm(msgConfirm))
        {
            setTimeout("MLX_UpdateSlowPageStatus(" + delay + ",'" + msgStatus + "')", delay);
            return true;
        }
        return false
    }
    function MLX_UpdateSlowPageStatus(delay, msg)
    {
        var divStatus = document.getElementById("divStatus");
        var divStatusText = document.getElementById("divStatusText");
        if (!divStatus)
        {
            divStatus = document.createElement("div");
			document.body.appendChild(divStatus);
		    divStatus.id = "divStatus";
		    divStatus.className = "modalDialog";
		    divStatus.style.display = "none";
		    divStatus.style.display.width = "300px";
		    divStatus.style.display.height = "60px;";
		    divStatusText = document.createElement("div");
			divStatus.appendChild(divStatusText);
			divStatusText.id = "divStatusText";
        }
        
        if (divStatusText)
        {
            if (msg && msg != "")
            {
                divStatusText.innerHTML = msg;
                SE_CenterElement(document.getElementById('divStatus'));
                SE_Modal_ToggleDivModalCover();
            }
            else
                divStatusText.innerHTML += ". ";
            setTimeout('MLX_UpdateSlowPageStatus(' + delay + ', null)', delay);
        }
    }

    function MLX_Dialog(msg, title) {
        $("<div class=\"ui-mlx-dialog-content\" style=\"text-align:center;\">" + msg + "</div>").dialog({title: title});
    }

    function MLX_CloseDialog()
    {
        $("ui-mlx-dialog-content").dialog("destroy");
    }


    function SE_ValidateEmail(source, arguments)
	{
	    arguments.IsValid = SE_IsValidEmailAddress(arguments.Value);
	    if (!arguments.IsValid && arguments.Value.indexOf("@" == -1))
	        arguments.IsValid = SE_IsValidEmailAddress(arguments.Value + "@test.com");
	    if (!arguments.IsValid)
	        source.errormessage = "Please enter an email address containing only " 
	            + MLX_ValidEmailCharacters + ".";
	}
	
	function SE_IsValidEmailAddress(strAddress)
    {
	    strAddress = strAddress.replace(/^\s+/,'').replace(/\s+$/,'');
	    return (MLX_ValidEmailRegExp.test(strAddress));
	}

	function SE_IsInteger(s) {
	    var i;

	    if (s == null || typeof (s) == 'undefined' || s.length == 0) return false;
	    var re = new RegExp(/^-?\d*$/)
	    return re.test(s);
	}

	function SE_GetBackgroundColor(styleName) {
	
	    var divColor = document.createElement("DIV");
	    divColor.className = styleName;
	    divColor.style.display = "none";
	    document.body.appendChild(divColor);
	    var color = ($("." + styleName).css('background-color'));
	    document.body.removeChild(divColor);
	    
	    
	    return color;
	}

    function SR_FavoriteAction_CallBack(contactListingID, action) {
        switch (action) {
            case $aa.Registration.Action.SaveListing:
                $(".sr_remove_" + contactListingID).show();
                $(".sr_save_" + contactListingID).hide();
                break;
            case $aa.Registration.Action.RemoveListing:
                $(".sr_remove_" + contactListingID).hide();
                $(".sr_save_" + contactListingID).show();
                break;
        }
    }

	function MLX_ReplaceNodeText(node, text) {
	    if (node.hasChildNodes()) {
	        while (node.childNodes.length >= 1) {
	            node.removeChild(node.firstChild);
	        }
	    }
	    textNode = document.createTextNode(text);
	    node.appendChild(textNode);
	}

	function SE_ClauseFromList(list) {
	    if (list.length == 0)
	        return "";
	    else if (list.length == 1)
	        return list[0];
	    else {
	        var msg = "";
	        for (var item = 0; item < list.length; item++) {
                var separator = ", ";
                if (item == 0)
                    separator = "";
                else if (item == list.length - 1)
                    separator = " and ";
                msg += separator + list[item];
            }
            return msg;
	    }
	}

	function HexToR(h) { return parseInt((cutHex(h)).substring(0, 2), 16) }
	function HexToG(h) { return parseInt((cutHex(h)).substring(2, 4), 16) }
	function HexToB(h) { return parseInt((cutHex(h)).substring(4, 6), 16) }
	function cutHex(h) { return (h.charAt(0) == "#") ? h.substring(1, 7) : h }

	function SE_NOP() { }

	function MLX_LoadSMSCarriers(ctlID) {
	    var smsUrl = "/common/utilities/sms.aspx?action=listproviders";
	    $.getJSON(smsUrl,
            function(data) {
                if (data.options.length > 0) {
                    var options = document.getElementById(ctlID).options;
                    options.length = 0;
                    options[options.length] = new Option("-- Select your provider --", ""); ;
                    for (o in data.options) {
                        var opt = data.options[o];
                        options[options.length] = new Option(opt.provider, opt.smsdomain);
                    }
                }
            }
        )
        }
        function MLX_SendSMSMessage(txtPhoneID, cboCarriersID, successMessage, url) {
        
            var phone = SE_StripNonDigit($("#" + txtPhoneID).val());
            var carrier = $("#" + cboCarriersID).val();
            var postUrl = url;
            if (!url)
                postUrl = location.href;

            if (!SE_IsPossiblePhoneNumber_Accurate(phone)) {
                alert("Please enter a valid phone number.")
                $("#" + txtPhoneID).focus();
            }
            else if (!SE_IsPossiblePhoneNumber_Accurate(phone, true)) {
                alert("Please include the area code.")
                $("#" + txtPhoneID).focus();
            }
            else if (carrier == "") {
                alert("Please select your mobile carrier from the list.");
                $("#" + cboCarriersID).focus();
            }
            else {
                $.post(postUrl, {
                    phone: phone,
                    carrier: carrier,
                    postaction: 'sendsms'
                },
                function(data) {
                    if (data == "Success") {
                        alert(successMessage);
                    }
                    else {
                        if (data.length < 500)
                            alert(data);
                        else
                            alert("We had a problem sending your message.");
                    }
                });
            }
        }

        function MLX_AddRequiredMark(reqClass) {
            if (!reqClass)
                reqClass = "required";
            $("label." + reqClass).append("<span class=\"required_indicator\">*</span>");
            $("div." + reqClass).append("<span class=\"required_indicator\">*</span>");
            $("span." + reqClass).append("<span class=\"required_indicator\">*</span>");
        }

        function MLX_OuterHTML(node) {
            var span = document.createElement("span"); 
            span.appendChild(node.cloneNode(true));
            return span.innerHTML;
        }
/* ------------------------ VALIDATION -----------------------*/
function SE_IsValidDate(dateStr, format)
{
    return IsValidDate(dateStr, format);
}

function IsValidDate(dateStr, format) {
    //so far, only formats being sent are: null, emptystring, MDY (2 places) & MM/DD/yyyy  (2 places)
    if ((format == null) || (format.length == 0)) 
    {
         format = Date.CultureInfo.formatPatterns.shortDate;
    }
    if(Date.parseExact(dateStr,format))
      return true;    
    else    
        return false;
}

function SE_IsPossiblePhoneNumber(phone)
{
	var reFilter = /[2-9][0-9]{2}.*[0-9]{4}/gi;
	return (reFilter.test(phone));
}

function SE_IsPossiblePhoneNumber_Accurate(sText, withAreaCode)
{
    if(!withAreaCode)
        reFilter = /^1{0,1}([\(]{0,1}[0-9]{3}[\)]{0,1}[\.| |\-]{0,1}|^[0-9]{3}[\.|\-| ]?)?[0-9]{3}(\.|\-| )?[0-9]{4}$/;
    else
        reFilter = /^1{0,1}([\(]{0,1}[0-9]{3}[\)]{0,1}[\.| |\-]{0,1}|^[0-9]{3}[\.|\-| ]?){1}[0-9]{3}(\.|\-| )?[0-9]{4}$/;
    return (reFilter.test(sText));
}

function SE_IsNumeric(sText)
{
    var reFilter = /^[-+]?\d*\.?\d*$/;
    return (reFilter.test(sText));
}

function SE_IsDomain(sText)
{
    var reFilter = /^(?:[\-A-Z0-9]+\.)+[\-A-Z0-9]{1,5}\b/gi;
    return (reFilter.test(sText));
}

function SE_IsURL(sText)
{
    var reFilter = /^(https?:\/\/)?[-A-Z0-9.]+(\/[-A-Z0-9+&@#/%=~_|!:,.;]*)?(\?[-A-Z0-9+&@#/%=~_|!:,.;]*)?/gi;
    return (reFilter.test(sText));
}

function SE_IsZipCode(sText)
{
    var reFilter = /^\d{5}$|^\d{5}-\d{4}$/;
    return (reFilter.test(sText));
}

function SE_HasHTML(sText)
{
    var reFilter = /<\/?[a-z][a-z0-9]*[^<>]*>/gi;
    return (reFilter.test(sText));
}

function SE_IsValidHexidecimalColorCode(objValue)
{
	objValue = objValue.replace(/^\s+/,'').replace(/\s+$/,'');
	var reFilter = /^#[a-fA-F0-9]{6}/;
	return (reFilter.test(objValue));
}

function SE_IsValidColorName(value)
{
    var validColors = ",Gainsboro,Green,Lime,Teal,Aqua,Navy,Blue,Purple,Fuchsia,Maroon,Red,Olive,Yellow,White,Silver,Gray,Black,DarkOliveGreen,DarkGreen,DarkSlateGray,SlateGray,DarkBlue,MidnightBlue,Indigo,DarkMagenta,Brown,DarkRed,Sienna,SaddleBrown,DarkGoldenrod,Beige,Honeydew,DimGray,OliveDrab,ForestGreen,DarkCyan,LightSlateGray,MediumBlue,DarkSlateBlue,DarkViolet,MediumVioletRed,IndianRed,Firebrick,Chocolate,Peru,Goldenrod,LightGoldenrodYellow,MintCream,DarkGray,YellowGreen,SeaGreen,CadetBlue,SteelBlue,RoyalBlue,BlueViolet,DarkOrchid,DeepPink,RosyBrown,Crimson,DarkOrange,Burlywood,DarkKhaki,LightYellow,Azure,LightGrey,LawnGreen,MediumSeaGreen,LightSeaGreen,DeepSkyBlue,DodgerBlue,SlateBlue,MediumOrchid,PaleVioletRed,Salmon,OrangeRed,SandyBrown,Tan,Gold,Ivory,GhostWhite,Gainsboro,Chartreuse,LimeGreen,MediumAquamarine,DarkTurquoise,CornflowerBlue,MediumSlateBlue,Orchid,HotPink,LightCoral,Tomato,Orange,Bisque,Khaki,Cornsilk,Linen,WhiteSmoke,GreenYellow,DarkSeaGreen,Turquoise,MediumTurquoise,SkyBlue,MediumPurple,Violet,LightPink,DarkSalmon,Coral,NavajoWhite,BlanchedAlmond,PaleGoldenrod,Oldlace,Seashell,GhostWhite,PaleGreen,SpringGreen,Aquamarine,PowderBlue,LightSkyBlue,LightSteelBlue,Plum,Pink,LightSalmon,Wheat,Moccasin,AntiqueWhite,LemonChiffon,FloralWhite,Snow,AliceBlue,LightGreen,MediumSpringGreen,PaleTurquoise,LightCyan,LightBlue,Lavender,Thistle,MistyRose,Peachpuff,PapayaWhip,"
    return validColors.toLowerCase().indexOf(value.toLowerCase()) != -1;
}

    // -- limit text entry in a textarea or asp:TextBox in multiline mode
	// In code behind, use the following:
    // SonicEagle.Common.Tools.SetTextAreaMaxSize(System.Web.UI.WebControls.TextBox txtBox, int maxSize)

    var SE_PrePasteText = "";
	var SE_PostPasteText = "";
	var SE_IsAfterPaste = false;
	
	function SE_LimitSize(ctl, size)
	{
	    if (event)
	    {
	        switch (event.type)
	        {
	            case "drop":
	                if (event.dataTransfer)
	                {
	                    var droppedText = event.dataTransfer.getData("TEXT");
	                    if ((droppedText.length + ctl.value.length) > size)
	                    {
	                        SE_HandleSizeExceedance(ctl, size);
	                    }
	                }
    	            break;
	            case "paste":	            
	                SE_PrePasteText = ctl.value;
	                SE_IsAfterPaste = true;
	                //Call the blur method (the field will necessarily have focus), the handling of which is where the pasted text will be evaluated.
	                setTimeout("document.getElementById('" + ctl.id + "').blur()", 10);
	                break;
	            case "blur":
	                if (SE_IsAfterPaste)
	                {
	                    SE_PostPasteText = ctl.value;
	                    if (SE_PostPasteText.length > size)
	                    {
	                        ctl.value = SE_PrePasteText;
	                        SE_HandleSizeExceedance(ctl, size);
	                    }
	                    else
	                        ctl.focus();
	                    SE_PrePasteText = "";
	                    SE_IsAfterPaste = false;
	                }
    	            break;
	            case "keypress":
	                if (ctl.value.length >= size)
	                {
	                    SE_HandleSizeExceedance(ctl, size);
	                }
    	            break;
	        }   
	    }
	}
	
	function SE_HandleSizeExceedance(ctl, size)
	{
	    alert("Please limit entry to " + size + " characters.");
	    ctl.focus();
        SE_CancelEvent();
	}
	
	function SE_TestRegEx(pattern, flags, testValue)
	{
	    var re = new RegExp(pattern, flags);
	    return (re.test(testValue));
	}
	
	function MLX_Validator()
    {
        this.firstProblem = null;
        this.errorMessage = "";
        this.handleError = MLX_ValidateHandleFoundError;
        this.result = MLX_Validate_Result;
        this.confirm = MLX_Validate_Confirm;
    }
    
    function MLX_ValidateHandleFoundError(ctlTest, errMsg)
    {
        this.errorMessage += (this.errorMessage == "" ? "" : "\n") + errMsg;
        if (this.firstProblem == null)
            this.firstProblem = ctlTest;
    }
    
    function MLX_Validate_Result()
    {
        if (this.errorMessage != "")
        {
            alert(this.errorMessage);
            if (this.firstProblem.focus)
            {
                // the control may not be visible but I don't know of a way to
                // reliably determine if it is or not - so I used the crappy hack - mja
                try {this.firstProblem.focus();}
                catch(e) {}
            }
            return false;
        }
        return true;
    }
    
    function MLX_Validate_Confirm()
    {
        if (this.errorMessage != "")
        {
            if(!confirm(this.errorMessage))
            {
                if (this.firstProblem.focus)
                {
                    // the control may not be visible but I don't know of a way to
                    // reliably determine if it is or not - so I used the crappy hack - mja
                    try {this.firstProblem.focus();}
                    catch(e) {}
                }
                return false;
            }
        }
        return true;
}
/* ------------------------ END VALIDATION -----------------------*/

function SE_IsIPlatformDevice()
{
    var p = navigator.platform.toLowerCase();
    return (p == "ipod" || p == "iphone" || p == "ipad");
}

function MLX_SysPageRequestManagerExists()
{
    return typeof(Sys) != 'undefined' 
        && Sys.WebForms
        && Sys.WebForms.PageRequestManager;
}

// these are called for tracking purposes in js methods
// they have to work even if the pagetimer object is null
function MLX_PageTimer_SaveEvent(msg)
{
    if (typeof(MLX_PageTimer) != 'undefined'  &&  pageTimer)
    {
        __pageTimer.addTime(msg);
    }
}
function MLX_PageTimer_RecordClientSubmitTime()
{
    if (typeof(MLX_PageTimer) != 'undefined'  &&  pageTimer)
    {
        __pageTimer.recordClientSubmitTime();
    }
}

function MLX_CheckForSlowClient()
{
    var start = new Date().getTime();
    for (var i = 0; i< 10; i++)
    {
        var a = $(".test" + i);
    }
    
    var done =  new Date().getTime();
    
    var isIE7XP = SE_MSIEVersion() <= 7 && SE_UserAgent("Windows NT 5.1");
    if(isIE7XP || (done - start > 100))
        $.cookie("TESTED_FOUND_SLOW", '1', {path: "/"});
    else
        $.cookie("TESTED_FOUND_SLOW", '0', {path: "/"});
}

function MLX_IsSlowClient()
{
    return $.cookie("TESTED_FOUND_SLOW") ? true : false;
    }
function MLX_PreLoad()
{
    MLX_CheckForSlowClient();
}

function MLX_GoogleSnippet(http, trackingID)
{
    if(/(UA-)(\d*)(-1)/.test(trackingID) != true)
    {
        trackingID = trackingID.replace(/(UA)(\d*)(1)/, "$1-$2-$3")
    }
    $.ajax({
        type: 'GET',
        url: http + '://www.google-analytics.com/ga.js',
        dataType: 'script',
        cache: true,
        success: function(){
            if (typeof(_gat) != 'undefined')
            {
                var firstTracker = _gat._getTracker(trackingID);
                firstTracker._trackPageview();
            }
        }
    });  
}

function MLX_VisistatSnippet(http, DID, customPageName, customID)
{
    window.DID = DID;
    window.MyPageName = customPageName;
    window.MyID = customID;
    $.ajax({
        type: 'GET',
        url: http + '://sniff.visistat.com/sniff.js',
        dataType: 'script',
        cache: true
    });  
}

function IsValidImageFileExtention(type)
{
    type = type.toLowerCase();

    if ((type.indexOf("gif") == -1) && (type.indexOf("jpg") == -1) && (type.indexOf("png") == -1))
        return false;
    else
        return true;
}

function SE_Trim(text)
{
	var temp = text.replace(/^\s+|\s+$/, '');    //possibly spaces at front and back
	return temp.replace(/^\s+|\s+$/, '');
}

if(!String.prototype.stripHtml)
{
    String.prototype.stripHtml = function()
	{
	    var re = new RegExp(/<.*?>/g);
        var s = this.replace(re, "");
        return s;
    }
}


/* ----------------------------------------------------
-------------    Strings    -------------------
-------------------------------------------------------  */

if(!String.prototype.trim)
{
	String.prototype.trim = function()
	{
		var temp = this.replace(/^\s+|\s+$/, '');    //possibly spaces at front and back
		return temp.replace(/^\s+|\s+$/, '');
	};
}

if(!String.prototype.startsWith)
{
	String.prototype.startsWith = function(s)
	{
		return (this.indexOf(s) == 0);
	};
}

if(!String.prototype.endsWith)
{
	String.prototype.endsWith = function(s)
	{
		return (this.lastIndexOf(s) == (this.length - s.length));
	};
}

if(!String.prototype.isValidEmailAddress)
{
	String.prototype.isValidEmailAddress = function()
	{
		return (MLX_ValidEmailRegExp.test(this.trim()));
	};
}
	
if(!String.prototype.format)
{
	String.prototype.format = function(type)
	{
		var ret = "";
		var decimalPlaces = type.length == 2 ? parseInt(type.substr(1,1)) : 0;
		var intValue;
		
		try
		{
			if(type.toUpperCase().startsWith("C") || type.toUpperCase().startsWith("N"))
			{
				dblValue = parseFloat(this.replace(/\$|\,/g,''));				
				blnSign = (dblValue == (dblValue = Math.abs(dblValue)));
				intValue = Math.floor(dblValue);
				strCents = (Math.floor(Math.floor(((dblValue - intValue) * Math.pow(10,decimalPlaces))+.0000000001))/Math.pow(10,decimalPlaces)).toString();
				
				if(strCents == "0")
					strCents = ".";
				else
					strCents = strCents.substr(1,strCents.length-1);
				
				while(strCents.length - 1 < decimalPlaces)
					strCents += "0";
				
				dblValue = intValue.toString();
				for (var i = 0; i < Math.floor((dblValue.length-(1+i))/3); i++)
					dblValue = dblValue.substring(0,dblValue.length-(4*i+3))+','+ dblValue.substring(dblValue.length-(4*i+3));
				ret = (((blnSign)?'':'-') + (type.toUpperCase().startsWith("C") ? '$' : '') + dblValue + (decimalPlaces > 0 ? strCents : ''));
			}
			else if(type.toUpperCase().startsWith("P"))
			{
				var flt = (this.indexOf("%") != -1 ? (parseFloat(this.replace(/%/g,'')) / 100.0) : (parseFloat(this.replace(/%/g,''))));
				intValue = Math.floor(flt * 100.0 + 0.0000000001);
				flt = flt * 100.0 + 0.0000000001;
				var decimals = (Math.floor(Math.floor(((flt - intValue) * Math.pow(10,decimalPlaces))+.0000000001))/Math.pow(10,decimalPlaces)).toString();
				
				if(decimals == "0")
					decimals = ".";
				else
					decimals = decimals.substr(1,decimals.length-1);
				
				while(decimals.length - 1 < decimalPlaces)
					decimals += "0";

				ret = intValue.toString() + (decimalPlaces > 0 ? decimals : '') + '%';
			}
		}
		catch(err)
		{
		}
		
		return ret.length > 0 ? ret : this;
	};
}

if(!String.prototype.HTMLDecode)
{
	String.prototype.HTMLDecode = function()
	{
		var re = new RegExp("&amp;", "g");
		var s = this.replace(re, "&");
		re = new RegExp("&gt;", "g");
		s = s.replace(re, ">");		
		return s;
	};
}

if(!String.prototype.XmlEncode)
{
	String.prototype.XmlEncode = function()
	{
		var re = new RegExp("&", "g");
		var s = this.replace(re, "&amp;");
		re = new RegExp("<", "g");
		s = s.replace(re, "&lt;");		
		return s;
	};
}

if(!String.prototype.XmlDecode)
{
	String.prototype.XmlDecode = function()
	{
		var re = new RegExp("&amp;", "g");
		var s = this.replace(re, "&");
		re = new RegExp("&lt;", "g");
		s = s.replace(re, "<");		
		return s;
	};
}

if(!String.prototype.stripHtml)
{
    String.prototype.stripHtml = function()
	{
	    var re = new RegExp(/<.*?>/g);
        var s = this.replace(re, "");
        return s;
    }
}
if(!String.prototype.stripWhitespace)
{
    String.prototype.stripWhitespace = function()
	{
	    var re = new RegExp(/\s/g);
        var s = this.replace(re, "");
        return s;
    }
}

if(!String.prototype.stripWrappingTags)
{
    String.prototype.stripWrappingTags = function(tag)
	{
		var s = this.trim()
	    var re = new RegExp("\^<" + tag + ">([\\s\\S]*)(?=<\/" + tag + ">$)", "i");
        found = re.exec(s);
		if (found && found.length > 1)
		    return found[1];
		else
            return s;
    }
}

/* ----------------------------------------------------
-------------    End Forms    -------------------
-------------------------------------------------------  */

/* ----------------------------------------------------
-------------    Forms    -------------------
-------------------------------------------------------  */

$aa.Forms = {}
$aa.Forms.ValidationSettings = {
    submitHandler: function(form) {event.preventDefault();},
    errorClass: "form-error",
    errorElement: "div",
    errorPlacement: function(error, element) {
        element.after(error);
    },
    onfocusout: function(element) { $(element).valid()}
};
/* ----------------------------------------------------
-------------    End Forms    -------------------
-------------------------------------------------------  */

/* ----------------------------------------------------
-------------    Registration Login Popup    -------------------
-------------------------------------------------------  */
$aa.optional = "(optional)";
$aa.Registration = function(request, title) {
    this.notInPopup = request.notInPopup ? true : false;
    this.request = request;
    this.title = this.getTitle(title);      
    this.$regDiv = $(".reg_area");   
    this.registrationUrl = $aa.urls.toolkitRegistration;
    this.$forgotPassword = this.$regDiv.find(".reg_forgotpassword");
    this.$newAccount = this.$regDiv.find(".reg_new_account");
    
    this.$login = this.$regDiv.find(".reg_login");
    this.$saveSearchForm = this.$regDiv.find("#search-name").parents("form"); 
    this.updateRegistrationAction();
    this.setupBehaviors();
    this.setupValidation();
    this.setPanels();
    this.loadContent();
    this.$regDiv.dialog('option', 'title', this.title );
}

$aa.Registration.Popup_Loading_Timeout = null;
$aa.Registration.fullWidth = 600;
$aa.Registration.loggedInWidth  = 400;
$aa.Registration.Action = {};
$aa.Registration.Action.Login = "Login";
$aa.Registration.Action.FacebookLogin = "FacebookLogin";
$aa.Registration.Action.Logout = "Logout";
$aa.Registration.Action.ForgetMe = "ForgetMe";
$aa.Registration.Action.ForgotPassword = "ForgotPassword";
$aa.Registration.Action.NoAction = "NoAction";
$aa.Registration.Action.RegisterLead = "RegisterLead";
$aa.Registration.Action.RegisterBST = "RegisterBST";
$aa.Registration.Action.UpdateContactInfo = "UpdateContactInfo";
$aa.Registration.Action.SaveSearch = "SaveSearch";
$aa.Registration.Action.SaveListing = "SaveListing";
$aa.Registration.Action.RemoveSearch = "RemoveSearch";
$aa.Registration.Action.RemoveListing = "RemoveListing";
$aa.Registration.Action.RequestInfo = "RequestInfo";
$aa.Registration.Action.GoToFavorites = "GoToFavorites";
$aa.Registration.Action.GoToSavedSearches = "GoToSavedSearches";
$aa.Registration.Action.GoToMyPlaces = "GoToMyPlaces";
$aa.Registration.Action.GoToPreferences = "GoToPreferences";

$aa.Registration.Action.LoginTitle = "Sign In";
$aa.Registration.Action.RegisterLeadTitle = "Free Account Registration";
$aa.Registration.Action.RegisterBSTTitle = "";
$aa.Registration.Action.UpdateContactInfoTitle = "";
$aa.Registration.Action.SaveSearchTitle = "Save Search";
$aa.Registration.Action.RemoveSearchTitle = "Remove Search";
$aa.Registration.Action.SaveListingTitle = "Save Listing";
$aa.Registration.Action.RemoveListingTitle = "Remove Listing";
$aa.Registration.Action.RecoverPasswordTitle = "Recover Password";
$aa.Registration.Action.GoToFavoritesTitle = "Favorite Properties";
$aa.Registration.Action.GoToSavedSearchesTitle = "Saved Searches";
$aa.Registration.Action.GoToMyPlacesTitle = "My Places";
$aa.Registration.Action.GoToPreferencesTitle = "Preferences";

$aa.Registration.EmailValidationAction = {};
$aa.Registration.EmailValidationAction.Login = "login";
$aa.Registration.EmailValidationAction.ForgotPassword = "ForgotPassword";
$aa.Registration.EmailValidationAction.UpdateEmail = "UpdateEmail";
$aa.Registration.EmailValidationAction.ForgetMe = "ForgetMe";

$aa.Registration.Validate = {};
$aa.Registration.Validate.IsEmailAvailable = "IsEmailAvailable";

$aa.Registration.Reason = {};
$aa.Registration.Reason.ExceededUnregisteredPropertyDetailVisits = 1;

$aa.Registration.EmailAlreadyUsed ="This email address is already in use. Do you want to<ul>"
    + "<li><a href='javascript:SE_NOP()' onclick='$aa.RegistrationForm.emailValidationAction($aa.Registration.EmailValidationAction.Login, this)'>Sign In</a>, or</li>"
    + "<li><a href='javascript:SE_NOP()' onclick='$aa.RegistrationForm.emailValidationAction($aa.Registration.EmailValidationAction.ForgotPassword, this)'>Recover you password</a>?</li></ul>"
$aa.Registration.EmailChanged = "You have changed the email that you previously entered. Do you want to:\n"
    + "<ul><li><a href='javascript:SE_NOP()' onclick='$aa.RegistrationForm.emailValidationAction($aa.Registration.EmailValidationAction.UpdateEmail, this)'>Update the email you previously entered</a>, or</li>\n"
    + "<li><a href='javascript:SE_NOP()' onclick='$aa.RegistrationForm.emailValidationAction($aa.Registration.EmailValidationAction.ForgetMe, this)'>Create a new account</a>.</li></ul>";
    
$aa.Registration.loginOrRegister = function()
{ 
    var action = $aa.Registration.Action.Login;    
    if (location.search.indexOf('login=1') != -1)
    {
    // nop
    }
    else if (location.search.indexOf('register=1') != -1
        || ($aa.contact.bstUserName != '' && !$aa.contact.hasPassword))
        action = $aa.Registration.Action.RegisterBST;
    return action;
}

$aa.Registration.Execute = function (request, title, callback, event) {
    // stop fall through to div below
    SE_CancelEvent(event);
    if (typeof(SEMap) != 'undefined' && typeof(SEMap.ClosePopups) == 'function')
        SEMap.ClosePopups();
    $(".ui-dialog").remove();
    
    var settings = {}
    settings.needsPopup = true;  
    settings.dialogWidth = $aa.Registration.fullWidth; 
    $aa.Registration.handleLoggedInActions(request, settings, callback);
    
    if ($aa.RegistrationForm && $('.reg_area').is(":visible"))
    {
        if (request.registrationAction == $aa.Registration.Action.Login)
        {
           $aa.RegistrationForm.showLogin();
           settings.needsPopup = false;
        }
        else if( request.registrationAction == $aa.Registration.Action.RegisterBST)
        {
            $aa.RegistrationForm.showRegistration();
            settings.needsPopup = false;
        }       
    }    

    if (!settings.needsPopup)
        return;

    var dialog = $(".reg_area");
    if (dialog.length == 0)
        dialog = $('<div class="reg_area"></div>').appendTo('body');  
    else
        dialog.html();  
    if (request.dialogMessage)
    {
        dialog.html("<div class='form-alert-message-box ui-state-highlight '><div class='form-alert-message' >" + request.dialogMessage + "</div></div>");
        settings.dialogWidth = $aa.Registration.loggedInWidth;
    }
    else 
        dialog.html("<div  class='loading_message'><img src='/common/images/rotating_arrow.gif' class='loading_image' /> Loading ...</div>"); 
     
    dialog.dialog({
        width: settings.dialogWidth,
        height: 'auto',
        modal: true,
        title: title,
        position: [($('body').width() - settings.dialogWidth) / 2, 100],
        beforeclose: function () {
            if (request.registrationAction == $aa.Registration.Action.RegisterLead
                &&  request.callback)
             request.callback();
        }
    });
    $(".ui-dialog").cl_shadow();

    if (request.dialogMessage)
    {
        $aa.Registration.showDialogMessage(dialog);
    }
    else {
        request.isInitialLoad = true;
        // load remote content
        dialog.load($aa.urls.toolkitRegistration, request, function(){
            request.callback = callback;
            $aa.RegistrationForm = new $aa.Registration(request, title);
        });         
    }       
}

$aa.Registration.handleLoggedInActions = function (request, settings, callback)
{
    if ($aa.contact
            && $aa.contact.contactID > 0  
            && $aa.contact.isLoggedIn)
    {
        switch (request.toolkitAction)
        {
            case $aa.Registration.Action.SaveSearch:
                settings.dialogWidth = $aa.Registration.loggedInWidth;
                break;
            case $aa.Registration.Action.RemoveSearch:
            case $aa.Registration.Action.SaveListing:
            case $aa.Registration.Action.RemoveListing:
                $.post($aa.urls.toolkitRegistration, request, function(data, textStatus, jqXHR){   
                     if (data.indexOf("<!DOCTYPE") != -1)
                        alert("We had a problem processing your request.");
                    else if (callback)
                        callback(request.toolkitAction); 
                });                 
                settings.needsPopup = request.dialogMessage && request.dialogMessage != '';
                break;
            case $aa.Registration.Action.GoToFavorites:
                settings.needsPopup = false;
                location.href = $aa.urls.savedProperties;
                break;
           case $aa.Registration.Action.GoToMyPlaces:
                settings.needsPopup = false;
                location.href = $aa.urls.toolkitPOIs;
                break;
           case $aa.Registration.Action.GoToPreferences:
                settings.needsPopup = false;
                location.href = $aa.urls.toolkitPreferences;
                break;
           case $aa.Registration.Action.GoToSavedSearches:
                settings.needsPopup = false;
                location.href = $aa.urls.toolkitSearchProfiles;
                break;
        }
    }
}

$aa.Registration.HandleGoTo = function(request, settings)
{
    switch (request.toolkitAction)
    {
        case $aa.Registration.Action.GoToFavorites:
            if (settings)
                settings.needsPopup = false;
            location.href = $aa.urls.savedProperties;
            break;
        case $aa.Registration.Action.GoToMyPlaces:
            if (settings)
                settings.needsPopup = false;
            location.href = $aa.urls.toolkitPOIs;
            break;
        case $aa.Registration.Action.GoToPreferences:
            if (settings)
                settings.needsPopup = false;
            location.href = $aa.urls.toolkitPreferences;
            break;
        case $aa.Registration.Action.GoToSavedSearches:
            if (settings)
                settings.needsPopup = false;
            location.href = $aa.urls.toolkitSearchProfiles;
            break;
    }
    if (settings && !settings.needsPopup)
        return true;
}

$aa.Registration.showDialogMessage = function (dialog)
{
    dialog.dialog("option", "hide", {effect: "fade", duration: 1000});
    var $msgBox = dialog.find(".form-alert-message-box");
    $msgBox.addClass("centered");
    $msgBox.center({against : 'parent'});
    setTimeout(function(){dialog.dialog("close");}, 2000);        
} 

$aa.Registration.logout = function (refreshPage)
{
    var post = {};
    post.registrationAction = $aa.Registration.Action.Logout   
    $.post($aa.urls.toolkitRegistration, post, function(data, textStatus, jqXHR){    
        if (refreshPage)
            location.href = "http://" + location.hostname;
    });  
}

$aa.Registration.forgetMe = function (refreshPage)
{
    var post = {};
    post.registrationAction = $aa.Registration.Action.ForgetMe   
     
    $.post($aa.urls.toolkitRegistration, post, function(data, textStatus, jqXHR){  
        if (refreshPage)
            location.href = SE_PrepURL(location.href) + "&" + MLX_UniqueString();
        else 
        {        
            $aa.contact = {};
            $aa.agent = {};
            $aa.Registration.setWelcomeArea();     
            $aa.Registration.clearFormContent();
            $(".reg-form").show();
            $(".reg-welcome-forget-me").hide();
            if ($aa.Registration.onContactChange)
                 $aa.Registration.onContactChange();
        }
    });      
}

$aa.Registration.loadWelcomeArea = function()
{
    $(document).ready($aa.Registration.loadWelcomeAreaNow);
}
$aa.Registration.loadWelcomeAreaNow = function()
{
    if (($(".reg_welcome_placeholder").length > 0) && (typeof($aa.urls) != 'undefined'))
    {
         $(".reg_welcome_placeholder").load('http://' + location.hostname + "/" + $aa.urls.toolkitWelcomeArea + '?' + MLX_UniqueString());  
    } 
}

$aa.Registration.setWelcomeArea = function() {

    $aa.Registration.loadWelcomeAreaNow();
    return;
//    var $loggedIn = $(".reg-welcome-logged-in");
//    if ($loggedIn.length > 0) {
//        var isKnown = $aa.contact.contactID > 0;
//        $loggedIn.toggle(isKnown);
//        $(".reg-welcome-forget-me").toggle(isKnown);
//       
//        if (isKnown)
//        {
//            var $name = $(".reg-welcome-name");
//            if ($name.length > 0) 
//                $name.html($aa.contact.firstName ? $aa.contact.firstName : $aa.contact.displayName);
//                
//            $(".reg-welcome-log-out").toggle($aa.contact.isLoggedIn)
//            $(".reg-login").toggle($aa.contact.hasPassword && !$aa.contact.isLoggedIn);
//            $(".reg-register").toggle(!$aa.contact.hasPassword);
//        }
//        else
//        {
//            $(".reg-login").toggle(true);
//            $(".reg-register").toggle(true);
//        }
//    }
}

$aa.Registration.prototype.setupBehaviors = function () {
    this.$regDiv.find(".reg-phone").showDefaultText($aa.optional, "default");

    this.$login.keypress(function (e) {
        return SE_ClickOnEnterKey(e, $(this).find("#btnSignIn"));
    });
    
    this.$newAccount.keypress(function (e) {
        return SE_ClickOnEnterKey(e, $(this).find("#btnSaveNewUser"));
    });

    this.$regDiv.find("#reg_container").keypress(function (e) { return SE_CancelEnterKeyOnly(e); });
    
    $('.reg_button').hover(
		function () { $(this).removeClass('ui-state-default').addClass('ui-state-hover'); },
		function () { $(this).removeClass('ui-state-hover').addClass('ui-state-default'); }
	);
}

$aa.Registration.prototype.setupValidation = function () {
    this.$saveSearchForm.validate($aa.Forms.ValidationSettings);   
    this.$newAccount.find("form").validate($aa.Forms.ValidationSettings);    
    this.$login.find("form").validate($aa.Forms.ValidationSettings);   
    this.$forgotPassword.find("form").validate($aa.Forms.ValidationSettings);       
    this.addEmailValidation();
}

$aa.Registration.prototype.addEmailValidation = function()
{
    var myRegPopup = this;
    var EmailIsAvailable = true;            

    jQuery.validator.addMethod("email_is_changed", function(value, element) {
    if (value.toLowerCase() != $aa.contact.email.toLowerCase() 
        && !myRegPopup.isEmailChange)
    {
        var post = {}
        post.email = value;
        post.validate = $aa.Registration.Validate.IsEmailAvailable;
        $.ajax({
            type: 'POST',
            url: $aa.urls.toolkitRegistration,
            data: post,
            async: false,
            success: function(data, textStatus, jqXHR){
            EmailIsAvailable = data == "true";
            }}); 
           
        return EmailIsAvailable; 
    }
    else
        return true;
    }, function() {
        if (EmailIsAvailable)
        {
            return $aa.Registration.EmailChanged;
        }
        else {
            return $aa.Registration.EmailAlreadyUsed;
        }
    });
    
    if (this.$newAccount.find(".reg-email").is(":visible"))
    {
        if (typeof($aa.contact.contactID) == 'undefined' || $aa.contact.contactID < 0)
        {
            this.$newAccount.find(".reg-email").rules("add", {
                remote: {
                    url: $aa.urls.toolkitRegistration,
                    type: "post",
                    data: {
                      validate: $aa.Registration.Validate.IsEmailAvailable
                    }
                }, 
                messages: {remote: $aa.Registration.EmailAlreadyUsed}
            });
         }
         else { 
            this.$newAccount.find(".reg-email").rules("add", {
                email_is_changed: true      
            });
         }
     }
}

$aa.Registration.prototype.emailValidationAction= function(action, thisLink)
{
    var updateEmailFields = false;         
    switch (action)
    {
        case $aa.Registration.EmailValidationAction.Login:
            this.showLogin();
            updateEmailFields = true;
            break;
        case $aa.Registration.EmailValidationAction.ForgotPassword:
            this.showForgotPassword();
            updateEmailFields = true;
            break;
        case $aa.Registration.EmailValidationAction.UpdateEmail:
           this.isEmailChange=true;
           updateEmailFields = true;
            $(thisLink).parents(".form-error").remove();
           break;
        case $aa.Registration.EmailValidationAction.ForgetMe:
           $aa.Registration.forgetMe();
           $(thisLink).parents(".form-error").remove();
           break;
     }
     if (updateEmailFields)
        this.$regDiv.find(".reg-email").val($(thisLink).parents(".form-box").find(".reg-email").val());
}

$aa.Registration.prototype.loadContent = function () {
    $aa.Registration.LoadContent(this.$regDiv);
}
$aa.Registration.LoadContent = function ($regDiv) {
    if ($aa.contact)
    {
        $regDiv.find(".reg-first-name").each(function(){
            if ($(this).val() == "" && $aa.contact.firstName)
                $(this).val($aa.contact.firstName)
        });
        $regDiv.find(".reg-last-name").each(function(){
            if ($(this).val() == "" && $aa.contact.lastName)
                $(this).val($aa.contact.lastName)
        });
        $regDiv.find(".reg-email").each(function(){
            if ($(this).val() == "")
            {
                if ($aa.contact.bstUserName != '')
                    $(this).val($aa.contact.bstUserName)
                else if ($aa.contact.email != '')
                    $(this).val($aa.contact.email)
            }
        });
     }
     if ($aa.publicSearch) {
         $regDiv.find("#searchname").each(function(){
            if ($(this).val() == "" && $aa.publicSearch.searchName)
                $(this).val($aa.publicSearch.searchName)
        }); 
     }
}

$aa.Registration.clearFormContent = function () {
    if ($aa.contact)
    {
        $(".reg-first-name").val("") ;
        $(".reg-last-name").val("");
        $(".reg-email").val("");
     }
     if ($aa.publicSearch) {
         $("#searchname").each(function(){
            if ($(this).val() == "" && $aa.publicSearch.searchName)
                $(this).val($aa.publicSearch.searchName)
        }); 
     }
}

$aa.Registration.prototype.updateRegistrationAction = function(){       
 
    if (!this.request.registrationAction) {
        if ($aa.contact.hasPassword)
            this.request.registrationAction = $aa.Registration.Action.Login;              
        else if ($aa.contact.contactID > 0)
            this.request.registrationAction = $aa.Registration.Action.UpdateContactInfo;   
        else
            this.request.registrationAction = $aa.Registration.Action.RegisterBST;    
    } else if (this.request.registrationAction == $aa.Registration.Action.RegisterBST 
        && $aa.contact.contactID > 0)
        this.request.registrationAction = $aa.Registration.Action.UpdateContactInfo;   
}

$aa.Registration.prototype.setPanels = function(){        
    this.$regDiv.find(".reg-welcome-forget-me").toggle($aa.contact.contactID > 0);   
    this.$regDiv.find(".reg-welcome-name").html($aa.contact.displayName);   
    this.$regDiv.find(".reg_save_search_buttons").toggle($aa.contact.isLoggedIn);
    this.$regDiv.find(".reg-cancel").toggle(!this.notInPopup);
    
    switch (this.request.registrationAction)
    {
        case $aa.Registration.Action.Login:
        {
            this.showLogin();   
            break;      
        }
        case $aa.Registration.Action.RegisterBST:
        case $aa.Registration.Action.UpdateContactInfo:
        {
            if ($aa.contact.hasPassword)
                this.showLogin();                
            else
                this.showRegistration();
            this.$regDiv.find(".reg-bst-reg-only").show();            
            break;
        }
        case $aa.Registration.Action.ForgotPassword:
            this.showForgotPassword();
            break;;
        case $aa.Registration.Action.RegisterLead:
        default:
        {
            this.showRegistration();
            this.$regDiv.find(".reg-bst-reg-only").hide();
            break;
        }
    }  
}

$aa.Registration.prototype.getTitle = function(title){      
  
    if (title)
        return title;
    else 
    {
        switch (this.request.toolkitAction)
        {
            case $aa.Registration.Action.SaveSearch:
                return $aa.Registration.Action.SaveSearchTitle;
            case $aa.Registration.Action.SaveListing:
                return $aa.Registration.Action.SaveListingTitle;
            case $aa.Registration.Action.RemoveSearch:
                return $aa.Registration.Action.RemoveSearchTitle;
            case $aa.Registration.Action.RemoveListing:
                return $aa.Registration.Action.RemoveListingTitle;
        }  
        switch (this.request.registrationAction)
        {
            case $aa.Registration.Action.Login:
                return $aa.Registration.Action.LoginTitle;
            case $aa.Registration.Action.RegisterBST:
            {
                if ($aa.Registration.Action.RegisterBSTTitle == "")
                    $aa.Registration.Action.RegisterBSTTitle = "Free " + ($aa.company.bstName ?  $aa.company.bstName : " Account ") + " Registration";
                return $aa.Registration.Action.RegisterBSTTitle;
            }
            case $aa.Registration.Action.UpdateContactInfo:
            {
                if ($aa.Registration.Action.UpdateContactInfoTitle == "")
                    $aa.Registration.Action.UpdateContactInfoTitle = "Free " + ($aa.company.bstName ?  $aa.company.bstName : " Account ") + " Registration";
                return $aa.Registration.Action.RegisterBSTTitle;
            }
            case $aa.Registration.Action.RegisterLead:
            default:
                return $aa.Registration.Action.RegisterLeadTitle;
           
        }
    }
}

$aa.Registration.prototype.showLogin = function () {
    this.clearReturnMessages();
    
    this.$forgotPassword.hide();
    this.$newAccount.hide();
    this.$login.show();
    
    this.$regDiv.find(".reg_intro").hide();
    this.$regDiv.find(".reg_intro_login").show();
    
     if (this.request.toolkitAction == $aa.Registration.Action.SaveSearch)
        this.showSaveSearch();
     
     this.$regDiv.find(".reg-create-new-account-link").toggle(!($aa.contact && $aa.contact.hasPassword)); 
     this.setDialogTitle($aa.Registration.Action.LoginTitle);       
}

$aa.Registration.prototype.setDialogTitle = function (suggestedTitle) {
    var newTitle = ""
    if (this.isActionTitle(this.title))
        newTitle = this.title;
    else
        newTitle = suggestedTitle;
    this.$regDiv.dialog("option", "title", newTitle); 
}

$aa.Registration.prototype.isActionTitle = function(title)
{
    switch(title) {
        case $aa.Registration.Action.SaveSearchTitle:
        case $aa.Registration.Action.SaveListingTitle:
            return true;
        default:
            return false;
    }
}

$aa.Registration.prototype.showRegistration = function () {

    this.clearReturnMessages();
    
    this.$forgotPassword.hide();
    this.$newAccount.show();
    this.$login.hide();
    
    this.$regDiv.find(".reg_intro").hide();
    if (this.request.registrationAction == $aa.Registration.Action.RegisterLead)
        this.$regDiv.find(".reg_intro_new_account").show();
    else {
        this.$regDiv.find(".reg_intro_new_bst_account").show();         
    }
    
    if (this.request.toolkitAction == $aa.Registration.Action.SaveSearch)
        this.showSaveSearch();
    this.setDialogTitle(this.request.registrationAction == $aa.Registration.Action.RegisterLead 
        ? $aa.Registration.Action.RegisterLeadTitle
        : $aa.Registration.Action.RegisterBSTTitle);     
}

$aa.Registration.prototype.showSaveSearch = function () {
    this.clearReturnMessages();    
        
    if (this.request.toolkitAction == $aa.Registration.Action.SaveSearch)
    {
        this.$saveSearchForm.parent().show();
        this.$saveSearchForm.find("#search-name").val($aa.publicSearch.searchName);

        this.$regDiv.dialog("option", "title", $aa.Registration.Action.SaveSearchTitle);
    }
}

$aa.Registration.prototype.showForgotPassword = function() {
    this.clearReturnMessages();
    this.$newAccount.hide();
    this.$forgotPassword.show();
    this.$login.hide();
    this.$regDiv.find(".reg_save_search").hide();
    
    this.$regDiv.find(".reg_intro").hide();
    this.$regDiv.find(".reg_intro_recover_password").show();
    this.$regDiv.dialog("option", "title", $aa.Registration.Action.RecoverPasswordTitle);
}

$aa.Registration.prototype.saveSearch = function() {
  if (this.$regDiv.find(".reg_save_search_top_container").find("form").valid())
  {
        var post = {};
        this.loadActionRequest(post);
        var myRegForm = this;
        this.showLoadingCover(true);
        $.post(this.registrationUrl, post, function(data, textStatus, jqXHR){    
            var resp = $.parseJSON(data)  ;   
            if (resp.IsError)
                myRegForm.setReturnMessage(myRegForm.$saveSearchForm, resp.responseMessage, resp.IsError);
            else {
                myRegForm.removeForm();
                myRegForm.setReturnMessage(myRegForm.$regDiv, resp.responseMessage, resp.IsError);
                setTimeout(function(){myRegForm.cancel();}, 1000);
            }
        });   
   }
}
$aa.Registration.prototype.startFormSubmit = function () {
    this.clearReturnMessages();
    return this.validateSaveSearch();
}

$aa.Registration.prototype.login = function () {

    if (this.$login.find("form").valid() && this.startFormSubmit())
    {       
        this.request.registrationAction = $aa.Registration.Action.Login;
        this.postLoginOrRegistration(this.$login)      
    }
}

$aa.Registration.prototype.facebook_login = function () {
    
    if (this.startFormSubmit())
    {   
        // load facebook login in iframe
        if (typeof(this.$iFrame) == 'undefined')
        {
            this.$iFrame = $("<iframe class='reg-fb-login' frameborder='0' scrolling='0' src='/common/blank.htm'/>");
            this.$iFrame.appendTo("body");
        }
        
        this.$iFrame.attr("src", $aa.urls.aaUrl + "/common/facebook/login.aspx?returnUrl=" +  escape(SE_GetServerUrl() + $aa.urls.toolkitRegistration));
        // this will redirect to facebook login site and get facebook fb username and email
        // the name and email are sent back to the toolkit registraiton page where the contact is logged in
        // continue action with callback parentWindow.$aa.RegistrationForm.facebook_login_callback(response) 
    }
}

$aa.Registration.prototype.facebook_login_callback = function (response) {
    
    if(this.$iFrame)
        this.$iFrame.attr("src", "/common/blank.htm");
    if (response.IsError) {
        this.setReturnMessage(this.$login, response.responseMessage, response.isError);
    }
    else {
        $aa.contact = response.contact;
        this.request.registrationAction = $aa.Registration.Action.NoAction;
        this.handleResponse(response, this.$login);
        $(".mlx_fb_login_button").hide();
    }
}
    
$aa.Registration.prototype.handleResponse = function(resp, $form)
{
    this.showLoadingCover(false);   
    if (resp.IsError)
        this.setReturnMessage($form, resp.responseMessage, resp.IsError);
    else {
        this.removeForm();
        this.setReturnMessage(this.$regDiv, resp.responseMessage, resp.IsError);
        var pageMoved = false;
        if (resp.contact)
        {
            $aa.contact = resp.contact;
            $aa.agent = resp.contactOwner;
            $aa.Registration.setWelcomeArea();       
            if (!this.request.toolkitAction
            && this.request.reason != $aa.Registration.Reason.ExceededUnregisteredPropertyDetailVisits)
            {    
                location.href = $aa.urls.toolkitSearchProfiles;
                pageMoved = true;
            }
            else if (this.request.toolkitAction == $aa.Registration.Action.SaveSearch 
                && this.request.registrationAction == $aa.Registration.Action.NoAction)
            {
                this.saveSearch();
            }
            else if (this.request.toolkitAction == $aa.Registration.Action.SaveListing
                && this.request.registrationAction == $aa.Registration.Action.NoAction)
            {
                $.post($aa.urls.toolkitRegistration, this.request, function(data, textStatus, jqXHR){    
                     if (data.indexOf("<!DOCTYPE") != -1)
                        alert("We had a problem processing your request.");
                    else 
                        pageMoved = true;
                });  
            }
            else if (this.request.toolkitAction
            && !$aa.pageSettings.addressesVisible
            && $aa.contact.hasPassword)
            {
                location.href = location.href;
                pageMoved = true;
            }       
            else
                pageMoved = $aa.Registration.HandleGoTo(this.request);
        }
        if (this.request.callback)
            this.request.callback ();
        var myRegForm = this;
        if (!pageMoved)
        {
            if ($aa.Registration.onContactChange)
                 $aa.Registration.onContactChange();
            setTimeout(function(){myRegForm.cancel();}, 2000);
        }
    }
}

$aa.Registration.prototype.postLoginOrRegistration = function($form)
{
    var post = {};
    post.registrationAction = this.request.registrationAction
    post.email = $form.find(".reg-email").val();
    post.v37 = $form.find(".reg-password").val();
    post.firstName = $form.find(".reg-first-name").val();
    post.lastName = $form.find(".reg-last-name").val();
    post.phone = $form.find(".reg-phone").val();
    if (post.phone == $aa.optional)
            post.phone = "";
    post.pageTitle = $aa.pageSettings.pageTitle;
    post.listingID = $aa.listing.concatListingID;
    post.searchID = $aa.publicSearch.searchID;  
    
    if ($aa.agent  && $aa.agent.userID)
        post.agentID = $aa.agent.userID    
    this.loadActionRequest(post);
    var myRegForm = this;
    
    this.showLoadingCover(true);
   
    $.post(this.registrationUrl, post, function(data, textStatus, jqXHR){    
        var resp = $.parseJSON(data)  ;
        myRegForm.handleResponse(resp, $form);
    });      
}

$aa.Registration.prototype.removeForm = function()
{
    this.$regDiv.html("");    
}

$aa.Registration.prototype.reloadPage = function()
{
    history.go(0);
} 

$aa.Registration.prototype.forgotPassword = function() {

    if (this.$forgotPassword.find("form").valid())
    {        
        var post = {};
        post.registrationAction = $aa.Registration.Action.ForgotPassword;
        post.email = this.$forgotPassword.find(".reg-email").val();
        var myRegForm = this;
        $.post(this.registrationUrl, post, function(data, textStatus, jqXHR){    
            var resp = $.parseJSON(data)  ;   
            myRegForm.setReturnMessage(myRegForm.$forgotPassword, resp.responseMessage, resp.IsError);
        });        
    }
}

$aa.Registration.prototype.clearReturnMessages = function ($element, msg)
{
    this.$regDiv.remove(".form-alert-message-box");
}

$aa.Registration.prototype.clearReturnMessages = function ($element)
{
    $(".form-alert-message-box").remove();
}

$aa.Registration.prototype.setReturnMessage = function ($element, msg, isError)
{
    var $msgBox = $element.find(".form-alert-message-box")
    $msgBox.remove();
    if (isError)
        $msgBox =$("<div class='form-error-box form-alert-message-box'><div class='form-error form-alert-message'></div></div>");
    else {
        $msgBox =$("<div class='form-alert-message-box ui-state-highlight '><div class='form-alert-message'></div></div>");
    }
    var hasContent = $element.html() != "";
    
    $element.prepend($msgBox);
    $msgBox.find(".form-alert-message").html(msg);
    if (!hasContent)
    {
        $msgBox.addClass("centered");
        $msgBox.center({against : 'parent'});
    }
}

$aa.Registration.prototype.loadActionRequest = function (post) {

    post.toolkitAction = this.request.toolkitAction;       
                
    switch (this.request.toolkitAction)
    {
        case $aa.Registration.Action.SaveSearch:
            if ($aa.publicSearch)
            {
                post.searchID = $aa.publicSearch.searchID;
                post.searchName = this.$saveSearchForm.find("#search-name").val();
                post.searchFrequency = this.$saveSearchForm.find("#search-frequency").val();
            }
            break;
        case $aa.Registration.Action.RemoveSearch:
            if (this.request.searchID)
                post.searchID = this.request.searchID;                
            break;
        case $aa.Registration.Action.SaveListing:
        case $aa.Registration.Action.RemoveListing:
            post.listingID = this.request.listingID;
            break;
    }
}

$aa.Registration.prototype.validateSaveSearch = function()
{
    if (this.$saveSearchForm.length > 0)    
        return this.$saveSearchForm.valid()
    else
        return true;
} 

$aa.Registration.prototype.register = function () {
    if (this.$newAccount.find("form").valid() && this.startFormSubmit())
    {     
        switch(this.request.registrationAction)
        {
            case $aa.Registration.Action.RegisterLead:
            case $aa.Registration.Action.RegisterBST:
            case $aa.Registration.Action.UpdateContactInfo:
                break;
            default:
                if ($aa.contact.contactID)
                    this.request.registrationAction = $aa.Registration.Action.UpdateContactInfo;
                else if (this.$regDiv.find(".reg-bst-reg-only").is(":visible"))
                    this.request.registrationAction = $aa.Registration.Action.RegisterBST;
                else
                    this.request.registrationAction = $aa.Registration.Action.RegisterLead;
                break;
        }
        this.postLoginOrRegistration(this.$newAccount)      
    }
}

$aa.Registration.prototype.showLoadingCover = function (show) {
   
    var $itemToCover = $("#reg_container");
    $itemToCover.css("position", "relative");
    if (show)
        $aa.Registration.Popup_Loading_Timeout = setTimeout(function () {
            SE_Toggle_LoadingCover($itemToCover, show, null, .1);
            clearTimeout($aa.Registration.Popup_Loading_Timeout);
            $aa.Registration.Popup_Loading_Timeout = null;
        }, 100);
    else {
        clearTimeout($aa.Registration.Popup_Loading_Timeout);
        $aa.Registration.Popup_Loading_Timeout = null;
       SE_Toggle_LoadingCover($itemToCover, false);
    }

}


$aa.Registration.prototype.done = function() {
    
}

$aa.Registration.Close = function() {
    
    $('.reg_area').dialog("close"); 
    $(".ui-dialog").remove();
    if (typeof(SEMap) != 'undefined' && typeof(SEMap.ClosePopups) == 'function')
        SEMap.ClosePopups();
}

$aa.Registration.prototype.cancel = function () {
    this.$regDiv.dialog("close");     
};

$aa.Registration.prototype.setWidth = function (divWidth) {

    this.$regDiv.dialog("option", "width", divWidth);
    this.$regDiv.dialog("option", "position", "center");
};


$aa.auto_suggest= function ($field, url) {
    var autocomplete_cache =  {};
    var LastXhr = null;
     $field.autocomplete({ minLength: 2, source: function (request, response) {
	        var term = request.term;

	        for (key in autocomplete_cache) {
	            if (term.toLowerCase().indexOf(key.toLowerCase()) >=0 ) {
                if(autocomplete_cache[key].length!=0)
                {
	                var op = new Array();
	                var i = 0;
	                for (t in autocomplete_cache[key]) {
	                    if (autocomplete_cache[key][t].toLowerCase().indexOf(term.toLowerCase()) >= 0) {
	                        op[i] = autocomplete_cache[key][t];
	                        i++;
	                    }
	                }
	                response(op);
	                return;
                    }
	            }
	        }
	        LastXhr = $.getJSON(url, request, function (data, status, xhr) {
	            autocomplete_cache[term] = data; if (xhr === LastXhr) { response(data); }
	        });
	    }
	    });
        }


$aa.auto_suggest_click = function ($field, url, $btnClick) {
var autocomplete_cache =  {};
var LastXhr = null;
$field.autocomplete({ minLength: 2, 

  select: function (event, ui) {
                     $field.val(ui.item.label);
                     $btnClick.click();
                     return true;
                 },
source: function (request, response) {
	var term = request.term;

	for (key in autocomplete_cache) {
	    if (term.toLowerCase().indexOf(key.toLowerCase()) >= 0) {
        if(autocomplete_cache[key].length!=0)
        {
	        var op = new Array();
	        var i = 0;
	        for (t in autocomplete_cache[key]) {
	            if (autocomplete_cache[key][t].toLowerCase().indexOf(term.toLowerCase()) >= 0) {
	                op[i] = autocomplete_cache[key][t];
	                i++;
	            }
	        }
	        response(op);
	        return;
            }
	    }
	}
	LastXhr = $.getJSON(url, request, function (data, status, xhr) {
	    autocomplete_cache[term] = data; if (xhr === LastXhr) { response(data); }
	});
}
});
}
/* ----------------------------------------------------
-------------    End BST Login Popup    -------------------
-------------------------------------------------------  */

