var movielist = 
[[1, 'Pulp Fiction', 1994],
[2, 'The Lord of the Rings trilogy', 2001],
[3, 'Titanic', 1997],
[4, 'Blue Velvet', 1986],
[5, 'Toy Story', 1995],
[6, 'Saving Private Ryan', 1998],
[7, 'Hannah and Her Sisters', 1986],
[8, 'The Silence of the Lambs', 1991],
[9, 'Die Hard', 1988],
[10, 'Moulin Rouge', 2001],
[11, 'This Is Spinal Tap', 1984],
[12, 'The Matrix', 1999],
[13, 'GoodFellas', 1990],
[14, 'Crumb', 1995],
[15, 'Edward Scissorhands', 1990],
[16, 'Boogie Nights', 1997],
[17, 'Jerry Maguire', 1996],
[18, 'Do the Right Thing', 1989],
[19, 'Casino Royale', 2006],
[20, 'The Lion King', 1994],
[21, 'Schindler\'s List', 1993],
[22, 'Rushmore', 1998],
[23, 'Memento', 2001],
[24, 'A Room With a View', 1986],
[25, 'Shrek', 2001],
[26, 'Hoop Dreams', 1994],
[27, 'Aliens', 1986],
[28, 'Wings of Desire', 1988],
[29, 'The Bourne Supremacy', 2004],
[30, 'When Harry Met Sally...', 1989],
[31, 'Brokeback Mountain', 2005],
[32, 'Fight Club', 1999],
[33, 'The Breakfast Club', 1985],
[34, 'Fargo', 1996],
[35, 'The Incredibles', 2004],
[36, 'Spider-Man 2', 2004],
[37, 'Pretty Woman', 1990],
[38, 'Eternal Sunshine of the Spotless Mind', 2004],
[39, 'The Sixth Sense', 1999],
[40, 'Speed', 1994],
[41, 'Dazed and Confused', 1993],
[42, 'Clueless', 1995],
[43, 'Gladiator', 2000],
[44, 'The Player', 1992],
[45, 'Rain Man', 1988],
[46, 'Children of Men', 2006],
[47, 'Men in Black', 1997],
[48, 'Scarface', 1983],
[49, 'Crouching Tiger, Hidden Dragon', 2000],
[50, 'The Piano', 1993],
[51, 'There Will Be Blood', 2007],
[52, 'The Naked Gun: From the Files of Police Squad', 1988],
[53, 'The Truman Show', 1998],
[54, 'Fatal Attraction', 1987],
[55, 'Risky Business', 1983],
[56, 'The Lives of Others', 2006], 
[57, 'There’s Something About Mary', 1998], 
[58, 'Ghostbusters', 1984],
[59, 'L.A. Confidential', 1997],
[60, 'Scream', 1996],
[61, 'Beverly Hills Cop', 1984],
[62, 'sex, lies and videotape', 1989],
[63, 'Big', 1988],
[64, 'No Country For Old Men', 2007],
[65, 'Dirty Dancing', 1987], 
[66, 'Natural Born Killers', 1994], 
[67, 'Donnie Brasco', 1997], 
[68, 'Witness', 1985], 
[69, 'All About My Mother', 1999], 
[70, 'Broadcast News', 1987],
[71, 'Unforgiven', 1992],
[72, 'Thelma &amp; Louise', 1991],
[73, 'Office Space', 1999],
[74, 'Drugstore Cowboy', 1989],
[75, 'Out of Africa', 1985],
[76, 'The Departed', 2006],
[77, 'Sid and Nancy', 1986],
[78, 'Terminator 2: Judgment Day', 1991],
[79, 'Waiting for Guffman', 1996],
[80, 'Michael Clayton', 2007],
[81, 'Moonstruck', 1987],
[82, 'Lost in Translation', 2003],
[83, 'Evil Dead 2: Dead by Dawn', 1987],
[84, 'Sideways', 2004],
[85, 'The 40 Year-Old Virgin', 2005],
[86, 'Y Tu Mamá También', 2002],
[87, 'Swingers', 1996],
[88, 'Austin Powers: International Man of Mystery', 1997],
[89, 'Breaking the Waves', 1996],
[90, 'Napoleon Dynamite', 2004],
[91, 'Back to the Future', 1985],
[92, 'Menace II Society', 1993], 
[93, 'Ed Wood', 1994],
[94, 'Full Metal Jacket', 1987], 
[95, 'In the Mood for Love', 2001],
[96, 'Far From Heaven', 2002], 
[97, 'Glory', 1989],
[98, 'The Talented Mr. Ripley', 1999],
[99, 'The Blair Witch Project', 1999],
[100, 'South Park: Bigger Longer &amp; Uncut', 1999]];

//we're using a command pattern and store swaps made by the user
//lower bandwidth and storage used

var inviteMessage = 'I have created my personal list of top movies at Entertainment Weekly, how does your list look like? Join me at ' + window.location;
var activityMessage = ' has created <a href="'  + window.location +  '">a personal list of top movies</a> at Entertainment Weekly. How does your list look like?';
var gdata;

function initAllData() {
//	console.log('initAllData');
  var req = opensocial.newDataRequest();
  req.add(req.newFetchPersonRequest("OWNER"), "owner_data");
  req.add(req.newFetchPersonRequest("VIEWER"), "viewer_data");
  var id_site_friends = new opensocial.IdSpec({
      'userId' : 'OWNER',
      'groupId' : 'FRIENDS'
  });
  var params = {};
  params[opensocial.DataRequest.PeopleRequestFields.PROFILE_DETAILS] =
  [opensocial.Person.Field.PROFILE_URL, 'aboutMe'];
  req.add(req.newFetchPeopleRequest(id_site_friends, params), 'site_friends');
  var id_viewer = opensocial.newIdSpec({ "userId" : "VIEWER" });
  var id_member = opensocial.newIdSpec({ "userId" : "OWNER", "groupId" : "FRIENDS" });
  req.add(req.newFetchPersonAppDataRequest(id_member, 'swaps'), 'swaps');
//  req.add(req.newFetchPersonAppDataRequest(id_viewer, 'swaps'), 'swaps');
  req.send(onData);
};

function onData(data) {
	gdata = data;
  if (!data.get("owner_data").hadError()) {
    var owner_data = data.get("owner_data").getData();
    //document.getElementById("site-name").innerHTML = owner_data.getDisplayName();
  }

  if (data.get("viewer_data").hadError()) {
    google.friendconnect.renderSignInButton({ 'id': 'viewer-info' });
		$("#viewer-info").append('If you login, you can reorder the list to share it with your friends');
  } else {
    var viewer = data.get("viewer_data").getData();
    $("#viewer-info").html('<img align="left" src="' + viewer.getField("thumbnailUrl")  + '">' +
    '<b>Welcome ' +  viewer.getField("displayName") + '!</b><br>' +
    '<a href="#" onclick="google.friendconnect.requestSettings()">Settings</a><br>' +
    '<a href="#" onclick="google.friendconnect.requestInvite(inviteMessage)">Invite</a><br>' +
    '<a href="#" onclick="signout()">Sign out</a><br>');
		$("#ews-menu").show();
		swaps = getSwaps(data, viewer.getId());
		applySwaps(swaps, "#movielist li");
		makeEditable();
  }

  if (!data.get("site_friends").hadError()) {
    var site_friends = data.get("site_friends").getData();
		$("#friends-list").empty();
		var lswaps = [];
    site_friends.each(function(friend) {
			lswaps = getSwaps(data, friend.getId());
			if ((lswaps.length > 0) && (friend.getId() !== viewer.getId())) {
	      $("#friends-list").append('<img class="memberPhoto" onclick="showList(gdata, \'' + friend.getId() + '\');" title="' + friend.getDisplayName() +
	 						'" src="' + friend.getField("thumbnailUrl")  + '" style="cursor: pointer;"/>');
			}
    });
		$("#membersText").html('Recent Members who have created a list: click on their picture to see their list');
  }
};

function signout() {
	$("#ews-menu").hide();
	google.friendconnect.requestSignOut();
};

function postActivity() {
  var title = activityMessage;
  var params = {};
  params[opensocial.Activity.Field.TITLE] = title;
  var activity = opensocial.newActivity(params)
  opensocial.requestCreateActivity(activity, opensocial.CreateActivityPriority.HIGH, function() {});
}

function getSwaps(data, id) {
			var swapsdata = data.get("swaps");
		  if (!swapsdata.hadError()) {
				if (swapsdata.getData()) {
//					console.log(swapsdata.getData());
//					console.log(id);
					if (swapsdata.getData()[id]) {
						var swapstxt = swapsdata.getData()[id].swaps;
									//			console.log(JSON.parse(swapstxt));
						return gadgets.json.parse(gadgets.util.unescapeString(swapstxt));
					}
				}
			}
			return [];
};

function fetchList(id) {
	console.log(id);
  var req = opensocial.newDataRequest();
  var id_member = opensocial.newIdSpec({ "userId" : "OWNER", "groupId" : "FRIENDS" });
  req.add(req.newFetchPersonAppDataRequest(id_member, 'swaps'), 'swaps');
  req.send(function(data) {showList(data, id);});
};

function showList(data, id) {
//	console.log(data);
	var myswaps = getSwaps(data, id);
	$("#movielist1 li").remove();
	addMemberHeader(id);
	if (myswaps.length > 0) {
		$.map(movielist, function(movie) {addMovie(movie, "#movielist1");});
		applySwaps(myswaps, "#movielist1 li");
	}	else {
		$("#movielist1 li").remove();
	}
}

function addMemberHeader(id) {
	var member = profileInfo(id);
	if (member.getId() === id) {
		$("#member-header").html('List of ' + member.getDisplayName() + '. <a href="' + member.getField(opensocial.Person.Field.PROFILE_URL) + '>Click on his profile if you want to befriend him.</a>');
//+ member.getField('aboutMe')		
	}
};

function profileInfo(id) {
  var site_friends = gdata.get("site_friends").getData().asArray();
  for (var i = 0; i < site_friends.length; i++) {
		if (site_friends[i].getId() === id) {
			return site_friends[i];
		}
	}
};

function applySwaps(swaplist, target) {
	if (swaplist.length > 0) {
		$.map(swaplist, function(swap) { applySwap(swap, target)} );
	}
};

function applySwap(swap, target) {
  $($(target)[parseInt(swap[0])]).insertBefore($($(target)[parseInt(swap[1])])).css('background-color', 'yellow');
};

function addMovie(movie, destination) {
	$('<li class=\"movieLine\">' + movie[0] + '. <i>' + movie[1] + '</i> (' + movie[2] + ')</li>').appendTo(destination);
};

function dropMovie(event, op) {
	op.droppable.after(op.draggable);
};

function movieHigh(event) {
	$(event.target).toggleClass('movieHigh');
};

function saveList() {
	//we use the opensocial persistence api so we don't need a server for this app
	var req = opensocial.newDataRequest();
  var json = gadgets.json.stringify(swaps);
  req.add(req.newUpdatePersonAppDataRequest("VIEWER", 'swaps', json));
  req.send();
	postActivity();
};

// Array Remove - By John Resig (MIT Licensed)
Array.prototype.remove = function(from, to) {
  var rest = this.slice((to || from) + 1 || this.length);
  this.length = from < 0 ? this.length + from : from;
  return this.push.apply(this, rest);
};

function makeEditable() {
		var dropOptions = {tolerance:'pointer',
												hoverClass:'movieHover',
												accept:function (draggable) { return true;},
												drop:function(event, ui) {
													idrop = $("#movielist li").index($(this));
													idrag = $("#movielist li").index(ui.draggable);
//													if ($(this).attr('ew.rank') && ui.draggable.attr('ew.rank')) {
													if ((idrag > -1) && (idrop > -1)) {
														swaps.push([idrag, idrop]);
													}
										      ui.draggable.insertBefore($(this)).css('left', '0').css('top', '0').css('background-color', 'yellow');
												}
											};
	//	$("#movielist li").hover(movieHigh, movieHigh).draggable({}).droppable(dropOptions);
		$("#movielist li").draggable({}).droppable(dropOptions);	
};

$(function() {
/*  $("#ew_BannerDiv1057178").hide();
  $("#ew_FlashDiv1057178").hide();
  $("#ewad1057178").hide();
  $("#ew1057178_wrapper").hide();
  $("#nos").hide();
  $("object").hide();
*/
//  $("#min-chicks ul").append('<li id="viewer-info"></li>').append('<li><ol id="friends-list"></ol></li>');
//  $("#article").prepend('');
//	$.map(movielist, function(movie) {addMovie(movie, "#movielist");});
});
