var FotoMozo = function() {
	
	// empty object for now
	var result = {
		
	};
	return result;

}();

FotoMozo.logout = function() {
	FB.Connect.logoutAndRedirect(Pop.info.baseUrl);
	return false;
}

FotoMozo.toggleFriend = function() {
	var uid = $(this).attr('uid');
	if ((uid in FotoMozo.expandedFriends) && FotoMozo.expandedFriends[uid]) {
		FotoMozo.collapseFriend(uid, this);
	} else {
		FotoMozo.expandFriend(uid, this);
	}
}

FotoMozo.expandFriend = function(uid, name_div) {
	$('.triangle', name_div).attr('src', 'img/triangle2.gif');
	$('#albumsForUid'+uid).slideDown(500);
	FotoMozo.expandedFriends[uid] = 1;
	FotoMozo.getAlbums(uid);
};

FotoMozo.collapseFriend = function(uid, name_div) {
	$('.triangle', name_div).attr('src', 'img/triangle.gif');
	$('#albumsForUid'+uid).slideUp(500);
	FotoMozo.expandedFriends[uid] = 0;
};

FotoMozo.getAlbums = function(uid) {
	if (uid in FotoMozo.albumsForUid)
		return;
	var api = FB.Facebook.apiClient;
	api.fql_query("SELECT aid, owner, name, visible FROM album WHERE owner = " + uid, function(results) {
		FotoMozo.albumsForUid[uid] = results;
		var albums_div = $('#albumsForUid' + uid);
		var photosContainer_div = $('#photosContainerForUid' + uid);
		var ul = $('<ul class="albums" />');
		var loggedInUid = api.get_session().uid;
		if (Pop.typeOf(results) === 'array')
		for (var i=0; i<results.length; ++i) {
			FotoMozo.userForAid[results[i].aid] = uid;
			if (uid != loggedInUid) {
				//if (results[i].visible == 'friends' || results[i].visible == 'custom')
				//	continue;
			}
			results.sort(FotoMozo.sortByName);
			ul.append(
				$('<li />')
				.attr('id', 'linkForAid' + results[i].aid)
				.attr('aid', results[i].aid)
				.append('<img class="check" src="img/checkNone.gif" style="width: 11px; height: 11px;"/>')
				.append('&nbsp;')
				.append(results[i].name)
				.click(FotoMozo.toggleAlbum)
			);
			photosContainer_div.append(
				$('<div class="photosContainerForAlbum"><a name="photosForAid' + results[i].aid + '" /></div>')
				.attr('id', 'photosContainerForAid' + results[i].aid)
			);
			FotoMozo.albums[results[i].aid] = results[i];
		}
		albums_div.html(ul);
	}, function(error) { if (typeof(console) != 'undefined') console.log(error) });
}

FotoMozo.toggleAlbum = function() {
	var aid = $(this).attr('aid');
	if ((aid in FotoMozo.checkedAlbums) && FotoMozo.checkedAlbums[aid]) {
		FotoMozo.uncheckAlbum(aid, this);
	} else {
		FotoMozo.checkAlbum(aid, this);
	}
}

FotoMozo.checkAlbum = function(aid, album_li) {
	$('.check', album_li).attr('src', 'img/checkAll.gif');
	$('#photosContainerForAid'+aid).slideDown(500);
	FotoMozo.checkedAlbums[aid] = 1;
	$('#photosContainerForAid' + aid + ' .check').attr('src', 'img/checkAll.gif');
	FotoMozo.uncheckedPidsForAid[aid] = {};
	// todo: check all the photos
	FotoMozo.getPhotos(aid);
	if (aid in FotoMozo.photoCountForAid) {
		FotoMozo.setCheckedPhotoCount(
			FotoMozo.getCheckedPhotoCount() + FotoMozo.photoCountForAid[aid]
		);
		FotoMozo.checkedPhotoCountForAid[aid] = FotoMozo.photoCountForAid[aid];
	}
};

FotoMozo.uncheckAlbum = function(aid, album_li) {
	$('.check', album_li).attr('src', 'img/checkNone.gif');
	$('#photosContainerForAid'+aid).slideUp(500);
	// todo: uncheck all the photos
	FotoMozo.checkedAlbums[aid] = 0;
	if (aid in FotoMozo.checkedPhotoCountForAid) {
		FotoMozo.setCheckedPhotoCount(
			FotoMozo.getCheckedPhotoCount() - FotoMozo.checkedPhotoCountForAid[aid]
		);
	}
};

FotoMozo.getPhotos = function(aid) {
	var numPhotoColumns = 4;
	for (t = 200; t <= 1000; t += 800) {
		setTimeout('document.location.hash = "photosForAid'+aid+'"', t);
	}
	if (aid in FotoMozo.photosForAid)
		return;
	var api = FB.Facebook.apiClient;
	api.fql_query("SELECT pid, src_small, src_small_width, src_small_height, owner FROM photo "
	 + "WHERE aid = " + aid, function(results) {
		for (t = 200; t < 1000; t += 100) {
			setTimeout('document.location.hash = "photosForAid'+aid+'"', t);
		}
		photosForAid = {};
		if (results && Pop.typeOf(results) === 'array') {
			for (var i=0; i<results.length; ++i) {
				photosForAid[results[i].pid] = results[i];
			}
			FotoMozo.photoCountForAid[aid] = results.length;
		} else {
			FotoMozo.photoCountForAid[aid] = 0;
		}
		FotoMozo.photosForAid[aid] = photosForAid;
		// If the album has meanwhile been unchecked, uncheck all the photos
		if (!(aid in FotoMozo.checkedAlbums) || !FotoMozo.checkedAlbums[aid]) {
			var pids = {};
			if (Pop.typeOf(results) === 'array')
			for (var i=0; i < results.length; ++i) {
				pids[results[i].pid] = 1;
			}
			FotoMozo.uncheckedPidsForAid[aid] = pids;
		} else {
			if (results && Pop.typeOf(results) === 'array') {
				FotoMozo.checkedPhotoCountForAid[aid] = results.length;
				FotoMozo.setCheckedPhotoCount(
					FotoMozo.getCheckedPhotoCount() + results.length
				);
			} else {
				FotoMozo.checkedPhotoCountForAid[aid] = 0;
			}
		}
		var photosContainer_div = $('#photosContainerForAid' + aid);
		photosContainer_div.append($('<h2 />').text(FotoMozo.albums[aid]['name']));
		var photosContainer_table = $('<table style="max-height: 280px;"/>');
		var col = 0;
		var tr = $('<tr />');
		FotoMozo.pidsForAid[aid] = {};
		
		if (Pop.typeOf(results) === 'array')
		for (var i=0; i<results.length; ++i) {
			FotoMozo.pidsForAid[aid][results[i].pid] = 1;
			tr.append(
				$('<td class="photoContainer" />')
				.attr('pid', results[i].pid)
				.attr('aid', aid)
				.attr('background', results[i].src_small)
				.css('background-repeat', 'no-repeat')
				.css('background-position', 'center center')
				.append($('<img class="photo_thumb" />').attr('src', results[i].src_small).css('visibility','hidden'))
				.append($('<img class="check" style="width: 15px; height: 15px;"/>').attr('src', 'img/checkAll.gif'))
			);
			FotoMozo.photos[results[i].pid] = results[i];
			if (++col % numPhotoColumns == 0) {
				col = 0;
				photosContainer_table.append(tr);
				tr = $('<tr />');
			}
		}
		if (col != 0) {
			while (col < numPhotoColumns) {
				++col;
				tr.append($('<td />'));
			}
			photosContainer_table.append(tr);
		}
		photosContainer_div.append(photosContainer_table);
		photosContainer_div.addClass('filled');
		$('td', photosContainer_div).click(FotoMozo.togglePhoto);
	});
}

FotoMozo.togglePhoto = function() {
	var pid = $(this).attr('pid');
	var aid = $(this).attr('aid');
	if (aid in FotoMozo.uncheckedPidsForAid
	&& pid in FotoMozo.uncheckedPidsForAid[aid]
	&& FotoMozo.uncheckedPidsForAid[aid][pid]) {
		FotoMozo.checkPhoto(aid, pid, this);
	} else {
		FotoMozo.uncheckPhoto(aid, pid, this);
	}
	return false;
}

FotoMozo.checkPhoto = function(aid, pid, photo_td) {
	$('img.check', $(photo_td)).attr('src', 'img/checkAll.gif');
	FotoMozo.uncheckedPidsForAid[aid][pid] = 0;
	var someUnchecked = false;
	for (k in FotoMozo.uncheckedPidsForAid[aid]) {
		if (FotoMozo.uncheckedPidsForAid[aid][k]) {
			someUnchecked = true;
			break;
		}
	}
	if (!someUnchecked) {
		$('#linkForAid'+aid+' img.check').attr('src', 'img/checkAll.gif');		
	}
	FotoMozo.setCheckedPhotoCount(
		FotoMozo.getCheckedPhotoCount() + 1
	);
	++FotoMozo.checkedPhotoCountForAid[aid];
}

FotoMozo.uncheckPhoto = function(aid, pid, photo_td) {
	$('img.check', $(photo_td)).attr('src', 'img/checkNone.gif');
	FotoMozo.uncheckedPidsForAid[aid][pid] = 1;
	$('#linkForAid'+aid+' img.check').attr('src', 'img/checkSome.gif');
	FotoMozo.setCheckedPhotoCount(
		FotoMozo.getCheckedPhotoCount() - 1
	);
	--FotoMozo.checkedPhotoCountForAid[aid];
}

FotoMozo.sortByFirstName = function (a, b) {
    var x = a.first_name.toLowerCase() + ' ' + a.last_name.toLowerCase();
    var y = b.first_name.toLowerCase() + ' ' + b.last_name.toLowerCase();
    return ((x < y) ? -1 : ((x > y) ? 1 : 0));
}

FotoMozo.sortByName = function (a, b) {
    var x = a.name.toLowerCase();
	var y = b.name.toLowerCase();
	return ((x < y) ? -1 : (x > y) ? 1 : 0)
}

FotoMozo.makeMosaic = function() {
	if (FotoMozo.checkedPhotoCount < 20) {
		alert("You need to select more than 20 photos in order to make a good mosaic.");
		return false;
	}
	if (FotoMozo.checkedPhotoCount > 300) {
		alert("Too many photos selected. Please select less than 300 photos.");
		return false;
	}
	if (
		!$('#fb_photo_src_big').attr('value') &&
		!$('#source_upload_file').attr('value') &&
		!$('#presets_src_big').attr('value')
	) {
		alert("Select a final picture to produce a mosaic.");
		return false;
	}

	var temp_div = $("<div />");
	for (aid in FotoMozo.checkedAlbums) {
		if (!FotoMozo.checkedAlbums[aid]) {
			continue;
		}
		for (pid in FotoMozo.pidsForAid[aid]) {
			if (pid in FotoMozo.uncheckedPidsForAid[aid])
				continue;
			temp_div.append(
				$("<input type='hidden' />")
				 .attr('name', 'selectedPids['+aid+']['+pid+']')
				 .attr('value', FotoMozo.photosForAid[aid][pid].src_small)
			); 
			if (! (aid in FotoMozo.selectedPids)) {
				FotoMozo.selectedPids[aid] = {};
			}
			FotoMozo.selectedPids[aid][pid] = {
				"src_small": FotoMozo.photosForAid[aid][pid].src_small,
				"src_big": FotoMozo.photosForAid[aid][pid].src_small
			};
		}
	}
	$('#generating_info_div').html(temp_div);

	$('.generate.mosaic').attr('value', 'Please wait...').attr('disabled', 'disabled');

	$('#formNext')
	 //.attr('action', Pop.ajaxExtend('makeMosaic', 'content,alternate'))
	 .submit();
	
	// The iframe will load javascript to update all this stuff.
	
	return false;
	//$('#formNext').submit();
}

FotoMozo.friends = null;
FotoMozo.expandedFriends = {};
FotoMozo.checkedAlbums = {};
FotoMozo.userForAid = {};
FotoMozo.albumsForUid = {};
FotoMozo.albums = {};
FotoMozo.photosForAid = {};
FotoMozo.photoCountForAid = {};
FotoMozo.photos = {};
FotoMozo.checkedPhotoCount = 0;
FotoMozo.checkedPhotoCountForAid = {};
FotoMozo.pidsForAid = {};
FotoMozo.uncheckedPidsForAid = {};
FotoMozo.selectedPids = {};
FotoMozo.chosenPid = null;


// Photo selector and dialog

FotoMozo.facebookPhotoDialog = null;

FotoMozo.onPhotoClick = function(img) {
	var img_j = $(img);
	$('#fb_photo_src_big').attr('value', img_j.attr('src_big'));
	FotoMozo.chosenPid = img_j.attr('pid');
	//$('#preview_img').attr('src', img_j.attr('src')).zoomer('remove');
	$('#preview_img').attr('src', img_j.attr('src_big')).zoomer();
	$('.source.facebook.radio').attr('checked', 'checked');
	FotoMozo.facebookPhotoDialog.close();
	$('.generate.mosaic').removeAttr('disabled')
		.attr('value', 'Generate mosaic!');
	$('#preview_img').css('visibility', 'visible');
};

// Output dialog

FotoMozo.outputDialog = null;

FotoMozo.refreshMosaicOutput = function(secs, job_id) {
	window.setTimeout(
		function() {
			$.get(
				Pop.ajaxExtend('mosaicOutput?', 'content,alternate'),
				{"job_id": job_id}, 
				function(response) {
					FotoMozo.updateOutputDialogContents(response);
				}
			);
		}, 
		secs * 1000
	);
};

FotoMozo.updateOutputDialogContents = function(response, justOpening) {
	if (!justOpening && !FotoMozo.outputDialog.isOpened()) {
		return false;
	}
	var contents_div = $('div#outputDialog div.contents');
	if (typeof(response) == 'string') {
		eval('var data = ' + response + ';');
	} else {
		data = response;
	}
	if (('content' in data.slots) && data.slots.content) {
		contents_div.html(data.slots.content);
		$('img', contents_div).zoomer();
	} else {
		contents_div.html(data.slots.alternate);
	}
};

FotoMozo.showOutputDialog = function() {
	FotoMozo.outputDialog = $('div#outputDialog').overlay({
		api: true,
		color: '#c0c0c0',
		top: '20%',
		expose: {
			color: '#c0c0c0',
			opacity: 0.7,
			speed: 'fast',
			closeOnClick: false,
			closeOnEsc: true
		},
		onLoad: function(event) {
			
		},
		onClose: function(event) {
			$('.generate.mosaic').removeAttr('disabled')
				.attr('value', 'Generate mosaic!');
		}
	});
	
	FotoMozo.outputDialog.load();
};

FotoMozo.getCheckedPhotoCount = function() {
	return FotoMozo.checkedPhotoCount;
};

FotoMozo.setCheckedPhotoCount = function(newValue) {
	FotoMozo.checkedPhotoCount = newValue;
	var div = $('#checkedPhotoCount');
	div.html("Selected: <span class='blue'>" + newValue.toString() + "</span>");
	if (newValue > 0) {
		div.show(1000);
	}
};

FotoMozo.generateTagList = function() {

	// Get list of selected pids
	var c = 0, c_max = 50;
	var pids = [], pids_list = '';
	
	for (aid in FotoMozo.selectedPids) {
		for (pid in FotoMozo.selectedPids[aid]) {
			pids.push(pid);
		}
	}
	$.shuffle(pids);
	
	// Create a friend selector for tagging purposes
	var friend_selector = $('<ul />');
	var friends = FotoMozo.friends;
	var id = 'tag_uid' + uid;
	friend_selector.append(
		$('<li />').html(
			$('<input id="' + id + '" type="checkbox" />')
			.attr('value', uid)
		).append(
			$('<label for="' + id + '"/>').text('Me')
		)
	);
	if (Pop.typeOf(friends) === 'array')
	for (var i=0; i<friends.length; ++i) {
		id = 'tag_uid' + friends[i].uid;
		friend_selector.append(
			$('<li />').html(
				$('<input id="' + id + '" type="checkbox" />')
				.attr('value', friends[i].uid)
			).append(
				$('<label for="' + id + '"/>').text(
					friends[i].first_name + ' ' + friends[i].last_name
				)
			)
		);
	}
	$('input', friend_selector).change(function() {
		$('input:checked', friend_selector)
			.parent().prependTo(friend_selector);
	});
	
	// loop through all the pids, c_max at a time
	var pids2;
	for (var m_max = 0; m_max < pids.length; m_max += c_max) {
		pids2 = pids.slice(m_max, m_max+c_max-1);
		if ($('#fb_photo_src_big').attr('value')) {
			pids.push(FotoMozo.chosenPid);
		}
		pids_list = '"' + pids2.join('","') + '"';
		// Get a list of people tagged in them
		var api = FB.Facebook.apiClient;
		var uid = api.get_session().uid
		var query = "SELECT subject, pid FROM photo_tag WHERE pid IN (" + pids_list + ")";
		api.fql_query(query, function(results) {
			if (Pop.typeOf(results) == 'array')
			for (var i=0; i<results.length; ++i) {
				var id = 'tag_uid' + results[i].subject;
				$('#'+id).attr('checked', 'checked')
					.parent().prependTo(friend_selector);
			}
		});
	}
	
	var tagged_friends_div = $('#outputDialog .tagged_friends');
	tagged_friends_div.html(friend_selector);
	tagged_friends_div.css('display', 'block');
	return false;
	
	//FotoMozo.outputDialog.close();
	//$('#photosPane').html(friend_selector);
};

FotoMozo.startPublish = function() {
	$('.publish_button').hide();
	FB.Connect.showPermissionDialog("photo_upload", function(perms) {
		if (!perms) {
			alert("To publish your fotomozo, you must cilck Allow Photo Uploads. Please try again.");
			$('.publish_button').show();
			return false;
		}
		// Create an array of tagged UIDs
		var tagged_uids = [];
		var tagged_friends_div = $('#outputDialog .tagged_friends');
		$('input', tagged_friends_div).each(function() {
			if (this.checked) {
				tagged_uids.push(this.value);
			}
		});
		
		// Call our webservice to upload the photo
		if ('outBasename' in FotoMozo) {
			$.post(
				Pop.ajaxExtend('uploadMosaic?', 'content'),
				{
					"basename": FotoMozo.outBasename,
					"tagged_uids": tagged_uids.join(',')
				}, 
				function(response) {
					alert("SUCCESS! Your mosaic has been posted to your photo album.");
					FotoMozo.outputDialog.close();
				}
			);
		}
	});
};

FotoMozo.tag20 = function() {
	var tagged_friends_div = $('#outputDialog .tagged_friends');
	var checked_inputs = $('input:checked', tagged_friends_div);
	var other_inputs = $('input:not(:checked)', tagged_friends_div);
	if (checked_inputs.length < 20) {
		other_inputs.shuffle().slice(0,20-checked_inputs.length)
			.attr('checked', 'checked');
	}
	$('input:checked', tagged_friends_div)
		.parent().prependTo($('ul', tagged_friends_div));
};

FotoMozo.tagNoOne = function() {
	var tagged_friends_div = $('#outputDialog .tagged_friends');
	$('input[checked]', tagged_friends_div).each(function() {
		$(this).removeAttr('checked');
	});
};















(function($){
  $.fn.shuffle = function() {
    return this.length ? $.shuffle(this) : this;
  }
 
  $.shuffle = function( myArray ) {
    var i = myArray.length;
    if ( i == 0 ) return myArray;
    while ( --i ) {
       var j = Math.floor( Math.random() * ( i + 1 ) );
       var tempi = myArray[i];
       var tempj = myArray[j];
       myArray[i] = tempj;
       myArray[j] = tempi;
     }
    return myArray;
  };

/*

  $.shuffle = function(arr) {
    for(
      var j, x, i = arr.length; i;
      j = parseInt(Math.random() * i),
      x = arr[--i], arr[i] = arr[j], arr[j] = x
    );
    return arr;
  }

*/

})(jQuery);

