
Type.registerNamespace("MySpace.Utils.Media");
MySpace.Utils.Media.loadStaticContent = function(root){
	root=root || document;
    // Images
    var a_imgs = root.getElementsByTagName("img");
    for(var i = 0 ; i < a_imgs.length ; i++){
        if(!a_imgs[i].getAttribute("MaxWidth") && !a_imgs[i].getAttribute("MaxHeight") && a_imgs[i].getAttribute("source")){
            //this is a hack for ProfileImageLink on Firefox 2.0 or lower versions.           
            if(a_imgs[i].parentNode.parentNode.style.display=="-moz-inline-box"){
                a_imgs[i].parentNode.parentNode.style.display="";
                setTimeout(function(){
                    a_imgs[i].parentNode.parentNode.style.display="-moz-inline-box";
                }, 0);
            }
	        a_imgs[i].src = a_imgs[i].getAttribute("source");
        }
    }
    
    // Flash Objects
    var a_objs = root.getElementsByTagName("object");
    if(a_objs){
        for(var i = 0 ; i < a_objs.length ; i++){
            if(a_objs[i].getAttribute("movie")){
                
                var url = a_objs[i].getAttribute("movie");
                
                try{//Try loading it using activeX method
                    a_objs[i].LoadMovie(0,url);
                    var disableAutoPlay = a_objs[i].getAttribute("disableAutoPlay");
                    if(disableAutoPlay == undefined || disableAutoPlay == ""){
                        a_objs[i].Play();
                    }
                    continue;
                }catch(e){
                }
                //Failed loading using activeX, continue loading by replacing the object
                
                var height = a_objs[i].getAttribute("height");
                var width = a_objs[i].getAttribute("width");
                var vars = "";
                var prms = a_objs[i].getElementsByTagName("param");
                for(var x = 0 ; x < prms.length ; x++){
                    try{
                        if(prms[x].getAttribute("name").toLowerCase() === "flashvars"){
                            vars = prms[x].getAttribute("value");
                            break;
                        }
                    }catch(e){
                    }
                }
                
                
                var so = new SWFObject(url, "obj"+Math.random(), width, height, "8", "#FFFFFF");
                
                if(vars){
                    var keyvalue = vars.split(/\&/);
                    for(var v = 0 ; v < keyvalue.length ; v++){
                        var kv = keyvalue[v].split("=");
                        if(kv.length == 2)
                            so.addVariable(kv[0],kv[1]);
                    }
                }
                
                var wrapper = document.createElement("div");
                a_objs[i].parentNode.insertBefore(wrapper,a_objs[i]);
                so.write(wrapper);
                a_objs[i].parentNode.removeChild(a_objs[i]);
            }
        }
    }
}

try{
    MySpace.Utils.Media.loadStaticContent();
}catch(e){
}


Type.registerNamespace("MySpace.UI");

Date.prototype.addDays = function(value){
	/// <param name="value" type="Number" integer="true"></param>
	this.setDate(this.getDate()+value);return this;
}




MySpace.CMS = {
	track: function(id,linkId){
      /// <param name="id" type="String"></param>
      MySpace.WebRequest.invoke("/Modules/Common/HttpHandlers/CMSClick.ashx?_i=" + id + "&_l=" + linkId, true, null, null, Function.emptyFunction, null, 0);
	},
	trackV2: function(sender, id, linkId) {
		/// <param name="id" type="String"></param>
		var href = sender.href;
		var hasTarget = (sender.target && sender.target != "");

		// Build click tracking url.  Append datetime to prevent caching.
		var url = "/Modules/Common/HttpHandlers/CMSClick.ashx?_i=" + id +"&_l=" + linkId + "&t=" + new Date().getTime();

		// Call click tracking service, redirect to link on success, or after 2 seconds if no response from service
		MySpace.WebRequest.invoke(url, true, null,
			function() { if (!hasTarget) { location.href = href; } },
			function() { if (!hasTarget) { location.href = href; } }, null, 2000);

		// Return false to prevent link from performing default action so that click tracking can finish
		if (!hasTarget) return false;
	}
};




//Sitewide implimentations of global controls
if(typeof MySpace.Cookies.MSCulture!=='undefined'){
	var d = new Date();
	MySpace.Cookies.MSCulture.get_values().timeZone=(d.getTimezoneOffset()/-60);
	MySpace.Cookies.save(MySpace.Cookies.MSCulture,".myspace.com",new Date().addDays(7));
}




//
// Base64 encoding/decoding
//

MySpace.Util.Base64KeyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";

// If urlSafe is true, + and / will be replaced with - and _, so the
// result can be used with no URL-encoding.
MySpace.Util.Base64Encode = function(input, urlSafe) {
    var output = "",
		chr1, chr2, chr3,
		enc1, enc2, enc3, enc4,
		i = 0,
		keyStr = MySpace.Util.Base64KeyStr;

    do {
        chr1 = input.charCodeAt(i++);
        chr2 = input.charCodeAt(i++);
        chr3 = input.charCodeAt(i++);

        enc1 = chr1 >> 2;
        enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
        enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
        enc4 = chr3 & 63;

        if (isNaN(chr2)) {
            enc3 = enc4 = 64;
        } else if (isNaN(chr3)) {
            enc4 = 64;
        }

        output = output + keyStr.charAt(enc1) + keyStr.charAt(enc2) +
         keyStr.charAt(enc3) + keyStr.charAt(enc4);
    } while (i < input.length);
    
    if (urlSafe) {
		output = output.replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
	}
	
    return output;
}

MySpace.Util.Base64Decode = function(input) {
    var output = "",
		chr1, chr2, chr3,
		enc1, enc2, enc3, enc4,
		i = 0,
		keyStr = MySpace.Util.Base64KeyStr;
	
	// Handle URL-safe variant of Base64
    input = input.replace(/-/g, "+").replace(/_/g, "/");
	if (input.length % 4) {
		input += (input.length % 4 == 2) ? "==" : "=";
	}
	
    // remove all characters that are not A-Z, a-z, 0-9, +, /, or =
    input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
	
    do {
        enc1 = keyStr.indexOf(input.charAt(i++));
        enc2 = keyStr.indexOf(input.charAt(i++));
        enc3 = keyStr.indexOf(input.charAt(i++));
        enc4 = keyStr.indexOf(input.charAt(i++));

        chr1 = (enc1 << 2) | (enc2 >> 4);
        chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
        chr3 = ((enc3 & 3) << 6) | enc4;

        output = output + String.fromCharCode(chr1);

        if (enc3 != 64) {
            output = output + String.fromCharCode(chr2);
        }
        if (enc4 != 64) {
            output = output + String.fromCharCode(chr3);
        }
    } while (i < input.length);

    return output;
}



MySpace.CultureSwitchPrompt=function(){throw "Cannot instantiate static class.";}
MySpace.CultureSwitchPrompt.getContent=function(culture, callback, context){
	/// <param name="culture" type="String"></param>
	/// <param name="callback" type="Function" mayBeNull="true" optional="true"></param>
	/// <param name="context" type="Object" mayBeNull="true" optional="true"></param>		
	MySpace.WebRequest.invoke("/Modules/Common/HttpHandlers/CultureSwitch.ashx", false, "culture="+culture+"&userid="+MySpace.ClientContext.UserId, _onComplete, null, context, 0);
	
	function _onComplete(response, eventArgs) {
		if(callback) callback(response, eventArgs);
	}
	return null;
}
MySpace.CultureSwitchPrompt.registerClass('MySpace.CultureSwitchPrompt');


MySpace.UI.Header=function(){throw "Cannot instantiate static class.";}
MySpace.UI.Header.languageLinkClick=function(culture, domain, index){
	/// <param name="culture" type="String"></param>
	/// <param name="domain" type="String"></param>
	/// <param name="index" type="Number"></param>
	MySpace.CultureSwitchPrompt.getContent(culture, _contentRetrieved);
	function _contentRetrieved(content){
        var cspContent = Sys.Serialization.JavaScriptSerializer.deserialize(content);                                          
        var p=MySpace.UI.Popup.create('',''); 
        p._element.innerHTML = "<div class='popup_box2'><a class='popup_ex'></a><div class='popup_title'></div><div class='popup_content2'></div><div class='popup_buttons'></div></div>";
        p._box = p._element.firstChild;
        p.set_content(cspContent.content);
        p.set_title(cspContent.header);                                          
        p.add_button(cspContent.continuebtn);
        p.add_button(cspContent.cancelbtn, true).isCancel=true;
        p.set_state({culture:culture, domain:domain});
        p.addCssClass("popupChangeLanguage");
        p.show(_popupCallback);		
	}
	function _popupCallback(sender, args){		
	    var state=sender.get_state();    
		if(args.target.isCancel) {//clicked cancel
		    MySpace.Cookies.MSCulture.get_values().PreferredCulturePending=culture.replace("-","*");                	            		        
	        MySpace.Cookies.save(MySpace.Cookies.MSCulture,".myspace.com",new Date().addDays(7));		       
	        if(domain.length==0) 
	            window.location.reload(false);	        
            return;
        }		
        MySpace.Cookies.MSCulture.get_values().PreferredCulturePending=culture;                	
        MySpace.Cookies.MSCulture.get_values().PreferredCulture=culture;                	        
	    MySpace.Cookies.save(MySpace.Cookies.MSCulture,".myspace.com",new Date().addDays(7));	
	    //if they are logged in,there **SHOULD** be two radio buttons
	    var c=sender._box.childNodes[2].getElementsByTagName("input");
		if(c[1]!=null && c[1].checked) {//Persist user's language
			Sys.Net.WebServiceProxy.invoke("/Services/GeoLocation.asmx", "SavePreferredCulture", false, {culture:state.culture}, _goToDomain, _goToDomain, null, 0);
			return;
		}
		_goToDomain();
	}
	function _goToDomain(){//needed for callback
		if(domain.length > 0) window.location = "http://" + domain;		
		else window.location.reload(true);
	}
}

// Wrapper for legacy language link calls
function popLanguageOverlay(culture, url){ MySpace.UI.Header.languageLinkClick(culture, url, 1); }


MySpace.UI.Header.registerClass('MySpace.UI.Header');



// Function to dynamically add CSS rules to the document
MySpace.UI.addStyles=function(cssText, isFirst, key){
	if(key){
		if(MySpace.UI.addStyles._added[key]){ return; }
		MySpace.UI.addStyles._added[key]=true;
	}
	
	var styleSheet;
	if(document.createStyleSheet){
		if(isFirst){
			styleSheet=document.createStyleSheet("", 0);
		}
		else{
			styleSheet=document.createStyleSheet();
		}
	}
	else{
		styleSheet=document.createElement("style");
		var head=document.getElementsByTagName("head")[0];
		if(isFirst){
			head.insertBefore(styleSheet, head.childNodes[0]);
		}
		else{
			head.appendChild(styleSheet);
		}
	}
	
	if(Sys.Browser.agent==Sys.Browser.InternetExplorer){
		styleSheet.cssText=cssText;
	}
	else if(Sys.Browser.agent==Sys.Browser.Safari){
		styleSheet.innerText=cssText;
	}
	else{
		styleSheet.innerHTML=cssText;
	}
};
MySpace.UI.addStyles._added={};

// Dynamically adds a script file to the page.
//   scriptUrl: URL of the script to add, or just the filename (e.g. "QuickPost.js") if it was registered
//              via DeferredScript.Register
//   testObj:   Object name to look for to detect if the script has loaded, e.g. "MySpace.SomeModule.FrobWidget"
//   callback:  Function to call when the script has loaded
MySpace.UI.addScript=function(scriptUrl, testObj, callback){
	function isLoaded(test){
		var comps=test.split(".");
		for(var obj=window, i=0; i<comps.length; i++){
			if(!(obj=obj[comps[i]])){
				return false;
			}
		}
		return true;
	}
	
	if(testObj && isLoaded(testObj)){
		if(typeof callback == "function"){ callback(); }
		return;
	}
	
	if(!MySpace.UI.addScript._loading[scriptUrl]){
		var scriptNode=document.createElement("script");
		scriptNode.src=scriptUrl;
		document.getElementsByTagName("head")[0].appendChild(scriptNode);
		MySpace.UI.addScript._loading[scriptUrl]=true;
	}
	
	if(testObj){
		var interval=window.setInterval(function(){
			if(isLoaded(testObj)){
				window.clearInterval(interval);
				delete MySpace.UI.addScript._loading[scriptUrl];
				if(typeof callback == "function"){ callback(); }
			}
		}, 200);
	}
};
MySpace.UI.addScript._loading={};

MySpace.UI.addDeferredScript=function(filename, callback){
	var info=MySpace.deferredScripts[filename.toLowerCase()];
	MySpace.UI.addScript(info.url, info.test, callback);
};
if(MySpace.deferredScripts && !queryString.noautoload){
	Sys.Application.add_load(function(){
		var delay=0;
		for(var key in MySpace.deferredScripts){
			delay+=1000;
			window.setTimeout(Function.createPartial(window, MySpace.UI.addDeferredScript, key), delay);
		}
	});
}




//
// Assign the given value to the given object reference.  Use this instead of eval.
// ex.  MySpace.Util.setJSValue("MySpace.Comments.commentID", 175213);
//
MySpace.Util.setJSValue = function(name, value) {
	var comps = name.split("."), root = window;
	for (var i = 0; i < comps.length - 1; i++) {
		root = root[comps[i]] = root[comps[i]] || {};
	}
	root[comps[i]] = value;
};


// Generic wiring of elements

// Binding global search box
(function() {
    //Get Container
    var searchElements = $q("form.msSearchBox");
    if (searchElements && searchElements.length >= 1) {
        var contelem = searchElements[0];
        var inputelem = $q(".mssbText input", contelem, true);
        var submitelem = $q(".mssbSubmit input", contelem, true);
    }

    if (inputelem && contelem && submitelem) {
        $addHandler(inputelem, 'focus', function() {
            if (!msglobalnav.autosuggestscriptloaded) {
                MySpace.UI.addDeferredScript("AutoSuggestSearch.js", function() {
                    $create(MySpace.UI.SearchBox, { searchBtn: submitelem, searchTxtBx: inputelem }, null, null, contelem);
                    msglobalnav.autosuggestscriptloaded = true;
                });
            }
        });
    }
})();

// Wire intl links
new function(){
	var el = $get("intlLink");
	if (el) $addHandler(el, 'click', msglobalnav.toggleInternationalLinks);
}();


new function(){
    if (MySpace != null && MySpace.ClientContext != null && MySpace.ClientContext.DisplayFriendId != null && MySpace.ClientContext.DisplayFriendId > 0) {
        var abuseSpn = $q('.disabled',$get('footer'));
        if (abuseSpn && (abuseSpn.length > 0) && (abuseSpn[0].nodeName === 'SPAN')){
            var abuseLnk = abuseSpn[0].getElementsByTagName('A');
            if (abuseLnk && (abuseLnk.length > 0)) abuseLnk[0].href += MySpace.ClientContext.DisplayFriendId;
            Sys.UI.DomElement.removeCssClass(abuseSpn[0],'disabled');
        }
    }    
}();

Array.find = function Array$find(array, callback, instance) {
    for (var i = 0, l = array.length; i < l; i++) {
        var elt = array[i];

        if (typeof (elt) !== 'undefined' && callback.call(instance, elt) === true) {
            return elt;
        }
    }
    return null;
};


//
// Framebuster
//
(function(){
	if(!MySpace.Application.keyDisabled("FrameBuster") && !window.suppressFrameBuster && (window != top)){
		var bust=true;
		try{
			// If we can read the top-level URL, it must be a MySpace page, so don't bust the frame.
			bust=!top.location.href;
		}
		catch(e){}
		
		// Allow framing by known good sites
		bust=bust && !(document.referrer.match(/^https?:\/\/[-a-z0-9.]*\.google\.(co\.|com\.)?[a-z]+\/imgres/i))
				  && !(document.referrer.match(/^https?:\/\/([^\/]*\.)?(myspace\.com|myspace\.cn|simsidekick\.com|levisawards\.com|digg\.com|myspaceespana\.com|eurodemosantander2016\.es)\//i));
		
		if(bust){
			top.location.replace(window.location.href);
		}
	}
})();
//
//
// All this stuff is deprecated, either because it's not needed at a global level, or can be done with
// jQuery instead.  Please don't use any of this.
//
//

MySpace.UI.hideElements = function(tagNames, TorF){
	/// <param name="value" type="Array" elementType="String"></param>
	/// <param name="TorF" type="Boolean"></param>
	for(var j=0;j<tagNames.length;j++){
		var t = document.getElementsByTagName(tagNames[j]);
		for(var i=0;i<t.length;i++){
		    if (TorF) t[i].setAttribute('origvis', t[i].style.visibility);    
		    t[i].style.visibility = TorF? "hidden" : (t[i].getAttribute('origvis') ? t[i].getAttribute('origvis') : "");
        }
	}
};


MySpace.WebRequest=function(){throw "Cannot instantiate static class.";};
MySpace.WebRequest.invoke = function(path, useGet, params, onSuccess, onFailure, userContext, timeout) {
	/// <param name="path" type="String"></param>
	/// <param name="useGet" type="Boolean"></param>
	/// <param name="params"></param>
	/// <param name="onSuccess" type="Function" mayBeNull="true" optional="true"></param>
	/// <param name="onFailure" type="Function" mayBeNull="true" optional="true"></param>
	/// <param name="userContext" mayBeNull="true" optional="true"></param>
	/// <returns type="Sys.Net.WebRequest"></returns>
	if (!params) params = {};
	var request = new Sys.Net.WebRequest();
	if (!useGet) {
		if(typeof params==="string")
		var body = (typeof params!=="string")? Sys.Serialization.JavaScriptSerializer.serialize(params) : params;
		if (body === "{}") body = "";
		request.set_body(body);
	}
	request.set_url(Sys.Net.WebRequest._createUrl(path, (useGet)?params:{}));

	request.add_completed(onComplete);
	if (timeout && timeout > 0) request.set_timeout(timeout);
	request.invoke();

	function onComplete(response, eventArgs) {
		if (response.get_responseAvailable()) {
			var statusCode = response.get_statusCode();

			var result = null;
			try {
				var contentType = response.getResponseHeader("Content-Type");
				if (contentType.startsWith("application/json"))
					result = response.get_object();
				else if (contentType.startsWith("text/xml"))
					result = response.get_xml();
				else result = response.get_responseData();
			} catch (ex) {}

			//handle errors
			if ((statusCode < 200) || (statusCode >= 300)) {
				if (onFailure) {
					if (!result) {
						result = new Sys.Net.WebServiceError(false , "WebRequest failed for an unknown reason.", "", "");
					}
					result._statusCode = statusCode;
					onFailure(result, userContext);
				}
				else {//dev doesn't want to handle the error, just alert it
					var error;
					if (result)
						error = result.get_exceptionType() + "-- " + result.get_message();
					else error = response.get_responseData();
					window.alert("WebRequest Failed: "+error);
				}
			}
			else if (onSuccess) {
				onSuccess(result, userContext);
			}
		}
		else {
			var msg;
			if (response.get_timedOut()) msg = "WebRequest timed out.";
			else msg = "WebRequest failed for an unknown reason.";

			if (onFailure) onFailure(new Sys.Net.WebServiceError(response.get_timedOut(), msg, "", ""), userContext);
			else alert(msg);
		}
	}
	return request;
};
MySpace.WebRequest.registerClass('MySpace.WebRequest');


MySpace.CMS.cache={};
MySpace.CMS.getContent=function(placementId, callback, context){
	/// <param name="placementId" type="Number"></param>
	/// <param name="callback" type="Function" mayBeNull="true" optional="true"></param>
	/// <param name="context" type="Object" mayBeNull="true" optional="true"></param>
	var cacheItem=MySpace.CMS.cache[placementId];
	if(cacheItem && new Date() < cacheItem.expire) {
		callback(cacheItem.response);
		return null;
	}

	MySpace.WebRequest.invoke("/Modules/Common/HttpHandlers/CMS.ashx", false, "placementId="+placementId, _onComplete, null, context, 0);
	
	function _onComplete(response, eventArgs) {
		var expire = new Date();
		expire.setTime(expire.getTime()+120000);//2 minute cache
		MySpace.CMS.cache[placementId] = {response:response,expire:expire};
		if(callback) callback(response, eventArgs);
	}
	return null;
};

MySpace.UI.getElementsByClassName = function(className, element) {
    element = element || document;
    className = ' ' + className + ' ';
    var potentials = element.all || element.getElementsByTagName("*");
    var l = potentials.length, results = [], i;
    for (i = 0; i < l; i++) {
        if ((' ' + potentials[i].className + ' ').indexOf(className) !== -1) {
            results[results.length] = potentials[i];
        }
    }
    return results;
};

MySpace.UI.getComputedStyle = function(node){
            switch(Sys.Browser.agent) {
            case Sys.Browser.Safari:
                {
                        var s;
                        if(node instanceof HTMLElement){
                                var dv = node.ownerDocument.defaultView;
                                s = dv.getComputedStyle(node, null);
                                if(!s && node.style){
                                        node.style.display = "";
                                        s = dv.getComputedStyle(node, null);
                                }
                        }
                        return s || {};
                }

            case Sys.Browser.InternetExplorer:
                {
                        // IE (as of 7) doesn't expose Element like sane browsers
                        return node.nodeType == 1 /* ELEMENT_NODE*/ ? node.currentStyle : {};
                }
            
            default:
                {
                        return node instanceof HTMLElement ?
                                node.ownerDocument.defaultView.getComputedStyle(node, null) : {};
                }
            }
        };
        
MySpace.UI.getContentBox = function(node){
    //  Returns an object that encodes the height
    //  of the node's content box, irrespective of the
    //  current box model.
	var s=MySpace.UI.getComputedStyle(node);
	var pe={
		h: parseFloat(s.paddingTop)+parseFloat(s.paddingBottom),
		w: parseFloat(s.paddingLeft)+parseFloat(s.paddingRight)
	};
	var be = {
		h: (s.borderTopStyle!="none" ? parseFloat(s.borderTopWidth) : 0) + (s.borderBottomStyle!="none" ? parseFloat(s.borderBottomWidth) : 0),
		w: (s.borderLeftStyle!="none" ? parseFloat(s.borderLeftWidth) : 0) + (s.borderRightStyle!="none" ? parseFloat(s.borderRightWidth) : 0)
	};
	return {
		h: node.clientHeight - pe.h - be.h,
		w: node.clientWidth - pe.w - be.w
	};
};


Sys.UI.Control.overlaps = function(r1, r2) {
    var xLeft = (r1.x >= r2.x && r1.x <= (r2.x + r2.width));
    var xRight = ((r1.x + r1.width) >= r2.x && (r1.x + r1.width) <= r2.x + r2.width);
    var xComplete = ((r1.x < r2.x) && ((r1.x + r1.height) > (r2.x + r2.height)));
    
    var yLeft = (r1.y >= r2.y && r1.y <= (r2.y + r2.height));
    var yRight = ((r1.y + r1.height) >= r2.y && (r1.y + r1.height) <= r2.y + r2.height);
    var yComplete = ((r1.y < r2.y) && ((r1.y + r1.height) > (r2.y + r2.height)));
    if ((xLeft || xRight || xComplete) && (yLeft || yRight || yComplete)) {
        return true;
    }
   
    return false;
};

/* Flash Detection for MS Player */
Type.registerNamespace("MySpace.FlashDetection");
MySpace.FlashDetection = function() {
    return this;
};
MySpace.FlashDetection.prototype = {
    getFlashVersion: function (desc) {
	    var matches = desc.match(/[\d]+/g);
	    matches.length = 3;  // To standardize IE vs FF
	    return matches.join('.');
    },
    
    removeFlashVersionPrefix: function(completeVersion) {
        var version = completeVersion.split(" ");
        if (version.length == 1)
            return version;
        else if (version.length > 1)
            return version[1];
        else        
            return completeVersion;
    },

    hasRequiredFlashVersion: function (requiredVer){        
	    var requiredVerIE = (requiredVer.toString()+".0.0");
	    var requiredVerFF = requiredVer;
	    var hasRequiredVer = 0;
	    var pluginVer = "0.0.0";
	    
	    var plugin = (navigator.mimeTypes && navigator.mimeTypes["application/x-shockwave-flash"]) ? navigator.mimeTypes["application/x-shockwave-flash"].enabledPlugin : 0;	
	    if(plugin){
		    var str = navigator.plugins["Shockwave Flash"].description.split(" ");
		    for(var i=0;i<str.length;++i){
			    if(isNaN(parseInt(str[i]))) continue;
			    pluginVer = str[i]; 
		    }
		    hasRequiredVer = pluginVer >= requiredVerFF;	
	    }else if(navigator.userAgent && navigator.userAgent.indexOf("MSIE")>=0 && (navigator.appVersion.indexOf("Win")!=-1)) {
	        try { //ie7
	            var a = new ActiveXObject('ShockwaveFlash.ShockwaveFlash.7');
	            var versionVariable = this.removeFlashVersionPrefix(a.GetVariable('$version'));
	            var pluginVer = this.getFlashVersion(versionVariable);
	        }catch(e){ //ie6
		        try {
			        var a = new ActiveXObject('ShockwaveFlash.ShockwaveFlash.7');
    	            versionVariable = a.GetVariable('$version');
			        pluginVer = this.getFlashVersion(versionVariable);
		        } catch (e) {
			        try {
				        var a = new ActiveXObject('ShockwaveFlash.ShockwaveFlash.6');
				        versionVariable = a.GetVariable('$version');
				        pluginVer = '6.0.21';
			        } catch (e) {
				        try {
					        var a = new ActiveXObject('ShockwaveFlash.ShockwaveFlash');
					        versionVariable = a.GetVariable('$version');
					        pluginVer = this.getFlashVersion(versionVariable);
				        } catch (e) { }			
			        }		
		        }	
		    }           
            
	        var pv = pluginVer.split(".");	
	        var rv = requiredVerIE.split(".");	
    	    
	        rv[0] = parseInt(rv[0], 10);	
	        rv[1] = parseInt(rv[1], 10);	
	        rv[2] = parseInt(rv[2], 10);	
	        
	        pv[0] = parseInt(pv[0], 10);	
	        pv[1] = parseInt(pv[1], 10);	
	        pv[2] = parseInt(pv[2], 10);	        

	        hasRequiredVer = (pv[0] > rv[0] || (pv[0] == rv[0] && pv[1] > rv[1]) || (pv[0] == rv[0] && pv[1] == rv[1] && pv[2] >= rv[2])) ? true : false;      
	    }
    	
	    return hasRequiredVer;
    }
};

Type.registerNamespace("MySpace.UI.Effects");

MySpace.UI.Effects.Glitz=function(){
	throw Error.invalidOperation()
};

MySpace.UI.Effects.Glitz.interpolate=function(value1,value2,percentage,easingFn){
	if(easingFn){percentage=100*easingFn(percentage/100);}
	return value1+(value2-value1)*(percentage/100)
};
MySpace.UI.Effects.Glitz.setElementOpacity=function(a,b){
	if(a.filters){
		if(b==1){	// opacity=100 makes text fuzzy on IE7, so remove it
			a.style.cssText=a.style.cssText.replace(/FILTER:[^;]*;?/i, "");
		}
		else{
			a.style.filter="progid:DXImageTransform.Microsoft.Alpha(opacity="+b*100+")"
		}
	}
	else a.style.opacity=b
};

MySpace.UI.Effects.Easing={
	linear:function(n){
		return n;
	},
	quadIn:function(n){
		return n*n;
	},
	quadOut:function(n){
		return n*(n-2)*-1;
	},
	quadInOut: function(n){
		n=n*2;
		if(n<1){ return Math.pow(n, 2) / 2; }
		return -1 * ((--n)*(n-2) - 1) / 2;
	},
	quartIn: function(n){
		return Math.pow(n, 4);
	},
	quartOut: function(n){
		return -1 * (Math.pow(n-1, 4) - 1);
	},
	quartInOut: function(n){
		n=n*2;
		if(n<1){ return Math.pow(n, 4) / 2; }
		n-=2;
		return -1/2 * (Math.pow(n, 4) - 2);
	},
	circIn: function(n){
		return -1 * (Math.sqrt(1 - Math.pow(n, 2)) - 1);
	},
	circOut: function(n){
		n = n-1;
		return Math.sqrt(1 - Math.pow(n, 2));
	},
	circInOut: function(n){
		n = n*2;
		if(n<1){ return -1/2 * (Math.sqrt(1 - Math.pow(n, 2)) - 1); }
		n-=2;
		return 1/2 * (Math.sqrt(1 - Math.pow(n, 2)) + 1);
	},
	backIn: function(n){
		var s = 1.70158;
		return Math.pow(n, 2) * ((s+1)*n - s);
	},
	backOut: function(n){
		// summary: an easing function that pops past the range briefly, and 
		// 	slowly comes back. 
		n = n - 1;
		var s = 1.70158;
		return Math.pow(n, 2) * ((s + 1) * n + s) + 1;
	},
	backInOut: function(n){
		var s = 1.70158 * 1.525;
		n = n*2;
		if(n < 1){ return (Math.pow(n, 2)*((s+1)*n - s))/2; }
		n-=2;
		return (Math.pow(n, 2)*((s+1)*n + s) + 2)/2;
	},
	elasticIn: function(n){
		if(n==0){ return 0; }
		if(n==1){ return 1; }
		var p = .3;
		var s = p/4;
		n = n - 1;
		return -1 * Math.pow(2,10*n) * Math.sin((n-s)*(2*Math.PI)/p);
	},
	elasticOut: function(n){
		// summary: An easing function that elasticly snaps around the target value, near the end of the Animation
		if(n==0) return 0;
		if(n==1) return 1;
		var p = .3;
		var s = p/4;
		return Math.pow(2,-10*n) * Math.sin((n-s)*(2*Math.PI)/p) + 1;
	},
	elasticInOut: function(n){
		// summary: An easing function that elasticly snaps around the value, near the beginning and end of the Animation		
		if(n==0) return 0;
		n = n*2;
		if(n==2) return 1;
		var p = .3*1.5;
		var s = p/4;
		if(n<1){
			n-=1;
			return -.5*(Math.pow(2,10*n) * Math.sin((n-s)*(2*Math.PI)/p));
		}
		n-=1;
		return .5*(Math.pow(2,-10*n) * Math.sin((n-s)*(2*Math.PI)/p)) + 1;
	},
	bounceIn: function(n){
		// summary: An easing function that "bounces" near the beginning of an Animation
		return (1 - MySpace.UI.Effects.Easing.bounceOut(1-n)); // Decimal
	},
	bounceOut: function(n){
		// summary: An easing function that "bounces" near the end of an Animation
		var s=7.5625;
		var p=2.75;
		var l; 
		if(n < (1 / p)){
			l = s*Math.pow(n, 2);
		}else if(n < (2 / p)){
			n -= (1.5 / p);
			l = s * Math.pow(n, 2) + .75;
		}else if(n < (2.5 / p)){
			n -= (2.25 / p);
			l = s * Math.pow(n, 2) + .9375;
		}else{
			n -= (2.625 / p);
			l = s * Math.pow(n, 2) + .984375;
		}
		return l;
	},
	bounceInOut: function(n){
		// summary: An easing function that "bounces" at the beginning and end of the Animation
		if(n<0.5){ return MySpace.UI.Effects.Easing.bounceIn(n*2) / 2; }
		return (MySpace.UI.Effects.Easing.bounceOut(n*2-1) / 2) + 0.5;
	}	
};

MySpace.UI.Effects.Animation=function(){
	MySpace.UI.Effects.Animation.initializeBase(this)
};
MySpace.UI.Effects.Animation.prototype={
	_duration:1,
	_fps:25,
	_target:null,
	_tickHandler:null,
	_timer:null,
	_percentComplete:0,
	_percentDelta:null,
	_parentAnimation:null,
	get_duration:function(){
		return this._duration
	},
	set_duration:function(a){
		this._duration=a
	},
	get_fps:function(){
		return this._fps
	},
	set_fps:function(a){
		this._fps=a
	},
	get_isActive:function(){
		return this._timer!==null
	},
	get_isPlaying:function(){
		return this._timer!==null&&this._timer.get_enabled()
	},
	get_percentComplete:function(){
		return this._percentComplete
	},
	get_target:function(){
		return this._target
	},
	set_target:function(a){
		this._target=a
	},
	add_ended:function(a){
		this.get_events().addHandler("ended",a)
	},
	remove_ended:function(a){
		this.get_events().removeHandler("ended",a)
	},
	add_started:function(a){
		this.get_events().addHandler("started",a)
	},
	remove_started:function(a){
		this.get_events().removeHandler("started",a)
	},
	dispose:function(){
		if(this._timer){
			this._timer.dispose();
			this._timer=null
		}
		this._tickHandler=null;
		this._target=null;
		MySpace.UI.Effects.Animation.callBaseMethod(this,"dispose")
	},
	getAnimatedValue:function(){
		throw Error.notImplemented()
	},
	onEnd:function(){
	},
	onStart:function(){
	},
	onStep:function(percentage){
		this.setValue(this.getAnimatedValue(percentage))
	},
	pause:function(){
		if(!this._parentAnimation)if(this._timer){
			this._timer.set_enabled(false);
			this.raisePropertyChanged("isPlaying")
		}
	},
	play:function(){
		if(!this._parentAnimation){
			var a=true;
			if(!this._timer){
				a=false;
				if(!this._tickHandler)this._tickHandler=Function.createDelegate(this,this._onTimerTick);
				this._timer=new MySpace.Timer;
				this._timer.set_interval(1000/this._fps);
				this._timer.add_tick(this._tickHandler);
				this._percentDelta=100/(this._duration*this._fps);
				this.onStart();
				this._updatePercentComplete(0,true)
			}
			this._timer.set_enabled(true);
			this.raisePropertyChanged("isPlaying");
			if(!a)this.raisePropertyChanged("isActive")
		}
	},
	setOwner:function(a){
		this._parentAnimation=a
	},
	setValue:function(){
		throw Error.notImplemented()
	},
	stop:function(){
		if(!this._parentAnimation){
			var a=this._timer;
			this._timer=null;
			if(a){
				a.dispose();
				this._updatePercentComplete(100);
				this.onEnd();
				var handler = this.get_events().getHandler("ended");
				if (handler) {
				    handler(this, null);
				}					
				this.raisePropertyChanged("isPlaying");
				this.raisePropertyChanged("isActive")
			}
		}
	},
	_onTimerTick:function(){
		this._updatePercentComplete(this._percentComplete+this._percentDelta,true)
	},
	_updatePercentComplete:function(percentComplete,animate){
		if(percentComplete>100)percentComplete=100;
		this._percentComplete=percentComplete;
		this.raisePropertyChanged("percentComplete");
		if(animate)this.onStep(percentComplete);
		if(percentComplete===100)this.stop()
	}
};
MySpace.UI.Effects.Animation.registerClass("MySpace.UI.Effects.Animation",Sys.Component);
MySpace.UI.Effects.PropertyAnimation=function(){
	MySpace.UI.Effects.PropertyAnimation.initializeBase(this)
};
MySpace.UI.Effects.PropertyAnimation.prototype={
	_property:null,
	_propertyKey:null,
	get_property:function(){
		return this._property
	},
	set_property:function(a){
		this._property=a
	},
	get_propertyKey:function(){
		return this._propertyKey
	},
	set_propertyKey:function(a){
		this._propertyKey=a
	},
	add_ended:function(a){
		this.get_events().addHandler("ended",a)
	},
	remove_ended:function(a){
		this.get_events().removeHandler("ended",a)
	},
	add_started:function(a){
		this.get_events().addHandler("started",a)
	},
	remove_started:function(a){
		this.get_events().removeHandler("started",a)
	},
	setValue:function(value){
		if(this._propertyKey){
			this.get_target()[this._property][this._propertyKey] = value;
		}
		else{
			this.get_target()[this._property] = value;
		}
	}
};
MySpace.UI.Effects.PropertyAnimation.registerClass("MySpace.UI.Effects.PropertyAnimation",MySpace.UI.Effects.Animation);
MySpace.UI.Effects.InterpolatedAnimation=function(){
	MySpace.UI.Effects.InterpolatedAnimation.initializeBase(this)
};
MySpace.UI.Effects.InterpolatedAnimation.prototype={
	_startValue:null,
	_endValue:null,
	_easingFunction:null,
	get_endValue:function(){
		return this._endValue
	},
	set_endValue:function(a){
		this._endValue=a
	},
	get_startValue:function(){
		return this._startValue
	},
	set_startValue:function(a){
		this._startValue=a
	},
	get_easingFunction:function(){
		return this._easingFunction;
	},
	set_easingFunction:function(a){
		this._easingFunction=a;
	}
};
MySpace.UI.Effects.InterpolatedAnimation.registerClass("MySpace.UI.Effects.InterpolatedAnimation",MySpace.UI.Effects.PropertyAnimation);
MySpace.UI.Effects.DiscreteAnimation=function(){
	MySpace.UI.Effects.DiscreteAnimation.initializeBase(this);
	this._values=[]
};
MySpace.UI.Effects.DiscreteAnimation.prototype={
	get_values:function(){
		return this._values
	},
	set_values:function(a){
		this._values=a
	},
	getAnimatedValue:function(percentage){
		var b=Math.round(percentage/100*(this._values.length-1));
		return this._values[b]
	}
};
MySpace.UI.Effects.DiscreteAnimation.registerClass("MySpace.UI.Effects.DiscreteAnimation",MySpace.UI.Effects.PropertyAnimation);
MySpace.UI.Effects.NumberAnimation=function(){
	MySpace.UI.Effects.NumberAnimation.initializeBase(this)
};
MySpace.UI.Effects.NumberAnimation.prototype={
	_integralValues:false,
	get_integralValues:function(){
		return this._integralValues
	},
	set_integralValues:function(a){
		this._integralValues=a
	},
	getAnimatedValue:function(percentage){
		var a=MySpace.UI.Effects.Glitz.interpolate(this.get_startValue(),this.get_endValue(),percentage,this.get_easingFunction());
		if(this._integralValues)a=Math.round(a);
		return a
	}
};
MySpace.UI.Effects.NumberAnimation.registerClass("MySpace.UI.Effects.NumberAnimation",MySpace.UI.Effects.InterpolatedAnimation);
MySpace.UI.Effects.LengthAnimation=function(){
	MySpace.UI.Effects.LengthAnimation.initializeBase(this)
};
MySpace.UI.Effects.LengthAnimation.prototype={
	_unit:"px",
	get_unit:function(){
		return this._unit
	},
	set_unit:function(a){
		this._unit=a
	},
	getAnimatedValue:function(percentage){
		var b=MySpace.UI.Effects.Glitz.interpolate(this.get_startValue(),this.get_endValue(),percentage,this.get_easingFunction());
		return Math.round(b)+this._unit
	}
};
MySpace.UI.Effects.LengthAnimation.registerClass("MySpace.UI.Effects.LengthAnimation",MySpace.UI.Effects.InterpolatedAnimation);
MySpace.UI.Effects.CompositeAnimation=function(){
	MySpace.UI.Effects.CompositeAnimation.initializeBase(this);
	this._animations=[];
};
MySpace.UI.Effects.CompositeAnimation.prototype={
	get_animations:function(){
		return this._animations
	},
	add_animation:function(a){
		this._animations.push(a);
	},
	getAnimatedValue:function(){
		throw Error.invalidOperation()
	},
	dispose:function(){
		for(var a=0;a<this._animations.length;a++)this._animations[a].dispose();
		this._animations=null;
		MySpace.UI.Effects.CompositeAnimation.callBaseMethod(this,"dispose")
	},
	onEnd:function(){
		for(var a=0;a<this._animations.length;a++)this._animations[a].onEnd()
	},
	onStart:function(){
		for(var a=0;a<this._animations.length;a++)this._animations[a].onStart()
	},
	onStep:function(b){
		for(var a=0;a<this._animations.length;a++)this._animations[a].onStep(b)
	}
};
MySpace.UI.Effects.CompositeAnimation.registerClass("MySpace.UI.Effects.CompositeAnimation",MySpace.UI.Effects.Animation);

MySpace.UI.Effects.ColorAnimation = function(target, duration, fps, property, propertyKey, startValue, endValue) {
    MySpace.UI.Effects.ColorAnimation.initializeBase(this, [target, duration, fps, property, propertyKey, startValue, endValue]);
    
    this._start = null;
    this._end = null;
    
    this._interpolateRed = false;
    this._interpolateGreen = false;
    this._interpolateBlue = false;
}
MySpace.UI.Effects.ColorAnimation.prototype = {
    onStart : function() {
        MySpace.UI.Effects.ColorAnimation.callBaseMethod(this, 'onStart');
       
        this._start = MySpace.UI.Effects.ColorAnimation.getRGB(this.get_startValue());
        this._end = MySpace.UI.Effects.ColorAnimation.getRGB(this.get_endValue());
        
        this._interpolateRed = (this._start.Red != this._end.Red);
        this._interpolateGreen = (this._start.Green != this._end.Green);
        this._interpolateBlue = (this._start.Blue != this._end.Blue);
    },
    
    getAnimatedValue : function(percentage) {
        var r = this._start.Red;
        var g = this._start.Green;
        var b = this._start.Blue;
        
        if (this._interpolateRed)
            r = Math.round(MySpace.UI.Effects.Glitz.interpolate(r, this._end.Red, percentage, this.get_easingFunction()));
        
        if (this._interpolateGreen)
            g = Math.round(MySpace.UI.Effects.Glitz.interpolate(g, this._end.Green, percentage, this.get_easingFunction()));
        
        if (this._interpolateBlue)
            b = Math.round(MySpace.UI.Effects.Glitz.interpolate(b, this._end.Blue, percentage, this.get_easingFunction()));
        
        return MySpace.UI.Effects.ColorAnimation.toColor(r, g, b);
    },
    
    set_startValue : function(value) {
        if (this._startValue != value) {
            this._startValue = value;
            this.raisePropertyChanged('startValue');
        }
    },
    
    set_endValue : function(value) {
        if (this._endValue != value) {
            this._endValue = value;
            this.raisePropertyChanged('endValue');
        }
    }   
}
MySpace.UI.Effects.ColorAnimation.getRGB = function(color) {
    if (!color || color.length != 7) {
        throw String.format(AjaxControlToolkit.Resources.Animation_InvalidColor, color);
    }
    return { 'Red': parseInt(color.substr(1,2), 16),
             'Green': parseInt(color.substr(3,2), 16),
             'Blue': parseInt(color.substr(5,2), 16) };
}
MySpace.UI.Effects.ColorAnimation.toColor = function(red, green, blue) {
    var r = red.toString(16);
    var g = green.toString(16);
    var b = blue.toString(16);
    if (r.length == 1) r = '0' + r;
    if (g.length == 1) g = '0' + g;
    if (b.length == 1) b = '0' + b;
    return '#' + r + g + b;
}
MySpace.UI.Effects.ColorAnimation.registerClass('MySpace.UI.Effects.ColorAnimation', MySpace.UI.Effects.InterpolatedAnimation);

MySpace.UI.Effects.FadeEffect=function(){
	throw Error.invalidOperation()
};
MySpace.UI.Effects.FadeEffect.prototype={
	FadeIn:0,FadeOut:1
};
MySpace.UI.Effects.FadeEffect.registerEnum("MySpace.UI.Effects.FadeEffect");
MySpace.UI.Effects.FadeAnimation=function(){
	MySpace.UI.Effects.FadeAnimation.initializeBase(this)
};
MySpace.UI.Effects.FadeAnimation.prototype={
	_effect:MySpace.UI.Effects.FadeEffect.FadeIn,
	get_effect:function(){
		return this._effect
	},
	set_effect:function(a){
		this._effect=a
	},
	getAnimatedValue:function(c){
		var a=0,b=1;
		if(this._effect===MySpace.UI.Effects.FadeEffect.FadeOut){
			a=1;
			b=0
		}
		return MySpace.UI.Effects.Glitz.interpolate(a,b,c)
	},
	onStart:function(){
		var a=0;
		if(this._effect===MySpace.UI.Effects.FadeEffect.FadeOut){a=1;}
		this.setValue(a)
		if(a==0){this.get_target().style.visibility="visible";}
	},
	onEnd:function(){
		var a=1;
		if(this._effect===MySpace.UI.Effects.FadeEffect.FadeOut)a=0;
		this.setValue(a)
		if(a==0){this.get_target().style.visibility="hidden";}
	},
	setValue:function(a){
		MySpace.UI.Effects.Glitz.setElementOpacity(this.get_target(),a)
	}
};
MySpace.UI.Effects.FadeAnimation.registerClass("MySpace.UI.Effects.FadeAnimation",MySpace.UI.Effects.Animation);

//Sliding Automation Start
//Defining the slideEffect enum
MySpace.UI.Effects.SlideEffect=function(){
	throw Error.invalidOperation()
};
MySpace.UI.Effects.SlideEffect.prototype={
	SlideIn:0,SlideOut:1
};
MySpace.UI.Effects.SlideEffect.registerEnum("MySpace.UI.Effects.SlideEffect");

MySpace.UI.Effects.SlidingAnimation=function(){
    
	MySpace.UI.Effects.SlidingAnimation.initializeBase(this)
};

MySpace.UI.Effects.SlidingAnimation.prototype = {
	_effect:MySpace.UI.Effects.SlideEffect.SlideIn,
    
	get_effect:function(){
		return this._effect
	},
	set_effect:function(a){
		this._effect=a
	},

	initialize : function() {
        this.get_target().style.overflow="hidden";
        
        var display = this.get_target().style.display;
        this.get_target().style.display="block";
        
        this.set_property("style");
        this.set_propertyKey("height");
        if(this._effect===MySpace.UI.Effects.SlideEffect.SlideIn)
        {
            this.set_startValue(MySpace.UI.getContentBox(this.get_target()).h);
            this.set_endValue(0);
        }
        else{
            this.set_startValue(0);
            this.set_endValue(MySpace.UI.getContentBox(this.get_target()).h);
        }
        this.get_target().style.display=display;
    },
	
	onStart:function(){
        //Set the display to block before expanding the div
        if(this._effect===MySpace.UI.Effects.SlideEffect.SlideOut){
			this.get_target().style.display="block";
		}
	},
	onEnd:function(){
        //Set the display to none only after collapsing the div
        if(this._effect===MySpace.UI.Effects.SlideEffect.SlideIn){
			this.get_target().style.display="none";
        }
    }
}
MySpace.UI.Effects.SlidingAnimation.registerClass('MySpace.UI.Effects.SlidingAnimation', MySpace.UI.Effects.LengthAnimation);

//
// AutoComplete
//

MySpace.UI.AutoCompleteBehavior=function(element){
	/// <summary>
	/// This behavior can be attached to a textbox to enable auto-complete/auto-suggest scenarios.
	/// </summary>
	/// <param name="element" type="Sys.UI.DomElement" DomElement="true" mayBeNull="false">
	/// DOM Element the behavior is associated with
	/// </param>
	/// <returns />
	MySpace.UI.AutoCompleteBehavior.initializeBase(this, [element]);
	
	// Path to the web service, or null if a page method
	this._servicePath=null;
	
	// Name of the web method
	this._serviceMethod=null;
	
	// Additional params to pass to the web service
	this._serviceParams=null;
	
	// Flag to indicate that it is a JSONP service instead of an ASMX
	this._isJsonpService=false;
	
	// User/page specific context provided to the web method
	this._contextKey=null;
	
	// Whether or not the the user/page specific context should be used
	this._useContextKey=false;
	this._minimumPrefixLength=3;
	this._triggerPrefix="";
	this._completionItems=null;
	this._completionInterval=1000;
	this._completionListWrapperID=null;	
	this._completionListElementID=null;
	this._completionListAlwaysVisible=false;
	this._closeObsoleteResults=true;
	this._currentPrefix=null;
	this._selectIndex=-1;
	this._enableCaching=true;
	this._enableCacheSubstrings=false;
	this._flyoutHasFocus=false;
	this._textBoxHasFocus=false;
	this._completionListCssClass=null;
	this._completionListItemCssClass=null;
	this._completionListFixedHeight=null;
	this._completionListMaxHeight=200;
	this._completionListWidth=null;
	this._lazyLoadPlaceholderHeight=null;
	this._groupHeaderCssClass=null;
	this._highlightedItemCssClass=null;
	this._delimiterCharacters=null;
	this._firstRowSelected=false;
	this._showOnlyCurrentWordInCompletionListItem=false;
	this._webRequest=null;  
	
	// Specifies the parameter name for the web service call which carries the search text
	this._postParameterName = "prefixText"; 
};

MySpace.UI.AutoCompleteBehavior.prototype={
	initialize: function(){
		/// <summary>
		/// Initializes the autocomplete behavior.
		/// </summary>
		/// <returns />
		MySpace.UI.AutoCompleteBehavior.callBaseMethod(this, 'initialize');
		
		this._popupBehaviorHiddenHandler=Function.createDelegate(this, this._popupHidden);
		this._tickHandler=Function.createDelegate(this, this._onTimerTick);
		this._focusHandler=Function.createDelegate(this, this._onGotFocus);
		this._blurHandler=Function.createDelegate(this, this._onLostFocus);
		this._keyDownHandler=Function.createDelegate(this, this._onKeyDown);
		this._mouseDownHandler=Function.createDelegate(this, this._onListMouseDown);
		this._mouseUpHandler=Function.createDelegate(this, this._onListMouseUp);
		this._mouseOverHandler=Function.createDelegate(this, this._onListMouseOver);
		this._mouseOutHandler=Function.createDelegate(this, this._onListMouseOut);
		this._completionListBlurHandler=Function.createDelegate(this, this._onCompletionListBlur);
		this._completionListScrollHandler=Function.createDelegate(this, this._drawMissingItems);
		this._bodyClickHandler=Function.createDelegate(this, this._onBodyClick);
		
		this.initializeTextBox();
		
		if(this._completionListElementID !== null){
			this._completionListElement=$get(this._completionListElementID);
		}
		if(this._completionListElement == null){
			this._completionListElement=document.createElement('div');
			this._completionListElement.id=this.get_id() + '_completionListElem';
			this._getOuterEl().parentNode.insertBefore(this._completionListElement, this._getOuterEl().nextSibling);
		}
		if(this._completionListWrapperID){
			this._completionListWrapper=$get(this._completionListWrapperID);
		}
		else{
			this._completionListWrapper=this._completionListElement;
		}
		this.initializeCompletionList();
		
		if(this._completionListAlwaysVisible){
			// List starts out visible, so we need to show data right away
			this._onTimerTick();
		}
		else{
			this._popupBehavior=$create(MySpace.UI.PopupBehavior, 
					{ 'id':this.get_id()+'PopupBehavior', 'parentElement':this._getOuterEl(), "positioningMode": MySpace.UI.PositioningMode.BottomLeft }, null, null, this._completionListWrapper);
			this._popupBehavior.add_hidden(this._popupBehaviorHiddenHandler);
		
			// Create the animations (if they were set before initialize was called)
			if(this._onShow){
				this._popupBehavior.set_onShow(this._onShow);
			}
			if(this._onHide){
				this._popupBehavior.set_onHide(this._onHide);
			}
		}
	},
	
	dispose: function(){
		/// <summary>
		/// Disposes the autocomplete behavior
		/// </summary>
		/// <returns />
	   
		if(this._popupBehavior){
			if(this._popupBehaviorHiddenHandler){
				this._popupBehavior.remove_hidden(this._popupBehaviorHiddenHandler);
			}
			this._popupBehavior.dispose();
			this._popupBehavior=null;
		}
		this._stopTimer();

		if(this._completionListElement){
			$removeHandler(this._completionListElement, 'blur', this._completionListBlurHandler);
			$removeHandler(this._completionListElement, 'scroll', this._completionListScrollHandler);
			$removeHandler(this._completionListElement, 'mousedown', this._mouseDownHandler);
			$removeHandler(this._completionListElement, 'mouseup', this._mouseUpHandler);
			$removeHandler(this._completionListElement, 'mouseover', this._mouseOverHandler);
			$removeHandler(this._completionListElement, 'mouseout', this._mouseOutHandler);
		}
		if(this._bodyClickHandler){
			$removeHandler(document.body, 'click', this._bodyClickHandler);
			this._bodyClickHandler=null;
		}
		
		this._popupBehaviorHiddenHandler=null;
		this._tickHandler=null;
		this._focusHandler=null;
		this._blurHandler=null;
		this._keyDownHandler=null;
		this._completionListBlurHandler=null;
		this._mouseDownHandler=null;
		this._mouseUpHandler=null;
		this._mouseOverHandler=null;
		this._mouseOutHandler=null;
		
		MySpace.UI.AutoCompleteBehavior.callBaseMethod(this, 'dispose');
	},
	
	_startTimer: function(){
		this._intervalId=window.setInterval(this._tickHandler, this._completionInterval);
	},
	_stopTimer: function(){
		window.clearInterval(this._intervalId);
	},
	
	initializeTextBox: function(){
		/// <summary>
		/// Initializes the textbox
		/// </summary>
		/// <returns />	
		var element=this._getInnerEl();
		element.autocomplete="off";
		element.setAttribute("autocomplete", "off");
		$addHandler(element, "focus", this._focusHandler);		
		$addHandler(element, "blur", this._blurHandler);
		$addHandler(element, "keydown", this._keyDownHandler);
	},
	
	initializeCompletionList: function(){
		/// <summary>
		/// Initializes the autocomplete list element
		/// </summary>
		/// <returns />		
		
		var element=this._completionListElement;
		var wrapper=this._completionListWrapper;
		var completionListStyle=element.style;
		
		if(this._completionListCssClass){
			Sys.UI.DomElement.addCssClass(element, this._completionListCssClass);
		}
		else{
			completionListStyle.textAlign='left';
			completionListStyle.overflow='auto';
			completionListStyle.overflowX='hidden';
			completionListStyle.cursor='default';
			completionListStyle.padding='0px';
			completionListStyle.margin='0px! important';
			if(Sys.Browser.agent === Sys.Browser.Safari){
				completionListStyle.border='solid 1px gray';	
				completionListStyle.backgroundColor='white';
				completionListStyle.color='black';			
			}
			else{
				completionListStyle.border='solid 1px buttonshadow';			
				completionListStyle.backgroundColor='window';
				completionListStyle.color='windowtext';
			}
			if(this._completionListAlwaysVisible){
				if(this.get_servicePath()){
					// Show a progress indicator while we're loading the list
					completionListStyle.background='url("'+MySpace.StaticContentBase+'/modules/common/static/img/loadercircles.gif") center center no-repeat';
				}
			}
			else{
				wrapper.style.visibility='hidden';
			}
			
			var elementBounds=Sys.UI.DomElement.getBounds(this._getOuterEl());		
			this._completionListElement.style.width=(this.get_completionListWidth() || Math.max(1, elementBounds.width - 2)) + 'px';
		}
		if(this._completionListFixedHeight){
			completionListStyle.height=this._completionListFixedHeight+"px";
		}
		$addHandler(element, "mousedown", this._mouseDownHandler);
		$addHandler(element, "mouseup", this._mouseUpHandler);
		$addHandler(element, "mouseover", this._mouseOverHandler);
		$addHandler(element, "mouseout", this._mouseOutHandler);
		$addHandler(element, "blur", this._completionListBlurHandler); 
		$addHandler(element, "scroll", this._completionListScrollHandler);  
		$addHandler(document.body, 'click', this._bodyClickHandler);
	},
	
	_currentCompletionWord: function(){
		var elementValue=this.get_value();
		var word=elementValue;
		
		if(this.get_isMultiWord()){
			var startIndex=this._getCurrentWordStartIndex();
			var endIndex=this._getCurrentWordEndIndex(startIndex);
			
			if(endIndex <= startIndex){
				word=elementValue.substring(startIndex);
			} else{
				word=elementValue.substring(startIndex, endIndex);
			}
		}
		
		var trigger=this.get_triggerPrefix().toLowerCase();
		if(trigger){
			if(!word.toLowerCase().startsWith(trigger)){
				return "";
			}
			else{
				return word.substring(trigger.length);
			}
		}
		else{
			return word;
		}
	},
	
	_getCursorIndex: function(){
		return this.get_element().selectionStart;
	},
	
	_getCurrentWordStartIndex: function(){
		var elementText=this.get_value().substring(0,this._getCursorIndex());
		
		var index=0;
		var lastIndex=-1;
		
		for(var i=0; i < this._delimiterCharacters.length; ++i){
			var curIndex=elementText.lastIndexOf(this._delimiterCharacters.charAt(i));
			if(curIndex > lastIndex){
				lastIndex=curIndex;
			}
		}	
		
		index=lastIndex;
		if(index >= this._getCursorIndex()){
			index=0;
		}
		
		return index < 0 ? 0:index + 1;	
	},
	
	_getCurrentWordEndIndex: function(wordStartIndex){
		var elementValue=this.get_value();
		var elementText=elementValue.substring(wordStartIndex);
		var index=0;
		
		for(var i=0; i < this._delimiterCharacters.length; ++i){
			var curIndex=elementText.indexOf(this._delimiterCharacters.charAt(i));
			if(curIndex > 0 && (curIndex < index || index == 0)){
				index=curIndex;
			}
		}
			   
		return index <= 0 ? elementValue.length:index + wordStartIndex;
	},
	
	get_isMultiWord:function(){
		/// <value type="Boolean" mayBeNull="false">
		/// Whether the behavior is currently in multi-word mode
		/// </value>
		return (this._delimiterCharacters != null) && (this._delimiterCharacters != '');
	},
	
	_getTextWithInsertedWord: function(wordToInsert){
		var text=wordToInsert;
		var replaceIndex=0;
		var originalText=this.get_value();
		
		if(this.get_isMultiWord()){
			var startIndex=this._getCurrentWordStartIndex();
			var endIndex=this._getCurrentWordEndIndex(startIndex);
			var prefix='';
			var suffix='';
			
			if(startIndex > 0){
				prefix=originalText.substring(0, startIndex);
			}
			if(endIndex > startIndex){
				suffix=originalText.substring(endIndex);
			}
			
			text=prefix + wordToInsert + suffix;
		}
		
		return text;
	},
	
	_hideCompletionList: function(){
		/// <summary>
		/// Hides the autocomplete flyout list
		/// </summary>
		/// <returns />
		if(!(this._popupBehavior && this._popupBehavior.get_visible())){
			return;
		}
		
		var eventArgs=new Sys.CancelEventArgs();
		this.raiseHiding(eventArgs);
		if(eventArgs.get_cancel()){
			return;
		}
		
		// Actually hide the popup
		this.hidePopup();
	},
	
	showPopup:function(){
		/// <summary>
		/// Show the completion list popup
		/// </summary>
		/// <remarks>
		/// If you cancel the showing event, you should still call
		/// showPopup to ensure consistency of the internal state
		/// </remarks>
		if(this._popupBehavior){
			this._popupBehavior.show();
			this.raiseShown(Sys.EventArgs.Empty);
		}
	},
	
	hidePopup:function(){
		/// <summary>
		/// Hide the completion list popup
		/// </summary>
		/// <remarks>
		/// If you cancel the hiding event, you should still
		/// call hidePopup to ensure consistency of the internal
		/// state
		/// </remarks>

		if(this._popupBehavior){
			this._popupBehavior.hide();
		}
		else{
			this._popupHidden();
		}
	},
	
	_popupHidden:function(){
		/// <summary>
		/// Clean up the completion list popup after it has been hidden
		/// </summary>
	
		this._completionListElement.innerHTML='';
		this._selectIndex=-1;
		this._flyoutHasFocus=false;
		
		this.raiseHidden(Sys.EventArgs.Empty);
	},
	
	_highlightItem: function(item){
		/// <summary>
		/// Highlights the specified item
		/// </summary>
		/// <param name="item" type="Sys.UI.DomElement" DomElement="true" mayBeNull="false" />
		/// <returns />
		
		var children=this._completionListElement.childNodes;

		// Unselect any previously highlighted item
		for(var i=0; i < children.length; i++){
			var child=children[i];
			if(child._highlighted){
				child._highlighted=false;
				if(this._completionListItemCssClass){
					Sys.UI.DomElement.removeCssClass(child, this._highlightedItemCssClass);
					Sys.UI.DomElement.addCssClass(child, this._completionListItemCssClass);
				}
				else{
					if(Sys.Browser.agent === Sys.Browser.Safari){
						child.style.backgroundColor='white';
						child.style.color='black';
					}
					else{
						child.style.backgroundColor='window';
						child.style.color='windowtext';
					}
				}
				this.raiseItemOut(new MySpace.UI.AutoCompleteItemEventArgs(child, child.firstChild.nodeValue, child._value));
			}
		}
		
		if(item){
		    // Highlight the new item
		    if(this._highlightedItemCssClass){
			    Sys.UI.DomElement.removeCssClass(item, this._completionListItemCssClass);
			    Sys.UI.DomElement.addCssClass(item, this._highlightedItemCssClass);
		    }
		    else{
			    if(Sys.Browser.agent === Sys.Browser.Safari){
				    item.style.backgroundColor='lemonchiffon';
			    }
			    else{
				    item.style.backgroundColor='highlight';
				    item.style.color='highlighttext';
			    }
    			
		    }
		    item._highlighted=true;
		    if(!item._isPlaceholder){
			    this.raiseItemOver(new MySpace.UI.AutoCompleteItemEventArgs(item, item.firstChild.nodeValue, item._value));
		    }
		}
	},

	_onBodyClick:function(ev){
		var tgt=ev.target;
		while(tgt){
			if(tgt==this._completionListWrapper){
				return;
			}
			tgt=tgt.parentNode;
		}
		this._onCompletionListBlur(ev);
	},
	
	_onCompletionListBlur: function(ev){
		/// <summary>
		/// Handler for the blur event on the autocomplete flyout.
		/// </summary>
		/// <param name="ev" type="Sys.UI.DomEvent" DomElement="false" mayBeNull="false" />
		/// <returns />	
		this._hideCompletionList();
	},
	
	_getCompletionItem:function(node){
		/// <summary>
		/// Finds the list item that the node descends from, if any
		/// </summary>
		/// <returns />
		/// <param name="node" type="Sys.UI.DomElement" DomElement="true" mayBeNull="false" />
		while(node){
			if(node.parentNode==this._completionListElement && !node._isGroupHeader){
				return node;
			}
			node=node.parentNode;
		}
	},
	
	_onListMouseDown: function(ev){
		/// <summary>
		/// Handler for the mousedown event on the autocomplete flyout.
		/// </summary>
		/// <param name="ev" type="Sys.UI.DomEvent" DomElement="false" mayBeNull="false" />
		/// <returns />	
		var item=this._getCompletionItem(ev.target); 
		if(item){
			this._setText(item);
			this._flyoutHasFocus=false;
			ev.stopPropagation();
		}
		else{ // focus is still on the flyout and we do not want to hide it
			this._flyoutHasFocus=true;
		}
	},
	
	_onListMouseUp: function(ev){
		/// <summary>
		/// Handler for the mouseup event on the autocomplete flyout.
		/// </summary>
		/// <param name="ev" type="Sys.UI.DomEvent" DomElement="false" mayBeNull="false" />
		/// <returns />	
		if(!this._flyoutHasFocus){
			try{
				this._getInnerEl().focus();
			}catch(e){} // IE throws if the input box has been hidden
		}
	},
	
	_onListMouseOver: function(ev){
		/// <summary>
		/// Handler for the mouseover event on the autocomplete flyout.
		/// </summary>
		/// <param name="ev" type="Sys.UI.DomEvent" DomElement="false" mayBeNull="false" />
		/// <returns />	  
		var item=ev.target;
		if(item !== this._completionListElement){
			item=this._getCompletionItem(item);
			if(item){
				this._highlightItem(item);
				this._selectIndex=Array.indexOf(item.parentNode.childNodes, item);
			}
		}
	},
	
	_onListMouseOut:function(ev){
	    if(ev.target == this._completionListElement){
	        this._highlightItem(null);
	    }
	    else{
	        var item=this._getCompletionItem(ev.target);
	        if(item && item._highlighted){
	            this._highlightItem(null);
	        }
	    }
	},

	_onGotFocus: function(ev){
		/// <summary>
		/// Handler for textbox focus event.
		/// </summary>
		/// <param name="ev" type="Sys.UI.DomEvent" DomElement="false" mayBeNull="false" />
		/// <returns />	  
		this._textBoxHasFocus=true;
		if(this._flyoutHasFocus){
			// hide the flyout now that the focus is back on the textbox
			this._hideCompletionList();		  
		}
		if((this._minimumPrefixLength == 0) && (!this.get_value())){
			this._startTimer();
			// only start the timer if the minimumprefixlength is 0
			// since we would like to retrieve results even if
			// the user has not entered any text and the textbox is empty.
		}
	},
	
	_onKeyDown: function(ev){
		/// <summary>
		/// Handler for the textbox keydown event.
		/// </summary>
		/// <param name="ev" type="Sys.UI.DomEvent" DomElement="false" mayBeNull="false" />
		/// <returns />	  
		this._stopTimer();
		// the last key press occured so we need to "reset" the timer.
		var k=ev.keyCode ? ev.keyCode:ev.rawEvent.keyCode;
		if(k === Sys.UI.Key.esc){
			if(this._popupBehavior && this._popupBehavior.get_visible()){
				this._hideCompletionList();
				ev.preventDefault();
				ev.stopPropagation();
			}
		}
		else if(k === Sys.UI.Key.up){
			var newIndex=this._getAdjacentItemIndex(this._selectIndex, -1);
			if(newIndex >= 0){
				this._selectIndex=newIndex;
				this._handleScroll(this._completionListElement.childNodes[newIndex], newIndex);
				this._highlightItem(this._completionListElement.childNodes[newIndex]);
				ev.stopPropagation();	 
				ev.preventDefault();
			}
		}
		else if(k === Sys.UI.Key.down){
			var newIndex=this._getAdjacentItemIndex(this._selectIndex, 1);	
			if(newIndex < this._completionListElement.childNodes.length){
				this._selectIndex=newIndex;
				this._handleScroll(this._completionListElement.childNodes[newIndex], newIndex);
				this._highlightItem(this._completionListElement.childNodes[newIndex]);			  
				ev.stopPropagation();				
				ev.preventDefault();
			}
		}
		else if(k === Sys.UI.Key.enter){
			if(this._selectIndex !== -1){
				this._setText(this._completionListElement.childNodes[this._selectIndex]);
				ev.preventDefault();
				ev.stopPropagation();
			} else{
				// close the popup
				this.hidePopup();
			}
		}
		else if(k === Sys.UI.Key.tab){
			if(this._selectIndex !== -1){
				this._setText(this._completionListElement.childNodes[this._selectIndex]);

				if(this.get_isMultiWord()){
					// For a multi-word field, user may want to type more, so don't let it tab to the next field.
					ev.preventDefault();
					ev.stopPropagation();
				}
			}
		}
		else{
			this._startTimer();
			// start the timer to retrieve results since now it is an actual key
		}
	},
	
	_getAdjacentItemIndex:function(index, offset){
		var childNodes=this._completionListElement.childNodes;
		
		do{
			index+=offset;
		}while(index>=0 && index<childNodes.length && childNodes[index]._isGroupHeader);
		
		return index;
	},
	
	_handleScroll:function(element, index){
		/// <summary>
		/// Method to determine if an item is in view or not
		/// </summary>
		/// <returns />
		/// <param name="element" type="Sys.UI.DomElement" DomElement="true" mayBeNull="false" />
		/// <param name="index" type="Number" DomElement="false" mayBeNull="true" />		
		var flyout=this._completionListElement,
			elemHeight=element.offsetHeight || 0,
			isAbsolute=element.offsetParent==flyout,
			offsetStart=isAbsolute ? 0 : flyout.offsetTop;
		
		var scrollDown=element.offsetTop-offsetStart+elemHeight-flyout.scrollTop-flyout.offsetHeight;
		if(scrollDown>0){ flyout.scrollTop += scrollDown; }
		
		var scrollUp=flyout.scrollTop-element.offsetTop+offsetStart;
		if(scrollUp>0){ flyout.scrollTop -= scrollUp; }
	},
	
	_handleFlyoutFocus:function(){
		/// <summary>
		/// Method to handle flyout focus if textbox loses focus.
		/// </summary>
		/// <returns />   
		if(!this._textBoxHasFocus){ 
			if(!this._flyoutHasFocus){
				if(this._webRequest){
					// abort the web service call if we are losing focus. no sense having it delay future web requests.
					this._webRequest.get_executor().abort();
					this._webRequest=null;
				}
				// the textbox lost focus and the flyout does not have it
				this._hideCompletionList();
			} else{
				// keep the flyout around otherwise
			}
		}
	},	 
	
	_onLostFocus: function(){
		/// <summary>
		/// Handler textbox blur event.
		/// </summary>
		/// <returns />	 
		this._textBoxHasFocus=false;   
		this._stopTimer();
		/* the rest of the onblur handling will be done in
		this method after a minor delay to ensure we do not close the flyout 
		if a user clicks on its scroll bars for example */  
		window.setTimeout(Function.createDelegate(this, this._handleFlyoutFocus), 500);
	},  
	
	_onMethodComplete: function(result, context){
		/// <summary>
		/// Handler invoked when the webservice call is completed.
		/// </summary>
		/// <param name="result" type="Object" DomElement="false" mayBeNull="true" />
		/// <param name="context" type="String" DomElement="false" mayBeNull="true" />		
		/// <returns /> 
		this._webRequest=null; // clear out our saved WebRequest object	
		
		// Remove the progress indicator
		if(this._completionListElement){ this._completionListElement.style.backgroundImage=""; }
		
		this._update(context, result, /* cacheResults */ true);
	},
	
	_onMethodFailed: function(err, response, context){
		/// <summary>
		/// Handler invoked when the webservice call fails, currently a noop
		/// </summary>
		/// <param name="err" type="Object" DomElement="false" mayBeNull="true" />		
		/// <param name="result" type="Object" DomElement="false" mayBeNull="true" />
		/// <param name="context" type="String" DomElement="false" mayBeNull="true" />
		/// <returns />	 
		// clear out our saved WebRequest object
		this._webRequest=null; 
	},
	
	_onTimerTick: function(sender, eventArgs){
		/// <summary>
		/// Handler invoked when a timer tick occurs
		/// </summary>
		/// <param name="sender" type="Object" mayBeNull="true"/>
		/// <param name="eventArgs" type="Sys.EventArgs" mayBeNull="true" />		
		/// <returns />
		
		// turn off the timer until another key is pressed.
		this._stopTimer();
		
		var text=this._currentCompletionWord();
		
		if(text.trim().length < this._minimumPrefixLength){
			this._currentPrefix=null;
			this._update('', null, /* cacheResults */ false);
			return;
		}
		
		var isShowing=(!this._popupBehavior || this._popupBehavior.get_visible());
		// there is new content in the textbox or the textbox is empty but the min prefix length is 0
	   if((this._currentPrefix !== text || !isShowing) || ((text == "") && (this._minimumPrefixLength == 0) && !this._webRequest)){
			this._currentPrefix=text;
			if(this._cache){
				var items=this._getCachedItems(text);
				if(items){
					this._update(text, items, false);
					return;
				}
			}
			// Raise the populating event and optionally cancel the web service invocation
			var eventArgs=new Sys.CancelEventArgs();
			this.raisePopulating(eventArgs);
			if(eventArgs.get_cancel()){
				return;
			}
			
			this._fetchCompletionItems(text);
		}
	},
	
	_getCachedItems:function(prefix){
		if(!this._cache){
			return null;
		}
		
		if(this._cache[prefix]){
			return this._cache[prefix];
		}
		
		if(this.get_enableCacheSubstrings()){
			for(var key in this._cache){
				if(prefix.startsWith(key)){
					// If we're searching for "ab", for example, and we already have the results for "a"
					// cached, then takes those items, run them through a search for "ab", and return
					// the results.
					this._completionItems=this._cache[key];
					return this.getCompletionItems(prefix);
				}
			}
		}
		
		return null;
	},
	
	_fetchCompletionItems:function(prefixText){
		if(this._servicePath && (this._isJsonpService || this._serviceMethod)){
			// Create the service parameters and optionally add the context parameter
			// (thereby determining which method signature we're expecting...)
			var params={};
			params[this._postParameterName] = this._currentPrefix;
			if(this._serviceParams){
				for(var key in this._serviceParams){
					params[key]=this._serviceParams[key];
				}
			}
			if(this._useContextKey){
				params.contextKey=this._contextKey;
			}
			
			if(this._isJsonpService){
				MySpace.Net.JsonpWebServiceProxy.invoke(this.get_servicePath(), params,
					Function.createDelegate(this, this._onMethodComplete),
					Function.createDelegate(this, this._onMethodFailed),
					null, prefixText);
			}
			else{
				if(this._webRequest){
					// abort the previous web service call if we 
					// are issuing a new one and the previous one is 
					// active.
					this._webRequest.get_executor().abort();
					this._webRequest=null;
				}
				// Invoke the web service
				this._webRequest=Sys.Net.WebServiceProxy.invoke(this.get_servicePath(), this.get_serviceMethod(), false, params,
											Function.createDelegate(this, this._onMethodComplete),
											Function.createDelegate(this, this._onMethodFailed),
											prefixText);
			}
		}
		else{
			var matches=this.getCompletionItems(prefixText);
			if(matches){
				this._update(prefixText, matches);
			}
		}
	},
	
	getCompletionItems:function(prefixText){
		prefixText=prefixText.toLowerCase();
		var matches=[];
		
		for(var i=0;i<this._completionItems.length;i++){
			var item=this._completionItems[i];
			if((item.text || item).toLowerCase().startsWith(prefixText)){
				matches.push(this._completionItems[i]);
			}
		}
	
		return matches;
	},
	
	_setText: function(item){
		/// <summary>
		/// Method to set the selected autocomplete option on the textbox
		/// </summary>
		/// <param name="item" type="Sys.UI.DomElement" DomElement="true" mayBeNull="true">
		/// Item to select
		/// </param>
		/// <returns />
		
		var text=null;
		if(item){
			text=item._text || (item.firstChild ? item.firstChild.nodeValue : null);
		}
		this._stopTimer();

		var newText=this._showOnlyCurrentWordInCompletionListItem ? this._getTextWithInsertedWord(text):text;
		this.set_value(newText, true);

		this.raiseItemSelected(new MySpace.UI.AutoCompleteItemEventArgs(item, text, item ? item._value:null));

		this._currentPrefix=this._currentCompletionWord();
		this._hideCompletionList();
	},
	
	_update: function(prefixText, completionItems, cacheResults){
		/// <summary>
		/// Method to update the status of the autocomplete behavior
		/// </summary>
		/// <param name="prefixText" type="String" DomElement="false" mayBeNull="true" />
		/// <param name="completionItems" type="Object" DomElement="false" mayBeNull="true" />
		/// <param name="cacheResults" type="Object" DomElement="false" mayBeNull="true" />
		/// <returns />	   
		if(cacheResults && this.get_enableCaching()){
			if(!this._cache){
				this._cache={};
			}
			this._cache[prefixText]=completionItems;
		}
		
		this._currentCompletionItems=completionItems;
		
		// If the target control loses focus or 
		// if the value in textbox has changed before the webservice returned
		// completion items we don't need to show popup 
		if((!this._completionListAlwaysVisible && !this._textBoxHasFocus) || (this._closeObsoleteResults && prefixText != this._currentCompletionWord())){
			this._hideCompletionList();
			return;
		}  
		
		if(this._completionListAlwaysVisible || (completionItems && completionItems.length)){
			this._completionListElement.innerHTML='';
			this._selectIndex=-1;
			var _firstChild=null, text=null, value=null, itemElement=null, placeholderHeight=this._lazyLoadPlaceholderHeight;
			
			for(var i=0; i < completionItems.length; i++){
				if(completionItems[i] && completionItems[i].groupHeader){
					itemElement=this.createGroupHeader(completionItems[i]);
				}
				else if(placeholderHeight){
					itemElement=document.createElement("div");
					itemElement.style.height=placeholderHeight+"px";
					itemElement._isPlaceholder=true;
				}
				else{
					itemElement=this.createCompletionItem(completionItems[i]);
					
					// set the first child if it is null
					if(_firstChild == null){
						_firstChild=itemElement;
					}
				}

				this._completionListElement.appendChild(itemElement);
			}
			var elementBounds=Sys.UI.DomElement.getBounds(this._getOuterEl());		
			this._completionListElement.style.width=(this.get_completionListWidth() || Math.max(1, elementBounds.width - 2)) + 'px';
			
			var args=new Sys.EventArgs();
			args.completionItems = completionItems;
			args.completionListElement = this._completionListElement;
			this.raisePopulated(args);
			
			var eventArgs=new Sys.CancelEventArgs();
			this.raiseShowing(eventArgs);
			if(!eventArgs.get_cancel()){
				if(!this._completionListFixedHeight){
					this._completionListElement.style.height="1px";
				}
				this.showPopup();
				
				if(!this._completionListFixedHeight){
					// Cap its size at the max height
					this._completionListElement.style.height="";
					if(this._completionListElement.offsetHeight > this._completionListMaxHeight){
						this._completionListElement.style.height=this._completionListMaxHeight+"px";
					}
				}
				this._completionListElement.scrollTop=0;
				
				// Check if the first Row is to be selected by default and if yes highlight it and updated selectIndex.
				if(this._firstRowSelected && (_firstChild != null)){
					this._highlightItem( _firstChild );
					this._selectIndex=0;
				}
				
				this._drawMissingItems();
			}			
		} else{
			this._hideCompletionList();
		}
	},
	
	_drawMissingItems:function(){
		var list=this._completionListElement,
			isAbsolute=list.childNodes[0] && (list.childNodes[0].offsetParent==list),
			offsetStart=isAbsolute ? 0 : list.offsetTop,
			yStart=offsetStart+list.scrollTop-4*this._lazyLoadPlaceholderHeight,
			yEnd=yStart+list.offsetHeight+8*this._lazyLoadPlaceholderHeight,
			childNodesLength=list.childNodes.length,
			el=null;
			
		for(var i=0;i<childNodesLength;i++){			
			el=list.childNodes[i];
			
			if(el.offsetTop < yStart){ continue; }
			if(el.offsetTop > yEnd){ break; }
			
			if(el._isPlaceholder){
				var newEl=this.createCompletionItem(this._currentCompletionItems[i]);
				list.replaceChild(newEl, el);
				
				if(this._selectIndex==-1 && this._firstRowSelected){
					this._highlightItem(newEl);
					this._selectIndex=i;
				}
			}
		}
	},
	
	createCompletionItem:function(item){
		// Create the item				
		var itemElement=document.createElement('div');
		var text, value;
		
		// Get the text/value for the item
		if(item && item.text){
			// Use the text and value pair returned from the web service
			text=item.text;
			value=item.value;
		} else{
			// If the web service only returned a regular string, use it for
			// both the text and the value
			text=item;
			value=item; 
		} 

		// Set the text/value for the item
		// ShowOnlyCurrentWordInCompletionListItem support
		var optionText=this._showOnlyCurrentWordInCompletionListItem ? text: this._getTextWithInsertedWord(text);
		itemElement.innerHTML=optionText;
		itemElement._value=value;
		
		if(this._completionListItemCssClass){
			Sys.UI.DomElement.addCssClass(itemElement, this._completionListItemCssClass);
		}
		else{
			var itemElementStyle=itemElement.style;
			itemElementStyle.padding='0px';
			itemElementStyle.textAlign='left';
			itemElementStyle.textOverflow='ellipsis';
			itemElementStyle.cursor='pointer';
			// workaround for safari since normal colors do not
			// show well there.
			if(Sys.Browser.agent === Sys.Browser.Safari){
				itemElementStyle.backgroundColor='white';
				itemElementStyle.color='black';
			} else{
				itemElementStyle.backgroundColor='window';
				itemElementStyle.color='windowtext';
			}
		}	
		
		return itemElement;
	},
	
	createGroupHeader:function(item){
		var itemElement=document.createElement("div");
		itemElement.appendChild(document.createTextNode(item.groupHeader));
		itemElement._isGroupHeader=true;
		
		if(this._groupHeaderCssClass){
			Sys.UI.DomElement.addCssClass(itemElement, this._groupHeaderCssClass);
		}
		else{
			var itemElementStyle=itemElement.style;
			itemElementStyle.fontWeight='bold';
			itemElementStyle.fontStyle='italic';
		}
		
		return itemElement;
	},
	
	_getInnerEl:function(){ return this.get_element(); },
	_getOuterEl:function(){ return this.get_element(); },
	
	get_value:function(){
		var el=this.get_element();
		var b=Sys.UI.Behavior.getBehaviorByName(el, "DefaultTextboxBehavior");
		return b ? b.get_value() : el.value;
	},
	set_value:function(val, noUpdate){
		var el=this.get_element();
		var b=Sys.UI.Behavior.getBehaviorByName(el, "DefaultTextboxBehavior");
		if(b){
			b.set_value(val);
		}
		else{
			el.value=val || "";
		}
		
		if(!noUpdate){
			this._onTimerTick();	// Force an update of the completion list		
		}
	},
	
	get_onShow:function(){
		/// <value type="String" mayBeNull="true">
		/// Generic OnShow Animation's JSON definition
		/// </value>
		return this._popupBehavior ? this._popupBehavior.get_onShow():this._onShow;
	},
	set_onShow:function(value){
		if(this._popupBehavior){
			this._popupBehavior.set_onShow(value)
		} else{
			this._onShow=value;
		}
	},
	onShow:function(){
		/// <summary>
		/// Play the OnShow animation
		/// </summary>
		/// <returns />
		if(this._popupBehavior){
			this._popupBehavior.onShow();
		}
	},
		
	get_onHide:function(){
		/// <value type="String" mayBeNull="true">
		/// Generic OnHide Animation's JSON definition
		/// </value>
		return this._popupBehavior ? this._popupBehavior.get_onHide():this._onHide;
	},
	set_onHide:function(value){
		if(this._popupBehavior){
			this._popupBehavior.set_onHide(value)
		} else{
			this._onHide=value;
		}
	},
	onHide:function(){
		/// <summary>
		/// Play the OnHide animation
		/// </summary>
		/// <returns />
		if(this._popupBehavior){
			this._popupBehavior.onHide();
		}
	},
	
	get_visible:function(){
		return this._popupBehavior && this._popupBehavior.get_visible(); 
	},
	
	get_completionItems:function(){
		return this._completionItems;
	},
	set_completionItems:function(value){
		this._completionItems=value;
	},
	
	get_completionInterval: function(){
		/// <value type="Number" integer="true" maybeNull="true">
		/// Auto completion timer interval in milliseconds.
		/// </value>
		return this._completionInterval;
	},
	set_completionInterval: function(value){
		this._completionInterval=value;
	},
	
	get_completionList: function(){
		/// <value type="Sys.UI.DomElement" domElement="true" maybeNull="true">
		/// List dom element.
		/// </value>
		return this._completionListElement;
	},
	set_completionList: function(value){
		this._completionListElement=value;
	},
	
	get_minimumPrefixLength: function(){
		/// <value type="Number" integer="true" maybeNull="true">
		/// Minimum text prefix length required to call the webservice.
		/// </value>
		return this._minimumPrefixLength;
	},
	set_minimumPrefixLength: function(value){
		this._minimumPrefixLength=value;
	},
	
	// If specified, then the user must type this string prior to the text to autocomplete on.
	// For example, if we want to autocomplete on the user's friends when they type "@whoever",
	// then we set a triggerPrefix of "@".
	get_triggerPrefix:function(){ return this._triggerPrefix; },
	set_triggerPrefix:function(val){ this._triggerPrefix=val; },
	
	get_serviceMethod: function(){
		/// <value type="String" maybeNull="false">
		/// Web service method.
		/// </value>
		return this._serviceMethod;
	},
	set_serviceMethod: function(value){
		this._serviceMethod=value;
	},
	
	get_servicePath: function(){
		/// <value type="String" maybeNull="true">
		/// Web service url.
		/// </value>
		return this._servicePath;
	},
	set_servicePath: function(value){
		this._servicePath=value;
	},
	
	// Dictionary of extra params to pass to the web service, in addition
	// to the prefix.
	get_serviceParams:function(){ return this._serviceParams; },
	set_serviceParams:function(val){ this._serviceParams=val; },
	
	// If true, the web service is assumed to be a JSONP service instead
	// of an ASMX.
	get_isJsonpService:function(){ return this._isJsonpService; },
	set_isJsonpService:function(val){ this._isJsonpService=val; },
	
	get_contextKey:function(){
		/// <value type="String" mayBeNull="true">
		/// User/page specific context provided to an optional overload of the
		/// web method described by ServiceMethod/ServicePath.  If the context
		/// key is used, it should have the same signature with an additional
		/// parameter named contextKey of type string.
		/// </value>
		return this._contextKey;
	},
	set_contextKey:function(value){
		this._contextKey=value;
		this.set_useContextKey(true);
	},
	
	get_useContextKey:function(){
		/// <value type="Boolean">
		/// Whether or not the ContextKey property should be used.  This will be
		/// automatically enabled if the ContextKey property is ever set
		/// (on either the client or the server).  If the context key is used,
		/// it should have the same signature with an additional parameter
		/// named contextKey of type string.
		/// </value>
		return this._useContextKey;
	},
	set_useContextKey:function(value){
		this._useContextKey=value;
	},
	
	get_enableCaching: function(){
		/// <value type="Boolean" maybeNull="true">
		/// Get or sets whether suggestions retrieved from the webservice
		/// should be cached.
		/// </value>
		return this._enableCaching;
	},
	set_enableCaching: function(value){
		this._enableCaching=value;
	},
	
	// If true, it's assumed that the results for "abcd" are a subset of the results
	// for "abc", so there's no need for another web service call.  If you are
	// truncating at N results, you wouldn't want to set this to true.
	get_enableCacheSubstrings:function(){ return this._enableCacheSubstrings; },
	set_enableCacheSubstrings:function(val){ this._enableCacheSubstrings=val; },
	
	get_completionListWrapperID:function(){
		return this._completionListWrapperID;
	},
	set_completionListWrapperID:function(value){
		this._completionListWrapperID=value;
	},
	
	get_completionListElementID: function(){
		/// <value type="String" maybeNull="true">
		/// ID of the completion div element.
		/// </value>
		return this._completionListElementID;
	},
	set_completionListElementID: function(value){
		this._completionListElementID=value;
	},  
	
	get_completionListAlwaysVisible:function(){
		return this._completionListAlwaysVisible;
	},
	set_completionListAlwaysVisible:function(value){
		this._completionListAlwaysVisible=value;
	},
	
	get_completionListCssClass:function(){
		/// <value type="String" maybeNull="true">
		/// Css class name that will be used to style the completion list element.
		/// </value>
		return this._completionListCssClass;
	},
	set_completionListCssClass:function(value){
		this._completionListCssClass=value;	
	},   
	
	get_completionListItemCssClass:function(){
		/// <value type="String" maybeNull="true">
		/// Css class name that will be used to style an item in the completion list.
		/// </value>
		return this._completionListItemCssClass;
	},
	set_completionListItemCssClass:function(value){
		this._completionListItemCssClass=value;	
	},
	
	get_completionListFixedHeight:function(){
		/// <value type="Number" maybeNull="true">
		/// Height in pixels of the completion list.  If not specified, the list will grow or
		/// shrink to fit the displayed items (subject to completionListMaxHeight).
		/// </value>
		return this._completionListFixedHeight;
	},
	set_completionListFixedHeight:function(value){
		this._completionListFixedHeight=value;
	},
	
	get_completionListMaxHeight:function(){
		/// <value type="Number" maybeNull="true">
		/// Maximum height in pixels of the completion list.  Has no effect if
		/// a completionListFixedHeight is specified. Default is 200.
		/// </value>
		return this._completionListMaxHeight;
	},
	set_completionListMaxHeight:function(value){
		this._completionListMaxHeight=value;
	},
	
	get_completionListWidth:function(){
		return this._completionListWidth;
	},
	set_completionListWidth:function(value){
		this._completionListWidth=value;
	},

	get_lazyLoadPlaceholderHeight:function(){
		return this._lazyLoadPlaceholderHeight;
	},
	set_lazyLoadPlaceholderHeight:function(value){
		this._lazyLoadPlaceholderHeight=value;
	},
	
	get_groupHeaderCssClass:function(){
		return this._groupHeaderCssClass;
	},
	set_groupHeaderCssClass:function(value){
		this._groupHeaderCssClass=value;
	},
	
	get_highlightedItemCssClass:function(){
		/// <value type="String" maybeNull="true">
		/// Css class name that will be used to style a highlighted item in the list.
		/// </value>
		return this._highlightedItemCssClass;
	},
	set_highlightedItemCssClass:function(value){
		this._highlightedItemCssClass=value;
	},
	
	get_delimiterCharacters: function(){
		/// <value type="String">
		/// Gets or sets the character(s) used to seperate words for autocomplete.
		/// </value>
		return this._delimiterCharacters;
	},
	set_delimiterCharacters: function(value){
		this._delimiterCharacters=value;
	},
	
	get_firstRowSelected:function(){
		/// <value type="Boolean" maybeNull="true">
		/// Flag to determine if the first option in the flyout is selected or not. 
		/// </value>
		return this._firstRowSelected;
	},
	set_firstRowSelected:function(value){
		this._firstRowSelected=value;
	},
	
	get_showOnlyCurrentWordInCompletionListItem:function(){
		/// <value type="Boolean">
		/// If Delimiter characters are specified and showOnlyCurrentWordInCompletionListItem is 
		/// set to true, then the completion list displays suggestions just for the current word, 
		/// otherwise, it displays the whole string that will show up in the TextBox if that
		/// item is selected, which is the current default.
		/// </value>
		return this._showOnlyCurrentWordInCompletionListItem;
	},
	set_showOnlyCurrentWordInCompletionListItem:function(value){
		this._showOnlyCurrentWordInCompletionListItem=value;
	},
	
	// If true, a set of results will not be shown if the user has typed more since the request
	// was sent.  Defaults to true.
	get_closeObsoleteResults:function() { return this._closeObsoleteResults; },
	set_closeObsoleteResults:function(value) { this._closeObsoleteResults = value; },
	
	get_postParameterName:function() { return this._postParameterName; },
	set_postParameterName:function(value) { this._postParameterName = value; },
	
	add_populating:function(handler){
		/// <summary>
		/// Add an event handler for the populating event
		/// </summary>
		/// <param name="handler" type="Function" mayBeNull="false">
		/// Event handler
		/// </param>
		/// <returns />
		this.get_events().addHandler('populating', handler);
	},
	remove_populating:function(handler){
		/// <summary>
		/// Remove an event handler from the populating event
		/// </summary>
		/// <param name="handler" type="Function" mayBeNull="false">
		/// Event handler
		/// </param>
		/// <returns />
		this.get_events().removeHandler('populating', handler);
	},
	raisePopulating:function(eventArgs){
		/// <summary>
		/// Raise the populating event
		/// </summary>
		/// <param name="eventArgs" type="Sys.CancelEventArgs" mayBeNull="false">
		/// Event arguments for the populating event
		/// </param>
		/// <returns />
		/// <remarks>
		/// The populating event can be used to provide custom data to AutoComplete
		/// instead of using a web service.  Just cancel the event (using the
		/// CancelEventArgs) and pass your own data to the _update method.
		/// </remarks>
		
		var handler=this.get_events().getHandler('populating');
		if(handler){
			handler(this, eventArgs);
		}
	},
	
	add_populated:function(handler){
		/// <summary>
		/// Add an event handler for the populated event
		/// </summary>
		/// <param name="handler" type="Function" mayBeNull="false">
		/// Event handler
		/// </param>
		/// <returns />
		this.get_events().addHandler('populated', handler);
	},
	remove_populated:function(handler){
		/// <summary>
		/// Remove an event handler from the populated event
		/// </summary>
		/// <param name="handler" type="Function" mayBeNull="false">
		/// Event handler
		/// </param>
		/// <returns />
		this.get_events().removeHandler('populated', handler);
	},
	raisePopulated:function(eventArgs){
		/// <summary>
		/// Raise the populated event
		/// </summary>
		/// <param name="eventArgs" type="Sys.EventArgs" mayBeNull="false">
		/// Event arguments for the populated event
		/// </param>
		/// <returns />
		
		var handler=this.get_events().getHandler('populated');
		if(handler){
			handler(this, eventArgs);
		}
	},
	
	add_showing:function(handler){
		/// <summary>
		/// Add an event handler for the showing event
		/// </summary>
		/// <param name="handler" type="Function" mayBeNull="false">
		/// Event handler
		/// </param>
		/// <returns />
		this.get_events().addHandler('showing', handler);
	},
	remove_showing:function(handler){
		/// <summary>
		/// Remove an event handler from the showing event
		/// </summary>
		/// <param name="handler" type="Function" mayBeNull="false">
		/// Event handler
		/// </param>
		/// <returns />
		this.get_events().removeHandler('showing', handler);
	},
	raiseShowing:function(eventArgs){
		/// <summary>
		/// Raise the showing event
		/// </summary>
		/// <param name="eventArgs" type="Sys.CancelEventArgs" mayBeNull="false">
		/// Event arguments for the showing event
		/// </param>
		/// <returns />
		
		var handler=this.get_events().getHandler('showing');
		if(handler){
			handler(this, eventArgs);
		}
	},
	
	add_shown:function(handler){
		/// <summary>
		/// Add an event handler for the shown event
		/// </summary>
		/// <param name="handler" type="Function" mayBeNull="false">
		/// Event handler
		/// </param>
		/// <returns />
		this.get_events().addHandler('shown', handler);
	},
	remove_shown:function(handler){
		/// <summary>
		/// Remove an event handler from the shown event
		/// </summary>
		/// <param name="handler" type="Function" mayBeNull="false">
		/// Event handler
		/// </param>
		/// <returns />
		this.get_events().removeHandler('shown', handler);
	},
	raiseShown:function(eventArgs){
		/// <summary>
		/// Raise the shown event
		/// </summary>
		/// <param name="eventArgs" type="Sys.EventArgs" mayBeNull="false">
		/// Event arguments for the shown event
		/// </param>
		/// <returns />
		
		var handler=this.get_events().getHandler('shown');
		if(handler){
			handler(this, eventArgs);
		}
	},
	
	add_hiding:function(handler){
		/// <summary>
		/// Add an event handler for the hiding event
		/// </summary>
		/// <param name="handler" type="Function" mayBeNull="false">
		/// Event handler
		/// </param>
		/// <returns />
		this.get_events().addHandler('hiding', handler);
	},
	remove_hiding:function(handler){
		/// <summary>
		/// Remove an event handler from the hiding event
		/// </summary>
		/// <param name="handler" type="Function" mayBeNull="false">
		/// Event handler
		/// </param>
		/// <returns />
		this.get_events().removeHandler('hiding', handler);
	},
	raiseHiding:function(eventArgs){
		/// <summary>
		/// Raise the hiding event
		/// </summary>
		/// <param name="eventArgs" type="Sys.CancelEventArgs" mayBeNull="false">
		/// Event arguments for the hiding event
		/// </param>
		/// <returns />
		
		var handler=this.get_events().getHandler('hiding');
		if(handler){
			handler(this, eventArgs);
		}
	},
	
	add_hidden:function(handler){
		/// <summary>
		/// Add an event handler for the hidden event
		/// </summary>
		/// <param name="handler" type="Function" mayBeNull="false">
		/// Event handler
		/// </param>
		/// <returns />
		this.get_events().addHandler('hidden', handler);
	},
	remove_hidden:function(handler){
		/// <summary>
		/// Remove an event handler from the hidden event
		/// </summary>
		/// <param name="handler" type="Function" mayBeNull="false">
		/// Event handler
		/// </param>
		/// <returns />
		this.get_events().removeHandler('hidden', handler);
	},
	raiseHidden:function(eventArgs){
		/// <summary>
		/// Raise the hidden event
		/// </summary>
		/// <param name="eventArgs" type="Sys.EventArgs" mayBeNull="false">
		/// Event arguments for the hidden event
		/// </param>
		/// <returns />
		
		var handler=this.get_events().getHandler('hidden');
		if(handler){
			handler(this, eventArgs);
		}
	},
	
	add_itemSelected:function(handler){
		/// <summary>
		/// Add an event handler for the itemSelected event
		/// </summary>
		/// <param name="handler" type="Function" mayBeNull="false">
		/// Event handler
		/// </param>
		/// <returns />
		this.get_events().addHandler('itemSelected', handler);
	},
	remove_itemSelected:function(handler){
		/// <summary>
		/// Remove an event handler from the itemSelected event
		/// </summary>
		/// <param name="handler" type="Function" mayBeNull="false">
		/// Event handler
		/// </param>
		/// <returns />
		this.get_events().removeHandler('itemSelected', handler);
	},
	raiseItemSelected:function(eventArgs){
		/// <summary>
		/// Raise the itemSelected event
		/// </summary>
		/// <param name="eventArgs" type="MySpace.UI.AutoCompleteItemEventArgs" mayBeNull="false">
		/// Event arguments for the itemSelected event
		/// </param>
		/// <returns />
		
		var handler=this.get_events().getHandler('itemSelected');
		if(handler){
			handler(this, eventArgs);
		}
	},
	
	add_itemOver:function(handler){
		/// <summary>
		/// Add an event handler for the itemOver event
		/// </summary>
		/// <param name="handler" type="Function" mayBeNull="false">
		/// Event handler
		/// </param>
		/// <returns />
		this.get_events().addHandler('itemOver', handler);
	},
	remove_itemOver:function(handler){
		/// <summary>
		/// Remove an event handler from the itemOver event
		/// </summary>
		/// <param name="handler" type="Function" mayBeNull="false">
		/// Event handler
		/// </param>
		/// <returns />
		this.get_events().removeHandler('itemOver', handler);
	},
	raiseItemOver:function(eventArgs){
		/// <summary>
		/// Raise the itemOver event
		/// </summary>
		/// <param name="eventArgs" type="MySpace.UI.AutoCompleteItemEventArgs" mayBeNull="false">
		/// Event arguments for the itemOver event
		/// </param>
		/// <returns />
		
		var handler=this.get_events().getHandler('itemOver');
		if(handler){
			handler(this, eventArgs);
		}
	},
	
	add_itemOut:function(handler){
		/// <summary>
		/// Add an event handler for the itemOut event
		/// </summary>
		/// <param name="handler" type="Function" mayBeNull="false">
		/// Event handler
		/// </param>
		/// <returns />
		this.get_events().addHandler('itemOut', handler);
	},
	remove_itemOut:function(handler){
		/// <summary>
		/// Remove an event handler from the itemOut event
		/// </summary>
		/// <param name="handler" type="Function" mayBeNull="false">
		/// Event handler
		/// </param>
		/// <returns />
		this.get_events().removeHandler('itemOut', handler);
	},
	raiseItemOut:function(eventArgs){
		/// <summary>
		/// Raise the itemOut event
		/// </summary>
		/// <param name="eventArgs" type="MySpace.UI.AutoCompleteItemEventArgs" mayBeNull="false">
		/// Event arguments for the itemOut event
		/// </param>
		/// <returns />
		
		var handler=this.get_events().getHandler('itemOut');
		if(handler){
			handler(this, eventArgs);
		}
	}
}
MySpace.UI.AutoCompleteBehavior.registerClass('MySpace.UI.AutoCompleteBehavior', Sys.UI.Behavior);


MySpace.UI.AutoCompleteItemEventArgs=function(item, text, value){
	/// <summary>
	/// Event arguments used when the itemSelected event is raised
	/// </summary>
	/// <param name="item" type="Sys.UI.DomElement" DomElement="true" mayBeNull="true">
	/// Item
	/// </param>
	/// <param name="text" type="String" mayBeNull="true">
	/// Text of the item
	/// </param>
	/// <param name="value" type="String" mayBeNull="true" optional="true">
	/// Value of the item different from text if specifically returned by the webservice
	/// as autocomplete json text/value item(using AutoComplete.CreateAutoCompleteItem); otherwise same as text.
	/// </param>
	MySpace.UI.AutoCompleteItemEventArgs.initializeBase(this);
	
	this._item=item;
	this._text=text;
	this._value=(value !== undefined) ? value:null;
}
MySpace.UI.AutoCompleteItemEventArgs.prototype={
	get_item:function(){
		/// <value type="Sys.UI.DomElement" DomElement="true" mayBeNull="true">
		/// Item
		/// </value>
		return this._item;
	},
	set_item:function(value){
		this._item=value;
	},
	
	get_text:function(){
		/// <value type="String" maybeNull="true">
		/// Text of the item
		/// </value>
		return this._text;
	},
	set_text:function(value){
		this._text=value;
	},
	
	get_value:function(){
		/// <value type="String" maybeNull="true">
		/// Value of the item different from text if specifically returned by the webservice
		/// as autocomplete json text/value item(using AutoComplete.CreateAutoCompleteItem); otherwise same as text.
		/// </value>
		return this._value;
	},
	set_value:function(value){
		this._value=value;
	}
}
MySpace.UI.AutoCompleteItemEventArgs.registerClass('MySpace.UI.AutoCompleteItemEventArgs', Sys.EventArgs);
MySpace.Beacon = new (function() {
    var pvStatus = 0;

    this.SendPageBeacon = function(isAdditionalRequest) {
        if (MySpace.ManualPageBeacon)
            return;

        if (MySpace.BeaconData) {
            var fv = swfobject.getFlashPlayerVersion();
            MySpace.BeaconData.cef = (document.cookie ? 1 : 0);
            MySpace.BeaconData.cfv = fv.major + ':' + fv.minor + ':' + fv.release;
            var urlParts = document.URL.split("#");
            for (var i = 1; i < urlParts.length; i++) {    
                if (urlParts[i].indexOf("pm_cmp=") === 0 || urlParts[i].indexOf("mssrc=") === 0) {
                    if (MySpace.BeaconData.qs === '' || MySpace.BeaconData.qs.substr(-1) === "&")
                        MySpace.BeaconData.qs += urlParts[i];
                    else
                        MySpace.BeaconData.qs += "&" + urlParts[i];
                }
            }
            
            if (MySpace.BeaconData.pggd === '' || isAdditionalRequest === true) {
                MySpace.BeaconData.pggd = getGuid();
            }
            
            if (MySpace.IsBeaconHeatMapEnabled) {
                var vpDimensions = getViewportDimensions();
                MySpace.BeaconData.kvp += "screenw=" + screen.width + "&screenh=" + screen.height +
                    "&vieww=" + vpDimensions.width + "&viewh=" + vpDimensions.height + "&";
            }

            if (MySpace.AdditionalPageBeaconKVPs) {
                var kvps = MySpace.AdditionalPageBeaconKVPs;
                for (var key in kvps) {
                    MySpace.BeaconData.kvp += key + "=" + encodeURIComponent(kvps[key]) + "&";
                }
            }
            
            addDisplayCounts();
            var handler = createBeaconRequest(MySpace.BeaconData);
            sendBeacon(handler, false, null, false);
        }

        renderClickTrack();
    };

    this.Request = function(args) {
        if (MySpace.BeaconData && MySpace.BeaconData.pggd) {
            beaconData = createClickTrackData(args);
            var handler = createBeaconRequest(beaconData);
            sendBeacon(handler, false, null, true);
        }
    };
    
    function sendBeacon(handler, useCallback, href, isClickTrack) {
        var msbeacon = document.createElement("img");

        msbeacon.height = "0";
        msbeacon.width = "0";
        msbeacon.style.display = "none";
        msbeacon.style.position = "absolute";
        msbeacon.style.left = "-1px";
        msbeacon.style.top = "-1px";
        if (!isClickTrack)
            msbeacon.setAttribute("id", "msbeacon");

        document.body.insertBefore(msbeacon, document.body.firstChild);    
        
        if(isClickTrack)
            $addHandler(msbeacon, "load", function() {
                try {
                    msbeacon.parentNode.removeChild(msbeacon);
                } catch(e) {}
            });
        else { 
             $addHandler(msbeacon, "load", function() {
                    pvStatus = 2;
             });      
             $addHandler(msbeacon, "error", function() {
                    pvStatus = 3;
            });  
            $addHandler(msbeacon, "abort", function() {
                    pvStatus = 4;
            });                    
        }         
                
        msbeacon.setAttribute("src", handler);
        
        if (!isClickTrack) 
            pvStatus = 1;
        
        if (href && href.length > 0)
            document.location = href;
    }

    function getCurrentTimer() {
        //Sending to time as milliseconds
        var d = new Date();
        var t = (d.getTime() / 1000.0) * 1000;
        return t;
    }

    function getGuid() {
        return getRand4() + getRand4() + "-" + getRand4() + "-" + getRand4() + "-" + getRand4() + "-" + getRand4() + getRand4() + getRand4();
    }

    function getRand4() {
        return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
    }

    //look for beacon tracked links and add onclick to call the beacon
    //if onclick already exist, append beacon at first
    function renderClickTrack() {
        if (MySpace.Beacon.ClickTrack && MySpace.BeaconData) {
            for (var eventkey in MySpace.Beacon.ClickTrack) {
                var elemt = MySpace.Utils.Selector.query('a.' + eventkey + '', null, true);
                if (elemt && !elemt.getAttribute("onclick")) {
                    $addHandler(elemt, "click", Function.createPartial(this, requestClickTrackBeacon, eventkey, elemt));
                }
            }
        }
    };
    
    function addDisplayCounts() {
        if (MySpace.Beacon.DisplayTrack && MySpace.BeaconData) {
            var displayData = {};
            for (var i = 0; i < MySpace.Beacon.DisplayTrack.length; i++) {
                var elemts = MySpace.Utils.Selector.query(MySpace.Beacon.DisplayTrack[i], null, false);
                for(var j = 0; j < elemts.length; j++) {
                    var bdataString = elemts[j].getAttribute("bdata");
                    if(bdataString) {
                        var bdata = eval(bdataString);
                        for(var key in bdata)  {
                            if(displayData[key])
                                displayData[key] += "," + bdata[key];
                            else
                                displayData[key] = bdata[key];
                        }
                    }
                }   
            }
            for (var dataKey in displayData) {
                MySpace.BeaconData.kvp += dataKey + "=" + encodeURIComponent(displayData[dataKey]) + "&";
            }
        }
    }

    function requestClickTrackBeacon(arg, ele, evt) {
        if (MySpace.Beacon.ClickTrack[arg]) {
            var beaconData = MySpace.Beacon.ClickTrack[arg];
            var href;
            if (ele) {
                href = ele.getAttribute("href");
            }
            var bd = createClickTrackData(beaconData);
            var handler = createBeaconRequest(bd);
            evt.preventDefault();
            sendBeacon(handler, true, href, true);
        }
    };

    function OnClickTrackCallBack(response, eventArgs) {
        if (eventArgs && eventArgs.length > 0)
            document.location = eventArgs;
    }
    
    var clickTrackCount = 0;
    function createClickTrackData(args) {
        if (MySpace.BeaconData && MySpace.BeaconData.pggd) {
            clickTrackCount++;
            var beaconData = {
                dsid: '3',
                dsv: '1',
                pggd: MySpace.BeaconData.pggd,
                pid: MySpace.BeaconData.pid,
                t: MySpace.BeaconData.t,
                ct: getCurrentTimer(),
                kvp: "pf=" + MySpace.ClientContext.FunctionalContext + "&seq=" + clickTrackCount + 
                    "&pvs=" + pvStatus + "&userid=" + MySpace.BeaconData.uid + "&"
            }

            if (args) {
                for (var argkey in args) {
                    beaconData.kvp += argkey + "=" + encodeURIComponent(args[argkey]) + "&";
                }
            }
            return beaconData;
        }
    }

    function createBeaconRequest(data) {
        var handler = document.location.protocol + "//b.myspace.com/~myspace/beacon/b.ashx?"
        if (MySpace.BeaconAddress && MySpace.BeaconAddress.length > 0) {
            handler = MySpace.BeaconAddress;
        }
        data.ct = getCurrentTimer();
        if (!MySpace.Application.keyDisabled("DWBeaconBase64")) {
            //convert to base 64
            var dataHandler = "";
            for (var key in data) {
                if (key == "dsid" || key == "dsv")
                    handler += key + "=" + encodeURIComponent(data[key]) + "&";
                else
                    dataHandler += key + "=" + encodeURIComponent(data[key]) + "&";
            }
            handler += "b=" + encodeURIComponent(MySpace.Util.Base64Encode(dataHandler, true));
        }
        else {
            for (var key in data) {
                handler += key + "=" + encodeURIComponent(data[key]) + "&";
            }
        }
        return handler;
    }
    
    function getViewportDimensions() {
        var height = document.body.clientWidth;
        var width = document.body.clientHeight;
        if (document.compatMode == 'CSS1Compat') {
            width = document.documentElement.clientWidth; 
            height = document.documentElement.clientHeight;                     
        }
        return { height: height, width: width}; 
    }

	function getDomPath(e)
	{
		var node = e.srcElement || e.target;
		var path = "";

		while (node.nodeName != "BODY" && (!node.id || node.id === "undefined")) {
			var parent = node.parentNode;
			var childNodes = parent.childNodes;
			var number = 0;
			for (var i = 0; i < childNodes.length; i++) {
				if(childNodes[i].nodeName == node.nodeName) {
					if(childNodes[i] == node)
					break;

					number++;
				}
			}

			if(number === childNodes.length)
				number = "UNKNOWN";

			path = node.nodeName + "_" + number + "|" + path;
			node = node.parentNode;
		}

		//grab body if we didn't find a unique ID
		if (!node.id)
			path = "|" + node.nodeName + "_0|" + path;
		else
			path = node.id + "|" + path;

		return path;
	}

      
    var lastClickTime = -1;
    function trackHMClick(evt) {
        try
        {
            if (evt.button !== 0)
                return;

            var vpDimensions = getViewportDimensions();
            if (evt.clientX < vpDimensions.width && evt.clientY < vpDimensions.height) {    
                var currTime = new Date();
                if (currTime - lastClickTime >= 1000) {
                    lastClickTime = currTime;
                    MySpace.Beacon.Request({ dompath : getDomPath(evt)});
                }
            }
        }
        catch(e){}
    }

    if (MySpace.IsBeaconHeatMapEnabled) {
        $addHandler(document, "mousedown", trackHMClick);
    }
})();
MySpace.UI.ComboBoxBehavior=function(element){
	MySpace.UI.ComboBoxBehavior.initializeBase(this, [element]);
	
	this._lazyLoadPlaceholderHeight=13;
};
MySpace.UI.ComboBoxBehavior.prototype={
	initialize:function(){
		MySpace.UI.ComboBoxBehavior.callBaseMethod(this, 'initialize');
	
		var el=this.get_element();
		var arrow=el.nextSibling;
		Sys.UI.DomElement.addCssClass(el, "msComboBox");
		if (arrow && Sys.UI.DomElement.containsCssClass(arrow, "msComboBoxArrow")){
		    this._arrowNode=arrow;
		}
		else{
		    arrow = this._arrowNode = document.createElement("img");
		    arrow.src="http://x.myspacecdn.com/modules/common/static/img/spacer.gif";
		    arrow.className="msComboBoxArrow";
		    arrow.style.height=(el.offsetHeight-2)+"px";
    		
		    // CSS hack is needed on Safari but not Chrome
		    if(navigator.userAgent.indexOf("Safari") != -1 && navigator.userAgent.indexOf("Chrome") == -1){
			    Sys.UI.DomElement.addCssClass(arrow, "msComboBoxArrowSafari");
		    }
    		
		    if(el.nextSibling){
			    el.parentNode.insertBefore(arrow, el.nextSibling);
		    }
		    else{
			    el.parentNode.appendChild(arrow);
		    }
		}
		
		$addHandler(arrow, "click", Function.createDelegate(this, this._toggleComboBoxList));
	},
	
	_toggleComboBoxList:function(ev){
		if(this._popupBehavior && this._popupBehavior.get_visible()){
			this.hidePopup();
		}
		else{
			this._textBoxHasFocus=true;
			this._showingFullList=true;
			this._fetchCompletionItems("");
			this._showingFullList=false;
		}
		
		ev.stopPropagation();
	},
	
	_onKeyDown:function(ev){
		var k=ev.keyCode ? ev.keyCode:ev.rawEvent.keyCode;
		if(k==Sys.UI.Key.down && this._popupBehavior && !this._popupBehavior.get_visible()){
			this._toggleComboBoxList(ev);
		}
		else{
			MySpace.UI.ComboBoxBehavior.callBaseMethod(this, "_onKeyDown", arguments);
		}
	},
	
	_currentCompletionWord:function(){
		if(this._showingFullList){
			return "";
		}
		else{
			return MySpace.UI.ComboBoxBehavior.callBaseMethod(this, "_currentCompletionWord");
		}
	},
	
	get_completionListWidth:function(){
		var elementBounds=Sys.UI.DomElement.getBounds(this.get_element());		
		return elementBounds.width + (this._arrowNode ? this._arrowNode.offsetWidth : 0) - 2;
	}
};
MySpace.UI.ComboBoxBehavior.registerClass("MySpace.UI.ComboBoxBehavior", MySpace.UI.AutoCompleteBehavior);



//DragDrop.js
//----------------------------------------------------------
MySpace.UI._DragDropManager=function(){ };
MySpace.UI._DragDropManager.prototype={
	_instance:null,
	_events:null,
	add_dragStart:function(a){
		this.get_events().addHandler("dragStart",a)
	},
	remove_dragStart:function(a){
		this.get_events().removeHandler("dragStart",a)
	},
	get_events:function(){
		if(!this._events)this._events=new Sys.EventHandlerList;
		return this._events
	},
	add_dragStop:function(a){
		this.get_events().addHandler("dragStop",a)
	},
	remove_dragStop:function(a){
		this.get_events().removeHandler("dragStop",a)
	},
	add_afterDragStart:function(a){
		this.get_events().addHandler("afterDragStart",a)
	},
	remove_afterDragStart:function(a){
		this.get_events().removeHandler("afterDragStart",a)
	},
	_getInstance:function(){
		if(!this._instance){
			this._instance=new MySpace.UI.GenericDragDropManager;
			this._instance.initialize();
			this._instance.add_dragStart(Function.createDelegate(this,this._raiseDragStart));
			this._instance.add_dragStop(Function.createDelegate(this,this._raiseDragStop))
		}
		return this._instance
	},
	afterDragStart:function(){
	    this._getInstance().afterDragStart();
	},
	startDragDrop:function(dragSource,dragVisual,context){
		this._getInstance().startDragDrop(dragSource,dragVisual,context)
	},
	registerDropTarget:function(target){
		this._getInstance().registerDropTarget(target)
	},
	unregisterDropTarget:function(target){
		this._getInstance().unregisterDropTarget(target)
	},
	dispose:function(){
		delete this._events;
		Sys.Application.unregisterDisposableObject(this);
		Sys.Application.removeComponent(this)
	},
	_raiseDragStart:function(sender,eventArgs){
		var handler=this.get_events().getHandler("dragStart");
		if(handler)handler(this,eventArgs)
	},
	_raiseDragStop:function(sender,eventArgs){
		var handler=this.get_events().getHandler("dragStop");
		if(handler)handler(this,eventArgs)
	}
};
MySpace.UI._DragDropManager.registerClass("MySpace.UI._DragDropManager");
MySpace.UI.DragDropManager=new MySpace.UI._DragDropManager;
MySpace.UI.DragDropEventArgs=function(dragMode,dragDataType,dragData){
	this._dragMode=dragMode;
	this._dataType=dragDataType;
	this._data=dragData;
};
MySpace.UI.DragDropEventArgs.prototype={
	get_dragMode:function(){
		return this._dragMode||null
	},
	get_dragDataType:function(){
		return this._dataType||null
	},
	get_dragData:function(){
		return this._data||null
	}
};
MySpace.UI.DragDropEventArgs.registerClass("MySpace.UI.DragDropEventArgs");
MySpace.UI.IDragSource=function(){
};
MySpace.UI.IDragSource.prototype={
	get_dragDataType:function(){
		throw Error.notImplemented()
	},
	getDragData:function(){
		throw Error.notImplemented()
	},
	get_dragMode:function(){
		throw Error.notImplemented()
	},
	onDragStart:function(){
		throw Error.notImplemented()
	},
	onDrag:function(){
		throw Error.notImplemented()
	},
	onDragEnd:function(){
		throw Error.notImplemented()
	}
};
MySpace.UI.IDragSource.registerInterface("MySpace.UI.IDragSource");
MySpace.UI.IDropTarget=function(){
};
MySpace.UI.IDropTarget.prototype={
	get_dropTargetElement:function(){
		throw Error.notImplemented()
	},
	canDrop:function(){
		throw Error.notImplemented()
	},
	drop:function(){
		throw Error.notImplemented()
	},
	onDragEnterTarget:function(){
		throw Error.notImplemented()
	},
	onDragLeaveTarget:function(){
		throw Error.notImplemented()
	},
	onDragInTarget:function(){
		throw Error.notImplemented()
	}
};
MySpace.UI.IDropTarget.registerInterface("MySpace.UI.IDropTarget");
MySpace.UI.DragMode=function(){
	throw Error.invalidOperation()
};
MySpace.UI.DragMode.prototype={
	Copy:0,Move:1
};
MySpace.UI.DragMode.registerEnum("MySpace.UI.DragMode");
MySpace.UI.GenericDragDropManager=function(){
	MySpace.UI.GenericDragDropManager.initializeBase(this)
};
MySpace.UI.GenericDragDropManager.prototype={
	_dropTargets:null,
	_radius:10,
	_activeDragVisual:null,
	_activeContext:null,
	_activeDragSource:null,
	_underlyingTarget:null,
	_oldOffset:null,
	_potentialTarget:null,
	_isDragging:false,
	_mouseUpHandler:null,
	_mouseMoveHandler:null,

	_scrollEdgeConst:40,
	_scrollByConst:10,
	_scroller:null,
	_scrollDeltaX:null,
	_scrollDeltaY:null,
	_keyPressHandler:null,
	
	add_dragStart:function(a){
		this.get_events().addHandler("dragStart",a)
	},
	remove_dragStart:function(a){
		this.get_events().removeHandler("dragStart",a)
	},
	add_dragStop:function(a){
		this.get_events().addHandler("dragStop",a)
	},
	remove_dragStop:function(a){
		this.get_events().removeHandler("dragStop",a)
	},
	add_afterDragStart:function(a){
		this.get_events().addHandler("afterDragStart",a)
	},
	remove_afterDragStart:function(a){
		this.get_events().removeHandler("afterDragStart",a)
	},
	initialize:function(){
		MySpace.UI.GenericDragDropManager.callBaseMethod(this,"initialize");
		this._mouseUpHandler=Function.createDelegate(this,this.mouseUpHandler);
		this._mouseMoveHandler=Function.createDelegate(this,this.mouseMoveHandler);
		this._keyPressHandler=Function.createDelegate(this,this.keyPressHandler);
		this._scroller=new MySpace.Timer;
		this._scroller.set_interval(10);
		this._scroller.add_tick(Function.createDelegate(this,this.scrollerTickHandler))
	},
	dispose:function(){
		if(this._dropTargets){
			for(var a=0;a<this._dropTargets;a++)this.unregisterDropTarget(this._dropTargets[a]);
			this._dropTargets=null
		}
		MySpace.UI.GenericDragDropManager.callBaseMethod(this,"dispose")
	},
	afterDragStart:function(){
	},
	startDragDrop:function(dragSource,dragVisual,context){
		this._activeDragSource=dragSource;
		this._activeDragVisual=dragVisual;
		this._activeContext=context;
			      
		var h=window._event;
		if(this._isDragging)return;
		this._underlyingTarget=null;
		var e={
			x:h.clientX,y:h.clientY
		};

		dragVisual.originalPosition=dragVisual.style.position;
		dragVisual.style.position="absolute";
		document._lastPosition=e;
		dragVisual.startingPoint=e;
		var i=this.getScrollOffset(dragVisual,true);
		dragVisual.startingPoint=this.addPoints(dragVisual.startingPoint,i);
		if(dragVisual.style.position=="absolute"){
			dragVisual.startingPoint=this.subtractPoints(dragVisual.startingPoint,Sys.UI.DomElement.getLocation(dragVisual));
		}
		else{
			var c=parseInt(dragVisual.style.left),d=parseInt(dragVisual.style.top);
			if(isNaN(c))c="0";
			if(isNaN(d))d="0";
			dragVisual.startingPoint=this.subtractPoints(dragVisual.startingPoint,{
				x:c,y:d
			});
		}
		this._prepareForDomChanges();
		
		dragSource.onDragStart();
		
		var j=new MySpace.UI.DragDropEventArgs(dragSource.get_dragMode(),dragSource.get_dragDataType(),dragSource.getDragData(context)),g=this.get_events().getHandler("dragStart");
		if(g)g(this,j);
		this._recoverFromDomChanges();
		this._wireEvents();
		this._drag(true)
		
		var handler=this.get_events().getHandler("afterDragStart");
		if(handler)handler(this);
	},
	_stopDragDrop:function(canceled){
		this._scroller.set_enabled(false);
			      
		var c=window._event;
		if(this._activeDragSource){
			this._unwireEvents();
			if(!canceled){
				canceled=this._underlyingTarget==null;
			}
			if(!canceled&&this._underlyingTarget){
				this._underlyingTarget.drop(this._activeDragSource.get_dragMode(),this._activeDragSource.get_dragDataType(),this._activeDragSource.getDragData(this._activeContext));
			}
			this._activeDragSource.onDragEnd(canceled);
			var b=this.get_events().getHandler("dragStop");
			if(b){
				b(this,Sys.EventArgs.Empty);
			}
			this._activeDragVisual.style.position=this._activeDragVisual.originalPosition;
			this._activeDragSource=null;
			this._activeContext=null;
			this._activeDragVisual=null;
			this._isDragging=false;
			this._potentialTarget=null;
			c.preventDefault()
		}
	},
	_drag:function(isInitialDrag){
		var d=window._event,c={
			x:d.clientX,y:d.clientY
		};
		document._lastPosition=c;
		var f=this.getScrollOffset(this._activeDragVisual,true),a=this.addPoints(this.subtractPoints(c,this._activeDragVisual.startingPoint),f);

		//Constrain to the page
		var dragVisualRect=Sys.UI.DomElement.getBounds(this._activeDragVisual);
		if(a.x<0){
			a.x=0;
		}else if(a.x+dragVisualRect.width>document.body.offsetWidth){
			a.x=document.body.offsetWidth-dragVisualRect.width;
		}
		if(a.y<0){
			a.y=0;
		}

		if(!isInitialDrag&&parseInt(this._activeDragVisual.style.left)==a.x&&parseInt(this._activeDragVisual.style.top)==a.y)return;
		Sys.UI.DomElement.setLocation(this._activeDragVisual,a.x,a.y);
		this._prepareForDomChanges();
		this._activeDragSource.onDrag();
		this._recoverFromDomChanges();
		this._potentialTarget=this._findPotentialTarget(this._activeDragSource,this._activeDragVisual);
		var b=this._potentialTarget!=this._underlyingTarget||this._potentialTarget==null;
		if(b&&this._underlyingTarget!=null)this._leaveTarget(this._activeDragSource,this._underlyingTarget);
		if(this._potentialTarget!=null){
			if(b){
				this._underlyingTarget=this._potentialTarget;
				this._enterTarget(this._activeDragSource,this._underlyingTarget)
			}
			else{
				this._moveInTarget(this._activeDragSource,this._underlyingTarget);
			}
		}
		else{
		       this._underlyingTarget=null
		}

		this._autoScroll()
	},
	_wireEvents:function(){
		Sys.UI.DomEvent.addHandler(document,"mouseup",this._mouseUpHandler);
		Sys.UI.DomEvent.addHandler(document,"mousemove",this._mouseMoveHandler);
		Sys.UI.DomEvent.addHandler(document,"keypress",this._keyPressHandler)
	},
	_unwireEvents:function(){
		Sys.UI.DomEvent.removeHandler(document,"keypress",this._keyPressHandler);
		Sys.UI.DomEvent.removeHandler(document,"mousemove",this._mouseMoveHandler);
		Sys.UI.DomEvent.removeHandler(document,"mouseup",this._mouseUpHandler)
	},
	registerDropTarget:function(target){
		if(!this._dropTargets)this._dropTargets=[];
		Array.add(this._dropTargets,target);
	},
	unregisterDropTarget:function(target){
		if(this._dropTargets)Array.remove(this._dropTargets,target)
	},
	mouseUpHandler:function(evt){
		window._event=evt;
		this._stopDragDrop(false)
	},
	mouseMoveHandler:function(evt){
		window._event=evt;
		this._drag()
	},
	keyPressHandler:function(evt){
		window._event=evt;
		var b=evt.keyCode?evt.keyCode:evt.rawEvent.keyCode;
		if(b==27)this._stopDragDrop(true)
	},
	_autoScroll:function(){
		var b=window._event,a=this.getBrowserRectangle();
		if(a.width>0){
			this._scrollDeltaX=this._scrollDeltaY=0;
			if(b.clientX<a.x+this._scrollEdgeConst)this._scrollDeltaX=-this._scrollByConst;
			else if(b.clientX>a.width-this._scrollEdgeConst)this._scrollDeltaX=this._scrollByConst;
			if(b.clientY<a.y+this._scrollEdgeConst)this._scrollDeltaY=-this._scrollByConst;
			else if(b.clientY>a.height-this._scrollEdgeConst)this._scrollDeltaY=this._scrollByConst;
			if(this._scrollDeltaX!=0||this._scrollDeltaY!=0)this._scroller.set_enabled(true);
			else this._scroller.set_enabled(false)
		}
	},
	scrollerTickHandler:function(){
		var d=document.body.scrollLeft,f=document.body.scrollTop;
		
		// Don't scroll if already at bottom of page
		var browserRect=this.getBrowserRectangle();
		var scrollY=(document.documentElement.scrollTop + browserRect.height + this._scrollEdgeConst) < document.body.offsetHeight;
		var scrollX=(document.documentElement.scrollLeft + browserRect.width + this._scrollEdgeConst) < document.body.offsetWidth;
		
		window.scrollBy(scrollX ? this._scrollDeltaX : 0, scrollY ? this._scrollDeltaY : 0);
		var c=document.body.scrollLeft,e=document.body.scrollTop,a=this._activeDragVisual,b={
			x:parseInt(a.style.left)+(c-d),y:parseInt(a.style.top)+(e-f)
		};
		Sys.UI.DomElement.setLocation(a,b.x,b.y)
	},
	_getDropTarget:function(element){
		while(element){
			if(element._dropTarget!=null)return element._dropTarget;
			element=element.parentNode
		}
		return null
	},
	_dragDrop:function(){
		if(this._isDragging)return;
		this._isDragging=true;
		this._activeDragVisual.dragDrop();
		document.selection.empty()
	},
	_moveInTarget:function(dragSource,dropTarget){
		this._prepareForDomChanges();
		dropTarget.onDragInTarget(dragSource.get_dragMode(),dragSource.get_dragDataType(),dragSource.getDragData(this._activeContext));
		this._recoverFromDomChanges()
	},
	_enterTarget:function(dragSource,dropTarget){
		this._prepareForDomChanges();
		dropTarget.onDragEnterTarget(dragSource.get_dragMode(),dragSource.get_dragDataType(),dragSource.getDragData(this._activeContext));
		this._recoverFromDomChanges()
	},
	_leaveTarget:function(dragSource,dropTarget){
		this._prepareForDomChanges();
		dropTarget.onDragLeaveTarget(dragSource.get_dragMode(),dragSource.get_dragDataType(),dragSource.getDragData(this._activeContext));
		this._recoverFromDomChanges()
	},
	_findPotentialTarget:function(dragSource){
		var f=window._event;
		if(!this._dropTargets)return null;
		var m=dragSource.get_dragDataType(),l=dragSource.get_dragMode(),k=dragSource.getDragData(this._activeContext),d=this.getScrollOffset(document.body,true),n=f.clientX+d.x,o=f.clientY+d.y,g={
			x:n-this._radius,y:o-this._radius,width:this._radius*2,height:this._radius*2
		};
		for(var c=0;c<this._dropTargets.length;c++){
			var b=this._dropTargets[c],j=b.canDrop(l,m,k);
			if(!j)continue;
			var e=b.get_dropTargetElement(),h=Sys.UI.DomElement.getBounds(e),i=Sys.UI.Control.overlaps(g,h);
			if(i||e===document.body)return b
		}
		return null
	},
	_prepareForDomChanges:function(){
		this._oldOffset=Sys.UI.DomElement.getLocation(this._activeDragVisual)
	},
	_recoverFromDomChanges:function(){
		var a=Sys.UI.DomElement.getLocation(this._activeDragVisual);
		if(this._oldOffset.x!=a.x||this._oldOffset.y!=a.y){
			this._activeDragVisual.startingPoint=this.subtractPoints(this._activeDragVisual.startingPoint,this.subtractPoints(this._oldOffset,a));
			scrollOffset=this.getScrollOffset(this._activeDragVisual,true);
			var b=this.addPoints(this.subtractPoints(document._lastPosition,this._activeDragVisual.startingPoint),scrollOffset);
			Sys.UI.DomElement.setLocation(this._activeDragVisual,b.x,b.y)
		}
	},
	addPoints:function(p1,p2){
		return{
			x:p1.x+p2.x,y:p1.y+p2.y
		}
	},
	subtractPoints:function(p1,p2){
		return{
			x:p1.x-p2.x,y:p1.y-p2.y
		}
	},
	getScrollOffset:function(element,recursive){
		var c=element.scrollLeft,d=element.scrollTop;
		if(recursive){
			var a=element.parentNode;
			while(a!=null&&a.scrollLeft!=null){
				c+=a.scrollLeft;
				d+=a.scrollTop;
				if(a==document.body&&(c!=0&&d!=0))break;
				a=a.parentNode
			}
		}
		return{
			x:c,y:d
		}
	},
	getBrowserRectangle:function(){
		return {
			x:0,
			y:0,
			width:window.innerWidth || document.documentElement.clientWidth,
			height:window.innerHeight || document.documentElement.clientHeight
		};
	},
	getNextSibling:function(item){
		for(item=item.nextSibling;item!=null;item=item.nextSibling)if(item.innerHTML!=null)return item;
		return null
	},
	hasParent:function(element){
		return element.parentNode!=null&&element.parentNode.tagName!=null
	}
};
MySpace.UI.GenericDragDropManager.registerClass("MySpace.UI.GenericDragDropManager",Sys.Component);

MySpace.UI.FriendSelector=function(element){
	MySpace.UI.FriendSelector.initializeBase(this, [element]);
	
	this._userId=null;//when passed, returns matching results from this user's friends list otherwise returns matches from the logged in user's friends list.
	this._minimumPrefixLength=1;
	this._lazyLoadPlaceholderHeight=25;
	this._firstRowSelected=true;
	this._completionInterval=300;
	this._completionListItemCssClass="friendSelectItem";
	this._highlightedItemCssClass="friendSelectItem friendSelectHighlighted";
	this._groupHeaderCssClass="friendSelectHeader";
	
	this._showUserImg=true;
	this._showUserName=true;
	this._showRealName=true;
	this._showSelectedUserImg=true;
	this._selectedFriend=null;
	this._enableCaching=true;
	this._enableCacheSubstrings=true;
};

MySpace.UI.FriendSelector.prototype={
	initialize:function(){
		MySpace.UI.FriendSelector.callBaseMethod(this, 'initialize');
		
		this.addStyles();
		this._createSelectedFriendNode();
	},
	
	_createSelectedFriendNode:function(){	
		var el=this.get_element();
		var newEl=this.wrapperDiv=document.createElement("div");
		var width=el.offsetWidth;
		newEl.style.width=width+"px";
		newEl.className="friendSelect";
		
		this._selectedNode=document.createElement("div");
		this._selectedNode.className="selected";
		newEl.appendChild(this._selectedNode);
		
		if(this.get_showSelectedUserImg()){
			this._selectedImage=document.createElement("img");
			this._selectedNode.appendChild(this._selectedImage);
		}
		
		this._selectedDisplayNameNode=document.createElement("div");
		this._selectedDisplayNameNode.className="displayName";
		this._selectedNode.appendChild(this._selectedDisplayNameNode);
		
		var closeButton=document.createElement("div");
		closeButton.className="close";
		$addHandler(closeButton, "click", Function.createDelegate(this, this._clearSelection));
		this._selectedNode.appendChild(closeButton);
		
		var clearDiv=document.createElement("div");
		clearDiv.style.clear="both";
		this._selectedNode.appendChild(clearDiv);
		
		el.parentNode.replaceChild(newEl, this.get_element());
		el.style.width=(width-2)+"px";	// Inputs use the border-box model in IE
		newEl.appendChild(el);
		
		if(this._popupBehavior){
			this._popupBehavior.set_parentElement(newEl);
		}
	},
	
	addStyles:function(){
		MySpace.UI.addStyles(
			".friendSelect { padding:1px; background:#fff; border:1px solid #A5ACB2; width:200px; }" +
			".friendSelect input { border:none; width:100%; margin:-1px 0 0; padding-top:1px; }" +
			".friendSelect .selected { display:none; background:#BCD2E9; font-weight:bold; width:80% }" +
			".friendSelect .selected img { float:left; margin:4px 8px 0 4px; height:30px; }" +
			".friendSelect .selected .displayName { float:left; height:28px; padding:12px 0 0 4px; }" +
			".friendSelect .selected .close { float:right; height:38px; width:32px; cursor:pointer; background:url('http://x.myspacecdn.com/modules/common/static/img/friendSelectorClose.gif') center no-repeat; }" +
			".friendSelectHeader { background:#608BC1; color:#FFF; font-weight:bold; padding:2px }" +
			".friendSelectItem { padding:2px !important; border-bottom:1px solid #CCC; cursor:pointer; line-height:1.2em; }" +
			".friendSelectItem td { vertical-align:middle; }" +
			".friendSelectItem img { width:28px; height:28px; vertical-align:middle; margin-right:3px; }" +
			".friendSelectItem .prefix { background-color:#E8F1FA; font-weight:bold; }" +
			".friendSelectItem .userName { color:#999; }" +
			".friendSelectItem .realName { display:block; }" +
			".friendSelectHighlighted { background:#E8F1FA }"
		, true, "FriendSelector");
	},
	
	createCompletionItem:function(item){
		var el=document.createElement("div");
		el._value=item;
		el._text=item.UserId;
		el.className="friendSelectItem";
		
		var displayName=item.DisplayName ? this._highlightPrefix(item.DisplayName) : "",
		    userName=(this._showUserName && item.UserName && item.UserName != item.UserId) ? ("("+this._highlightPrefix(item.UserName)+")") : "",
		    realName=(this._showRealName && item.RealName) ? this._highlightPrefix(item.RealName) : "";
		
		var displayImg=this._showUserImg ? String.format("<td><img src='{0}'></td>", item.ImageUri) : '';
		    
		// Yeah I'm using tables. You got a better way to vertically center the text, be my guest.
		el.innerHTML=String.format(
			"<table><tr>{0}<td>{1} <span class='userName'>{2}</span> <span class='realName'>{3}</span></td></tr></table>",
			displayImg,
			displayName,
			userName,
			realName
		);
		
		return el;
	},
	
	getCompletionItems:function(prefix){
		if(!prefix){
			if(this._recentFriends && this._recentFriends.length){
				return [].concat([{groupHeader:this._recentFriendsLabel}], this._recentFriends, [{groupHeader:this._allFriendsLabel}], this._completionItems);
			}
			else{
				return this._completionItems;
			}
		}
		
		var searchPrefix=prefix.toLowerCase().replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#39;");
		var matches=[], item=null;
		
		for(var i=0;i<this._completionItems.length;i++){
			item=this._completionItems[i];
			if((item.DisplayName && item.DisplayName.toLowerCase().startsWith(searchPrefix)) ||
			   (this._showUserName && item.UserName && (item.UserName != item.UserId) && item.UserName.toLowerCase().startsWith(searchPrefix)) ||
			   (this._showRealName && item.RealName && item.RealName.toLowerCase().startsWith(searchPrefix))){
				matches.push(item);
			}
		}
		
		return matches;
	},
	
	addRecentFriend:function(friend, max){
		// Remove from the recent friends array if it's there
		for(var i=0;i<this._recentFriends.length;i++){
			if(this._recentFriends[i].UserId==friend.UserId){
				this._recentFriends.splice(i, 1);
				break;
			}
		}
		
		// Add to the head of the recent friends array
		this._recentFriends.unshift(friend);
		
		// Truncate at 5 entries
		this._recentFriends.splice(max || 5);
	},
	
	_highlightPrefix:function(text){
		if(this._currentPrefix && text.toLowerCase().startsWith(this._currentPrefix.toLowerCase())){
			return "<span class='prefix'>"+text.substring(0, this._currentPrefix.length)+"</span>"+text.substring(this._currentPrefix.length);
		}
		else{
			return text;
		}
	},
	
	_setText: function(item){
		/// <summary>
		/// Method to set the selected autocomplete option on the textbox
		/// </summary>
		/// <param name="item" type="Sys.UI.DomElement" DomElement="true" mayBeNull="true">
		/// Item to select
		/// </param>
		/// <returns />
		
		var friend=item ? item._value : null;
		this._selectedFriend=friend;
		
		if(friend){
			this.get_element().style.display="none";
			this.get_element().value=friend.UserId;
			this._selectedNode.style.display="block";
			if(this.get_showSelectedUserImg()){
				this._selectedImage.onload=this._onImageLoad;
				this._selectedImage.style.visibility="hidden";
				this._selectedImage.src=friend.ImageUri;
			}
			this._selectedDisplayNameNode.innerHTML=friend.DisplayName;
		}
		else{
			this.set_value("");
		}
		this._stopTimer();

		this.raiseItemSelected(new MySpace.UI.AutoCompleteItemEventArgs(item, item ? item._text : null, friend));

		this._currentPrefix=this._currentCompletionWord();
		this._hideCompletionList();
	},
	
	_clearSelection:function(ev){
		this._setText(null);
		this.get_element().focus();
	},
	
	_onImageLoad:function(ev){
		// "this" in this function refers to the image
		this.style.height="";
		if(this.offsetWidth>30){
			this.style.height=Math.round(30*30/this.offsetWidth)+"px";
		}
		this.style.marginTop=(4+(30-this.offsetHeight)/2)+"px";
		this.style.marginRight=(8+(30-this.offsetWidth))+"px";
		this.style.visibility="";
		
		// Clear the onload handler, or else it will be repeatedly called for an animated gif
		this.onload=null;
	},
	
	// Public method to select a particular friend
	selectFriendById:function(id){
		if(id){
			for(var i=0;i<this._completionItems.length;i++){
				if(this._completionItems[i].UserId == id){
					this._setText({_value:this._completionItems[i]});
					return;
				}
			}
		}
		this._setText();
	},
	
	set_value:function(val){
		// If a friend was previously selected, clear it out
		this.get_element().style.display="";
		this._selectedNode.style.display="none";
		this._selectedFriend=null;
		
		MySpace.UI.FriendSelector.callBaseMethod(this, 'set_value');
	},
	
	get_showUserImg:function(){ return this._showUserImg; },
	set_showUserImg:function(val){ this._showUserImg=val; },
	
	get_showUserName:function(){ return this._showUserName; },
	set_showUserName:function(val){ this._showUserName=val; },
	
	get_showRealName:function(){ return this._showRealName; },
	set_showRealName:function(val){ this._showRealName=val; },
	
	get_showSelectedUserImg:function(){ return this._showSelectedUserImg; },
	set_showSelectedUserImg:function(val){ this._showSelectedUserImg=val; },
	
	get_selectedFriend:function(){ return this._selectedFriend; },
	
	get_recentFriends:function(){ return this._recentFriends; },
	set_recentFriends:function(val){ this._recentFriends=val; },
	
	get_recentFriendsLabel:function(){ return this._recentFriendsLabel; },
	set_recentFriendsLabel:function(val){ this._recentFriendsLabel=val; },

	get_allFriendsLabel:function(){ return this._allFriendsLabel; },
	set_allFriendsLabel:function(val){ this._allFriendsLabel=val; },
	
	get_userId:function(){ return this._userId; },
	set_userId:function(val){ this._userId=val; },
	
	get_useWebService:function(val){ return !!this.get_servicePath(); },
	set_useWebService:function(val){
		this.set_servicePath(val ? "/Modules/Common/Services/FriendAutocomplete.asmx" : null);
		this.set_serviceMethod(val ? "GetFriends" : null);

		this.set_serviceParams(val ? { userId:this._userId } : null);
	},
	
	get_completionListWidth:function(){
		// If the consumer didn't specify a width for the completion list, make it line up
		// with the wrapper div.  
		return this._completionListWidth ||
				 (this.wrapperDiv && Math.max(1, this.wrapperDiv.offsetWidth-2));
	}
};

MySpace.UI.FriendSelector.registerClass("MySpace.UI.FriendSelector", MySpace.UI.AutoCompleteBehavior);

MySpace.UI.FriendSelector.showPopup=(function(){
	var popup, selector, selectedFriend, callback, inp;
	
	return function(cb){
		callback=cb;
		
		if(popup){
			popup.show();
			selector.set_value("");
			inp.focus();
			return;
		}
		
		var div=document.createElement("div");
		inp=document.createElement("input");
		inp.style.width="375px";
		div.appendChild(inp);
		
		popup=MySpace.UI.Popup.create(div, "");
		popup.set_width(400);
		popup.set_top(50);
		popup.show();
		
		selector=$create(MySpace.UI.FriendSelector, {
			useWebService:true,
			completionListAlwaysVisible:true,
			completionListFixedHeight:300,
			minimumPrefixLength:0
		}, {
			itemSelected:function(sender, args){
				popup._hide();
				if(callback){
					callback(args.get_value());
				}
			}
		}, null, inp);
		
		inp.focus();
	};
})();
MySpace.UI.HistoryEventArgs=function(state){
	MySpace.UI.HistoryEventArgs.initializeBase(this);
	this._state = state;
};
MySpace.UI.HistoryEventArgs.prototype={
	get_state: function() {
		return this._state;
	}
};
MySpace.UI.HistoryEventArgs.registerClass('MySpace.UI.HistoryEventArgs', Sys.EventArgs);    

MySpace.UI._History=function(){
	MySpace.UI._History.initializeBase(this);

	this._appLoadHandler=null;
	this._clientId=null;
	this._currentEntry='';
	this._emptyPageUrl=null;
	this._historyFrame=null;
	this._historyInitialLength=0;
	this._historyLength=0;
	this._iframeLoadHandler=null;
	this._ignoreIFrame=false;
	this._ignoreTimer=false;
	this._historyPointIsNew=false;
	this._state={};
	this._timerCookie=0;
	this._timerHandler=null;
	this._uniqueId=null;
};
MySpace.UI._History.prototype={
	get_stateString: function(){
		var entry=decodeURIComponent(window.location.hash || '');
		if((entry.length > 0) && (entry.charAt(0) === '#')){
			entry=entry.substring(1);
		}
		return entry;    
	},
	add_navigate: function(handler){
		this.get_events().addHandler("navigate", handler);
	},
	remove_navigate: function(handler){
		this.get_events().removeHandler("navigate", handler);
	},
	addHistoryPoint: function(state, title){
		var initialState = this._state;
		for(var key in state){
			var value=state[key];
			if(value === null){
				if(typeof(initialState[key]) !== 'undefined'){
					delete initialState[key];
				}
			}
			else{
				initialState[key] = value;
			}
		}
		var entry=Sys.Serialization.JavaScriptSerializer.serialize(initialState);
		this._ignoreIFrame=true;
		this._historyPointIsNew=true;
		this._setState(entry, title);
	},
	dispose: function(){
		if (this._appLoadHandler) {
			Sys.Application.remove_load(this._appLoadHandler);
			delete this._appLoadHandler;
		}
		if (this._historyFrame) {
			Sys.UI.DomEvent.removeHandler(this._historyFrame, 'load', this._iframeLoadHandler);
			delete this._iframeLoadHandler;
			delete this._historyFrame;
		}
		if (this._timerCookie) {
			window.clearTimeout(this._timerCookie);
			delete this._timerCookie;
		}
		MySpace.UI._History.callBaseMethod(this, 'dispose');
	},
	initialize: function(){
		MySpace.UI._History.callBaseMethod(this, 'initialize');

		this._appLoadHandler = Function.createDelegate(this, this._onApplicationLoaded);
		Sys.Application.add_load(this._appLoadHandler);
	} ,
	setServerId: function(clientId, uniqueId){
		this._clientId = clientId;
		this._uniqueId = uniqueId;
	},
	setServerState: function(value){
		this._state.__s = value;
	},
        
	_navigate: function(entry){
		var state={};
		if(entry){
			try{
				// Test if it's safe to eval (stolen from json2.js)
				if (/^[\],:{}\s]*$/.
				 test(entry.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@').
				 replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').
				 replace(/(?:^|:|,)(?:\s*\[)+/g, '')))
					state=Sys.Serialization.JavaScriptSerializer.deserialize(entry, true);
			}
			catch(e){}
		}

		if (this._uniqueId) {
			var oldServerEntry = this._state.__s || '';
			var newServerEntry = state.__s || '';
			if (newServerEntry !== oldServerEntry) {
			__doPostBack(this._uniqueId, newServerEntry);
			this._state = state;
			return;
			}
		}
		this._setState(entry);
		this._state = state;
		this._raiseNavigate();
	},
	_onApplicationLoaded: function(sender, args){
		Sys.Application.remove_load(this._appLoadHandler);
		delete this._appLoadHandler;

		if(Sys.Browser.agent === Sys.Browser.InternetExplorer){
			var frameId='__historyFrame';
			var frame=$get(frameId);
			if(!frame){ throw Error.invalidOperation("For the history feature to work in IE, the page must have an iframe with id '__historyFrame' and src set to point to a page that sets its title to the 'title' querystring parameter when loaded."); }
			var src=frame.src;
			this._emptyPageUrl=src + (src.indexOf('?') === -1 ? '?' : '&') + '_state=';
			this._historyFrame=frame;
			if(frame.readyState === 'loading'){
				this._ignoreIFrame=true;
			}
			this._iframeLoadHandler=Function.createDelegate(this, this._onIFrameLoad);
			Sys.UI.DomEvent.addHandler(this._historyFrame, 'load', this._iframeLoadHandler);
		}

		this._timerHandler=Function.createDelegate(this, this._onIdle);
		this._timerCookie=window.setTimeout(this._timerHandler, 100);

		var loadedEntry=this.get_stateString();
		if(loadedEntry !== this._currentEntry){
			this._navigate(loadedEntry);
		}
	},
	_onIdle: function(){
		delete this._timerCookie;

		var entry=this.get_stateString();
		if(entry !== this._currentEntry){
			if(!this._ignoreTimer){
				this._historyPointIsNew=false;
				this._navigate(entry);
				this._historyLength=window.history.length;
			}
		}
		else{
			this._ignoreTimer=false;
		}
		this._timerCookie=window.setTimeout(this._timerHandler, 100);
	},
	_onIFrameLoad: function(){
		if(!this._ignoreIFrame){
			var entry=this._historyFrame.contentWindow.location.search;
			var statePos=entry.indexOf('_state=');
			if((statePos !== -1) && (statePos + 7 < entry.length)){
				entry=entry.substring(statePos + 7);
				var next=entry.indexOf('&');
				if(next !== -1){
					entry=entry.substring(0, next);
				}
			}
			else{
				entry='';
			}
			this._historyPointIsNew=false;
			this._navigate(entry);
		}
		this._ignoreIFrame=false;
	},
	_onPageRequestManagerBeginRequest: function(sender, args){
		this._ignoreTimer=true;
	},
	_onPageRequestManagerEndRequest: function(sender, args){
		var dataItem=args.get_dataItems()[this._clientId], title;

		if(typeof(dataItem) !== 'undefined'){
			var state=dataItem[0];
			title=dataItem[1];
			this.setServerState(state);
			this._historyPointIsNew=true;
		}
		else{
			this._ignoreTimer=false;
		}
		var entry=Sys.Serialization.JavaScriptSerializer.serialize(this._state);
		if(entry === '{}'){
			entry='';
		}
		if(entry != this._currentEntry){
			this._ignoreTimer=true;
			this._setState(entry, title);
			this._raiseNavigate();
		}
	},
	_raiseNavigate: function() {
		var h=this.get_events().getHandler("navigate");
		var args=new MySpace.UI.HistoryEventArgs(this._state);
		if(h){
			h(this, args);
		}
		if(window.pageNavigate){
			window.pageNavigate(this, args);
		}
	},
	_setState: function(entry, title) {
		if(entry !== this._currentEntry){
			if(this._historyFrame && this._historyPointIsNew){
				var newFrameUrl=this._emptyPageUrl + entry +
					'&title=' + encodeURIComponent(title || document.title);
				if(this._historyFrame.src != newFrameUrl){
					this._ignoreIFrame=true;
					this._historyFrame.src=newFrameUrl;
				}
				this._historyPointIsNew=false;
			}
			this._ignoreTimer=false;
			this._currentEntry=entry;
			var currentHash=this.get_stateString();
			if(currentHash === '{}'){
				currentHash='';
				this._currentEntry=null;
			}
			if(entry !== currentHash){
				window.location.hash=entry ? encodeURIComponent(entry) : '';
			}
			if(title){
				document.title=title;
			}
		}
	}
}
MySpace.UI._History.registerClass('MySpace.UI._History', Sys.Component);

MySpace.Application.get_history=function(){
	var h=this._history;
	if(!h){
		h=this._history=new MySpace.UI._History();
		Sys.Application.registerDisposableObject(h);
		h.initialize();
	}
	return h;
};

if (MySpace.UI._initHistory) {
	// get_history must be called during init in order for the history to be
	// correctly initialized.
	Sys.Application.add_init(function() {
		MySpace.Application.get_history();
	});
}
//
// MySpace.UI.PopupBehavior
//

MySpace.UI.PopupBehavior=function(element){
	/// <summary>
	/// The PopupBehavior is used to show/hide an element at a position
	/// relative to another element
	/// </summary>
	/// <param name="element" type="Sys.UI.DomElement" mayBeNull="false" domElement="true">
	/// The DOM element the behavior is associated with
	/// </param>
	MySpace.UI.PopupBehavior.initializeBase(this, [element]);

	this._x=0;
	this._y=0;
	this._positioningMode=MySpace.UI.PositioningMode.Absolute;
	this._parentElement=null;
	this._parentElementID=null;
	this._moveHandler=null;
	this._firstPopup=true;	
	this._originalParent=null;
	this._visible=false;
	this._hideOnDocumentClick=false;
	
	this._onShow=null;
	this._onShowEndedHandler=null;
	this._onHide=null;
	this._onHideEndedHandler=null;
}
MySpace.UI.PopupBehavior.prototype={
	initialize:function(){
		/// <summary>
		/// Initialize the PopupBehavior
		/// </summary>
		MySpace.UI.PopupBehavior.callBaseMethod(this, 'initialize');
		
		this._hidePopup();
		this.get_element().style.position="absolute";
		
		// Create handlers for the animation ended events
		this._onShowEndedHandler=Function.createDelegate(this, this._onShowEnded);
		this._onHideEndedHandler=Function.createDelegate(this, this._onHideEnded);
		
		$addHandler(document.body, "mousedown", Function.createDelegate(this, this._onDocumentClick));
	},
	
	dispose:function(){
		/// <summary>
		/// Dispose the PopupBehavior
		/// </summary>
	
		var element=this.get_element();
		if(element){
			if(this._visible){
				this.hide();
			}
			if(this._originalParent){
				element.parentNode.removeChild(element);
				this._originalParent.appendChild(element);
				this._originalParent=null;
			}
			
			// Remove expando properties
			element._hideWindowedElementsIFrame=null;
		}
		this._parentElement=null;

		// Remove the animation ended events and wipe the animations
		// (we don't need to dispose them because that will happen
		// automatically in our base dispose)
		if(this._onShow && this._onShowEndedHandler){
			this._onShow.remove_ended(this._onShowEndedHandler);
		}
		this._onShowEndedHandler=null;
		this._onShow=null;
		if(this._onHide && this._onHideEndedHandler){
			this._onHide.remove_ended(this._onHideEndedHandler);
		}
		this._onHideEndedHandler=null;
		this._onHide=null;
		
		MySpace.UI.PopupBehavior.callBaseMethod(this, 'dispose');
	},
	
	show:function(){
		/// <summary>
		/// Show the popup
		/// </summary>
		
		// Ignore requests to hide multiple times
		if(this._visible){
			return;
		}
		
		var eventArgs=new Sys.CancelEventArgs();
		this.raiseShowing(eventArgs);
		if(eventArgs.get_cancel()){
			return;
		}
		
		// Either show the popup or play an animation that does
		// (note: even if we're animating, we still show and position
		// the popup before hiding it again and playing the animation
		// which makes the animation much simpler)
		this._visible=true;
		var element=this.get_element();
		element.style.visibility="visible";
		this.setupPopup();
		if(this._onShow){
			element.style.visibility="hidden";
			this.onShow();
		} else {
			this.raiseShown(Sys.EventArgs.Empty);
		}
	},
	
	hide:function(){
		/// <summary>
		/// Hide the popup
		/// </summary>
		
		// Ignore requests to hide multiple times
		if(!this._visible){
			return;
		}
		
		var eventArgs=new Sys.CancelEventArgs();
		this.raiseHiding(eventArgs);
		if(eventArgs.get_cancel()){
			return;
		}

		// Either hide the popup or play an animation that does
		this._visible=false;
		if(this._onHide){
			this.onHide();
		} else {
			this._hidePopup();
			this._hideCleanup();
		}
	},
	
	getBounds:function(){
		/// <summary>
		/// Get the expected bounds of the popup relative to its parent
		/// </summary>
		/// <returns type="Sys.UI.Bounds" mayBeNull="false">
		/// Bounds of the popup relative to its parent
		/// </returns>
		/// <remarks>
		/// The actual final position can only be calculated after it is
		/// initially set and we can verify it doesn't bleed off the edge
		/// of the screen.
		/// </remarks>
	
		var element=this.get_element();
		
		// offsetParent (doc element if absolutely positioned or no offsetparent available)
		var offsetParent=element.offsetParent;
		if(!offsetParent || (offsetParent==document.documentElement)){ offsetParent=document.body; }
		
		// diff=difference in position between element's offsetParent and the element we will attach popup to.
		// this is basically so we can position the popup in the right spot even though it may not be absolutely positioned
		var diff;
		var parentBounds;
		if(this._parentElement){
			// we will be positioning the element against the assigned parent
			parentBounds=Sys.UI.DomElement.getBounds(this._parentElement);
			
			var offsetParentLocation=Sys.UI.DomElement.getLocation(offsetParent);
			diff={x: parentBounds.x - offsetParentLocation.x, y:parentBounds.y - offsetParentLocation.y};
		} else {
			// we will be positioning the element against the offset parent by default, since no parent element given
			parentBounds=Sys.UI.DomElement.getBounds(offsetParent);
			diff={x:0, y:0};
		}

		// width/height of the element, needed for calculations that involve width like centering
		var width=element.offsetWidth - (element.clientLeft ? element.clientLeft * 2:0);
		var height=element.offsetHeight - (element.clientTop ? element.clientTop * 2:0);

		// Setting the width causes the element to grow by border+passing every
		// time.  But not setting it causes strange behavior in safari. Just set it once.
		if(this._firstpopup){
			element.style.width=width + "px";
			this._firstpopup=false;
		}
		
		var position;
		switch (this._positioningMode){
			case MySpace.UI.PositioningMode.Center:
				position={
					x: Math.round(parentBounds.width / 2 - width / 2),
					y: Math.round(parentBounds.height / 2 - height / 2)
				};
				break;
			case MySpace.UI.PositioningMode.BottomLeft:
				position={
					x: 0,
					y: parentBounds.height
				};
				break;
			case MySpace.UI.PositioningMode.BottomRight:
				position={
					x: parentBounds.width - width,
					y: parentBounds.height
				};
				break;
			case MySpace.UI.PositioningMode.TopLeft:
				position={
					x: 0,
					y: -element.offsetHeight
				};
				break;
			case MySpace.UI.PositioningMode.TopRight:
				position={
					x: parentBounds.width - width,
					y: -element.offsetHeight
				};
				break;
			case MySpace.UI.PositioningMode.Right:
				position={
					x: parentBounds.width,
					y: 0
				};
				break; 
			case MySpace.UI.PositioningMode.Left:
				position={
					x: -element.offsetWidth,
					y: 0
				};
				break;				   
			default:
				position={x: 0, y: 0};
		}
		position.x += this._x + diff.x;
		position.y += this._y + diff.y;
		
		
		return new Sys.UI.Bounds(position.x, position.y, width, height);
	},

	adjustPopupPosition:function(bounds){
		/// <summary>
		/// Adjust the position of the popup after it's originally bet set
		/// to make sure that it's visible on the page.
		/// </summary>
		/// <param name="bounds" type="Sys.UI.Bounds" mayBeNull="true" optional="true">
		/// Original bounds of the parent element
		/// </param>

		var element=this.get_element();
		if(!bounds){
			bounds=this.getBounds();
		}
		
		// Get the new bounds now that we've shown the popup
		var newPosition=Sys.UI.DomElement.getBounds(element);
		var updateNeeded=false;

		if(newPosition.x < 0){
			bounds.x -= newPosition.x;
			updateNeeded=true;
		}
		if(newPosition.y < 0){
			bounds.y -= newPosition.y;
			updateNeeded=true;
		}

		// If the popup was off the screen, reposition it
		if(updateNeeded){
			Sys.UI.DomElement.setLocation(element, bounds.x, bounds.y);
		}
	},
	
	addBackgroundIFrame:function(){
		/// <summary>
		/// Add an empty IFRAME behind the popup (for IE6 only) so that SELECT, etc., won't
		/// show through the popup.
		/// </summary>
	
		// Get the child frame
		var element=this.get_element();
		if((Sys.Browser.agent === Sys.Browser.InternetExplorer) && (Sys.Browser.version < 7)){
			var childFrame=element._hideWindowedElementsIFrame;
			
			// Create the child frame if it wasn't found
			if(!childFrame){
				childFrame=document.createElement("iframe");
				childFrame.src="javascript:'<html></html>';";
				childFrame.style.position="absolute";
				childFrame.style.display="none";
				childFrame.scrolling="no";
				childFrame.frameBorder="0";
				childFrame.tabIndex="-1";
				childFrame.style.filter="progid:DXImageTransform.Microsoft.Alpha(style=0,opacity=0)";
				element.parentNode.insertBefore(childFrame, element);
				element._hideWindowedElementsIFrame=childFrame;
				this._moveHandler=Function.createDelegate(this, this._onMove);
				Sys.UI.DomEvent.addHandler(element, "move", this._moveHandler);
			}
			
			// Position the frame exactly behind the element
			childFrame.style.width=element.offsetWidth+"px";
			childFrame.style.height=element.offsetHeight+"px";
			childFrame.style.display=element.style.display;
			if(element.currentStyle && element.currentStyle.zIndex){
				childFrame.style.zIndex=element.currentStyle.zIndex;
			}
			else if(element.style.zIndex){
				childFrame.style.zIndex=element.style.zIndex;
			}
		}
	},
	
	setupPopup:function(){
		/// <summary>
		/// Position the popup relative to its parent
		/// </summary>
		
		var element=this.get_element();
		var bounds=this.getBounds();
		Sys.UI.DomElement.setLocation(element, bounds.x, bounds.y);

		// Tweak the position, set the zIndex, and add the background iframe in IE6
		this.adjustPopupPosition(bounds);
		element.style.zIndex=1000;
		this.addBackgroundIFrame();
	},
	
	_hidePopup:function(){
		/// <summary>
		/// Internal hide implementation
		/// </summary>
		
		var element=this.get_element();
		element.style.visibility="hidden";
		if(element.originalWidth){
			element.style.width=element.originalWidth + "px";
			element.originalWidth=null;
		}
	},
	
	_hideCleanup:function(){
		/// <summary>
		/// Perform cleanup after hiding the element
		/// </summary>
	
		var element=this.get_element();
		
		// Remove the tracking handler
		if(this._moveHandler){
			Sys.UI.DomEvent.removeHandler(element, "move", this._moveHandler);
			this._moveHandler=null;
		}
		
		// Hide the child frame
		if(Sys.Browser.agent === Sys.Browser.InternetExplorer){
			var childFrame=element._hideWindowedElementsIFrame;
			if(childFrame){
				childFrame.style.display="none";
			}
		}
		
		this.raiseHidden(Sys.EventArgs.Empty);
	},
	
	_onDocumentClick:function(e){
		if(!this._hideOnDocumentClick || !this._visible){ return; }
		
		for(var node=e.target; node; node=node.parentNode){
			if(node==this.get_element()){
				return;
			}
		}
		
		this.hide();
	},
	
	_onMove:function(){
		/// <summary>
		/// Track the popup's movements so the hidden IFrame (IE6 only) can
		/// be moved along with it
		/// </summary>
		
		var element=this.get_element();
		if(element._hideWindowedElementsIFrame){
			element.parentNode.insertBefore(element._hideWindowedElementsIFrame, element);
			element._hideWindowedElementsIFrame.style.top=element.style.top;
			element._hideWindowedElementsIFrame.style.left=element.style.left;
		}
	},
	
	get_onShow:function(){
		/// <value type="MySpace.UI.Effects.Animation" mayBeNull="true">
		/// Animation to play when the popup is shown
		/// </value>
		return this._onShow;
	},
	set_onShow:function(value){
		this._onShow=value;
		if(value){
			value.set_target(this.get_element());
			value.add_ended(this._onShowEndedHandler);
		}
	},
	onShow:function(){
		/// <summary>
		/// Play the OnShow animation
		/// </summary>
		/// <returns />
		if(this._onShow){
			if(this._onHide){
				this._onHide.stop();
			}
			this._onShow.play();
		}
	},
	_onShowEnded:function(){
		/// <summary>
		/// Handler for the OnShow Animation's Ended event
		/// </summary>
		
		// Make sure the popup is where it belongs
		this.adjustPopupPosition();
		this.addBackgroundIFrame();
		
		this.raiseShown(Sys.EventArgs.Empty);
	},
	
	get_onHide:function(){
		/// <value type="MySpace.UI.Effects.Animation" mayBeNull="true">
		/// Animation to play when the popup is hidden
		/// </value>
		return this._onHide;
	},
	set_onHide:function(value){
		this._onHide=value;
		if(value){
			value.set_target(this.get_element());
			value.add_ended(this._onHideEndedHandler);
		}
	},
	onHide:function(){
		/// <summary>
		/// Play the OnHide animation
		/// </summary>
		/// <returns />
		if(this._onHide){
			if(this._onShow){
				this._onShow.stop();
			}
			this._onHide.play();
		}
	},
	_onHideEnded:function(){
		/// <summary>
		/// Handler for the OnHide Animation's Ended event
		/// </summary>
		
		this._hideCleanup();
	},
	
	get_parentElement:function(){
		/// <value type="Sys.UI.DomElement" domElement="true">
		/// Parent dom element.
		/// </value>
		
		if(!this._parentElement && this._parentElementID){
			this.set_parentElement($get(this._parentElementID));
		}		
		return this._parentElement;
	},
	set_parentElement:function(element){
		this._parentElement=element;
	},
	
	get_parentElementID:function(){
		/// <value type="String">
		/// Parent dom element.
		/// </value>
		
		if(this._parentElement){
			return this._parentElement.id
		}
		return this._parentElementID;
	},
	set_parentElementID:function(elementID){
		this._parentElementID=elementID;
		if(this.get_isInitialized()){
			this.set_parentElement($get(elementID));
		}
	},
		
	get_positioningMode:function(){
		/// <value type="MySpace.UI.PositioningMode">
		/// Positioning mode.
		/// </value>
		return this._positioningMode;
	},
	set_positioningMode:function(mode){
		this._positioningMode=mode;
	},
	
	get_x:function(){
		/// <value type="Number">
		/// X coordinate.
		/// </value>
		return this._x;
	},
	set_x:function(value){
		if(value != this._x){
			this._x=value;
			
			// Reposition the popup if it's already showing
			if(this._visible){
				this.setupPopup();
			}
		}
	},
	
	get_y:function(){
		/// <value type="Number">
		/// Y coordinate.
		/// </value>
		return this._y;
	},
	set_y:function(value){
		if(value != this._y){
			this._y=value;
			
			// Reposition the popup if it's already showing
			if(this._visible){
				this.setupPopup();
			}
		}
	},
	
	get_visible:function(){
		/// <value type="Boolean" mayBeNull="false">
		/// Whether or not the popup is currently visible
		/// </value>
		return this._visible;
	},
	
	get_hideOnDocumentClick:function(){ return this._hideOnDocumentClick; },
	set_hideOnDocumentClick:function(value){ this._hideOnDocumentClick=value; },
	
	add_showing:function(handler){
		/// <summary>
		/// Add an event handler for the showing event
		/// </summary>
		/// <param name="handler" type="Function" mayBeNull="false">
		/// Event handler
		/// </param>
		/// <returns />
		this.get_events().addHandler('showing', handler);
	},
	remove_showing:function(handler){
		/// <summary>
		/// Remove an event handler from the showing event
		/// </summary>
		/// <param name="handler" type="Function" mayBeNull="false">
		/// Event handler
		/// </param>
		/// <returns />
		this.get_events().removeHandler('showing', handler);
	},
	raiseShowing:function(eventArgs){
		/// <summary>
		/// Raise the showing event
		/// </summary>
		/// <param name="eventArgs" type="Sys.CancelEventArgs" mayBeNull="false">
		/// Event arguments for the showing event
		/// </param>
		/// <returns />
		
		var handler=this.get_events().getHandler('showing');
		if(handler){
			handler(this, eventArgs);
		}
	},
	
	add_shown:function(handler){
		/// <summary>
		/// Add an event handler for the shown event
		/// </summary>
		/// <param name="handler" type="Function" mayBeNull="false">
		/// Event handler
		/// </param>
		/// <returns />
		this.get_events().addHandler('shown', handler);
	},
	remove_shown:function(handler){
		/// <summary>
		/// Remove an event handler from the shown event
		/// </summary>
		/// <param name="handler" type="Function" mayBeNull="false">
		/// Event handler
		/// </param>
		/// <returns />
		this.get_events().removeHandler('shown', handler);
	},
	raiseShown:function(eventArgs){
		/// <summary>
		/// Raise the shown event
		/// </summary>
		/// <param name="eventArgs" type="Sys.EventArgs" mayBeNull="false">
		/// Event arguments for the shown event
		/// </param>
		/// <returns />
		
		var handler=this.get_events().getHandler('shown');
		if(handler){
			handler(this, eventArgs);
		}
	},	
	
	add_hiding:function(handler){
		/// <summary>
		/// Add an event handler for the hiding event
		/// </summary>
		/// <param name="handler" type="Function" mayBeNull="false">
		/// Event handler
		/// </param>
		/// <returns />
		this.get_events().addHandler('hiding', handler);
	},
	remove_hiding:function(handler){
		/// <summary>
		/// Remove an event handler from the hiding event
		/// </summary>
		/// <param name="handler" type="Function" mayBeNull="false">
		/// Event handler
		/// </param>
		/// <returns />
		this.get_events().removeHandler('hiding', handler);
	},
	raiseHiding:function(eventArgs){
		/// <summary>
		/// Raise the hiding event
		/// </summary>
		/// <param name="eventArgs" type="Sys.CancelEventArgs" mayBeNull="false">
		/// Event arguments for the hiding event
		/// </param>
		/// <returns />
		
		var handler=this.get_events().getHandler('hiding');
		if(handler){
			handler(this, eventArgs);
		}
	},
	
	add_hidden:function(handler){
		/// <summary>
		/// Add an event handler for the hidden event
		/// </summary>
		/// <param name="handler" type="Function" mayBeNull="false">
		/// Event handler
		/// </param>
		/// <returns />
		this.get_events().addHandler('hidden', handler);
	},
	remove_hidden:function(handler){
		/// <summary>
		/// Remove an event handler from the hidden event
		/// </summary>
		/// <param name="handler" type="Function" mayBeNull="false">
		/// Event handler
		/// </param>
		/// <returns />
		this.get_events().removeHandler('hidden', handler);
	},
	raiseHidden:function(eventArgs){
		/// <summary>
		/// Raise the hidden event
		/// </summary>
		/// <param name="eventArgs" type="Sys.EventArgs" mayBeNull="false">
		/// Event arguments for the hidden event
		/// </param>
		/// <returns />
		
		var handler=this.get_events().getHandler('hidden');
		if(handler){
			handler(this, eventArgs);
		}
	}
}
MySpace.UI.PopupBehavior.registerClass('MySpace.UI.PopupBehavior', Sys.UI.Behavior);

MySpace.UI.PositioningMode=function(){
	/// <summary>
	/// Positioning mode describing how the popup should be positioned
	/// relative to its specified parent
	/// </summary>
	/// <field name="Absolute" type="Number" integer="true" />
	/// <field name="Center" type="Number" integer="true" />
	/// <field name="BottomLeft" type="Number" integer="true" />
	/// <field name="BottomRight" type="Number" integer="true" />
	/// <field name="TopLeft" type="Number" integer="true" />
	/// <field name="TopRight" type="Number" integer="true" />
	/// <field name="Right" type="Number" integer="true" />
	/// <field name="Left" type="Number" integer="true" />
	throw Error.invalidOperation();
}
MySpace.UI.PositioningMode.prototype={
	Absolute: 0,
	Center: 1,
	BottomLeft: 2,
	BottomRight: 3,
	TopLeft: 4,
	TopRight: 5,
	Right: 6,
	Left: 7
}
MySpace.UI.PositioningMode.registerEnum('MySpace.UI.PositioningMode');

//Generic window overlay
MySpace.UI._Overlay = function(element){
	/// <param name="element" domElement="true"></param>
	document.body.appendChild(element);
	MySpace.UI._Overlay.initializeBase(this,[element]);
}
MySpace.UI._Overlay.prototype = {
	_interval: null,_fadeIn: false,_opacity: 0,_max: 60,_fadeDelegate:null,_resizeHandler:null, _step:20,
	show: function(){MySpace.UI.hideElements(["iframe","object","embed","select"],true);this._fade(true);},
	hide: function(){MySpace.UI.hideElements(["iframe","object","embed","select"],false);this._fade(false);},

	add_fadeComplete:function(handler){
		/// <param name="fadeIn" type="Boolean"></param>
		this.get_events().addHandler("fadeComplete", handler);
	},
	remove_fadeComplete:function(handler){
		/// <param name="fadeIn" type="Boolean"></param>
		this.get_events().removeHandler("fadeComplete", handler);
	},

	initialize:function(){
		var element = this.get_element();
		element.id = "window_overlay";
		element.style.zIndex = "1000200";
		element.style.width = "100%";
		this.set_opacity(0);
		Sys.UI.DomElement.setLocation(element,0,0);
		this._setHeight();
		this._resizeHandler = Function.createDelegate(this, this._setHeight);
		$addHandler(window, "resize", this._resizeHandler);
	},
	_setHeight: function(){
		var a=document.body.scrollHeight;//scrolled content
		var b=document.documentElement.clientHeight;//no scroll
		var c=document.documentElement.scrollHeight;//ie7 friendly
		a = ((a>c)?a:c);
		this.get_element().style.height=((a>b)?a:b)+"px";
	},
	_fade: function(fadeIn){
		/// <param name="fadeIn" type="Boolean"></param>
		this._fadeIn = fadeIn;
		if(fadeIn) {
			this._element.style.visibility='visible';
			this._element.style.display='';
		}
		if(!this._fadeDelegate)this._fadeDelegate = Function.createDelegate(this,this._tick);
		this._interval = window.setInterval(this._fadeDelegate, 100);
	},
	_tick: function(){
		if(!this._interval) return;
		var increase = this._step;
		if(!this._fadeIn) increase*=-1;
		var newOpacity = this._opacity + increase;
		if(newOpacity<0) newOpacity = 0;
		else if(newOpacity>this._max) newOpacity = this._max;
		this.set_opacity(newOpacity);
		if(newOpacity<=0 || newOpacity>=this._max){
			window.clearInterval(this._interval);
            var fadeComplete = this.get_events().getHandler("fadeComplete");
            if(!this._fadeIn){
					this._element.style.visibility='hidden';
					this._element.style.display='none';
            }
            if (fadeComplete) fadeComplete(this, Sys.EventArgs.Empty);
		}
	},
	get_opacity:function(){return this._opacity;},
	set_opacity: function(value){
		/// <param name="value" type="Number" integer="true"></param>
		this._opacity = value;
		var s = this.get_element().style;
		s.opacity = value*.01;
		s.filter = "alpha(opacity="+value+")";
		if(value===0) this.set_visible(false);
	},
	dispose:function(){
		$removeHandler(window, "resize", this._resizeHandler);
		this._fadeDelegate=null;
		MySpace.UI._Overlay.callBaseMethod(this, 'dispose');
	}
}
MySpace.UI._Overlay.registerClass('MySpace.UI._Overlay', Sys.UI.Control);
window.get_overlay = function(){if(!window._overlay)window._overlay=$create(MySpace.UI._Overlay,null,null,null,document.createElement("div"));return window._overlay;};



MySpace.UI._Popup = function(element){
	/// <param name="element" domElement="true"></param>
	this._box = element.firstChild;
	MySpace.UI._Popup.initializeBase(this,[element]);
}
MySpace.UI._Popup.prototype = {
    _autoSize:true,
	_useFixedPos:true,
	_box:null,
	_state:null,
	_defaultButton:null,
	_callback:null,
	_globalCss:null,
	_multiple:false,
	_prevHeight:0,
	_checkHeightHandler:null,
	_resizeHandler:null,
	_ruleCnt:0,
	_timerId:null,
	_top:null,
	_left:null,
	_width:null,
	_ruleAdded:false,
	
	get_autoSize:function() { return this._autoSize; },
	set_autoSize:function(value) { this._autoSize = value; },
	get_useFixedPos:function() { return this._useFixedPos; },
	set_useFixedPos:function(value) { this._useFixedPos = value; this.get_element().style.position = value ? "" : "absolute"; },
	get_multiple: function() {return this._multiple;},
	set_multiple: function(value) {this._multiple = value;},
	
	get_top: function() {return this._top;},
	set_top: function(value) {this._top = value;},
	
	get_left: function() {return this._left;},
	set_left: function(value) {this._left = value;},
	
	get_width: function() {return this._width;},
	set_width: function(value) {
		this._width = value;
		this._box.style.width = value + "px";
	},

	get_state: function(){return this._state;},
	set_state: function(value){this._state = value;},

	get_title: function(){return this._box.childNodes[1].innerHTML;},
	set_title: function(value){this._box.childNodes[1].innerHTML = value;},

	get_content: function(){return this._box.childNodes[2].innerHTML;},
	set_content: function(value){this.clear_contents(); if (typeof(value) === 'object') {this._box.childNodes[2].appendChild(value);} else {this._box.childNodes[2].innerHTML = value;}},

	get_callback: function(){return this._callback;},
	set_callback: function(value){this._callback = value;},
	
	get_showing: function(){return this._element.style.display != "none";},
    
    clear_contents:function(){
        var c = this._box.childNodes[2];
        for(var i=c.childNodes.length-1;i>=0;i--)
            c.removeChild(c.childNodes[i]);
    },
	add_button: function(text, isDefault, onClick, cssClass){
		var b=document.createElement("input");
		b.type="button";
		b.value=text;
		if(cssClass)
			b.className = cssClass;
		if(isDefault)
			this._defaultButton = b;
		$addHandlers(b,{ click:(onClick || this._buttonClick) },this);
		this._box.lastChild.appendChild(b);
		return b;
	},
	
	remove_buttons: function(){
	    var buttons = this._box.lastChild.childNodes;
		for(var i=buttons.length-1;i>=0;i--){
			$clearHandlers(buttons[i]);
			this._box.lastChild.removeChild(buttons[i]);
	    }
	},

 	show: function(callBack){
		if(MySpace.UI._Popup._activePopup && !this._multiple)throw "A Popup is already active.";
		if(callBack)this._callback = callBack;
		if(!this._multiple) window.get_overlay().show();
		
		// control popup position through property settings
		if ((!this._globalCss || !this._useFixedPos) && this._top !== null){
			this._element.style.top = this._top + 'px';
		}
		if (this._left !== null){
			this._element.style.left = this._left + 'px';
		}
		if (this._width !== null){
			this._box.style.width = this._width + 'px';
		}
		
		this._element.style.display='';
		this._element.style.visibility='visible';
		var exclude = MySpace.Utils.Selector.query("iframe,object,embed,select", this._element);
		for (var i=0;i<exclude.length;i++) {exclude[i].style.visibility='';}
		if(this._defaultButton)this._defaultButton.focus();
		MySpace.UI._Popup._activePopup = this;
		
		this._addFixPosRule();
        this._elDim = this._getAdjBounds(this._element);
                
		this._checkBoxHeight();
	},
	_addFixPosRule:function(){
	    if (this._globalCss !== null && !this._ruleAdded && this._useFixedPos){
			// add the style to fix the popup position
			this._globalCss.addRule('.popup_wrapper', 'top:' + this._top + 'px');		
			this._top = (this._top == null ? this._element.offsetTop : this._top);	
			this._globalCss.addRule('.popup_wrapper', 'top:expression( (ignoreMe = (document.body.scrollTop || document.documentElement.scrollTop) + ' + this._top + ') + "px" )');
			this._ruleCnt+=2;
			this._ruleAdded=true;
		}
	},
	_removeFixPosRule:function(){
	    if (this._globalCss !== null && this._ruleCnt && !this._multiple){
	        while(this._ruleCnt){
			    this._globalCss.removeRule(this._globalCss.rules.length-1);
			    this._ruleCnt--;
			}
			
			this._ruleAdded=false;
		}
	},
	_heightCheck:function(){
	    var box = this._getBox('popup_box');
	    
        var d = Sys.UI.DomElement.getBounds(box);
        if (parseInt(d.height) != parseInt(this._prevHeight) || parseInt(this.get_element().scrollHeight) < parseInt(d.height)){
            this._checkBoxHeight();
        }
        else{
            clearTimeout(this._timerId);
            this._timerId = setTimeout(this._checkHeightHandler, 2000);
        }
	},
	hide: function(){
		this._hide();
	},
	_hide: function(){
	    clearTimeout(this._timerId);
		if (!this._multiple) window.get_overlay().hide();
		this._element.style.display='none';
		MySpace.UI._Popup._activePopup=null;
		
		this._removeFixPosRule();
        this.get_element().style.top=(this._top?this._top+'px':'auto');
	},
	_buttonClick: function(e){
		this._hide();
		var cb=this._callback;
		if(cb)cb(this, e);
	},
	initialize: function(){
	    this._checkHeightHandler = Function.createDelegate(this, this._heightCheck);
	    this._resizeHandler = Function.createDelegate(this, this._checkBoxHeight);
	    
		var element = this.get_element();
		//element should always have a parent because it should have been created by a template
		element.parentNode.removeChild(element);
		document.body.appendChild(element);
		this._box.firstChild.isCancel=true; //red-x
		$addHandlers(this._box.firstChild,{click:this._buttonClick},this);
		MySpace.UI._Popup.callBaseMethod(this, 'initialize');
		
		// Check if we need to add a CSS expression.  It's needed only if position:fixed is not
		// supported, which means IE6 on all pages, or any IE on a quirks mode page.
		var ieVer=(Sys.Browser.agent == Sys.Browser.InternetExplorer) ? Sys.Browser.version : 0;
		var isQuirks=(document.compatMode == "BackCompat");
		
		if ((ieVer == 6) || (isQuirks && ieVer >= 7)){
			for (var i = 0; i < document.styleSheets.length; i++){				
				if (/global.*(\.debug)*\.css/i.test(document.styleSheets[i].href)){					
					this._globalCss = document.styleSheets[i];					
				}
			}
		}
		
		if (this._autoSize) $addHandler(window, "resize", this._resizeHandler);
	},
	_getAdjBounds:function(el){
	    var d = Sys.UI.DomElement.getBounds(el);
	    
	    var sTop = (document.compatMode == 'BackCompat') ? document.body.scrollTop : document.documentElement.scrollTop;
	    d.sHeight=sTop;
	    
	    if (Sys.Browser.agent===Sys.Browser.InternetExplorer && (document.compatMode != "BackCompat"))
	        d.y -= sTop;

        return d;
	},
	_getBox:function(name){
        var a = this._element.getElementsByTagName('div');
         var i = 0;
         while (element = a[i++]) {
            if (element.className.indexOf(name) > -1)
                return element;
         }  
	},
	_checkBoxHeight:function(evt){
        if (!this._autoSize || !this._useFixedPos) return;
	    
	    var box = this._getBox('popup_box');
	    
	    var mode = document.compatMode;
	    var maxY = (window.innerHeight ? window.innerHeight : mode == 'BackCompat' ? document.documentElement.offsetHeight : document.documentElement.clientHeight);
        
        if (box){
            var d = this._getAdjBounds(box);
            
            if (!this._globalCss && d.height <= maxY && this._elDim.y+d.height>maxY){
                this.get_element().style.position='fixed';
                this.get_element().style.top=parseInt((maxY-d.height)/2)+'px';
            }
            //check if def top + height > visible screen height
            else if (this._elDim.y+d.height>maxY){
                this._removeFixPosRule();
                if (this._globalCss){
                    this._globalCss.addRule('.popup_wrapper', 'top:' + (d.y+d.sHeight) + 'px !important');
                    this._ruleCnt++;
                }
                else{
                    this.get_element().style.position='absolute';
                    this.get_element().style.top=(d.y+d.sHeight)+'px';
                }
            } else {
                if (this._globalCss){
                    this._removeFixPosRule();
                    this._addFixPosRule();
                } else {
                    this.get_element().style.position='fixed';
                    this.get_element().style.top=(this._top?this._top+'px':'');
                }
            }
            
            if (!evt || d.height < this._prevHeight) this._prevHeight = d.height;
        
            clearTimeout(this._timerId);
            this._timerId = setTimeout(this._checkHeightHandler, 2000);
        }
	},
	dispose: function(){
		var buttons = this._box.lastChild.childNodes;
		for(var i=0;i<buttons.length;i++)
			$clearHandlers(buttons[i]);
		MySpace.UI._Popup.callBaseMethod(this, 'dispose');
	},
	_getIsFixed:function(){
        var position;  
        var parent = this._box.parentNode;
        while (parent!==null) {
            var compStyle = MySpace.UI.getComputedStyle(parent);
            
            if (compStyle) {
                position = compStyle.position;
                
                if (position === 'fixed')
                    return true;
            }
            
            parent = parent.parentNode;
        }
        
        return false;        
    }
}
MySpace.UI._Popup.registerClass('MySpace.UI._Popup', Sys.UI.Control);
MySpace.UI._Popup._activePopup=null;

MySpace.UI.Popup=function(){throw "Cannot instantiate static class.";}
MySpace.UI.Popup.create=function(content, title, callback, multiple, autoSize){
	/// <param name="content" type="String"></param>
	/// <param name="title" type="String"></param>
	/// <param name="callback" type="Function" mayBeNull="true" optional="true"></param>
	/// <returns type="MySpace.UI.Popup"></returns>
	
	var temp=document.createElement("div");	
    temp.innerHTML="<div class='popup_wrapper' style='z-index:1000201;left:0px;width:100%;display:none;visibility:hidden;'><div class='popup_box'><a class='popup_x'></a><div class='popup_title'></div><div class='popup_content'></div><div class='popup_buttons'></div></div></div>";
	return $create(MySpace.UI._Popup,{title:title, content:content, callback:callback, multiple:multiple||false, autoSize:autoSize===undefined?true:autoSize},null,null,temp.firstChild);
}

MySpace.UI.Popup.generic = function(message, buttonText, callback){
	/// <param name="message" type="String"></param>
	/// <param name="buttonText" type="String"></param>
	/// <param name="callback" type="Function" mayBeNull="true" optional="true"></param>
	/// <returns type="MySpace.UI.Popup"></returns>
	var template = document.createElement("div");
	var p = MySpace.UI.Popup.create(message,MySpaceRes.Common.Attention);
	p.add_button(buttonText);
	template.innerHTML=message;
	p.show(callback);
	return p;
}
MySpace.UI.Popup.alert = function(message, callback){
	/// <param name="message" type="String"></param>
	/// <param name="callback" type="Function" mayBeNull="true" optional="true"></param>
	new MySpace.UI.Popup.generic(message,MySpaceRes.Common.Ok,callback);
}
MySpace.UI.Popup.confirm = function(message, callback){
	/// <param name="message" type="String"></param>
	/// <param name="callback" type="Function" mayBeNull="true" optional="true"></param>
	var p=new MySpace.UI.Popup.generic(message,MySpaceRes.Common.Yes,callback);
	p.add_button(MySpaceRes.Common.No);
}
MySpace.UI.Popup.registerClass('MySpace.UI.Popup');

//This class makes creating Iframe pop easier. It also shows the wait state when loading the frame.
MySpace.UI.Popup.IFrameContent = function(popTitle, popWidth, frameSrc, frameCss, callback) {
    var popContent = "<div class='popwithiframeloader' style='width:100%;text-align:center;position:absolute;top:50%;z-index:10;'><img src='" + MySpace.StaticContentBase + "/modules/common/static/img/loadercircles.gif'></div><iframe noresize='noresize' frameborder='0' scrolling='no' class='" + frameCss + "' style='visibility:hidden;'></iframe>";
    this._frameSrc = frameSrc;
    this._popup = MySpace.UI.Popup.create(popContent, popTitle, callback);
    this._popup.set_width(popWidth);
    this._loader = $q('.popwithiframeloader', this._popup.get_element(),true);
    this._frameElem = $q('.' + frameCss, this._popup.get_element(), true);   
    $addHandler(this._frameElem, "load", Function.createDelegate(this, this.hideLoader));
    this._frameElem.src = frameSrc;
}
MySpace.UI.Popup.IFrameContent.prototype = {
    get_popup: function() { return this._popup; },
    show: function() {
        this._frameElem.style.visibility = 'hidden';
        this._frameElem.style.width = this._frameElem.style.border = '0px';        
        this._loader.style.display = "block";
        this._frameElem.src = this._frameSrc;
        this._popup.show();
    },
    hideLoader: function() {
        this._loader.style.display = "none";
        this._frameElem.style.width = this._frameElem.style.border = '';        
        this._frameElem.style.visibility = 'visible';        
    }
}
MySpace.UI.Popup.IFrameContent.registerClass('MySpace.UI.Popup.IFrameContent');

MySpace.UI.DefaultButton=function(){throw "Cannot instantiate static class.";}

var $defBtn=MySpace.UI.DefaultButton.render=function(el, cssClass){
	if(el.parentNode && Sys.UI.DomElement.containsCssClass(el.parentNode, "msDefBtn")){
		// If it's already a DefaultButton, then do nothing.
		return;
	}
	
    var s = document.createElement('span');
    s.className = 'msDefBtn';
    
    if (cssClass) Sys.UI.DomElement.addCssClass(s, cssClass);
    
    el.parentNode.insertBefore(s, el);
    
    MySpace.UI.DefaultButton.attach(el);
    
    s.appendChild(el);
    
    return s;
}

MySpace.UI.DefaultButton.attach=function(el){
    el.hide=function(){this.parentNode.style.display='none';}
    el.show=function(){this.parentNode.style.display='';}
    el.disable=function(){  
                            this.disabled=true;
                            Sys.UI.DomElement.removeCssClass(this.parentNode,"msDefBtn");
                            Sys.UI.DomElement.addCssClass(this.parentNode,"msDefBtnDisabled");
                         }
    el.enable=function(){
                            this.removeAttribute('disabled');
                            Sys.UI.DomElement.removeCssClass(this.parentNode,"msDefBtnDisabled");
                            Sys.UI.DomElement.addCssClass(this.parentNode,"msDefBtn");
                        }
}

MySpace.UI.DefaultButton.attachAll=function(){
    var btns = MySpace.Utils.Selector.query('.msDefBtn input');
    
     for (var i=0;i<btns.length;i++){
        MySpace.UI.DefaultButton.attach(btns[i]);
        if (btns[i].disabled) btns[i].disable();
     }
}

MySpace.UI.DefaultButton.renderAll=function(cssClass){
    // can be added to dom loaded to auto convert all html buttons to default buttons
    var btns = MySpace.Utils.Selector.query('input.msDefBtn, button.msDefBtn');
            
    for (var i=0;i<btns.length;i++){
        $defBtn(btns[i], cssClass);
    }    
}
MySpace.UI.Tooltip = function(element) {
    MySpace.UI.Tooltip.initializeBase(this, [element]);
    this._initUI();
}
MySpace.UI.Tooltip.prototype = {
    _arrowDiv: null,
    _arrowOffsetX: 0,
    _arrowOffsetY: 0,
    _arrowPos: null,
    _autoPos:true,
    _bottomBorder: null,
    _container:null,
    _contentDiv:null,    
    _cssClass:"",
    _hideDelay: 500,
    _hideHandler: null,
    _hover: true,
    _left:null,
    _leftBorder: null,
    _margin: 10,
    _reflect : false,
    _rightBorder: null,
	_showDelay: 0,
	_showHandler: null,
	_theme: 'helper',
	_timerID: 0,
    _tipDiv: null,
    _tipOffsetX: 0,
    _tipOffsetY: 0,
    _tipPos: 'bottomright',
    _top:null,
    _topBorder: null,    
    _width: 0,
    get_arrowOffsetX : function(){return this._arrowOffsetX;},
	set_arrowOffsetX : function(value){this._arrowOffsetX = value;},
	get_arrowOffsetY : function(){return this._arrowOffsetY;},
	set_arrowOffsetY : function(value){this._arrowOffsetY = value;},
    get_arrowPos : function(){return this._arrowPos;},
	set_arrowPos : function(value){this._arrowPos = value;},
	get_autoPos : function(){return this._autoPos;},
	set_autoPos : function(value){this._autoPos = value;},
	get_container: function(){return this._container;},
	set_container: function(value){this._container = value;},
    get_content : function(){return this._contentDiv.innerHTML;},
    set_content : function(value){this._clearContents(); if (typeof(value) === 'object') {this._contentDiv.appendChild(value);} else {this._contentDiv.innerHTML = value;}},
	get_cssClass : function(){return this._cssClass || "";},
	set_cssClass : function(value){this._cssClass = value;},
	get_hideDelay : function(){return this._hideDelay;},
	set_hideDelay : function(value){this._hideDelay = value;},
	get_hover : function(){return this._hover;},
	set_hover : function(value){this._hover = value;},
	get_left : function(){return this._left;},
	set_left : function(value){this._left = value;},
	get_margin : function(){return this._margin;},
	set_margin : function(value){this._margin = value;},
	get_reflect : function(){return this._reflect;},
	set_reflect : function(value){this._reflect = value;},
    get_showDelay : function(){return this._showDelay;},
	set_showDelay : function(value){this._showDelay = value;},
	get_theme : function(){return this._theme;},
	set_theme : function(value){this._theme = value;},
    get_tipDiv : function(){return this._tipDiv;},
	set_tipDiv : function(value){this._tipDiv = value;},
	get_tipOffsetX : function(){return this._tipOffsetX;},
	set_tipOffsetX : function(value){this._tipOffsetX = value;},
	get_tipOffsetY : function(){return this._tipOffsetY;},
	set_tipOffsetY : function(value){this._tipOffsetY = value;},
	get_tipPos : function(){return this._tipPos;},
	set_tipPos : function(value){this._tipPos = value;},
	get_top : function(){return this._top;},
	set_top : function(value){this._top = value;},
	get_width : function(){return this._width;},
	set_width : function(value){this._width = value;},
	_initUI: function() {
	    this._tipDiv = document.createElement("div");
	    this._tipDiv.innerHTML = '<div style="position:absolute"></div><div class="t"><div><div></div></div></div>' +
            '<div class="m"><div id="fhLeftContentBorder" class="fhlborder"></div><div id="fhContent"></div>' +
            '<div id="fhRightContentBorder" class="fhrborder"></div><div class="clear"></div></div><div class="b">' +
            '<div><div></div></div></div>' +
            '<iframe src="javascript:false" scrolling="no" frameborder="0" style="filter:Alpha(opacity=0);position:absolute;top:0px;left:0px;display:none;z-index:1;"><\/iframe>'

	    this._tipDiv.id = 'tooltipdiv';
	    this._tipDiv.className = 'tooltipdiv ' + this.get_cssClass();

	    this._contentDiv = this._tipDiv.childNodes[2].childNodes[1];
	    this._leftBorder = this._tipDiv.childNodes[2].firstChild;
	    this._rightBorder = this._tipDiv.childNodes[2].childNodes[2];
	    this._topBorder = this._tipDiv.childNodes[1];
	    this._bottomBorder = this._tipDiv.childNodes[3];
	}, 
	initialize: function() {		
        this._hideHandler = Function.createDelegate(this,this._delayedHide);
        this._showHandler = Function.createDelegate(this,this._delayedShow);

        // Add the div element to the document
        if (this._hover){
            $addHandler(this._element,"mouseover", this._showHandler);
            $addHandler(this._element,"mouseout", this._hideHandler);
            $addHandler(this._tipDiv,"mouseover", Function.createDelegate(this, this._clearTimerID));
            $addHandler(this._tipDiv,"mouseout", this._hideHandler); 
        }
        
        if (this._getIsFixed())
            this._tipDiv.style.position='fixed';
        
        this._contentDiv.className = this._theme;
            
        this._tipDiv.firstChild.className = this._theme + 'arrow';
        
        if (this._container)
            this._container.appendChild(this._tipDiv);
        else
            document.body.appendChild(this._tipDiv);
        
        this._arrowDiv = this._tipDiv.firstChild;
        if (this._width) this._tipDiv.style.width=this._width+'px';
	},
    _clearContents:function(){
        //clear the contents of the tooltip
        var c = this._contentDiv;
        for(var i=c.childNodes.length-1;i>=0;i--)
            c.removeChild(c.childNodes[i]);
    },
	dispose : function(){
	  $clearHandlers(this._element);
	  
	  if (this._container)
	    this._container.removeChild(this._tipDiv);
	  else
	    document.body.removeChild(this._tipDiv);

	  MySpace.UI.Tooltip.callBaseMethod(this, 'dispose');
	},
	show : function(){
	  this._setPos();
      this._tipDiv.style.display='block';
      this._raiseEvent('visibilityChanged');
    },
    hide : function(){
      this._tipDiv.style.display='none';
      this._raiseEvent('tooltipClosed');
    },
    _clearTimerID: function(){
		if (this._timerID){
			clearTimeout(this._timerID);
			this._timerID = 0;
		}
	},
	_delayedHide: function(e){
		this._clearTimerID();		
		this._timerID = window.setTimeout(Function.createDelegate(this,this.hide),this._hideDelay);
	},
	_delayedShow: function(e){
		this._clearTimerID();		
		this._timerID = window.setTimeout(Function.createDelegate(this,this.show),this._showDelay);
	},
	_raiseEvent : function(evt){
	    var handler = this.get_events().getHandler(evt);
        if(handler) {
            var eventArgs = new Sys.EventArgs();
            handler(this, eventArgs);
        }
	},
	_setTipDivClass: function() {
	    this._tipDiv.className = 'tooltipdiv ' + this.get_cssClass();
	}, 
	_setPos: function() {
	    var tipX=tipY=0;
	    var margin;

	    this._setTipDivClass();
	    this._arrowDiv.className=this._theme+'arrow';
        this._arrowPos=null;

        if (this._rightBorder) this._rightBorder.className = 'fhrborder';
        if (this._leftBorder) this._leftBorder.className = 'fhlborder';
        if (this._topBorder) this._topBorder.className = 't';
        if (this._bottomBorder) this._bottomBorder.className = 'b';
	    
	    var elDim = Sys.UI.DomElement.getBounds(this._element);
	    var tipDims = this._getTipDims();
	    
	    var mode = document.compatMode;
	    var scrollLeft = (mode == 'BackCompat') ? document.body.scrollLeft : document.documentElement.scrollLeft; 
	    var scrollTop = (mode == 'BackCompat') ? document.body.scrollTop : document.documentElement.scrollTop;

	    if (Sys.Browser.agent===Sys.Browser.InternetExplorer && mode != 'BackCompat'){
	        // make sure scroll is from parent not top
	        elDim.x -= scrollLeft;
	        elDim.y -= scrollTop;
	    }
	    if (!this._getIsFixed() && Sys.Browser.agent===Sys.Browser.InternetExplorer){
		    elDim.x += scrollLeft;
            elDim.y += scrollTop;
	    }
	    
	    //if auto pos enabled, calc best position
	    if (this._autoPos) this._setAutoPos(elDim, tipDims);
	    	    
	    var tipStyle = MySpace.UI.getComputedStyle(this._tipDiv);
	    var arrowStyle = MySpace.UI.getComputedStyle(this._arrowDiv);
	    
	    var tipDir = (this._tipPos.indexOf('right') > -1 ? 1 : this._tipPos.indexOf('left') > -1 ? 3 :
	                  this._tipPos.indexOf('top') > -1 ? 4 : 2);

        var tipWidth = tipDims.width;
        if (this._width) tipWidth = this._width;
        
        tipX = elDim.x + elDim.width;
        switch (tipDir) {
            case 2:
                Sys.UI.DomElement.addCssClass(this._arrowDiv, 'top');
                Sys.UI.DomElement.addCssClass(this._tipDiv, 'tooltipbottom');
                break;
            case 3:
                Sys.UI.DomElement.addCssClass(this._arrowDiv, 'right');
                Sys.UI.DomElement.addCssClass(this._tipDiv, 'tooltipleft');
                tipX = elDim.x - tipWidth;

                if (this._rightBorder) this._rightBorder.className = 'fhrborderns';
                if (this._leftBorder) this._leftBorder.className = 'fhlborderws';
                if (this._bottomBorder) this._bottomBorder.className = 'blc';
                if (this._topBorder) this._topBorder.className = 'tlc';
                
                break;
            case 4:
                if (this._bottomBorder) this._bottomBorder.className = 'bc';
                if (this._topBorder) this._topBorder.className = 'tc';
                Sys.UI.DomElement.addCssClass(this._arrowDiv, 'bottom');
                Sys.UI.DomElement.addCssClass(this._tipDiv, 'tooltiptop');
                break;
            default: //right
                Sys.UI.DomElement.addCssClass(this._arrowDiv, 'left');
                Sys.UI.DomElement.addCssClass(this._tipDiv, 'tooltipright');
        }
	    
	    var arrowHeight = arrowStyle.height.replace('px','')-0;
	    var arrowWidth = arrowStyle.width.replace('px','')-0;
        
	    if (this._tipPos.indexOf('bottom') > -1) {
            tipY = (this._tipPos != 'bottom' ? this._reflect ? elDim.y : elDim.y + elDim.height - arrowHeight - this._margin : elDim.y + elDim.height);            
            tipX = (this._tipPos == 'bottom' ? elDim.x - (tipWidth/2) + (elDim.width/2) : tipX);
            this._arrowPos = this._arrowPos||'top';
        }
        else if (this._tipPos.indexOf('top') > -1) {
            tipY = elDim.y - tipDims.height + (this._tipPos != 'top' ? arrowHeight + this._margin : 0);
            tipX = (this._tipPos == 'top' ? elDim.x - (tipWidth/2) + (elDim.width/2) : tipX);
            this._arrowPos = this._arrowPos||'bottom';
        }
        else {
            tipY = elDim.y - (tipDims.height/2) + (elDim.height/2) - (arrowHeight/2); //tip middle pos
            this._arrowPos = this._arrowPos||'middle';
	    }
	    
	    this._tipDiv.style.left = (tipX + this._tipOffsetX) + 'px';
	    this._tipDiv.style.top = (tipY + this._tipOffsetY) + 'px';
        
	    //set arrow position
	    var arrowY,arrowX='';
	    switch(this._arrowPos){
	        case 'bottom':
	            arrowY=(this._tipPos == 'top' ? tipDims.height : tipDims.height - this._margin - arrowHeight);
	            if (this._tipPos == 'top') arrowX = (this._arrowOffsetX + (tipWidth/2) - (arrowWidth/2)) + 'px';
	        break;
	        case 'middle':
	            arrowY=((tipDims.height/2)-(arrowHeight/2));
	            break;
	        default:
	            arrowY=(this._tipPos == 'bottom' ? - arrowHeight : this._margin);
	            if (this._tipPos == 'bottom') arrowX = (this._arrowOffsetX + (tipWidth/2) - (arrowWidth/2)) + 'px';
	    }
	    this._arrowDiv.style.left=arrowX;
	    this._arrowDiv.style.top=(arrowY + this._arrowOffsetY) + 'px';
	    
        var tt_ifrm = this._tipDiv.lastChild;
        tt_ifrm.width = tipWidth+'px';
	    tt_ifrm.height = tipDims.height+'px';
	    tt_ifrm.style.zIndex =  -1;
	    tt_ifrm.style.display = "block";
            
        this._tipDiv.style.height=tipDims.height+'px';
                
        var cBox = MySpace.UI.getContentBox(this._contentDiv);
        
        if (browser.isIE6x && document.compatMode!="BackCompat"){
            cBox.w+=15;
            tipWidth+=11;
        }
	    if (cBox.w == 0 || cBox.w >= tipWidth-10) cBox.w = tipWidth-11;

        this._contentDiv.style.width=cBox.w+'px';
        this._tipDiv.style.width=tipWidth+'px';
        
        if (this._left) this._tipDiv.style.left=this._left+'px';
        if (this._top) this._tipDiv.style.top=this._top+'px';
	},
	_setAutoPos : function(el, tip) {
	    this._clearTimerID();
	    
	    var minX = (typeof(window.pageXOffset) !== 'undefined') ? window.pageXOffset : document.documentElement.scrollLeft;
        var minY = (typeof(window.pageYOffset) !== 'undefined') ? window.pageYOffset : document.documentElement.scrollTop;
        var maxX = (window.innerWidth ? window.innerWidth : document.documentElement.clientWidth);
        var maxY = (window.innerHeight ? window.innerHeight : document.documentElement.clientHeight);
        
        var quadrants = ["topleft","topright","bottomleft","bottomright"];
        
        var quadrant = 3;
        
        // determine the quadrant that the tooltip should appear in
        quadrant = (el.x - tip.width > minX ? 
                    (el.y - minY + tip.height > maxY && el.y - tip.height > minY ? (el.x + el.width + tip.width < maxX ? 2 : 1) : el.x + el.width + tip.width < maxX ? 4 : 3) :
                      (el.y - minY + tip.height > maxY ? 2 : 4));
                              
        this._tipPos = quadrants[quadrant-1];
	},
	_getTipDims : function() {
	    var tt_ifrm = this._tipDiv.lastChild;
	    tt_ifrm.style.display='none';
    
        this._contentDiv.style.width='';
        this._tipDiv.style.height='';
        this._tipDiv.style.width='';
	    this._tipDiv.style.width=(this._width ? this._width + 'px' : '');
	    this._tipDiv.style.display='block';
	    var tipDim = Sys.UI.DomElement.getBounds(this._tipDiv);
	    if (tipDim.width < 1) tipDim.width = 250;
	    this._tipDiv.style.display='none';
	    return {height:tipDim.height,width:tipDim.width};
	},
	_getIsFixed:function(){
        var position;    
        var parent = this._element.parentNode;
        while (parent!==null) {
            var compStyle = MySpace.UI.getComputedStyle(parent);
            
            if (compStyle) {
                position = compStyle.position;
                
                if (position === 'fixed')
                    return true;
            }
            
            parent = parent.parentNode;
        }
        
        return false;        
    },
	add_tooltipClosed : function(handler){
        this.get_events().addHandler("tooltipClosed", handler);
    },
    remove_tooltipClosed : function(handler){
        this.get_events().removeHandler("tooltipClosed", handler);
    },
    add_visibilityChanged : function(handler){
        this.get_events().addHandler("visibilityChanged", handler);
    },
    remove_visibilityChanged : function(handler){
        this.get_events().removeHandler("visibilityChanged", handler);
    }
}

MySpace.UI.Tooltip.registerClass('MySpace.UI.Tooltip', Sys.UI.Control);

//
// The meat of the QuickPost code is in QuickPostControl.js (not in Global).  This file contains
// wrapper functions to ensure that code has been lazy-loaded before trying to invoke it.
//


// Method that ensures QuickPost is loaded and then calls the callback.  Use this around any
// $create statement for QuickPostPopup or QuickPostInline.
MySpace.UI.addQuickPostScript=function(callback){
	MySpace.UI.addDeferredScript("QuickPost.js", function(){
		if(MySpace.UI._QuickPost.rte){
			MySpace.UI.addDeferredScript("RichTextEditor.js",function(){
				if(typeof callback=="function"){ callback(); }
			});
		}
		else{
			if(typeof callback=="function"){ callback(); }
		}
	});
};


// Set up the handlers for any <ms:QuickPostInline> controls.
MySpace.UI.initQuickPostInline = function() {
		function open(props, evt){
			if(evt && evt.preventDefault){ evt.preventDefault(); }
			
			MySpace.UI.addQuickPostScript(function(){
				MySpace.UI.QuickPostInline.createAndOpen(props);
			});
		}
		
		Array.forEach(MySpace.UI._QuickPost.inlines, function(props) {
			var opener = Function.createPartial(window, open, props),
			    el = $get(props.id),
			    ref = props.jsControlReference;
			    
			if (!el) return;
			
			var textarea = el.getElementsByTagName("textarea")[0];
			
			// If we put the hint text as the default value of the textarea, Firefox overwrites
			// it on a page refresh with the value that the user entered. So set it via JS instead.
			textarea.value = props.textboxTip;
			    
			$addHandler(textarea, "focus", opener);
			$addHandler($q(".msDefBtn", el, true), "click", opener);
			
			if (ref) {
				// Create a shim so the consumer can mess with the control properties even
				// before the user has clicked into it.
				MySpace.Util.setJSValue(ref, {
					set_webServiceParams: function(val) { props.webServiceParams = val; },
					set_textboxTip: function(val) { props.textboxTip = val; },
					set_width: function(val) { props.width = val; },
					set_webServiceUrl: function(val) { props.webServiceUrl = val; },
					reset: function() {}
				});
			}
		});
		
		MySpace.UI._QuickPost.inlines = null;
};

MySpace.UI.ProfileCommentQuickPostPopup = {
	show:function(evt, friendId, ref){
		if(evt && evt.preventDefault){
			evt.preventDefault();
		}
		if (!friendId && evt && evt.target && evt.target.href) {
			var result = evt.target.href.match(/friendid=(\d+)/i);
			if (result && result[1]){
				friendId = parseInt(result[1]);
			}
		}
		MySpace.UI.addQuickPostScript(function(){
			MySpace.UI.ProfileCommentQuickPostPopup.show(null, friendId, ref);
		});
	}
};

MySpace.UI.MessagingQuickPostPopup={
	show:function(evt, recipients, useAutoComplete, ref){
		if(evt && evt.preventDefault){
			evt.preventDefault();
		}
		MySpace.UI.addQuickPostScript(function(){
			MySpace.UI.MessagingQuickPostPopup.show(null, recipients, useAutoComplete, ref);
		});	
	}
};

MySpace.UI.AddFriendPopup = {
	show:function(evt){
		if(evt.preventDefault){
			evt.preventDefault();
		}
		
		evt={friendId:evt.friendId, acctType:evt.acctType, target:evt.target || evt.srcElement};
		
		MySpace.UI.addQuickPostScript(function(){
			if(!Friends.AddToFriendsPopOver.getInstance()){
				$create(Friends.AddToFriendsPopOver, {
					iFrameSrc: MySpace.UI._addFriendPopupUrl,
					id: "globalAddToFriendsPopover"
				}, null, null);
			}
			Friends.AddToFriendsPopOver.getInstance()._invokPopOver(evt);
		});
	},
	
	bind:function(selector){
		var els=MySpace.Utils.Selector.query(selector);
		for(var i=0;i<els.length;i++){
			$addHandler(els[i], "click", MySpace.UI.AddFriendPopup.show);
		}
	}
};

// Hook up the handlers for any AddToFriendsPopOver.ascx instances.
if(MySpace.UI._addFriendPopupSelectors){
	Array.forEach(MySpace.UI._addFriendPopupSelectors, MySpace.UI.AddFriendPopup.bind);
}
Type.registerNamespace("MySpace.Header.Search");
(function() {
	var searchbox = $get("search_q_Header");
	if (searchbox)
		MySpace.Header.Search.ORANGESearchBox = $create(MySpace.UI.DefaultTextboxBehavior, null, null, null, searchbox);
})();
//
// Tracker class for wrapping google analytics pageTracker and allowing the use of several GA accounts
//

MySpace.Tracker = (function() {
	var trackers = {};

	function init(callback) {
		if (typeof _gat === 'undefined') {
			var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
			MySpace.UI.addScript(gaJsHost + 'google-analytics.com/ga.js', "_gat", callback);
		} else {
			callback();
		}
	};

	return {
		initAccount: function(accountNumber) {
			// ensure that the ga.js script is already added to the page
			init(function() {
				var tracker = _gat._getTracker(accountNumber);
				trackers[accountNumber] = tracker;
			});
		},

		setSampleRate: function(accountNumber, rate) {
    		init(function() {
		    if (typeof trackers[accountNumber] === 'undefined') {
		        MySpace.Tracker.initAccount(accountNumber);
		    }
		    var pageTracker = trackers[accountNumber];
		    if (typeof pageTracker !== 'undefined' && typeof pageTracker._setSampleRate === 'function') {
		        pageTracker._setSampleRate(rate);
		    }
		});
		},

		track: function(pageName, accountNumber) {
			// ensure that the ga.js script is already added to the page
			init(function() {
				// check if the tracker already has been initialized for this account
				if (typeof trackers[accountNumber] === 'undefined') {
				    MySpace.Tracker.initAccount(accountNumber);
				}

				var pageTracker = trackers[accountNumber];

				if (typeof pageTracker !== 'undefined' && typeof pageTracker._trackPageview === 'function') {
				    if (pageName == '')
				        pageTracker._trackPageview();
					else pageTracker._trackPageview(pageName);
				}
			});
		},

		// add an onclick handler to track for all elements with the specified CSS class name
		trackClassName: function(className, pageName, accountNumber) {
			// ensure that the ga.js script is already added to the page
			init(function() {
				// check if the tracker already has been initialized for this account
				if (typeof trackers[accountNumber] === 'undefined') {
				    MySpace.Tracker.initAccount(accountNumber);
				}

				// find all of the matching elements to track and add an onclick handler
				var items = $q('a.' + className);
				var trackFunction = function() { MySpace.Tracker.track(pageName, accountNumber); };
				Array.forEach(items, function(item) {
					$addHandler(item, "click", trackFunction);
				});
			});
        },

        trackByAttribute: function(attrId, accountNumber) {
            // ensure that the ga.js script is already added to the page
            init(function() {
                // check if the tracker already has been initialized for this account
                if (typeof trackers[accountNumber] === 'undefined') {
                    MySpace.Tracker.initAccount(accountNumber);
                }

                // find all of the matching elements that contains gaid to track and add an onclick handler
                var items = $q('a[' + attrId + ']');
                Array.forEach(items, function(item) {
                var attrValue = item.getAttribute(attrId);
                $addHandler(item, "click", Function.createPartial(this, MySpace.Tracker.track, attrValue, accountNumber));
                });
            });
        }
	};
})();

