var loginWindow; //for the popup window to login

$(document).ready(function() {
    if (window.name == "loginWindow") {
        window.opener.location.href=window.location.href;
        window.close();
    }
    
    $("#login_LoginLink").click(function() {
        loginWindow = window.open($(this).attr("href"),'loginWindow','left=20,top=20,width=770,height=350,toolbar=1,resizable=1');
        
        return false;
    });
    
    $("#login_LogOutLink").click(function() {
    	$.ajax({
            type: 'POST', 
            url: 'http://twubs.com/ajax360/10229-4325376/',
            data: 'do=logout',
            success: function (data) {
                window.location = '';
            }
        });
    });
});

$(document).ready(function() {
    $("#widgetNavigator_title_tweets").click(function() {
        window.location = 'tweets';
    });
});
$(document).ready(function() {
    $("#widgetNavigator_title_media").click(function() {
        window.location = 'media';
    });
});
$(document).ready(function() {
    $("#widgetNavigator_title_members").click(function() {
        window.location = 'members';
    });
});
$(document).ready(function() {
    $("#widgetNavigator_title_info").click(function() {
        window.location = 'info';
    });
});
$(document).ready(function() {
	$("#10231_917504").unbind('Update').bind('Update', function(e, data) {
	    var parts = data.split("<<<embedpageseperator>>>");
	    $('#' + $(this).attr("id") + '_head').empty().html(parts[0]);
	    $('#' + $(this).attr("id") + '_body').empty().html(parts[1]);
	});
});

function TweetThisTwub(setPrefix) {
    // Set our module prefix
    this.prefix = setPrefix;
    
    // For uploading images -- if the user asked for a submit, we must wait for the image to finish, and then we need to submit the comment
    this.submit = false;
    this.sending = false; // Are we in the middle of sending already
    
    // Grab our DOM elements
    this.$form = $("#" + this.prefix + "tweetThisTwub");
    this.$charsLeft = $("#" + this.prefix + "charsLeft", this.$form);
    this.$contain = $("#" + this.prefix + "attachItemsContainer");
    
    this.$twubField = $("#" + this.prefix + "twub", this.$form);
    this.$replyStatusID = $("#" + this.prefix + "replyStatusID", this.$form);
    this.$textArea = $("#" + this.prefix + "textArea", this.$form);
    this.$sendTweet = $("#" + this.prefix + "sendTweet", this.$container);
    this.$sendTweetSpinner = $("#" + this.prefix + "sendTweetSpinner", this.$container);
    
    this.$previewContainer = $("#" + this.prefix + "previewContainer", this.$form);
    this.$previewText = $("#" + this.prefix + "previewText", this.$form);
    this.$previewItems = $("#" + this.prefix + "previewItems", this.$form);
    
    this.$attachPhoto = $("#" + this.prefix + "attachPhoto", this.$contain);
    this.$attachVideo = $("#" + this.prefix + "attachVideo", this.$contain);
    this.$attachLink = $("#" + this.prefix + "attachLink", this.$contain);
    
    this.$attachPhotoContainer = $("#" + this.prefix + "attachPhotoContainer", this.$contain);
    this.$attachVideoContainer = $("#" + this.prefix + "attachVideoContainer", this.$contain);
    this.$attachLinkContainer = $("#" + this.prefix + "attachLinkContainer", this.$contain);
    
    this.$attachmentInfo = $("#" + this.prefix + "attachmentInfo", this.$contain);
    
    // Grab any initial fields from the DOM elements
    this.twub = this.$twubField.val();
    
    // Bind our events
            this.$textArea.unbind('keyup').bind('keyup', {'ttt':this}, this.disable);
        this.$textArea.unbind('focus').bind('focus', {'ttt':this}, this.disable);
        
        this.$attachPhoto.unbind('click').bind('click', {'ttt':this}, this.disable);
        this.$attachVideo.unbind('click').bind('click', {'ttt':this}, this.disable);
        this.$attachLink.unbind('click').bind('click', {'ttt':this}, this.disable);
    
    // Initialize our items to nothing
    this.items = [];
    this.defaultItems = [];
}

TweetThisTwub.prototype = {
    update:function(e) {
        if(e != null && e.data != null && e.data.ttt != null) {
            var ttt = e.data.ttt;
        } else {
            var ttt = this;
        }
                
        ttt.openPreview();
        
        // Grab the tweet from the text area
        var tweet = ttt.$textArea.val();
        
        // Update the preview text
        ttt.$previewText.text(tweet);
        
        // Update the character count
        var charsLeft = 140 - tweet.length;
        
                
        // Update the characters left
        ttt.$charsLeft.text(charsLeft);
        
        // Change the color if we get close to the end
        ttt.$charsLeft.removeClass('charLimitNotice').removeClass('charLimitWarning');
        ttt.$sendTweet.removeClass('grayButtonDisabled');
        
        if(charsLeft < 0) {
            ttt.$sendTweet.addClass('grayButtonDisabled');
        }
        

        if(charsLeft < 10) { 
    	    ttt.$charsLeft.addClass('charLimitWarning'); 
    	} else if(charsLeft < 20) {
    	    ttt.$charsLeft.addClass('charLimitNotice');
    	}
    	
    	if (ttt.submit)
            ttt.$sendTweet.click();
        
    },
    disable:function(e) {
        if(e != null) {
            var ttt = e.data.ttt;
        } else {
            var ttt = this;
        }
        
        ttt.$textArea.attr("disabled", true).val('Please sign in...');
    	ttt.$sendTweet.addClass('grayButtonDisabled').find('.grayButtonContent').text('Please sign in');
    	
    	ttt.$attachPhoto.find("a").css("color", "#A0A0A0");
    	ttt.$attachVideo.find("a").css("color", "#A0A0A0");
    	ttt.$attachLink.find("a").css("color", "#A0A0A0");
    },
    sendTweet:function(e) {
        var ttt = e.data.ttt;
        
        // Already trying to send
        if(ttt.sending) { return; }
        
            
                ttt.disable();
        return;
                
        if (ttt.$attachLinkContainer.css("display") == "block") {
            ttt.submit = true;
            ttt.tryAttachLink(e);
            return false;
        }
        if (ttt.$attachVideoContainer.css("display") == "block") {
            ttt.submit = true;
            ttt.tryAttachVideo(e);
            return false;
        }
        //need to wait for upload to finish before continuing...this call is async
        if (ttt.$attachPhotoContainer.css("display") == "block") {
            ttt.submit = true;
            ttt.$attachPhotoContainer.find("form").submit();
            return false;
        }
        
        // Grab the status
    	var status = ttt.$textArea.val();
    	
    	// Check for an empty
    	if(status.length == 0 && !confirm("Are you sure you want to send a Tweet with an empty message?")) {
    	    return false;
    	}
    	
    	// Loop through the items and add their text
    	    	
    	if(status.length > 140) {
    	    alert("Your update is over 140 characters and was not submitted.");
    	    return false;
    	}
    	
    	ttt.sending = true;
        ttt.$sendTweet.addClass("grayButtonDisabled");
        ttt.$sendTweetSpinner.show();
    	
    	var replyStatusID = ttt.$replyStatusID.val();
    	
    	var ajaxOptions = {
    	    'url': 'http://twubs.com/ajax360/10234-1966080/sendTweet',
    	    'type': 'post',
    	    'dataType':'json',
    	    'data': {
        	    'func': 'sendTweet',
        	    'replyStatusID': replyStatusID,
        	    'status': status
    	    },
    	    'complete':function() {
    	        ttt.sending = false;
                ttt.$sendTweet.removeClass("grayButtonDisabled");
                ttt.$sendTweetSpinner.hide();
    	    },
    	    'success':function(data) {
    	        switch(data.results) {
    	            case 'success':
    	                ttt.resetForm();  	                   
    	                ttt.setAttachmentInfo('<div class="successBox" style="margin:5px 0;">Your Tweet was posted successfully and will show up in the feed shortly.</div>');
    	                
    	                    	                
    	                break;
    	            case 'message':
    	                ttt.setAttachmentInfo('<div class="errorBox" style="margin:5px 0;">' + data.message + ' Perhaps Twitter is not responding :(</div>');
    	                break;
    	        }
    	    }
    	};
    	
    	ttt.submit = false;
    	
        $.ajax(ajaxOptions);
        return false;
    },
    reply:function(username, statusID, mode) {
        window.location.hash = this.prefix;

        var prefixChar = '@';
        switch (mode) {
    	    case 'RT':
    	    case 'DM':
    	    	prefixChar = '';
    	    	break;
    	    default:
    	    	prefixChar = '@';
        		break;
        }

        this.$textArea.val(prefixChar + username).focus();
        this.$replyStatusID.val(statusID);
        
        this.items = this.defaultItems.slice();
        this.redrawItems();
        
        this.update();
    },
    preload:function(text) {
        window.location.hash = '#';
        
        this.$textArea.val(text).focus();
        
        this.flash();
        this.update();
    },
    flash:function() {
        var ttt = this.$textArea;
        
        ttt.animate({ backgroundColor: "#ffebc6" }, 1200, 'linear', function() {
        	ttt.animate({ backgroundColor: "#ffffff" }, 1200)
        });
    },
    resetForm:function() {
        this.$textArea.val('');
        this.$replyStatusID.val('');
        
        this.items = this.defaultItems.slice();
        this.redrawItems();
        
                
        this.update();
    },
    clearDefaultItems:function() {
        this.defaultItems = [];
    },
    attachPhoto:function(e) {
        var ttt = e.data.ttt;
        
        ttt.openPreview();
                
        // Hide all the attachment containers and show this one
        ttt.hideAttachments();
        ttt.$attachPhotoContainer.show();
        
    },
    attachVideo:function(e) {
        var ttt = e.data.ttt;
        
        ttt.openPreview();
        
        // Hide all the attachment containers and show this one
        ttt.hideAttachments();
        ttt.$attachVideoContainer.show();
    },
    tryAttachVideo:function(e) {
        var ttt = e.data.ttt;
        
        var ajaxOptions = {
            'url':'http://twubs.com/ajax360/10234-1966080/attachVideo',
            'type':'post',
            'dataType':'json',
            'data':{
                'videoURL':$('#' + ttt.prefix + 'videoURL').val()
            },
            'success':function(data) {
                
                ttt.setAttachmentInfo(data.message);
                
                if(parseInt(data.success) > 0) {
                    ttt.prependItem('video', data.shortURL);
                    ttt.hideAttachments();
                    ttt.update();
                }
            }
        }
        
        $.ajax(ajaxOptions);
    },
    attachLink:function(e) {
        var ttt = e.data.ttt;
        
        ttt.openPreview();
        
        // Hide all the attachment containers and show this one
        ttt.hideAttachments();
        ttt.$attachLinkContainer.show();
    },
    tryAttachLink:function(e) {
        var ttt = e.data.ttt;
        
        var ajaxOptions = {
            'url':'http://twubs.com/ajax360/10234-1966080/attachLink',
            'type':'post',
            'dataType':'json',
            'data':{
                'linkURL':$('#' + ttt.prefix + 'linkURL').val()
            },
            'success':function(data) {
                
                ttt.setAttachmentInfo(data.message);
                
                if(parseInt(data.success) > 0) {
                    ttt.prependItem('video', data.shortURL);
                    ttt.hideAttachments();
                    ttt.update();
                }
            }
        }
        
        $.ajax(ajaxOptions);
    },
    hideAttachments:function(e) {
        if(e != null) {
            var ttt = e.data.ttt;
        } else {
            var ttt = this;
        }
        
        // Hide the photo container
        ttt.$attachPhotoContainer.hide();
        // Reset the photo frame source if we need to
        $("#tweetTwubReplyBox_attachPhotoContainerForm").html($.ajax({
                url: "http://twubs.com/ajax360/10234-1966080/attachPhoto?prefix=tweetTwubReplyBox_",
                async: false,
                success: function() {
                    $(document).trigger("ttt.photoFormDone");
                }
            }).responseText
        );
        
        // Hide the video container and reset the text field
        ttt.$attachVideoContainer.hide();
        $('#' + ttt.prefix + 'videoURL').val('');
        
        // Hide the link container and reset the text field
        ttt.$attachLinkContainer.hide();
        $('#' + ttt.prefix + 'linkURL').val('');
    }, 
    setAttachmentInfo:function(info) {
        this.$attachmentInfo.html(info);
        setTimeout(this.prefix + "tweetThisTwub.resetAttachmentInfo();", 5000);
    },
    resetAttachmentInfo:function() {
        var ttt = this;
    
        ttt.$attachmentInfo.children().slideUp('normal', function() {
            ttt.$attachmentInfo.children().remove();
        });
    },
    openPreview:function() {
    
        $("#tweetTwubReplyBox_showTweetThisTwub").hide();
        $("#tweetTwubReplyBox_tweetThisTwub").show();
        $("#tweetTwubReplyBox_attachItemsContainer").show();
        
        // If the preview container is hidden, slide it down
        if(this.$previewContainer.css('display') == 'none') {
            this.$previewContainer.slideDown();
        }
    },
    appendItem:function(type, text, data) {
        if(data == null) {
            data = {};
        }
        
        // Create the new item
        var newItem = new TweetThisTwub.Item(this, type, text, data);
        
        
        // Find where we should insert the item.
        if(this.items.length > 0 && this.items[this.items.length - 1].type == 'twubLink') {
            // If the last item is a twub link, add the item before it
            var spliceIndex = this.items.length - 1;
        } else {
            // else add it to the end
            var spliceIndex = this.items.length;
        }
        
        // Add the new item at the correct location
        this.items.splice(spliceIndex, 0, newItem);
        
        // Redraw the items
            },
    prependItem:function(type, text, data) {
        if(data == null) {
            data = {};
        }
    
        // Create the new item
        var newItem = new TweetThisTwub.Item(this, type, text, data);
        
        // Add the new item at the beginning
        this.items.splice(0, 0, newItem);
        
        // Redraw the items
        this.redrawItems();
    },
    redrawItems:function() {
        // Clear out any existing items
        this.$previewItems.html("");
        
        // Redraw each item in sequence
        $.each(this.items, function() {
            this.draw();
        });
    },
    saveDefaultItems:function() {
        this.defaultItems = this.items.slice();
    }
};

TweetThisTwub.Item = function(setTTT, setType, setText, setData) {
    // Set the basic information
    this.ttt = setTTT;
    this.type = setType;
    this.text = setText;
    this.data = setData;
}

TweetThisTwub.Item.prototype = {
    draw:function() {
                this.ttt.$textArea.val(this.ttt.$textArea.val() + " " + this.text);
            },
    deleteItem:function(e) {
    
        var item = e.data.item;
        
        // Find the reference to this node in the parent items array
        var itemIndex = -1;
        
        $.each(item.ttt.items, function(i) {
            if(this == item) {
                itemIndex = i;
                return false;
            }
        });
                
        // If we found it remove it from the array and redraw
        if(itemIndex > -1) {
            item.ttt.items.splice(itemIndex, 1);
            item.ttt.redrawItems();
            item.ttt.update();
        }
    }
};


var tweetTwubReplyBox_tweetThisTwub;
$(document).ready(function() {

    $("#tweetTwubReplyBox_showTweetThisTwub").click(function() {
        tweetTwubReplyBox_tweetThisTwub.openPreview();
    });

    tweetTwubReplyBox_tweetThisTwub = new TweetThisTwub("tweetTwubReplyBox_");

    tweetTwubReplyBox_tweetThisTwub.$textArea.val("");

        tweetTwubReplyBox_tweetThisTwub.appendItem("hashtag", "#hr", null);
        tweetTwubReplyBox_tweetThisTwub.saveDefaultItems();
    tweetTwubReplyBox_tweetThisTwub.redrawItems();
    });



$(document).ready(function() {
    _mainFeed_setEventHandlers()
    
    //Set automatic refreshing of feed every minute
    setInterval('$(".TwitterFeed").trigger("refreshFeed", [0]);', 45000);
});

function _mainFeed_setEventHandlers() {
	$("#mainFeed_twitterfeed").unbind('refreshFeed').bind('refreshFeed', function(event, updateFeed){
		var maxtime = $("#mainFeed_twitterfeed #mainFeed_tfw_maxtime").attr("value");
		var filter = $("#mainFeed_twitterfeed #mainFeed_tfw_filter").attr("value");

		if(updateFeed == null || updateFeed == 0) {
		    updateFeed = 0;
		} else {
		    updateFeed = 1;
		}
		
		//Refresh my feed content
		$.post(
				"http://twubs.com/ajax360/10235-2097152/?embedded=1", 
				{ 
					'func': "refreshFeed",
					'twub': '#hr',
                    'feedid': '951-2695168',
					'maxtime': maxtime, 
					'updateFeed':updateFeed, 
					'filter': filter
				}, 
				function(data){
					var objTweetList = $("#mainFeed_twitterfeed ul.Tweets");
					objTweetList.css({'height': objTweetList.innerHeight() + 'px', 'overflow' : 'hidden'});
			    	objTweetList.prepend(data.results);
			    	var calcHeight = 0;
			    	objTweetList.find("li").each(function(){calcHeight += $(this).innerHeight() + 1;});
			    	objTweetList.animate({'height': calcHeight + 'px'}, 1000);
			    	
			    	//Set maxtime to new time
			    	if (data.results != "") {
			    		$("#mainFeed_twitterfeed #mainFeed_tfw_maxtime").attr("value", data.maxTime)
			    	}
			    	
			    	//Rebind event handlers
			    	_mainFeed_setFeedPageEventHandlers()
				}
				, "json");
			    	
    	//Cancel default action
		return false;
		
	});
	
    $("#mainFeed_twitterfeed #more").unbind('click').click(function(){
		var nextmaxtime = $("#mainFeed_twitterfeed #mainFeed_tfw_nextmaxtime").attr("value");
		var filter = $("#mainFeed_twitterfeed #mainFeed_tfw_filter").attr("value");
		
		var params = {
		    'func': "getPage", 
		    'maxtime': nextmaxtime, 
		    'twub': '#hr',
            'feedid': '951-2695168',
		    'filter': filter
		};
		
		$.post("http://twubs.com/ajax360/10235-2097152/?embedded=1", params, function(data) {
			// if (data.nextMaxTime != 0) $("#mainFeed_twitterfeed #pagination #more").attr("href", data.nextPageURL);
			// if (data.nextPageURL == '?') $("#mainFeed_twitterfeed #pagination").slideUp();
			var objTweetList = $("#mainFeed_twitterfeed ul.Tweets");
			objTweetList.css({'height': objTweetList.innerHeight() + 'px', 'overflow' : 'hidden'});
	    	objTweetList.append(data.results);
	    	var calcHeight = 0;
	    	objTweetList.find("li").each(function(){calcHeight += $(this).innerHeight() + 1;});
	    	objTweetList.animate({'height': calcHeight + 'px'}, 1000);
	    	
            if (data.nextMaxTime == '') {
                $("#mainFeed_twitterfeed #more").hide();
            }
            $("#mainFeed_twitterfeed #mainFeed_tfw_nextmaxtime").attr("value", data.nextMaxTime)
            
	    	//Rebind event handlers
	    	_mainFeed_setFeedPageEventHandlers()
		}
		, "json");
	    	
    	//Cancel default action
		return false;
    });
}




$(document).ready(function() {
    _mainFeed_setFeedPageEventHandlers()
});

function _mainFeed_limitChars(textid, limit) {
	var text = $('#'+ textid).val(); 
	var textlength = text.length;
	if(textlength > limit) {
		alert('Reply is limited to '+ limit + ' characters.');
		$('#' + textid).val(text.substr(0,limit));
		return false;
	}
	
	return true;	
}

function _mainFeed_setFeedPageEventHandlers() {
	$("#mainFeed_twitterfeed .litnv:not(.pleaseLogIn):not(.RT)").unbind('click').click(function() {
    	var paramString = $(this).attr('href').split("?")[1];
    	var paramParts = paramString.split("&");
    	var keyValues = new Array();
    	var parts;
    	
    	for(var i=0; i < paramParts.length; i++) {
    		parts = paramParts[i].split("=");
    		keyValues[(parts[0])] = parts[1];
    	}
    	
    	var username = keyValues['status'].substring(1, keyValues['status'].indexOf('%20')) + ' ';
    	var statusID = keyValues['in_reply_to_status_id'];
    	
    	tweetTwubReplyBox_tweetThisTwub.reply(username, statusID, 'R');
    	
    	return false;
    	    	
    	//Create a small form with a textbox for sending a tweet
    	if ($(this).closest("li").find(".replyBox").length == 0) {
    		$(this).closest("div").after("<div class=\"replyBox\">"+
    			"<form action=\"http://twubs.com/ajax360/10235-2097152/\" method=\"post\">" +
    				"<input type=\"hidden\" id=\"reply_to_id\" name=\"reply_to_id\" value=\"" + keyValues['in_reply_to_status_id'] + "\"/>" +
    				"<textarea id=\"status_" + keyValues['in_reply_to_status_id']+ "\" name=\"status\" rows=\"2\" cols=\"40\">" + keyValues['status'].replace(/%20/ig, ' ').replace(/%23/ig, '#') + "</textarea>" +
    				"<input type=\"submit\" id=\"sendTweet\" name=\"sendTweet\" value=\"Reply\"/>" +
    			"</form>" +
    		"</div>");
    		
    		//Start as hidden
    		$(this).closest("li").find(".replyBox").hide();
    		
    		//Set events for new items
    		_mainFeed_setFeedPageEventHandlers();
    	} else {
    		$(this).closest("li").find(".replyBox #status_" + keyValues['in_reply_to_status_id']).text(keyValues['status'].replace(/%20/ig, ' ').replace(/%23/ig, '#'));
    	}
    	
    	//Limit chars in reply to 140
    	$(this).closest("li").find(".replyBox #status_" + keyValues['in_reply_to_status_id']).keyup(function(){
    		_mainFeed_limitChars('status_' + keyValues['in_reply_to_status_id'], 140);
		});
    	
    	//Get rid of height attribute on UL if set, so slide will expand the box
    	$("#mainFeed_twitterfeed ul.Tweets").css({ 'height' : '' });
    	
		//Make reply box slide down
		$(this).closest("li").find(".replyBox").slideToggle("slow");
		
		//Set focus
		$(this).closest("li").find(".replyBox textarea").focus();
		
    	//Cancel default action
    	return false;
    });
    
    $("#mainFeed_twitterfeed .pleaseLogIn").unbind('click').click(function() {
    	$(this).html("Please Sign In");
    	return false;
    });
    
    $("#mainFeed_twitterfeed .litnv.RT:not(.pleaseLogIn)").unbind('click').click(function() {
    	var paramString = $(this).attr('href').split("?")[1];
    	var paramParts = paramString.split("&");
    	var keyValues = new Array();
    	var parts;
    	
    	for(var i=0; i < paramParts.length; i++) {
    		parts = paramParts[i].split("=");
    		keyValues[(parts[0])] = parts[1];
    	}
    	
    	var r = new RegExp(String.fromCharCode(0), 'g');
    	var message = $.trim($.base64Decode(keyValues['status']).replace(/>/g, '=').replace(r,''));
    	var statusID = keyValues['in_reply_to_status_id'];
    	
    	tweetTwubReplyBox_tweetThisTwub.reply(message, statusID, 'RT');
    	
    	//Cancel default action
    	return false;
    });
    
    $("#mainFeed_twitterfeed .litnv.DM:not(.pleaseLogIn)").unbind('click').click(function() {
    	var paramString = $(this).attr('href').split("?")[1];
    	var paramParts = paramString.split("&");
    	var keyValues = new Array();
    	var parts;
    	
    	for(var i=0; i < paramParts.length; i++) {
    		parts = paramParts[i].split("=");
    		keyValues[(parts[0])] = parts[1];
    	}
    	
    	var message = $.trim(keyValues['status'].replace(/%20/g, ' ')) + ' ';
    	var statusID = keyValues['in_reply_to_status_id'];
    	
    	tweetTwubReplyBox_tweetThisTwub.reply(message, statusID, 'DM');
    	
    	//Cancel default action
    	return false;
    });
    
    $("#mainFeed_twitterfeed #sendTweet").unbind('click').click(function() {
    	var replyToId = $(this).closest("li").find(".replyBox #reply_to_id").attr("value"); 
    	var status = $(this).closest("li").find(".replyBox #status_" + replyToId).val();
    	
		$.post("http://twubs.com/ajax360/10235-2097152/", { 'func': "sendTweet", 'reply_to_id': replyToId, 'status': status }, 
			function(data){
		    	if (data.results == "success") {
		    		$(".replyBox").slideUp("slow");
		    	} else {
		    		alert('Error: Message could not be sent.');
		    	}
			}
			, "json");
	    	
    	//Cancel default action
		return false;
    });
}
$(document).ready(function()
{
    var windowHeight = parseInt($(window).height());
    var scrollHeight = windowHeight - 110;
    
    $("#embed_tab_content_scroll").css('height', scrollHeight + 'px');
});

$(function() {
    hoverHeadshots();
    submitBadHeadshots();
});

//holds the item that is currently being hovered
var hover;

//holds the delay to close something
var hoverout;

//holds a reference to the current object
var _this;

//holds collection of users with bad headshots
var badHeadshots = [];

function hoverHeadshots() {
    $(".TwitterHeadShot").unbind().hover(
        function() {
            //if we are hovering a different headshot...the other window needs to be closed
            //(a hack to close the window if it is left open -- due to the closing delay, if I simply
            //clearTimeout(hoverout), then if I instantly hover on another headshot after I out on 
            //one, the window will stay open because i hovered on another $(".TwitterHeadShot"), and
            //as far as the script is concerned, the window should then remain open, this line stops
            //that behavior)
            if ($("#TwitterHeadShot[username="+$(this).attr("username")+"]").length == 0 && $(".twitterHeadShotInfo").length > 0)
                closeWindow();
            else if ($("#TwitterHeadShot[username="+$(this).attr("username")+"]").length > 0)
                clearTimeout(hoverout);
            
            _this = $(this);
            hover = setTimeout(function(){showInfo(_this);}, 750);
        },
        function() { //de-hover
            //stop any windows from opening when we are not hovering on something
            clearTimeout(hover);
            
            hoverout = setTimeout(function(){
                closeWindow();
            }, 250);
        }
    );
}

function closeWindow() {
    //fade out and remove the info dialog
    $(".twitterHeadshotInfo").fadeOut("fast", function() {
        $(this).remove();
        $(".qtip").remove();
    });
}

function follow(user) {
    $.ajax({
        url: "http://twubs.com/ajax360/63257-5046272/",
        type: "post",
        data: {"action": "follow", "user": user},
        success: function() {
            $(".TwitterHeadshotUserInfo input").hide();
            $(".TwitterHeadshotUserInfo .numFollowers").show();
        }
    });
}

function showInfo(item) {
    //don't show a headshot if one already exists
    if ($("#TwitterHeadShot").length > 0)
        return;
        
    //hover
    guy = $('<div/>').attr("id","TwitterHeadShot").attr("class","twitterHeadshotInfo").attr("username", item.attr("username"));
    guy.append('<div \
            <div id="arrow">&nbsp;</div> \
            <div id="title">'+item.attr("username")+'</div> \
            <div id="content"> \
                <img src="http://static.360hubs.com/images/spinner.gif" style="width: 16px; height: 16px;" /> \
            </div> \
    ');
    
    //add the pop-up box
    item.append(guy);
    
    //get the offset of the headshot
    offset = item.offset();
    
    //make the ajax request for info before we show so it gets a head start
    $.ajax({
        url: "http://twubs.com/ajax360/63257-5046272/",
        type: "post",
        data: {"action": "userInfo", "user": item.attr("rel")},
        success: function(data) {
            display = $(data);
            display.hide();
            guy.find("#content").html(display);
            display.slideDown("medium");
            
            guy.find(".twubTip").each(function() {
                var title = $(this).attr("title");
                var body = $(this).attr("rel");
                
                //make browser tooltips not show up
                $(this).attr("title", "").attr("rel", "");
                
                $(this).unbind().qtip({
                    show: 'mouseover',
                    hide: 'mouseout',
                    content: {
                        text: body,
                        title: {
                            text: title
                        }
                    },
                    position: {
                        adjust: {
                            y: -10,
                            x: 10
                        }
                    },
                    style: {
                        border: {
                            width: 5
                        },
                        tip: {
                            corner: 'leftTop'
                        },
                        name: 'blue',
                        width: 250
                    }
                });
            });
            
            $.ajax({
                url: "http://twubs.com/ajax360/63257-5046272/",
                type: "post",
                data: {"action": "posts", "user": display.attr("rel")},
                success: function(data) {
                    recentTweets = $(data);
                    recentTweets.hide();
                    display.find("#posts #content").html(recentTweets);
                    recentTweets.slideDown("medium");
                }
            });
        }
    });
    
    //fade in the info dialog
    guy
        .css("top", offset.top)
        .css("left", offset.left + item.outerWidth())
        .fadeIn("fast")
    ;
}

function noteBadHeadshot(item) {
    badHeadshots.push(item.closest(".TwitterHeadShot").attr('username'));
}

function submitBadHeadshots() {
    // wait a bit to give page load a chance to fail loading headshots
    setTimeout(
        function() {
            if (badHeadshots.length > 0) {
                $.ajax({
                    url: "http://twubs.com/ajax360/63257-5046272/",
                    type: "post",
                    data: {"action": "updateHeadshots", "userList": ""+badHeadshots}
                })
            }
        },
        5000
    );
}