var app_server = "www.honestybox.com";
var ajax_server = "http://" + app_server + "/opensocial/ms_canvas.php";
var viewerIdSpecParams = {};
viewerIdSpecParams[opensocial.IdSpec.Field.USER_ID] = opensocial.IdSpec.PersonId.VIEWER;
var viewerIdSpec = opensocial.newIdSpec(viewerIdSpecParams);

var viewerId = null;
var viewerGender = null;
var viewerProfilePic = null;
var viewerDisplayName = null;

var page_size = 20;
var loading = '<h1><img src="http://hbimages.s3.amazonaws.com/images/spinner.gif" border="0" /> Loading...</h1>';
var loaded = false;

// Initialization function
$(document).ready(function(){
	$("#body").html(loading);
	// This convoluted code is needed for the AppDataRequest
	var req = opensocial.newDataRequest();
	var params = {};
	params[opensocial.DataRequest.PeopleRequestFields.PROFILE_DETAILS] = [opensocial.Person.Field.GENDER];
	req.add(req.newFetchPersonRequest(opensocial.IdSpec.PersonId.VIEWER, params), "viewer");
	req.add(req.newFetchPersonAppDataRequest(viewerIdSpec, "*"), "appdata");
	req.send(getAppDataCallback);

	var params = gadgets.views.getParams();
	if(params.appParams != undefined){
		if(params.appParams.user_id != undefined && params.appParams.user_id > 0){
			loaded = true;
			doTab('user', {"user_id":params.appParams.user_id});
		}
	}
});
function getAppDataCallback(d){
	// Set the owner's attributes so we can keep the DB fresh
	var viewer = d.get("viewer");
	if(viewer.hadError()) { 
		// Display the login/install stuff
		doDialog("We were unable to access your account information from MySpace. If you are logged in, please be sure to refresh your browser window.", "Login Error");
		// console.log('Unable to access viewer data.');
		return;
	} else {
		viewer = viewer.getData();
		viewerId = getNumericId(viewer.getField(opensocial.Person.Field.ID));
		viewerGender = viewer.getField(opensocial.Person.Field.GENDER).getDisplayValue();
		viewerProfilePic = viewer.getField(opensocial.Person.Field.THUMBNAIL_URL);
		viewerDisplayName = viewer.getField(opensocial.Person.Field.NICKNAME);
	}
	// Set the values as requested by the user (if any).
	var data = d.get("appdata");
	if(data.hadError()) { 
		/* error handling here */ 
	} else {
		data = data.getData();
		if(data != null && data != "" && data != undefined 
			&& data[viewerId] != null && data[viewerId] != "" && data[viewerId] != undefined
			&& data[viewerId].profileData != null && data[viewerId].profileData != "" && data[viewerId].profileData != undefined){
			// set the question and other values as appropriate!
			if(data[viewerId].profileData.question != undefined){
				$("#question").html(data[viewerId].profileData.question);
			}
		}
	}
	if(!loaded){ doTab("home"); }
}

function sendReply(frm){
	var params = {};
	params.method = "send_reply";
	params.threadId = frm.threadid.value;
	params.signature = frm.signature.value;
	params.message = frm.message.value;
	MakeSignedRequest(ajax_server, sendReplyCallback, params);
}
function sendReplyCallback(d){
	$("#reply_form_div").html(d.html);
}

function sendMessage(frm){
	var form_data = $(frm).serialize();
	var params = {};
	params.method = "send_message";
	params.data = form_data;
	MakeSignedRequest(ajax_server, doSomething, params);
	$("#body").html(loading);
}
function sendMessageCallback(d){
	$("#body").html(d.html);
}

function sendMultipleMessages(frm, supress_response){
	if(supress_response == null || supress_response == undefined){
		supress_response = false;
	}
	var form_data = $(frm).serialize();
	var params = {};
	params.method = "send_message_multi";
	params.data = form_data;
	if(supress_response){
		MakeSignedRequest(ajax_server, doNothing, params);
	} else {
		MakeSignedRequest(ajax_server, sendMultipleMessagesCallback, params);
	}
	$("#body").html(loading);
}
function sendMultipleMessagesCallback(d){
	$("#body").html(d.html);
}

function setQuestion(question){
	// Refresh display
	$("#question").html(question);
	// Set app data
	var profile_data = {"question":question};
	var json = gadgets.json.stringify(profile_data);
	var req = opensocial.newDataRequest();
	req.add(req.newUpdatePersonAppDataRequest(opensocial.IdSpec.PersonId.VIEWER, "profileData", json));
	req.send();

	// Send to server
	MakeSignedRequest(ajax_server, doNothing, {"method":"question_set","question":question});

	// Publish to activity stream
	var my_params = '{"' ;
	my_params += "user_id" + '":';
	my_params += getNumericId(viewerId);
	my_params += "}";
	var my_question = question.substring(0,32);
	if(question.length > my_question.length){
		my_question += "...";
	}
	var params = {};
	params[opensocial.Activity.Field.TITLE_ID] = "question_change";
	params[opensocial.Activity.Field.TEMPLATE_PARAMS] = {"question":my_question,"params":my_params,"name":"my"};
	var mediaItemArray = [];
	mediaItemArray.push(opensocial.newMediaItem("", "http://api.myspace.com/v1/users/" + getNumericId(viewerId)));
	params[opensocial.Activity.Field.MEDIA_ITEMS] = mediaItemArray;
	var activity = opensocial.newActivity(params);
	opensocial.requestCreateActivity(activity, opensocial.CreateActivityPriority.HIGH, doNothing);
	doDialog('<a href="http://spreadsheets.google.com/viewform?formkey=dDBkUVczMjRNMW1TZ3VKNmVkbTJhR0E6MA.." target="_blank">Help us improve Honesty Box, complete this quick survey.</a>',"Question Changed!");
}
function changeQuestionDialog(){
	doDialog(loading, "Change Your Question");
	MakeRequest("http://" + app_server + "/opensocial/ms_questions.php", function(data){
		$("#dialog_content").html(data.html);
	},{});
}

function threadDelete(threadId){
	$("#thread_" + threadId).html("Deleting...");
	data = {};
	data.method = "thread_delete";
	data.threadId = threadId;
	MakeSignedRequest(ajax_server, threadDeleteCallback, data);
}
function threadDeleteCallback(d){
	$("#thread_" + d.threadId).hide();
	doDialog(d.html);
}

function threadReport(threadId){
	$("#body").html(loading);
	data = {};
	data.method = "thread_report";
	data.threadId = threadId;
	MakeSignedRequest(ajax_server, threadReportCallback, data);
}
function threadReportCallback(d){
	$("#body").html(d.html);
}

// This is the heavy lifting that swaps out the page content as needed
function doTab(name, data){
	if(data == undefined || data == null || data == ""){ var data = {}; }
	switch(name){
		case 'user':
			// This is a single user display
			tabSelect(null);
			data.method = "tab_user";
			$("#body").html(loading);
			MakeSignedRequest(ajax_server, doSomething, data);
			break;
		case 'invite':
			doInvite(1, page_size);
			break;
		case 'friends':
			doFriends(1, page_size);
			break;
		case 'thread':
			tabSelect(null);
			data.method = "tab_thread";
			$("#body").html(loading);
			MakeSignedRequest(ajax_server, doSomething, data);
			break;
		case 'home':
			data.method = "tab_myhb";
			data.display_name = viewerDisplayName;
			data.profile_pic = viewerProfilePic;
			data.gender = viewerGender;
			$("#body").html(loading);
			MakeSignedRequest(ajax_server, doSomething, data);
			break;
		case 'received':
			data.method = "tab_received";
			$("#body").html(loading);
			MakeSignedRequest(ajax_server, doSomething, data);
			break;
		case 'sent':
			data.method = "tab_sent";
			$("#body").html(loading);
			MakeSignedRequest(ajax_server, doSomething, data);
			break;
		case 'terms':
			$("#body").html(loading);
			data.method = 'terms';
			MakeRequest(ajax_server, doSomething, data);
			break;
		case 'privacy':
			$("#body").html(loading);
			data.method = 'privacy';
			MakeRequest(ajax_server, doSomething, data);
			break;
		case 'harassed':
			$("#body").html(loading);
			data.method = 'harassed';
			MakeRequest(ajax_server, doSomething, data);
			break;
		default:
			doDialog('Seems that hasn\'t been developed yet.','Error');
			break;
	}
}

// General handler for callbacks
function doSomething(d){
	// If something really bad happened...
	if(d == undefined || d == false){
		doDialog("Something broke... try again later.");
		return;
	}
	// Check the status
	if(!d.status){
		doDialog(d.error, "Error");
	} else {
		$("#body").html(d.html);
	}
	return;
}

// Display the dialog box
function doDialog(message, title, scroll){
	if(title != null && title != undefined){ $("#dialog_title").html(title); } else { $("#dialog_title").html(""); }
	if(message != null && message != undefined){ $("#dialog_content").html(message); }
	$("#dialog").show();
	if(scroll != "undefined" && scroll != null){
		// Reposition the window up
		$("#app").scrollTop(0);
	}
}
function closeDialog(){
	$('#dialog').hide(); 
}

// This is the friends write tab
function doFriends(page_num, page_size){
	// First send the form - just in case
	sendMultipleMessages(document.getElementById("friends_write"),true);

	// Now actually load the requested page
	page_num = page_num - 1;
	$("#body").html(loading);
	var req = opensocial.newDataRequest();
	var viewer_friends_spec = opensocial.newIdSpec({ "userId" : "VIEWER", "groupId" : "FRIENDS" });
	var friend_params = {};
	var params = {};
	params[opensocial.DataRequest.PeopleRequestFields.PROFILE_DETAILS] = [opensocial.Person.Field.GENDER];
	friend_params[opensocial.DataRequest.PeopleRequestFields.MAX] = page_size;
	friend_params[opensocial.DataRequest.PeopleRequestFields.FIRST] = (page_num * page_size) + 1;
	req.add(req.newFetchPersonRequest(opensocial.IdSpec.PersonId.VIEWER, params), "viewer");
	req.add(req.newFetchPeopleRequest(viewer_friends_spec, friend_params), "friends");
	req.send(doFriendsCallback);
}
function doFriendsCallback(d){
	var viewer = d.get("viewer");
	if(viewer.hadError()){
		$("#body").html("Unable to load your data, try clicking Friends again.");
	}
	var viewer_friends = d.get("friends");
	if(viewer_friends.hadError()){
		$("#body").html("Error loading your friends, try clicking Friends again.");
	}

	friends = viewer_friends.getData();
	var total_records = friends.getTotalSize();
	var current_page = Math.floor(friends.getOffset() / page_size) + 1;
	var total_pages = Math.ceil(total_records/page_size);
	friends = friends.asArray();
	
	var page_info = "<div>";
	if(current_page > 1){ 
		page_info += '<a href="#" onclick="doFriends(' + (current_page - 1) + ',' + page_size + ');">Previous Page</a>'; 
		page_info += " | "; 
	}
	page_info += "Page " + current_page + " of " + total_pages;
	if(current_page < total_pages){ page_info += " | "; }
	if(total_pages > current_page){ page_info += '<a href="#" onclick="doFriends(' + (current_page + 1) + ',' + page_size + ');">Next Page</a>'; }
	page_info += "</div>";
	
	var submit_button = '<div class="instruction_box"><b>Write on all your friends\' Honesty Boxes and submit: </b>';
	submit_button += '<input type="submit" name="button" value="Submit All Anonymously" />';
	submit_button += '</div>';
	
	body_string = "<p>We will only send messages to people you write to!</p>";
	body_string += page_info;
	body_string += '<form onsubmit="sendMultipleMessages(this); return false;" name="friends_write" id="friends_write">';
	body_string += submit_button;

	var friend_ids = "";
	for(i=0;i<friends.length;i++){
		var friend = friends[i];
		if(i == 0){
			body_string += '<div class="friend_write_row first_row">';
		} else {
			body_string += '<div class="friend_write_row">';
		}
		body_string += '<div class="alignleft" style="margin-right:10px;"><img src="' + friend.getField(opensocial.Person.Field.THUMBNAIL_URL) + '" width="75" border="0" alt="Profile Picture" /></div>';
		body_string += '<div class="alignleft" style="width:660px;">';
		body_string += '<div id="user_question_' + getNumericId(friend.getField(opensocial.Person.Field.ID)) + '">What do you really think of ' + friend.getField(opensocial.Person.Field.NICKNAME) + '?</div>';
		body_string += '<div>';
		body_string += '<input type="hidden" name="app_user_' + getNumericId(friend.getField(opensocial.Person.Field.ID)) + '" value="' + friend.getField(opensocial.Person.Field.HAS_APP) + '" />';
		body_string += '<input type="hidden" name="display_name_' + getNumericId(friend.getField(opensocial.Person.Field.ID)) + '" value="' + friend.getField(opensocial.Person.Field.NICKNAME) + '" />';
		body_string += '<input type="hidden" name="profile_pic_' + getNumericId(friend.getField(opensocial.Person.Field.ID)) + '" value="' + friend.getField(opensocial.Person.Field.THUMBNAIL_URL) + '" />';
		body_string += '<textarea name="message_' + getNumericId(friend.getField(opensocial.Person.Field.ID)) + '"></textarea><br />';
		body_string += '</div>';
		body_string += '</div>';
		body_string += '<div class="clearfix"></div>';
		body_string += '</div>';
	}

	body_string += submit_button;
	body_string += '</form>';
	body_string += page_info;

	$("#body").html(body_string);

	// After sending the content to the display, load the custom questions if they exist
	for(i=0;i<friends.length;i++){
		var friend = friends[i];
		MakeRequest("http://" + app_server + "/opensocial/user_question.php", function(d){
			if(d.question.length > 1){
				$("#user_question_" + getNumericId(friend.getField(opensocial.Person.Field.ID))).html(friend.getField(opensocial.Person.Field.NICKNAME) + " is asking, <span class=\"custom_question\">\"" + d.question + "\"</span>");
			}
		},{ "user_id" : getNumericId(friend.getField(opensocial.Person.Field.ID)) });
	}
	
}

// This will show the invite tab stuff
var inviteList = [];
function doInvite(page_num){
	inviteList = [];
	page_num = page_num - 1;
	$("#body").html(loading);
	var req = opensocial.newDataRequest();
	var viewer_friends_spec = opensocial.newIdSpec({ "userId" : "VIEWER", "groupId" : "FRIENDS" });
	var friend_params = {};
	var params = {};
	params[opensocial.DataRequest.PeopleRequestFields.PROFILE_DETAILS] = [opensocial.Person.Field.GENDER];
	friend_params[opensocial.DataRequest.PeopleRequestFields.FILTER] = opensocial.DataRequest.FilterType.ALL;
	friend_params[opensocial.DataRequest.PeopleRequestFields.MAX] = 45;
	friend_params[opensocial.DataRequest.PeopleRequestFields.FIRST] = (page_num * 45) + 1;
	req.add(req.newFetchPersonRequest(opensocial.IdSpec.PersonId.VIEWER, params), "viewer");
	req.add(req.newFetchPeopleRequest(viewer_friends_spec, friend_params), "friends");
	req.send(doInviteCallback);
}
function doInviteCallback(d){
	var body_string = "";
	var viewer = d.get("viewer");
	if(viewer.hadError()){
		$("#body").html("Unable to load your data, try clicking Invite again.");
	}
	var viewer_friends = d.get("friends");
	if(viewer_friends.hadError()){
		$("#body").html("Error loading your friends, try clicking Invite again.");
	}

	friends = viewer_friends.getData();
	var total_records = friends.getTotalSize();
	var current_page = Math.floor(friends.getOffset() / 45) + 1;
	var total_pages = Math.ceil(total_records/45);
	friends = friends.asArray();
	
	body_string += '<h2>Select Your Friends Then Click Invite!</h2>';
	
	var page_info = "<div>";
	if(current_page > 1){ 
		page_info += '<a href="#" onclick="doInvite(' + (current_page - 1) + ');">Previous Page</a>'; 
		page_info += " | "; 
	}
	page_info += "Page " + current_page + " of " + total_pages;
	if(current_page < total_pages){ page_info += " | "; }
	if(total_pages > current_page){ page_info += '<a href="#" onclick="doInvite(' + (current_page + 1) + ');">Next Page</a>'; }
	page_info += "</div>";

	body_string += page_info;
	body_string += '<div>';
	for(i=0;i<friends.length;i++){
		var friend = friends[i];
		body_string += '<div onclick="addToInvites(\'' + friend.getField(opensocial.Person.Field.ID) + '\');" class="invite_wrapper" id="friend_' + getNumericId(friend.getField(opensocial.Person.Field.ID)) + '"><img src="' + friend.getField(opensocial.Person.Field.THUMBNAIL_URL) + '" width="75" border="0" alt="Click to invite me." /><br /><span class="invite_name">' + friend.getField(opensocial.Person.Field.NICKNAME) + '</span></div>';
	}
	body_string += '<div class="clearfix"></div>';
	body_string += '</div>';
	body_string += page_info;
	body_string += '<p><a href="#" onclick="sendInvites();">Send Invites!</a></p>';
	$("#body").html(body_string);
}
function addToInvites(user){
	var add = true;
	for(var i = 0; i < inviteList.length; i++){
		if(inviteList[i] == user){ $("#friend_" + getNumericId(user)).removeClass("invite_selected"); add = false; }
	}
	if(inviteList.length >= 20){
		doDialog("You can only invite 20 people per day.","Sorry");
		return;
	}
	if(add){
		inviteList[inviteList.length] = user; 
		$("#friend_" + getNumericId(user)).addClass("invite_selected");
	}
}
function removeFromInvites(user){
	// FIND THIS ID IN THE LIST
	$("#friend_" + getNumericId(user)).removeClass("invite_selected");
}
function sendInvites(){
	var my_question = $("#question").html().substring(0,40);
	if($("#question").html().length > my_question.length){
		my_question += "...";
	}
	var inviteCopy = "Hey [recipient]! I'm using [app] to find out what people think of me! After you install it, please answer my question, \"" + my_question + "\" Thanks! [sender]";
	opensocial.requestShareApp(inviteList, opensocial.newMessage(inviteCopy), function(d){ 
		for(i=0;i<inviteList.length;i++){
			removeFromInvites(inviteList[i]);
			console.log(inviteList[i]);
			$("#friend_" + getNumericId(inviteList[i])).hide();
		}
		inviteList = []; 
		doDialog('Thank you for inviting your friends!'); 
	});
}

// Visual effect for navigation
function tabSelect(el){ 
	$("li.selected").removeClass("selected");
	if(el != null){
		$(el).addClass("selected");
	}
}

// Helper function to convert from OpenSocial v 0.8 idSpec
function getNumericId(id){
	if(Math.round(id) != id){
		var uid = id.split(":");
		return uid[1];
	} else {
		return id;
	}
}

// Helper function as a null callback
function doNothing(d){
	// do what it says
}

// Helper function for fetching data using MakeRequest
function MakeSignedRequest(u, c, p){
	var p2 = {};
	var q = "";
	for (k in p) { 
		if(q.length > 0) { q += "&"; }
		q += k + "=" + encodeURIComponent(p[k]);
	}
	if(q.length > 0) { q += "&"; }
 	q += "rand=" + Math.random() * 1000000000000;
	p2[gadgets.io.RequestParameters.METHOD] = gadgets.io.MethodType.POST;
	p2[gadgets.io.RequestParameters.POST_DATA] = q;
	p2[gadgets.io.RequestParameters.AUTHORIZATION] = gadgets.io.AuthorizationType.SIGNED;
	gadgets.io.makeRequest(u, rc, p2);
	function rc(d){
		var j = gadgets.json.parse(d.data);
		c(j);
	}
}

// Helper function for fetching data using MakeRequest
function MakeRequest(u, c, p){
	var p2 = {};
	var q = "";
	for (k in p) { 
		if(q.length > 0) { q += "&"; }
		q += k + "=" + encodeURIComponent(p[k]);
	}
	p2[gadgets.io.RequestParameters.METHOD] = gadgets.io.MethodType.POST;
	p2[gadgets.io.RequestParameters.POST_DATA] = q;
	gadgets.io.makeRequest(u, rc, p2);
	function rc(d){
		var j = gadgets.json.parse(d.data);
		c(j);
	}
}
