var $j = jQuery.noConflict();

function transformTweet(tweet) {
	// convert hyperlinks
	var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
	var t = tweet.replace(exp, "<a target='_blank' href='$1'>$1</a>");
	
	// convert @ links
	exp = /\B@([_a-z0-9]+)/ig;
	t = t.replace(exp, function(F){return F.charAt(0)+'<a target="_blank" href="http://www.twitter.com/'+F.substring(1)+'">'+F.substring(1)+"</a>"});

	return t;

}
function onError(title, text) {
	var alertDiv = $j("<div></div>");
	alertDiv.attr("title", title);
	alertDiv.append(text);
	alertDiv.dialog({resizable:false, buttons: {"Close" : function() { $j(this).dialog("close"); onLogout();}}});
}
function checkForError(result, title, msg) {
	try {
		var status = result.result;
		if (status != "OK") {
			onError(title, msg);
		}
	} catch (err) {
		onError(title, msg);
	}
}
function alertDialog(title, text) {
	var alertDiv = $j("<div></div>");
	alertDiv.attr("title", title);
	alertDiv.append(text);
	alertDiv.dialog({resizable:false, buttons: {"Close" : function() { $j(this).dialog("close");}}});
}

(function() {
    var r = $j.queryString = {};
    var params = location.search.replace(/^\?/,'').split('&');
    for( var i = params.length-1;  i >= 0;  i-- ) {
       var p = params[i].split('='), key = p[0];
       if( key ) r[key] = p[1];
    }
 })();

function doLogout() {
	if (user != null && user.facebook) {
		FB.Connect.logout(onLogout);
	} else {
		onLogout();
	}
}
function doLogin(url) {
	popLoginDialog("Login using one of the methods below.", function(userId, username, facebook) {
		if (url == null || typeof (url) == 'undefined') {
			window.location.reload(false);
		} else {
			window.location = url;
		}
	});
}
function onNotConnected() {
	FB.FBDebug.dump(user, "NOT Connected");
	// TODO: handle the situation when the user logs out from the comments widget...
}
function handleQuestionTweets(tweets, primary) {
	renderTweets(tweets, "questionTweets", 0, 15, true, true, false, !primary);
	$j("#questionTweets")[0].scrollTop = 0;
	
	if (tweets.results.length >= 15) {
		$j("#questionTweets").append("<div class='seeMore'><a href='http://search.twitter.com/search.html" + tweets.next_page + "' target='_blank'>see more</a></div>");
	}
}
function handleSearchTweets(tweets) {
	cycleTweets(tweets, "fanTweets", 0, 2, 20 * 1000, true, true);
}
function cycleTweets(tweets, destId, startIndex, numTweets, cycleRate, includeAvatar, includeAuthor) {
	if (tweets != null) {
		
		if (startIndex >= tweets.results.length) {
			startIndex = 0;
		}
		var endIndex = startIndex + numTweets - 1;
		if (endIndex >= tweets.results.length) {
			endIndex = tweets.results.length - 1;
		}
		renderTweets(tweets, destId, startIndex, endIndex, includeAvatar, includeAuthor, true, true);
	}
	var newstart = endIndex + 1;
	setTimeout(function() { cycleTweets(tweets, destId, newstart, numTweets, cycleRate, includeAvatar, includeAuthor) }, cycleRate);
}
function renderTweets(tweets, destId, start, end, includeAvatar, includeAuthor, clear, append) {
	var A=[];
	C = tweets.results;
	for(var D=start;D<C.length && D<=end;D++){
		var E=C[D].from_user;
		var B=transformTweet(C[D].text);
		var F="http://twitter.com/" + E;
		var G = "<div class='widgetTweetWrapper";
		G += "'>";
		var H = F + "/statuses/" + C[D].id;
		if (includeAvatar) {
			G += "<span class='avatar'><a href='" + F + "' target='_blank'><img src='" + C[D].profile_image_url + "'/></a></span> ";
		}
		G += "<span class='tweet'><span class='widgetTweetText'>"
		if (includeAuthor) {
			G += "<span class='tweeter'><a href='" + F + "' target='_blank'>" + E + "</a>:</span> ";
		}
		G += B + "</span>";
		G += "<span class='tweetInfo'>" + relative_time(C[D].created_at) ;//+ " . <a href='" + H + "' target='_blank'>View Tweet</a>"
		G += "</span>";
		G += "</span><div style='clear:both'></div></div>";

		
		A.push(G);
	}
	var dest = $j("#" + destId);
	if (clear) {
		dest.empty();
	}
	if (append) {
		dest.append(A.join(""));
	} else {
		dest.prepend(A.join(""));
	}
	//document.getElementById(destId).innerHTML=A.join("");
}

function renderTweets2(tweets, destId, start, end, includeAuthor) {
	var A=[];
	C = tweets.results;
	for(var D=start;D<C.length && D<=end;D++){
		var E=C[D].from_user;
		var B=transformTweet(C[D].text);
		var F="http://twitter.com/" + E;
		var G = "<div class='fanTweetWrapper'>";
		if (includeAuthor) {
			G += "<span class='fanTweeter'><a href='" + F + "' target='_blank'>" + E + "</a>:</span> ";
		}
		G += "<span class='fanTweetText'>" + B + "</span>";
		G += "<span class='fanTweetTime'>" + relative_time(C[D].created_at) + "</span>";
		G += "</div>";
		
		A.push(G);
	}
	document.getElementById(destId).innerHTML=A.join("");
}

function relative_time(C){
	var B=C.split(" ");
	C=B[2]+" "+B[1]+", "+B[3]+" "+B[4];
	var A=Date.parse(C);
	var D=(arguments.length>1)?arguments[1]:new Date();
	var E=parseInt((D.getTime()-A)/1000);
	E=E+(D.getTimezoneOffset()*60);
	if(E<60){return"less than a minute ago"}else{if(E<120){return"about a minute ago"}else{if(E<(60*60)){return(parseInt(E/60)).toString()+" minutes ago"}else{if(E<(120*60)){return"about an hour ago"}else{if(E<(24*60*60)){return"about "+(parseInt(E/3600)).toString()+" hours ago"}else{if(E<(48*60*60)){return"1 day ago"}else{return(parseInt(E/86400)).toString()+" days ago"}}}}}}
}
function postToFbNotLoggedIn(url, title) {
	var u = (typeof(url)=='undefined' || url == null || url == '') ? location.href : url;
	var t = (typeof(title)=='undefined' || title == null || title == '') ? document.title : title;
	window.open('http://www.facebook.com/sharer.php?u='+encodeURIComponent(u)+'&t='+encodeURIComponent(t),'sharer','toolbar=0,status=0,width=626,height=436');
	return false;
	
}
function postToFacebook(url, appName, bundleId) {
	if (typeof(bundleId) == "undefined") {
		bundleId = 86903526942;
	}
	// add some tracking to the URL
	url += "?utm_source=titlelink&utm_medium=facebook&utm_campaign=guptamedia";
	
	var templateData = createTemplateData(url, appName);
	FB.Connect.showFeedDialog(bundleId, templateData, null, null, null, FB.RequireConnect.require, null, "Add a comment", {value: ""});
}

function createTemplateData(url, appName) {
	var templateData = { "appUrl": url, "appName": appName,
			"images" : [{"src":"http://fusefest.fuse.tv/static/images/loll-wallpost2.jpg", "href":url}]
	};
	return templateData;
}

function popupInviteFriendsDialog(currentFriendIds, appUrl, appName, festName) {
	var actionUrl = window.location.href;
	var fbmlContent = "<fb:fbml><fb:request-form action=\"" + actionUrl + "\"";
	fbmlContent += " method=\"POST\" invite=\"true\" type=\"" + appName + "\" content=\"";
	fbmlContent += "Checkout what the " + festName + " bands are saying!";
	fbmlContent += "<fb:req-choice url='" + appUrl + "' label='Go!' />\"";
	fbmlContent += "<fb:multi-friend-selector condensed=\"false\" bypass=\"cancel\"";
	if (currentFriendIds != null && currentFriendIds.length > 0) {
		var excludeIds = "";
		for (var i=0; i<currentFriendIds.length; i++) {
			if (i > 0) {
				excludeIds += ",";
			}
			excludeIds += currentFriendIds[i];
		}
		fbmlContent += " exclude_ids=\"" + excludeIds + "\"";
	}
	fbmlContent += " showborder=\"false\" actiontext=\"Invite your friends to use " + appName + ".\">";
	fbmlContent += "</fb:request-form></fb:fbml>";
	
	var dialog = new FB.UI.FBMLPopupDialog ('Invite Friends');
	dialog.setFBMLContent(fbmlContent);
	dialog.setContentWidth(750);
	dialog.set_placement(FB.UI.PopupPlacement.topCenter );
	dialog.show();
}

function trackAnalytics(domElement) {
	try {
		var elem = $j(domElement);
	    var path = elem.attr("gaId");
	    if (path == null || path == "") {
	        path = elem.attr("id");
	    }
	    if (path == null || path == "") {
	        path = elem.attr("href");
	    }
	    pageTracker._trackPageview(path);
	} catch (err) {}
}

var questionMap = {};

function setupQuestions(questions, swfLoc, id, replaceId, width, height, installerLoc) {
	for (var i=0; i<questions.length; i++) {
		questionMap[questions[i].id] = questions[i];
	}
    var flashvars = {};
    flashvars.tour = "";

    var params = {};
    params.menu = "false";
    params.allowsscriptaccess = "always";
    params.wmode = "transparent";
    
    var attributes = {};
    attributes.id = id;

    swfobject.embedSWF(swfLoc, replaceId, width, height, "9.0.124", installerLoc, flashvars, params, attributes);	
}
function getFlexApp(appName) 
{
    if (navigator.appName.indexOf ("Microsoft") !=-1) 
        return window[appName];
    else
        return document[appName];
}



function onQuestionsFlashReady() 
{
	var questions = [];
	for (id in questionMap) {
		questions.push(questionMap[id]);
	}
    getFlexApp('questionsFlash').setQuestions(questions);
    //onQuestionSelected({id:1});
}
             
function onQuestionSelected(objId)
{
	try {
		pageTracker._trackPageview("/questions/question" + objId.id);
	} catch (err) {}
	
	var question = questionMap[objId.id];
	var primarySearch = question.searches[0];
	var hashtag = question.hashtag;
	$j("#questionTweets").empty();
	
	$j.getJSON("http://search.twitter.com/search.json?lang=all&q=" + encodeURIComponent(primarySearch) + "&callback=?", function(data) {
		handleQuestionTweets(data, true);
	});
	if (question.searches.length > 1) {
		$j.getJSON("http://search.twitter.com/search.json?lang=all&q=" + encodeURIComponent(question.searches[1]) + "&callback=?", function(data) {
			handleQuestionTweets(data, false);
		});		
	}
    //$j("#questionsRight .questionComments").empty().append("<fb:comments simple='true' css='http://fusefest.fuse.tv/static/styles/fbcomments3.css' width='320px' numposts='5' title='" + title + "' xid='question_" + question.id + "' url='http://fusefest.fuse.tv'></fb:comments>");
    //FB.XFBML.Host.parseDomTree();
	$j("#questionLink span").html(hashtag);
	$j("#questionLink a").attr("href", "http://twitter.com/home?status=" + encodeURIComponent(question.status));
	$j("#questionLink").show();
	
	$j("#questionText").html(question.text);
}
