Type.registerNamespace("MySpace.Friends.FriendHelper");
MySpace.Friends.FriendHelper = function() {
    this.baseImgUrl = null;
    this.sendMsgUrl = null;
    this.addFriendUrl = null;
    this.addCommentUrl = null;
	this.borderSize = 5;
	this.minimumWidth = 110;
	this.loading = null;
	this.localCache = {};
	this.hideTimeoutID = null;
	this.hideTimeoutInterval = 2000;
	this.currentFriendId = 0;
	this.toolTipSendMsg = "";
	this.toolTipAddFriend = "";
	this.toolTipAddComment = "";
	this.token = 0;
	this.initialized = false;
	this.CallStatus = {InProgress:1,Completed:2,Error:-1}
	this.delayTimerId = null;
	this.cacheEnabled = false;	
}

MySpace.Friends.FriendHelper.prototype = {
    Initialize : function(baseImgUrl, sendMsgUrl, addFriendUrl, addCommentUrl,baseElementId, ttSend, ttFriends, ttComment, cacheEnabled) {
    
		this.baseImgUrl = baseImgUrl;
		this.sendMsgUrl = sendMsgUrl.replace('%7b','{').replace('%7d','}');
		this.addFriendUrl = addFriendUrl.replace('%7b','{').replace('%7d','}');
		this.addCommentUrl = addCommentUrl.replace('%7b','{').replace('%7d','}');
		this.loading =  baseImgUrl + "loadercircles.gif";
		
		var baseElement = this.hElem = $get(baseElementId);
		MySpace.Friends.FriendHelper.initializeBase(this, [baseElement]);
		
		this.toolTipSendMessage = ttSend;
		this.toolTipAddFriend = ttFriends;
		this.toolTipAddComment = ttComment;
	
		this.tbElem = $get(baseElement.id + "TopBorder");
		this.bbElem = $get(baseElement.id + "BottomBorder");
		
		this.lbPic = $get(baseElement.id + "LeftPictureBorder");
		this.rbPic = $get(baseElement.id + "RightPictureBorder");
		this.Pic = $get(baseElement.id + "Picture");
		this.Spacer = $get(baseElement.id + "Spacer");
		
		this.lbCtnt = $get(baseElement.id + "LeftContentBorder");
		this.rbCtnt = $get(baseElement.id + "RightContentBorder");
		this.Ctnt = $get(baseElement.id + "Content");
		
		this.Buttons = $get(baseElement.id + "Buttons");
		this.lButton = $get(baseElement.id + "LButton");
		this.rButton = $get(baseElement.id + "RButton");
		
		this.msgLink = $get(baseElement.id + "SendMsgLink");
		this.actionLink = $get(baseElement.id + "ActionLink");
		this.actionImg = $get(baseElement.id + "ActionImg");
		
		this.profileLink = $get(baseElement.id + "profileLink");
		this.cacheEnabled = !!cacheEnabled;
		
		var helper = this;
		this.mouseOutHandler = function(evt) {		
					
		    if (helper.GetVisible())
		    {				
		        helper.SetHideTimeout();
		    }
		}
		
		this.mouseOverHandler = function(evt) {			
		    helper.ClearHideTimeout();
		}		

		
		$addHandler(this.hElem, "mouseout", this.mouseOutHandler);
		$addHandler(this.hElem, "mouseover", this.mouseOverHandler);
		
		this.initialized = true;
		
		//Wire up event handlers
		//var friendImgs = this.getElementsByClassName(document,"img","profileimagelink");
		//for(var i=0;i<friendImgs.length;i++)
        //{
            //$addHandlers(friendImgs[i], {mouseover:this.RenderHelper}, this);
        //}	
	},
	
	dispose : function() {
	    $removeHandler(this.hElem, "mouseout", this.mouseOutHandler);
	    $removeHandler(this.hElem, "mouseover", this.mouseOverHandler);
	},	
	
	RenderHelperWithDelay : function(friendElem, userId) 
	{			
		if(!friendHelper.initialized) return;
		
		friendHelper.hElem.style.display = "block";		
		
		if( friendElem.childNodes[2] && friendElem.childNodes[2].tagName == 'A')
		{
			friendHelper.profileLink.href = friendElem.childNodes[2].href;
			if(friendElem.childNodes[2].childNodes[0] && friendElem.childNodes[2].childNodes[0].tagName == 'IMG')
			{
				friendHelper.profileLink.title = friendElem.childNodes[2].childNodes[0].title;
				friendHelper.Spacer.style.height = friendElem.childNodes[2].childNodes[0].offsetHeight + "px";
			}
		}
		//Deleted users do not have profile link.
		else if(friendElem.childNodes[1] && friendElem.childNodes[1].tagName == 'A')
		{			
			friendHelper.profileLink.href = friendElem.childNodes[1].href;
			if(friendElem.childNodes[1].childNodes[0] && friendElem.childNodes[1].childNodes[0].tagName == 'IMG')
			{
				friendHelper.profileLink.title = friendElem.childNodes[1].childNodes[0].title;
				friendHelper.Spacer.style.height = friendElem.childNodes[1].childNodes[0].offsetHeight + "px";	
			}
						
		}
		
	    friendHelper.hideTimeoutID = null; // cancel any previous hide attempt
	    
	    friendHelper.currentFriendId = userId;  // set the current ID to avoid latent callback overwrites
	    
	    friendHelper.msgLink.href = String.format(friendHelper.sendMsgUrl, userId);
	    friendHelper.msgLink.title = friendHelper.toolTipSendMessage;
		friendHelper.WrapHelperAroundElement(friendElem);
		
		
		// TODO: IE has an edge case where mousing off of the image too fast will
		// cause the helper to stay visible, fix it
//		if (typeof(friendElem._events) === 'object' && 
//		    friendElem._events != null && 
//		    friendElem._events["mouseout"] instanceof Array) {
//		
//		    $removeHandler(friendElem, "mouseout", this.friendOutHandler);
//		}
//		$addHandler(friendElem, "mouseout", this.friendOutHandler);
		
		friendHelper.PrepContent();
		
		if(friendHelper.localCache["" + userId] == null) { friendHelper.localCache["" + userId] = {};}
		
		if (friendHelper.localCache["" + userId].state == friendHelper.CallStatus.Completed) {
		    friendHelper.WriteContent(friendHelper.localCache[userId].result);
		    return;
		}		
		
		friendHelper.GetUserInfo(userId, this.cacheEnabled);		
		
	},	
	
	RenderHelper : function(friendElem, userId) 
	{		
		
		friendHelper.delayTimerId = window.setTimeout(function() {friendHelper.RenderHelperWithDelay(friendElem, userId)},250);				
	},
	
	CancelHelper : function(friendElem, userId)
	{
		window.clearTimeout(friendHelper.delayTimerId);
	},
	
	GetUserInfo : function(userId, cachedCall)
	{
		if(friendHelper.localCache["" + userId].state != friendHelper.CallStatus.InProgress)
		{
			friendHelper.localCache["" + userId] = {state:friendHelper.CallStatus.InProgress};
			var friendHelprWS = cachedCall ? MySpace.Web.Modules.Friends.Services.FriendsService.GetFriendHelperDataNoPost : MySpace.Web.Modules.Friends.Services.FriendsService.GetFriendHelperData;
			friendHelprWS(userId, friendHelper.RenderCallback, friendHelper.RenderFailure, this);		    
		}
		
	},
	RenderCallback : function(result, userContext, methodName) {
		userContext.localCache["" + result.FriendId].state = userContext.CallStatus.Completed;
	    userContext.localCache["" + result.FriendId].result = result;
	    
	    // if a latent callback comes in and tries to overwrite the data
	    // ignore it
	    if (userContext.currentFriendId != result.FriendId)
	        return;
	    
	    userContext.WriteContent(result);
	},
	
	RenderFailure : function(error, userContext, methodName) {		
	    //alert(error.get_exceptionType() + "\n" + error.get_message() + "\n" + error.get_stackTrace());
	    if(error.get_statusCode() == 404 && methodName == "GetFriendHelperDataNoPost")
	    {
			userContext.localCache["" + userContext.currentFriendId].state = userContext.CallStatus.Error;
			userContext.GetUserInfo(userContext.currentFriendId, false);
	    }
	},
	
	HideFriendHelper : function() {
	    this.SetVisible(false);
	    this.ClearHideTimeout();
	},
	
	SetHideTimeout : function() {
	    if (this.hideTimeoutID == null) {
	        var helper = this;
	        this.hideTimeoutID = window.setTimeout(function() {
	            if (helper.hideTimeoutID != null)
	                helper.HideFriendHelper();
	        }, this.hideTimoutInterval);
	    }
	},
	
	ClearHideTimeout : function() {
	    if (this.hideTimeoutID != null) {
	        window.clearTimeout(this.hideTimoutID);
	        this.hideTimeoutID = null;
	    }
	},
	
	ResetHideTimeout : function(evt) {
	    this.ClearHideTimeout();
	    this.SetHideTimeout();
	},
	
	WrapHelperAroundElement : function(elem) {
		this.SetVisible(false);
		var pos = this.getElementPos(elem);	
		
		var dim = this.getElementDimensions(elem);

		var offset = this.SizeHelperWindow(dim);
		this.SetPosition(pos, offset);
		
		this.SetVisible(true);
	},
	
	SetPosition : function(pos, offset) {
		this.hElem.style.top = (pos.y - offset.y + 4) + "px";
		this.hElem.style.left = (pos.x - offset.x) + "px";
	},
	
	SizeHelperWindow : function(dim) {
		var baseWidth = dim.width;
		if (dim.width < this.minimumWidth) {
			dim.width = this.minimumWidth;
		}
		
		this.tbElem.style.width = dim.width + "px";
		this.bbElem.style.width = dim.width + "px";
		
		this.Pic.style.width = dim.width + "px";
		
		var paddingSize = 0;
		
		if (baseWidth < dim.width) {
			paddingSize = (dim.width - baseWidth) / 2;
			this.Pic.style.borderRight = 
				this.Pic.style.borderLeft = "solid " + paddingSize + "px #ffffff";
			
			this.Pic.style.width = baseWidth + "px";
		}
		
		this.Ctnt.style.width = dim.width + "px";		
		this.Buttons.style.width = dim.width + "px";
		var bWidth = (dim.width - 5) / 2;
		this.lButton.style.width = 
			this.rButton.style.width = bWidth + "px";
		
		var picheight = dim.height - 5;
		this.Pic.style.height = picheight + "px";
		this.Spacer.style.height = (picheight+10) + "px";
		this.lbPic.style.height = (picheight+12) + "px";
		this.rbPic.style.height = (picheight+12) + "px";
		
		this.Ctnt.style.height = 
			this.lbCtnt.style.height = 
			this.rbCtnt.style.height = "21px";
			
		this.hElem.style.width = ((this.borderSize * 2) + dim.width) + "px";
				
		return { x: this.borderSize + paddingSize, y: this.borderSize };
	},
	
	PrepContent : function() {
		this.Ctnt.innerHTML = "<center><img src=\"" + this.loading + "\" /></center>";
		this.Ctnt.style.height = "21px";
		this.actionImg.src = this.baseImgUrl + "spacer.gif";
		
	},
	
	WriteContent : function(data) {
		
		if (data.IsFriend) {
			this.actionImg.src = this.baseImgUrl + "fh_addcomment.gif";
			this.actionLink.href = String.format(this.addCommentUrl, data.FriendId);
			this.actionImg.alt = this.toolTipAddComment;
			this.actionLink.title = this.toolTipAddComment;
		} else {
			this.actionImg.src = this.baseImgUrl + "fh_addfriend.gif";
			this.actionLink.href = String.format(this.addFriendUrl, data.FriendId);
			this.actionImg.alt = this.toolTipAddFriend;
			this.actionLink.title = this.toolTipAddFriend;
		}
		
		// measure the text in a div -- works in firefox, not in IE
		var div = document.createElement("div");
		div.style.visibility = "hidden";
		div.style.width = this.tbElem.style.width;
		div.className = this.Ctnt.className;
		div.innerHTML = "<br />" + data.DisplayText + "<br />";
		
		document.body.appendChild(div);
		var dim = this.getElementDimensions(div);
		
		this.lbCtnt.style.height = 
			this.rbCtnt.style.height = 
			this.Ctnt.style.height = dim.height + "px";
		
		this.Ctnt.innerHTML = "<br />" + data.DisplayText + "<br />";
		
		// measure the text in the content area - works in IE
		var dim = this.getElementDimensions(this.Ctnt);
		this.lbCtnt.style.height = 
			this.rbCtnt.style.height = 
			this.Ctnt.style.height = dim.height + "px";
		
		document.body.removeChild(div);
		div = null;
	},
	
	SetVisible : function(on) {
		if (on) {
			this.hElem.style.visibility = "visible";
			
		} else {
			this.hElem.style.visibility = "hidden";
		
		}
	},
	
	GetVisible : function() {
	    return (this.hElem.style.visibility == "visible");
	},
	
	getElementPos : function(elem) {
        var pos = { x: 0, y: 0 };
        
        var e = elem;
        
        if (e == null)
            return pos;
            
        pos.x = e.offsetLeft;
        pos.y = e.offsetTop;
        
        e = e.offsetParent;
        
        while(e != null) {
            pos.x += e.offsetLeft;
            pos.y += e.offsetTop;
            e = e.offsetParent;
        }
        
        return pos;
    },
	
	getElementDimensions : function(elem) {
		var dimensions = { width: 0, height: 0 };
		
		if (elem == null)
		 return dimensions;
		
		if (elem.clientWidth > 0) {
		    dimensions.width = elem.clientWidth + 4;
		} else {
		    dimensions.width = elem.offsetWidth + 4;
		}
		
		if (elem.clientHeight > 0) {
		    dimensions.height = elem.clientHeight;
		} else {
		    dimensions.height = elem.offsetHeight;
		}
		
		return dimensions;
	},
	
	getElementsByClassName : function(parent, tagName, className)
	{
	    var classEls = new Array();
	    if(parent)
	    {	        
	        var allEls = parent.getElementsByTagName(tagName);
	        for(var i=0;i<allEls.length;i++)
	        {
	            if(allEls[i].className.indexOf(className) != -1)
	            {
	                Array.add(classEls, allEls[i]);
	            }
	        }
	    }
	    return classEls;
	}
}

MySpace.Friends.FriendHelper.registerClass('MySpace.Friends.FriendHelper', Sys.UI.Control);
//Singleton Object
var friendHelper = new MySpace.Friends.FriendHelper();
