var SMDelegate = function() {
};

SMDelegate.prototype = {
	connections: Array(),	
	connectionsLoaded: false,

	tsEvents: Array(),
	tsEventIndex: function() {
		return $("#event-select").val();
	},

	containerClass:'connection-container',
	containerSelectedClass:'connection-container-selected',	
	
	selectElementClass:'connection-select',	
	
	isFacebookLoggedIn: false,
	appPermissions: 'email, rsvp_event, publish_stream',
	
	loadingAnimationTimer: null,
	loadingAnimationDelay: 100,
	loadingAnimationBarTotal: 13,
	loadingAnimationDirection: 1,
	loaderCloseDelay: 3000,
	
	filterConnections: function() {
		var filter = $(this).val();
	
		var delegate = $("#friends-box").data("delegate");
		
		if (delegate) {
			for (i = 0; i < delegate.connections.length; i++) {
				delegate.connections[i].filter(filter);
			}
		}
	},
	
	sendInvites: function(callback) {
		this.facebookAPIDelegate(
			$.proxy(
				function() {
					this.showLoader("Sending invites");
					
					if (this.eventIndex == "none") {
						this.hideLoader("Please select an event");
					} else {
						eventName = this.tsEvents[this.tsEventIndex()]["eventName"];
						eventLink = this.tsEvents[this.tsEventIndex()]["eventLink"];
						eventPic = this.tsEvents[this.tsEventIndex()]["eventPic"];
						
						delegate = this;
						
						batch = Array();
						
						if ($('.'+this.containerSelectedClass).length) {
							$('.'+this.containerSelectedClass).each(function() {
								connection = $(this).data('connection');
								
								target = '/' + connection.connectionId + '/feed';
								options = {
									message: smInviteFriendText, 
									name:eventName, 
									link:eventLink, 
									picture:eventPic
								};
								
								post = {
									method: "POST", 
									relative_url: target,
									body: options
								};
								
								batch[batch.length] = post;
							});
							
							this.batchPostToFacebookWall(batch, 0, $.proxy(function() {
								delegate.hideLoader("Invites sent successfully");
								
								if (callback) callback();
							}), this);
						} else {
							this.hideLoader("Please select some friends to invite.");
						}
					}
				}, this
			)
			, this
			, this.sendInvites
			, arguments
		);
	},
	
	postToFacebookWall: function(target, body, callback) {
		this.facebookAPIDelegate(
			$.proxy(
				function() {
					FB.api(target, 'POST', body, $.proxy(
						function(response) {
							var fbPost = response;
						
							if (callback) {
								callback(response);
							}
								
						}, this)
					);			
				}, this
			)
			, this
			, this.postToFacebookWall
			, arguments
		);
	},
	
	batchPostToFacebookWall: function(batch, index, callback) {
		this.facebookAPIDelegate(
			$.proxy(
				function() {
					if (batch.length > index) {
						target = batch[index].relative_url;
						body = batch[index].body;
						
						this.postToFacebookWall(target, body, $.proxy(function(response) {
							this.batchPostToFacebookWall(batch, index + 1, callback);
						}, this));
					} else {
						if (callback) callback();
					}
				}, this
			)
			, this
			, this.batchPostToFacebookWall
			, arguments
		);
	},	
	loadFacebookFriends: function() {
		$("#fb-select-radio").attr("checked", true);
		
		this.facebookAPIDelegate(
			$.proxy(
				function() {
					if (!this.connectionsLoaded) {
						this.showLoader("Loading");
					
						this.connectionsLoaded = true;
		
						FB.api('/me/friends', $.proxy(
							function(response) {
								var friends = response.data;
			
								$('#facebook-button-text').text(" ("+friends.length+")");
				
								for (var count = 0; count < friends.length; count++) {
									var connection = new SMConnection();
									
									connection.connectionId = friends[count].id;
									connection.name = friends[count].name;
									connection.type = 'facebook';
									
									this.connections[this.connections.length] = connection;
								}
								
								this.hideLoader();
								
								this.showConnections();
							}, this)
						);	
					} else {
						this.showConnections();
					}
				}, this
			)
			, this
			, this.loadFacebookFriends
			, arguments
		);
	},
	
	getFacebookEventInfo: function(eventId, callback) {
		this.facebookAPIDelegate(
			$.proxy(
				function() {
					FB.api('/'+eventId, $.proxy(
						function(response) {
							if (callback) callback(response);
						}
						, this)
					)
				}
				, this
			)
			, this
			, this.getFacebookEventInfo
			, arguments
		);
	},	
	
	attendFacebookEvent: function(facebookEventId, postOptions, callback) {
		this.facebookAPIDelegate(
			$.proxy(function() {
				this.getFacebookEventInfo(facebookEventId, $.proxy(
					function(facebookEvent) {
						if (!facebookEvent.error) {
							this.submitFacebookAttendingInfo(facebookEvent);
						}
						
						this.postToFacebookWall("/me/feed", postOptions, callback);
					}, this)
				)
				}, this
			)
			, this
			, this.attendFacebookEvent
			, arguments
		)
	},
	
	submitFacebookAttendingInfo: function(facebookEvent) {
		this.facebookAPIDelegate(
			$.proxy(
				function() {
					FB.api('/'+facebookEvent.id+'/attending', 'post', $.proxy(
							function(response) {
								if (!response || response.error) {
								} else {
									// we sucessfully rsvp'd attending to the event
								}
							}
							, this
						)
					)
				}, this
			)
			, this
			, this.submitFacebookAttendingInfo
			, arguments
		);
	},	

	loginFacebook: function(callback) {
		FB.getLoginStatus($.proxy(
			function(response) {
				if (response.session){
					this.isFacebookLoggedIn = true;
					
					if (callback) callback();
				}
				else {
					FB.login($.proxy(
						function(response) {
							if (response.authResponse) {	
								this.isFacebookLoggedIn = true;
								
								if (callback) callback();
							}
						}
						, this)
						, {scope: this.appPermissions}
					);
				}
			}
			, this)
		);
	},
	
	facebookAPIDelegate: function(action, obj, caller, args) {
		if (this.isFacebookLoggedIn) {
			action();
		} else {
			this.loginFacebook($.proxy(
				function() {
					caller.apply(obj, args);
				}), this
			);
		}
	},

	showConnections: function() {
		$("#friends-box").html("");
		
		$("#friends-box").data("delegate", this);
		
		$div = $("<div></div>");
		
		for (var i = 0; i < this.connections.length; i++) {
			this.connections[i]
				.createContainer()
				.appendTo($div);
			
			if ($("#connections-filter").val() != $("#connections-filter").attr("title"))
				this.connections[i].filter($("#connections-filter").val());
		}
		
		$div.appendTo($("#friends-box"));
	},
	
	showLoader: function(message, hideAnimation) {
		$loadingDialog = $("#sm-loading-dialog");
		$contentArea = $("#sm-loading-dialog .content-area");
		
		if (!$loadingDialog || ($loadingDialog.length == 0)) {
		
			// loading dialog
			$loadingDialog = $("<div></div>")
				.attr({
					id: "sm-loading-dialog"
				}).css({					
					"display": "none"
			});

			$contentArea = $("<div></div>")
				.addClass("content-area")
				.appendTo($loadingDialog);


			if (message && message.length > 0) {
				// content area			
				$messageArea = $("<h2></h2>")
					.html(message)
					.appendTo($contentArea);
			}
				
			$loadingDialog.appendTo("body");
		}
		
		$animationContainer = $("#sm-loading-dialog .animation-container");
		
		if (!hideAnimation) {
			if (!$animationContainer || ($animationContainer.length == 0)) {
			
				$animationContainer = $("<div></div>")
					.addClass("animation-container")
					.appendTo($contentArea);
					
				for (i = 0; i < this.loadingAnimationBarTotal; i++) {
					$animationBar = $("<div></div>")
						.addClass("animation-bar")
						.appendTo($animationContainer);
				}
				
				$animationContainer.css({
					"width": (this.loadingAnimationBarTotal * (parseInt($animationBar.css("width")) + 
							parseInt($animationBar.css("margin-left")) + 
							parseInt($animationBar.css("margin-right")))) + "px",

					"height": $animationBar.css("height")
				});
			}

			this.updateLoadingAnimation();
			this.loadingAnimationTimer = setInterval($.proxy(this.updateLoadingAnimation, this), this.loadingAnimationDelay);
		}
		
		$("#sm-loading-dialog").dialog({
			width: 400,
			height: 200,
			modal: true,
			draggable: false,
			resizable: false,
			dialogClass: "sm-loading-dialog-container",
			open: function() {
			},
			close: $.proxy(function() {
				this.loaderDidClose();
			}, this)
		});
	},
	
	hideLoader: function(message) {
		var delay = 0;
	
		if (message && message.length > 0) {
			$messageArea = $("#sm-loading-dialog h2");
			$messageArea.html(message);
			
			delay = this.loaderCloseDelay;
		}
		
		setTimeout(function() {
				$("#sm-loading-dialog").dialog('close');
			},
			delay
		);
		
		this.loaderDidClose();
	},
	
	loaderDidClose: function() {
		clearInterval(this.loadingAnimationTimer);
	},
	
	updateLoadingAnimation: function() {
		// see if we have any medium or large bars
		largeBarIndex = -1;
		
		$animationBars = $("#sm-loading-dialog .animation-bar");
		
		$animationBars.each(function(index, value) {
			if ($(this).hasClass("large"))
				largeBarIndex = index;
		});
		
		if (largeBarIndex == -1) {
			largeBarIndex = Math.round(this.loadingAnimationBarTotal / 2);
		}
				
		if ((this.loadingAnimationDirection == 1 && (largeBarIndex + 2 >= this.loadingAnimationBarTotal)) || 
			(this.loadingAnimationDirection == -1 && (largeBarIndex - 1 <= 0)))
			this.loadingAnimationDirection = (this.loadingAnimationDirection == -1) ? 1 : -1;
		
		largeBarIndex = largeBarIndex + this.loadingAnimationDirection;		
		
		$animationBars.each(function(index, value) {
			$(this).removeClass("medium");
			$(this).removeClass("large");

			if (index == largeBarIndex) {
				$(this).addClass("large");
			}
				
			if (index == (largeBarIndex + 1) || index == (largeBarIndex - 1)) {
				$(this).addClass("medium");
			}
		});
	}
};


var SMConnection = function() {
};

SMConnection.prototype = {

	connectionId:0,
	name:'',
	type:'',
	
	$container:null,
	
	containerClass:'connection-container',
	containerSelectedClass:'connection-container-selected',	
	
	selectElementClass:'connection-select',

	createContainer: function () {
		this.$container = $("<div></div>")
			.addClass(this.containerClass)
			.click(this.containerWasSelected);

		this.$container.data("connection", this);

		$('<input type="checkbox" />')
			.appendTo(
				$('<div></div>')
					.addClass(this.selectElementClass)
					.appendTo(this.$container)
				);
		
		$('<img src="https://graph.facebook.com/' + this.connectionId + '/picture?type=square"></img>')
			.attr('width', '50')
			.attr('height', '50')
			.css('float', 'left')
			.appendTo(
				$('<div></div>')
				.addClass('friend-pic')
				.appendTo(this.$container)
			);

		$('<p>' + this.name + '</p><p><span class="facebook-type">Facebook</span></p>')
			.appendTo(
				$('<div></div>')
					.addClass('friend-info')
					.appendTo(this.$container)
			);

		
		return this.$container;	
	},

	containerWasSelected: function() {
		$container = $(this);
		
		if ($container) {
			var containerSelectedClass = $container.data("connection").containerSelectedClass;

			if ($container.hasClass(containerSelectedClass)) {
				$container.removeClass(containerSelectedClass);
				$container.find('input[type=checkbox]').removeAttr('checked');
			} else {
				$container.addClass(containerSelectedClass);
				$container.find('input[type=checkbox]').attr('checked', true);
			}
		}
	},
	
	filter: function(value) {
		if (value && value.length > 0) {
			if (this.name.toLowerCase().indexOf(value.toLowerCase()) >= 0) {
				this.$container.show();
			} else {
				this.$container.hide();
			}
		} else {
			this.$container.show();
		}
	}
}

/*
function fb_attendingEvent(fEventId, fEventLink) {
	eventId = fEventId;
	eventLink = fEventLink;

	FB.getLoginStatus(function(response){
		if (response.session){
			FB.api('/'+eventId, function(response) {
				fb_postAttendingInfo(response);
			});
		}
		else {
			FB.login(function(response) {
				if (response.authResponse) {						
					FB.api('/'+eventId, function(response) {
						fb_postAttendingInfo(response);
					});
				}
			}, {scope: appPermissions});
		}
	});
}
*/
