// JavaScript Document
var gAppId = 157133;
var gViewer;
var gSpecialItemCount = 0;

var gFriendIndex = 0;
var gFriendIdArray = new Array();
var gFriendSizePerGroup = 20;


var gFriendList = new Array();

var gFriendIncludedIdList = new Array();
var gFriendExcludedIdList = new Array();
var gItemCountList = new Array();
var gItemDateList = new Array();
var gFriendHtml = '';
var gFriendBatchSize = 100;
var gFriendMax = 6000;
var gInviteMode = 'send_items';

var gMenuHtml = '';

function init() {
    var req = opensocial.newDataRequest();
    req.add(req.newFetchPersonRequest(opensocial.IdSpec.PersonId.VIEWER), 'viewer');
    req.send(viewerResponse);

    function viewerResponse(response) {
		gViewer = response.get('viewer').getData();
		if (gViewer == null) {
			document.getElementById('loading').style.display = 'none';
			document.getElementById('not_installed').style.display = 'block'; 
			return;
		}
        switchToInviteByMode("send_items");
    } 
}

function viewInviteCallback(data, url, errored) {
	if (!errored) {
		document.getElementById('invite').innerHTML = data.text;
		document.getElementById('invite').style.display = 'block';
		document.getElementById('loading').style.display = 'none';
		document.getElementById('friends').innerHTML = gFriendHtml;
		document.getElementById('menu').innerHTML = gMenuHtml;
		if (gInviteMode == 'send_special_items' || gInviteMode == 'sent_special_items' || gInviteMode == 'received_special_items') {
			document.getElementById('special_items').style.display = 'block';
			document.getElementById('special_items_count').innerHTML = gSpecialItemCount;
		}
		else {
			document.getElementById('special_items').style.display = 'none';
		}
		
	} 
	else {
		// server error
		document.getElementById('unavailable').style.display = 'block';
		document.getElementById('loading').style.display = 'none';
	}
}
function viewInvite() {
	var	url = 'http://apps.stunme.com/widgets/rose_box/opensocial/invite';
	var params = {};
	params[gadgets.io.RequestParameters.METHOD] = gadgets.io.MethodType.GET;
	gadgets.io.makeRequest(url, viewInviteCallback, params);
}
function getMenuHtml() {
    var mode = gInviteMode;
	
	var menuHtml = '<img src="http://apps.stunme.com/images/rose_box/item_canvas.gif" width="31" height="31" border="0" align="absmiddle" /> ';
	
	if (mode != 'send_items') {
		menuHtml += '<a href="javascript:void(0)" onclick="switchToInviteByMode(\'send_items\')" class="whiteplain">';
	}
	menuHtml += 'Send Roses';
	if (mode != 'send_items') {
		menuHtml += '</a>';
	}
	menuHtml += ' | ';
	
	if (mode != 'received_items') {
		menuHtml += '<a href="javascript:void(0)" onclick="switchToInviteByMode(\'received_items\')" class="whiteplain">';
	}
	menuHtml += 'Received Roses';
	if (mode != 'received_items') {
		menuHtml += '</a>';
	}
	menuHtml += ' | ';
	
	if (mode != 'sent_items') {
		menuHtml += '<a href="javascript:void(0)" onclick="switchToInviteByMode(\'sent_items\')" class="whiteplain">';
	}
	menuHtml += 'Sent Roses';
	if (mode != 'sent_items') {
		menuHtml += '</a>';
	}
	menuHtml += ' <img src="http://apps.stunme.com/images/rose_box/special_item_canvas.gif" width="31" height="31" border="0" align="absmiddle" /> ';
	
	if (mode != 'send_special_items') {
		menuHtml += '<a href="javascript:void(0)" onclick="switchToInviteByMode(\'send_special_items\')" class="whiteplain">';
	}
	menuHtml += 'Send Animated Roses';
	if (mode != 'send_special_items') {
		menuHtml += '</a>';
	}
	menuHtml += ' | ';
	
	if (mode != 'received_special_items') {
		menuHtml += '<a href="javascript:void(0)" onclick="switchToInviteByMode(\'received_special_items\')" class="whiteplain">';
	}
	menuHtml += 'Received Animated Roses';
	if (mode != 'received_special_items') {
		menuHtml += '</a>';
	}
	menuHtml += ' | ';
	
	if (mode != 'sent_special_items') {
		menuHtml += '<a href="javascript:void(0)" onclick="switchToInviteByMode(\'sent_special_items\')" class="whiteplain">';
	}
	menuHtml += 'Sent Animated Roses';
	if (mode != 'sent_special_items') {
		menuHtml += '</a>';
	}
	menuHtml += ' | ';
	
	if (mode != 'offers') {
		menuHtml += '<a href="javascript:void(0)" onclick="switchToOffers()" class="whiteplain">';
	}
	menuHtml += 'Run out of Animated Roses?';
	if (mode != 'offers') {
		menuHtml += '</a>';
	}
	gMenuHtml = menuHtml;
}
function getInviteHtml() {
	var mode = gInviteMode;
	getMenuHtml();
	var friendHtml = '';
	if (mode == "send_items") {
		friendHtml += '<span class="whitehead">Here are your friends you have not sent roses to.</span><br>';
		friendHtml += 'Please click friends you\'d like to send roses to. They\'ll be notified by app invites.<br><br>';
	}
	else if (mode == "received_items") {
		friendHtml += '<span class="whitehead">Here are your friends who sent roses to you.</span><br>';
		friendHtml += 'Please click friends you\'d like to send roses to. They\'ll be notified by comments.<br><br>';

	}
	else if (mode == "sent_items") {
		friendHtml += '<span class="whitehead">Here are your friends you have sent roses to.</span><br>';
		friendHtml += 'Please click friends you\'d like to send roses again. They\'ll be notified by comments.<br><br>';
	}
	else if (mode == "send_special_items") {
		friendHtml += '<span class="whitehead">Here are your friends you have not sent animated roses to.</span><br>';
		friendHtml += 'Select friends to send animated roses to. They\'ll be notified by comments.<br><br>';
	}
	else if (mode == "received_special_items") {
		friendHtml += '<span class="whitehead">Here are friends who sent animated roses to you.</span><br>';
		friendHtml += 'Select friends to send animated roses back. They\'ll be notified by comments.<br><br>';
	}
	else {
	    // sent_special_items
		friendHtml += '<span class="whitehead">Here are your friends you have sent animated roses to.</span><br>';
		friendHtml += 'Select friends to send animated roses again. They\'ll be notified by comments.<br><br>';
		
	}
	if (gFriendList.length > 0) {
		friendHtml += '<br /><a href="javascript:void(0)" onclick="selectAllFriends()" class="whiteplain">select all</a> | ';
		friendHtml += '<a href="javascript:void(0)" onclick="deselectAllFriends()" class="whiteplain">deselect all</a> ';
		friendHtml += '<input type="button" value="click here to send roses to selected friends" style="color:#FFFFFF; background-color: #999999; font-family: Arial, Helvetica, sans-serif; font-size: 16px; font-weight: bold" onclick="inviteSelectedFriends(\'' + mode + '\')">';
	}

	var colNum = 6;
	friendHtml += '<br /><div style="height: 500px; overflow: auto;">';
	friendHtml += '<form name="friendForm"><table border="0" cellspacing="0" cellpadding="8">';
	var count = 0;
	for (var i = 0; i < gFriendList.length; i++) {
		var friendData = gFriendList[i];
		if (friendData == undefined) {
			continue;
		}
		if (count % colNum == 0) {
			friendHtml += '<tr>';
		}
		friendHtml += '<td align="center" class="greyplain" valign="bottom">';
		var friendId = getMyspaceId(friendData.getId());
		var friendName = friendData.getDisplayName();
		var thumbnail = friendData.getField(opensocial.Person.Field.THUMBNAIL_URL);
		
		var aTag = '<a href="javascript:void(0)" class="whiteplain" onclick="document.friendForm.check' + friendId + '.checked = true;">';
		friendHtml += '<div align="center" style="width: 95px; overflow: hidden; white-space: nowrap;">' + aTag + '<img src="' + thumbnail + '" border="0"/></a>';
		
		friendHtml += '<br /><input type="checkbox" name="check' + friendId + '" />';
		friendHtml += aTag + friendName + '</a>';
		
		if (mode == "sent_items" || mode == "received_items") {
			friendHtml += '<br />' + gItemDateList[i];
			friendHtml += '<br /><img src="http://apps.stunme.com/images/rose_box/item_sm.gif" border="0" align="absmiddle" /> x ' + gItemCountList[i];
		}
		else if (mode == "sent_special_items" || mode == "received_special_items") {
			friendHtml += '<br />' + gItemDateList[i];
			friendHtml += '<br /><img src="http://apps.stunme.com/images/rose_box/special_item_sm.gif" border="0" align="absmiddle" /> x ' + gItemCountList[i];
		}
		friendHtml += ' </div>';
		
		friendHtml += '</td>';
		if (count % colNum == colNum - 1) {
			friendHtml += '</tr>';
		}
		++count;
	}
	
	if (count == 0) {
		friendHtml += '<tr><td class="whiteplain">You don\'t have any roses in this list.</td></tr>';
	}
	else if (count % colNum != 0) {
		var moreColumms = colNum - (count % colNum);
		for (var i = 0; i < moreColumms; ++i) {
			friendHtml += '<td><img src="http://apps.stunme.com/images/pix.gif" width="75" height="75" border="0"/></td>';
		}
		friendHtml += '</tr>';
	}
	friendHtml += '</table></form>';
	friendHtml += '</div>';
	gFriendHtml = friendHtml;
	viewInvite();
}
function getFriends(start, functionCall) {
	var req = opensocial.newDataRequest();
	var spec = new opensocial.IdSpec();
    spec.setField(opensocial.IdSpec.Field.USER_ID, opensocial.IdSpec.PersonId.OWNER);
    spec.setField(opensocial.IdSpec.Field.GROUP_ID, 'FRIENDS');
    spec.setField(opensocial.IdSpec.Field.NETWORK_DISTANCE, 1);
	
	var params = {};
	params[opensocial.DataRequest.PeopleRequestFields.FIRST] = start;
   	params[opensocial.DataRequest.PeopleRequestFields.MAX] = gFriendBatchSize;

   	req.add(req.newFetchPeopleRequest(spec, params), 'viewerFriends');
    req.send(getFriendsResponse);
	
	function getFriendsResponse(response) {
        var friendsResponse = response.get('viewerFriends');
		if (friendsResponse.hadError()) {
			functionCall();
		}
		else {
			var friendsData = friendsResponse.getData();
			if (friendsData.size() > 0){
				friendsData.each(
					function(friendData) {
						var friendId = getMyspaceId(friendData.getId());	
						var isListed = false;
						if (gInviteMode == 'send_items' || gInviteMode == 'send_special_items') {
							isListed = true;
							for (var i = 0; i < gFriendExcludedIdList.length; ++i) {
								if (gFriendExcludedIdList[i] == friendId) {
									isListed = false;
									break;
								}
							}
							if (isListed)
								gFriendList.push(friendData);
						}
						else {
							for (var i = 0; i < gFriendIncludedIdList.length; ++i) {
								if (gFriendIncludedIdList[i] == friendId) {
									gFriendList.push(friendData);
									isListed = true;
									break;
								}
							}
						}
						
					}
				);
				start += gFriendBatchSize;
				if (start > gFriendMax)
					functionCall();
				else
					getFriends(start, functionCall);
				functionCall();
			}
			else {
				functionCall();
			}

		}
	}
}
function getFriendListCallback(data, url, errored) {
	if (!errored) {
		var resultText = data.text;
		if (gInviteMode == 'send_special_items' || gInviteMode == 'sent_special_items' || gInviteMode == 'received_special_items') {
			// read the number of special items
			var resultList = resultText.split(";");
			gSpecialItemCount = resultList[0];
			resultText = resultList[1];
		}
		
		var resultList = resultText.split(":");
		var newFriendIdList = resultList[0].split("|");
		if (gInviteMode == 'send_items' || gInviteMode == 'send_special_items') {
			gFriendExcludedIdList = newFriendIdList;
		}
		else {
			gFriendIncludedIdList = newFriendIdList;
		}
		gItemCountList = resultList[1].split("|")
		gItemDateList = resultList[2].split("|")
		
		getFriends(1, function () {
			getInviteHtml();
		});
	} 
	else {
		// server error
		document.getElementById('unavailable').style.display = 'block';
		document.getElementById('loading').style.display = 'none';
	}
}
function getFriendList() {
	var url;
	if (gInviteMode == 'send_items' || gInviteMode == 'sent_items') {
		url = 'http://apps.stunme.com/widgets/send_item/opensocial/list_sent_items?app=rose_box&user_id=' + getMyspaceId(gViewer.getId());
	}
	else if (gInviteMode == 'send_special_items' || gInviteMode == 'sent_special_items') {
		url = 'http://apps.stunme.com/widgets/send_item/opensocial/list_sent_items?app=rose_box&is_special=Y&user_id=' + getMyspaceId(gViewer.getId());
	}
	else if (gInviteMode == 'received_items') {
		url = 'http://apps.stunme.com/widgets/send_item/opensocial/list_received_items?app=rose_box&user_id=' + getMyspaceId(gViewer.getId());
	}
	else {
	   // 'received_special_items'
	   url = 'http://apps.stunme.com/widgets/send_item/opensocial/list_received_items?app=rose_box&is_special=Y&user_id=' + getMyspaceId(gViewer.getId());
	}
	var timestamp = new Date().getTime();
	url += '&timestamp=' + timestamp;
	var params = {};
	params[gadgets.io.RequestParameters.METHOD] = gadgets.io.MethodType.GET;
	gadgets.io.makeRequest(url, getFriendListCallback, params);
}
function switchToInviteByMode(mode) {
	gInviteMode = mode;
	// mode can be "send_items" "received_items" "sent_items" "send_special_items" "received_special_items" "sent_special_items"
	document.getElementById('main').style.display = 'none';
	document.getElementById('loading').style.display = 'block';
	document.getElementById('invite').innerHTML = '';
	
	gFriendList = new Array();
	gFriendIncludedIdList = new Array();
	gFriendExcludedIdList = new Array();
	getFriendList();
}
function selectAllFriends() {
	for (var i = 0; i < gFriendList.length; i++) {
		var friendData = gFriendList[i];
		var friendId = getMyspaceId(friendData.getId());	 
		eval('document.friendForm.check' + friendId).checked = true;
	}
}
function deselectAllFriends() {
	for (var i = 0; i < gFriendList.length; i++) {
		var friendData = gFriendList[i];
		var friendId = getMyspaceId(friendData.getId());	 
		eval('document.friendForm.check' + friendId).checked = false;
	}
}
function inviteSelectedFriends(mode) {
	document.getElementById('invite_error').style.display = 'none';
	document.getElementById('invite_special_error').style.display = 'none';
	gInviteMode = mode;
	gFriendIdArray = new Array();
	for (var i = 0; i < gFriendList.length; i++) { 
		var friendData = gFriendList[i];
		var friendId = getMyspaceId(friendData.getId());	 
		if (eval('document.friendForm.check' + friendId).checked) {
			gFriendIdArray.push(friendId);
		}
	}
	gFriendIndex = 0;
	if (gFriendIdArray.length == 0) {
		document.getElementById('invite_error').style.display = 'block';
		return;
	}
	else if (gInviteMode == 'send_special_items' || gInviteMode == 'received_special_items' || gInviteMode == 'sent_special_items') {
		if (gFriendIdArray.length > gSpecialItemCount) {
			document.getElementById('invite_special_error').style.display = 'block';
			return;
		}
	}
	inviteNextFriend();
}
function recordInviteCallback(data, url, errored) {
	++gFriendIndex;
	if (gInviteMode == 'send_special_items' || gInviteMode == 'received_special_items' || gInviteMode == 'sent_special_items') {
		if (gSpecialItemCount > 0)
			--gSpecialItemCount;
		document.getElementById('special_items_count').innerHTML = gSpecialItemCount;
	}
	inviteNextFriend();
}
function recordInvite(response) {
	if (response && !response.hadError() && response.getData() == 1) {
		var url = 'http://apps.stunme.com/widgets/send_item/opensocial/send?';
		var params = {};
		var postdata = {};
		postdata['sender_id'] = getMyspaceId(gViewer.getId());		
		postdata['recipient_id'] = gFriendIdArray[gFriendIndex];
		postdata['app'] = 'rose_box';
		if (gInviteMode == 'send_special_items' || gInviteMode == 'received_special_items' || gInviteMode == 'sent_special_items') {
			postdata['is_special'] = 'Y';
		}
		params[gadgets.io.RequestParameters.METHOD] = gadgets.io.MethodType.POST;
		params[gadgets.io.RequestParameters.POST_DATA] = gadgets.io.encodeValues(postdata);
		gadgets.io.makeRequest(url, recordInviteCallback, params);		
	}
	else {
		++gFriendIndex;
		inviteNextFriend();
	}
}
function recordGroupInviteCallback(data, url, errored) {
	gFriendIndex += gFriendSizePerGroup;
	inviteNextFriend();
}
function recordGroupInvite(response) {
	if (response && !response.hadError() && response.getData() == 1) {
		var url = 'http://apps.stunme.com/widgets/send_item/opensocial/send_all?';
		var params = {};
		var postdata = {};
		postdata['sender_id'] = getMyspaceId(gViewer.getId());
		var recipientIds = '';
		for (var i = 0; i < gFriendSizePerGroup; i++) {
			var thisIdx = gFriendIndex + i;
			if (thisIdx >= gFriendIdArray.length) {
				break;
			}
			recipientIds += gFriendIdArray[gFriendIndex + i] + '|';
		}
		postdata['recipient_ids'] = recipientIds;
		postdata['app'] = 'rose_box';
		params[gadgets.io.RequestParameters.METHOD] = gadgets.io.MethodType.POST;
		params[gadgets.io.RequestParameters.POST_DATA] = gadgets.io.encodeValues(postdata);
		gadgets.io.makeRequest(url, recordGroupInviteCallback, params);
	}
	else {
		gFriendIndex += gFriendSizePerGroup;
		inviteNextFriend();
	}
}
function inviteNextFriend() {
	if (gFriendIndex < gFriendIdArray.length) {
		if (gInviteMode == 'send_items') {
			var groupFriendIdArray = new Array();
			for (var i = 0; i < gFriendSizePerGroup; i++) {
				var thisIdx = gFriendIndex + i;
				if (thisIdx >= gFriendIdArray.length) {
					break;
				}
				groupFriendIdArray.push(gFriendIdArray[gFriendIndex + i]);
			}
			inviteGroup(groupFriendIdArray, recordGroupInvite);
		}
		else {
			inviteFriend(gFriendIdArray[gFriendIndex], recordInvite);
		}
	}
}

function inviteFriend(userId, callback) {
	var thisFriend = null;
	for (var i = 0; i < gFriendList.length; i++) {
		var friendData = gFriendList[i];
		var friendId = getMyspaceId(friendData.getId());	 	
		if (friendId == userId) {
			thisFriend = friendData;
		}
	};
	if (thisFriend == null) {
		return;
	}
	var subject;
	var html;
	if (gInviteMode == 'received_items' || gInviteMode == 'sent_items') {
		subject = 'Rose for you';
		html = 
	'Hey ' + thisFriend.getDisplayName() + ', here\'s a rose for you.<br /><br />' +
	'<a href="http://profile.myspace.com/Modules/Applications/Pages/Canvas.aspx?appId=' + gAppId + '" target="_top">' +
	'<img src="http://apps.stunme.com/images/rose_box/item_sticker.gif"  border="0" /></a><br />' +
	'<a href="http://www.stunme.com" target="_blank">' +
	'<img src="http://apps.stunme.com/images/by_stunme_250.gif" alt="widgets for myspace" border="0" /></a>';
	}
	else {
		subject = 'Animated rose for you';
		html = 
	'Hey ' + thisFriend.getDisplayName() + ', here\'s an animated rose for you.<br /><br />' +
	'<a href="http://profile.myspace.com/Modules/Applications/Pages/Canvas.aspx?appId=' + gAppId + '" target="_top">' +
	'<img src="http://apps.stunme.com/images/rose_box/special_item_sticker.gif" border="0" /></a><br />' +
	'<a href="http://www.stunme.com" target="_blank">' +
	'<img src="http://apps.stunme.com/images/by_stunme_250.gif" alt="widgets for myspace" border="0" /></a>';
	}
	var message = opensocial.newMessage(html);
	message.setField(opensocial.Message.Field.TITLE, subject);
	message.setField(opensocial.Message.Field.TYPE, opensocial.Message.Type.PUBLIC_MESSAGE);
	var recipientUserId = getMyspaceId(thisFriend.getId());
	opensocial.requestSendMessage(recipientUserId, message, callback);
}
function inviteGroup(userIds, callback) {
	var subject = 'Rose for you';
	var html = 'Add this app to see who sent roses to you!';
	var message = opensocial.newMessage(html);
	message.setField(opensocial.Message.Field.TITLE, subject);
	message.setField(opensocial.Message.Field.TYPE, MyOpenSpace.PostTo.Targets.SHARE_APP);
	opensocial.requestShareApp(userIds, message, callback);
}

// OFFERS PAGE

function viewOffersCallback(data, url, errored) {
	if (!errored) {
		getMenuHtml();
		document.getElementById('invite').innerHTML = data.text;
		document.getElementById('invite').style.display = 'block';
		document.getElementById('loading').style.display = 'none';
		document.getElementById('menu').innerHTML = gMenuHtml;
	} 
	else {
		// server error
		document.getElementById('unavailable').style.display = 'block';
		document.getElementById('loading').style.display = 'none';
	}
}
function switchToOffers() {
	if (gViewer != undefined) {
		var userId = getMyspaceId(gViewer.getId());
		document.getElementById('main').style.display = 'none';
		document.getElementById('loading').style.display = 'block';
		document.getElementById('invite').innerHTML = '';
		gInviteMode = 'offers';
		var	url = 'http://apps.stunme.com/widgets/rose_box/opensocial/offers?user_id=' + userId;
		var params = {};
		params[gadgets.io.RequestParameters.METHOD] = gadgets.io.MethodType.GET;
		gadgets.io.makeRequest(url, viewOffersCallback, params);
	}
}
function getMyspaceId(userId) {
	if (userId.indexOf('myspace.com:') == 0)
		return userId.substr(12);
	else
		return userId;
}
