// JavaScript Document
var gViewer;
var gSubscriberId = -1;
var gSum = '';

var gFriendIndex = 0;
var gFriendIdArray = new Array();
var gFriendList = new Array();
var gFriendHtml = '';
var gFriendBatchSize = 40;
var gFriendMax = 1000;
var gSubscriberIdData;
var gSubscriberIdList = new Array();
var gThisSubscriberId;

function selectedValue(selBox) {
  return selBox.options[selBox.selectedIndex].value;
}
function createSubscriber() {
	//if (confirm('Are you sure you want to create a completely new calendar?')) {
	saveSubscriber();
	//}
}
function saveSubscriber() {
	document.getElementById('saving').style.display = 'block';
	document.getElementById('unavailable').style.display = 'none';
    var url = 'http://stickit.stunme.com/widgets/calendar/opensocial/save_subscriber';
	
    var params = {};
    var postdata = {};
    postdata['user_id'] = gViewer.getId();
	postdata['subscriber_id'] = gSubscriberId;
	postdata['sum'] = gSum;
	postdata['name'] = encodeURIComponent(document.subscriberForm.name.value);
	postdata['birthday'] = selectedValue(document.subscriberForm.birthday);
	postdata['birthmonth'] = selectedValue(document.subscriberForm.birthmonth);
	postdata['is_birthday_private'] = document.subscriberForm.is_birthday_private.checked ? "Y" : "N";
	postdata['holiday_set_id'] = selectedValue(document.subscriberForm.holiday_set_id);
	postdata['is_shared'] = selectedValue(document.subscriberForm.is_shared);
	postdata['background_image'] = document.subscriberForm.background_image.value;
	var selectedColor = '666666';
	for (var i=0; i < document.subscriberForm.background_color.length; ++i) {
		if (document.subscriberForm.background_color[i].checked) {
			selectedColor = document.subscriberForm.background_color[i].value;
		}
	}
	postdata['background_color'] = selectedColor;
    params[gadgets.io.RequestParameters.METHOD] = gadgets.io.MethodType.POST;
    params[gadgets.io.RequestParameters.POST_DATA] = gadgets.io.encodeValues(postdata);
    gadgets.io.makeRequest(url, saveSubscriberCallback, params);
        
    function saveSubscriberCallback(data, url, errored) {
        if (!errored) {
			if (data.text == 'updated') {
				// updated
				document.getElementById('saving').style.display = 'none';
				document.getElementById('subscriber_form').style.display = 'none';
				document.getElementById('success').style.display = 'block';
			}
			else {
				// created
				var isSaved = false;
				var params = data.text.split("|");
				if (params[0] == 'created' && params.length >= 4) {
					var req = opensocial.newDataRequest();
					gSubscriberId = params[1];
					gSum = params[2];
					document.getElementById('saving').style.display = 'none';
					document.getElementById('subscriber_form').style.display = 'none';
					document.getElementById('success').style.display = 'block';
					isSaved = true;
				}
				if (!isSaved) {
					// server error
					document.getElementById('unavailable').style.display = 'block';
					document.getElementById('saving').style.display = 'none';
					document.getElementById('main').style.display = 'none';
				}
			}
        } 
        else {
			// server error
			document.getElementById('unavailable').style.display = 'block';
			document.getElementById('saving').style.display = 'none';
			document.getElementById('main').style.display = 'none';
        }
    }
}
function viewSubscriberCallback(data, url, errored) {
	if (!errored) {
		document.getElementById('main').innerHTML = data.text;
		document.getElementById('loading').style.display = 'none';
	} 
	else {
		// server error
		document.getElementById('unavailable').style.display = 'block';
		document.getElementById('loading').style.display = 'none';
	}
}

function authCallback(data, url, errored) {
	if (!errored) {
		var params = data.text.split("|");
		var	url = 'http://stickit.stunme.com/widgets/calendar/opensocial/view_subscriber';
		if (params[0] == 'found' && params.length >=  4) {
			var subscriberId = params[1];
			var sum = params[2];
			gSubscriberId = subscriberId;
			gSum = sum;
			url += '?subscriber_id=' + subscriberId + '&sum=' + sum + '&timestamp=' + new Date().getTime();
		}
		else {
			url += '?name=' + escape(gViewer.getDisplayName());
		}
		
		var osParams = opensocial.getEnvironment().getParams();
		if (osParams['mode'] == 'invite') {
			gFriendList = new Array();
			getFriends(0, function () {
				getInviteHtml();
			});
		}
		else {
			var params = {};
			params[gadgets.io.RequestParameters.METHOD] = gadgets.io.MethodType.GET;
    		gadgets.io.makeRequest(url, viewSubscriberCallback, params);
		}
	} 
	else {
		// server error
		document.getElementById('unavailable').style.display = 'block';
		document.getElementById('loading').style.display = 'none';
	}
}

function init() {
    var req = opensocial.newDataRequest();
    req.add(req.newFetchPersonRequest(opensocial.DataRequest.PersonId.VIEWER));
    req.send(viewerResponse);

    function viewerResponse(response) {
		gViewer = response.get(opensocial.DataRequest.PersonId.VIEWER).getData(); 
		if (gViewer == null) {
			document.getElementById('not_installed').style.display = 'block';
			document.getElementById('loading').style.display = 'none';
			return;
		}
        var userId = gViewer.getId();
		
		var url = 'http://stickit.stunme.com/widgets/calendar/opensocial/get_subscriber';
		var params = {};
		params[gadgets.io.RequestParameters.AUTHORIZATION] = gadgets.io.AuthorizationType.SIGNED;
		params[gadgets.io.RequestParameters.METHOD] = gadgets.io.MethodType.POST;					
		var postdata = {};
		postdata['timestamp'] = new Date().getTime();
		params[gadgets.io.RequestParameters.POST_DATA] = gadgets.io.encodeValues(postdata);
		gadgets.io.makeRequest(url, authCallback, params);
    } 
}

function viewInviteCallback(data, url, errored) {
	if (!errored) {
		document.getElementById('invite').innerHTML = data.text;
		document.getElementById('loading').style.display = 'none';
		document.getElementById('friends').innerHTML = gFriendHtml;
	} 
	else {
		// server error
		document.getElementById('unavailable').style.display = 'block';
		document.getElementById('loading').style.display = 'none';
	}
}
function viewInvite() {
	var osParams = opensocial.getEnvironment().getParams();
	var	url = 'http://stickit.stunme.com/widgets/calendar/opensocial/invite?subscriber_id=' + gSubscriberId + 
		'&sum=' + gSum + 
		'&year=' + osParams['year'] +
		'&month=' + osParams['month'] +
		'&day=' + osParams['day'] +
		'&day_of_week=' + osParams['day_of_week'] +
		'&title=' + escape(osParams['title']) +
		'&note=' + escape(osParams['note']);
	var params = {};
	params[gadgets.io.RequestParameters.METHOD] = gadgets.io.MethodType.GET;
	gadgets.io.makeRequest(url, viewInviteCallback, params);
}
function getFriends(start, functionCall) {
	var req = opensocial.newDataRequest();
	var params = {};
	params[opensocial.DataRequest.PeopleRequestFields.FIRST] = start; 
   	params[opensocial.DataRequest.PeopleRequestFields.MAX] = gFriendBatchSize;
	var fields = ['subscriber_id'];
   	req.add(req.newFetchPeopleRequest(opensocial.DataRequest.Group.VIEWER_FRIENDS, params), 'viewerFriends');
	req.add(req.newFetchPersonAppDataRequest(opensocial.DataRequest.Group.VIEWER_FRIENDS, fields), 'subscriberIds');
    req.send(getFriendsResponse);
	
	function getFriendsResponse(response) {
        var friendsResponse = response.get('viewerFriends');
		
		var subscriberIdResponse = response.get('subscriberIds');

		if (!subscriberIdResponse.hadError()) {
			gSubscriberIdData = subscriberIdResponse.getData();
		}
		
		if (friendsResponse.hadError()) {
			functionCall();
		}
		else {
			var friendsData = friendsResponse.getData();
			if (friendsData.size() > 0){
				friendsData.each(
					function(friendData) {
						gFriendList.push(friendData);
						if (gSubscriberIdData != undefined &&
							gSubscriberIdData[friendData.getField(opensocial.Person.Field.ID)] != undefined) {
							gSubscriberIdList.push(gSubscriberIdData[friendData.getField(opensocial.Person.Field.ID)]['subscriber_id']);
						}
						else {
							gSubscriberIdList.push(undefined);
						}
					}
				);
				start += gFriendBatchSize;
				if (start >= gFriendMax)
					functionCall();
				else
					getFriends(start, functionCall);
			}
			else {
				functionCall();
			}

		}
	}
}

function getInviteHtml() {
	var friendHtml = '<a href="javascript:void(0)" onclick="selectAllFriends()" class="blackplain">select all</a> | ';
	friendHtml += '<a href="javascript:void(0)" onclick="deselectAllFriends()" class="blackplain">deselect all</a> ';
	friendHtml += '<input type="button" value="click here to invite selected friends" style="color:#FFFFFF; background-color: #999999; font-family: Arial, Helvetica, sans-serif; font-size: 16px; font-weight: bold" onclick="inviteAll()">';

	var colNum = 5;
	friendHtml += '<br /><div style="height: 500px; overflow: auto;">';
	friendHtml += '<table border="0" cellspacing="0" cellpadding="8">';
	for (var i = 0; i < gFriendList.length; i++) {
		var friendData = gFriendList[i];

		if (i % colNum == 0) {
			friendHtml += '<tr>';
		}
		friendHtml += '<td align="center" class="greyplain" valign="bottom">';
		var friendId = friendData.getField(opensocial.Person.Field.ID);
		var friendName = friendData.getField(opensocial.Person.Field.NAME);
		var thumbnail = friendData.getField(opensocial.Person.Field.THUMBNAIL_URL);
		var aTag = '<a href="javascript:void(0)" class="blackplain" 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></div> ';
		friendHtml += '</td>';
		if (i % colNum == colNum - 1) {
			friendHtml += '</tr>';
		}
	}
	var count = gFriendList.length;
	if (count == 0) {
		friendHtml += '<tr><td class="greyplain">Sorry, you don\'t have any friends to invite.</td></tr>';
	}
	else if (count % colNum != 0) {
		var moreColumms = colNum - (count % colNum);
		for (var i = 0; i < moreColumms; ++i) {
			friendHtml += '<td>&nbsp;</td>';
		}
		friendHtml += '</tr>';
	}
	friendHtml += '</table>';
	friendHtml += '</div>';
	gFriendHtml = friendHtml;
	viewInvite();
}

function selectAllFriends() {
	for (var i = 0; i < gFriendList.length; i++) {
		var friendData = gFriendList[i];
		var friendId = friendData.getField(opensocial.Person.Field.ID);	 
		eval('document.friendForm.check' + friendId).checked = true;
	}
}
function deselectAllFriends() {
	for (var i = 0; i < gFriendList.length; i++) {
		var friendData = gFriendList[i];
		var friendId = friendData.getField(opensocial.Person.Field.ID);	 
		eval('document.friendForm.check' + friendId).checked = false;
	}
}
function inviteAll() {
	// check if the title is empty
	var thisTitle = document.friendForm.title.value;
	var isEmpty = true;
	for (var i = 0; i < thisTitle.length; ++i) {
		if (thisTitle.charAt(i) != ' ') {
			isEmpty = false;
			break;
		}
	}
	if (isEmpty)
		document.friendForm.title.value = 'My Event!';
		
	if (document.friendForm.is_bulletin.checked) {
		var subject = document.friendForm.title.value;
		var comment = getCommentHtml();
		postInvite(subject, comment, gViewer, 'BULLETINS', inviteSelectedFriends);
	}
	else {
		inviteSelectedFriends();
	}
}
function inviteSelectedFriends() {
	gFriendIdArray = new Array();
	for (var i = 0; i < gFriendList.length; i++) { 
		var friendData = gFriendList[i];
		var friendId = friendData.getField(opensocial.Person.Field.ID);	 
		if (eval('document.friendForm.check' + friendId).checked) {
			gFriendIdArray.push(friendId);
		}
	}
	gFriendIndex = 0;
	if (gFriendIdArray.length == 0) {
		return;
	}
	inviteNextFriend();
}

function saveNoteCallback(data, url, errored) {
	++gFriendIndex;
	inviteNextFriend();
}
function postEventNote(result) {
	if (result == MyOpenSpace.PostTo.Result.SUCCESS && gThisSubscriberId != undefined) {
		var url = 'http://stickit.stunme.com/widgets/calendar/function/save_note';
		var params = {};
		var postdata = {};
		postdata['viewer_id'] = gSubscriberId;
		postdata['owner_id'] = gThisSubscriberId;
		postdata['sum'] = gSum;
		postdata['title'] = encodeURIComponent(document.friendForm.title.value);
		postdata['note'] = encodeURIComponent(document.friendForm.note.value);
		postdata['day'] = document.friendForm.day.value;
		postdata['month'] = document.friendForm.month.value;
		postdata['year'] = document.friendForm.year.value;
		params[gadgets.io.RequestParameters.METHOD] = gadgets.io.MethodType.POST;
		params[gadgets.io.RequestParameters.POST_DATA] = gadgets.io.encodeValues(postdata);
		gadgets.io.makeRequest(url, saveNoteCallback, params);		
	}
	else {
		++gFriendIndex;
		inviteNextFriend();
	}
}

function inviteNextFriend() {
	if (gFriendIndex < gFriendIdArray.length) {
		inviteFriend(gFriendIdArray[gFriendIndex], postEventNote);	
	}
}

function inviteFriend(userId, callback) {
	var thisFriend = null;
	for (var i = 0; i < gFriendList.length; i++) {
		var friendData = gFriendList[i];
		var friendId = friendData.getField(opensocial.Person.Field.ID);	 	
		if (friendId == userId) {
			thisFriend = friendData;
			gThisSubscriberId = gSubscriberIdList[i];
		}
	};
	if (thisFriend == null) {
		return;
	}
	var subject = document.friendForm.title.value;
	var comment = getCommentHtml();
	postInvite(subject, comment, thisFriend, 'COMMENTS', callback);
}

function invite() {
	var subject = "Check out my calendar!";
	
	var html = 'Hi,<br />If you haven\'t seen my calendar, <br />' +
			  '<a href="http://www.myspace.com/' +
			  gViewer.getId() +
			  '">check it out on my profile</a>';
	postInvite(subject, html, gViewer, 'BULLETINS');
}

function getCommentHtml() {
	var icon = 'exclamation';
	for(var i = 0; i < document.friendForm.icon.length; i++) {
		if(document.friendForm.icon[i].checked) {
			icon = document.friendForm.icon[i].value;
			break;
		}
	}

	var html = 
	'<a href="http://www.stunme.com/" target="_blank"><img src="http://calendar.stunme.com/images/by_stunme_200.gif" alt="Widgets for Myspace" width="200" height="16" border="0" /></a>' +
	'   <br/><a href="http://profile.myspace.com/Modules/Applications/Pages/Canvas.aspx?appId=111171" target="_top"><img src="http://calendar.stunme.com/images/calendar/big_icons/' + icon + '.gif" alt="Free Calendar" border="0" /></a>' +
	 '   <br/><a href="http://profile.myspace.com/Modules/Applications/Pages/Canvas.aspx?appId=111171" target="_top"><img src="http://calendar.stunme.com/images/calendar/get_stick_it_calendar.gif" alt="Calendar for myspace" width="200" height="50" border="0" /></a>' +
	'    <br/><br/><strong>Event:</strong> ' + document.friendForm.title.value +
	'    <br/><strong>Date:</strong> ' + document.friendForm.full_date.value + '<br/><br/>' + document.friendForm.note.value;
	return html;
}

function postInvite(subject, html, receiver, where, callback) {
	var postType = MyOpenSpace.PostTo.Targets[where];
	var osToken = MyOpenSpace.MySpaceContainer.OSToken;
	var message = opensocial.newMessage(html);
	message.setField(opensocial.Message.Field.TITLE, subject);
	message.setField(opensocial.Message.Field.TYPE, postType);
	opensocial.Container.get().postTo(osToken, message, receiver, callback);	
}