var AttendForm = new Class({
	Implements: [Options, Events, Log],

	// Variables
	options: {
		maxAttendees: 30,
		attendeesCols: 5,
		attendingText: 'Ik ga ook!',
		declinedText: 'Ik ga niet meer'
	},
	element: null,
	
	// Variables
	eventFacebookId: null,
	form: null,
	attendingContainer: null,
	formContainer: null,
	attendButton: null,
	attendingStatus: false,
	

	// Class instances
	application: null,
	
	initialize: function( element, eventFacebookId, options )
	{
		this.enableLog();
		//this.disableLog();
		this.log("AttendForm::initialize()");

		// Set variables
		this.element = element;
		this.eventFacebookId = eventFacebookId;
		this.setOptions(options);
		
		if(!this.element) return;
		
		this.application = new Application();
		this.attendingContainer = this.element.getElement('.people');
		this.formContainer = this.element.getElement('#attend-form');
		this.attendButton = this.formContainer.getElement('.attend');

		var handlers = {
			onRequest: function()
			{
				this.log("onRequest");

			}.bind(this),
			onSuccess: function(response)
			{
				this.log("response.success: "+ response.success);

				if(response.success)
				{
					this.log("succes!");

					this.form.disable();
					//this.addAttendee(response.name, response.image, response.profile);
				}
				else
				{
					this.log("error!");

				}
			}.bind(this),
			onFailure: function(xhr)
			{
				this.log("onFailure");

			}.bind(this)
		};

		var options = {
			showLoader: true,
			allowStatus: false,
			formErrorMessage: {
				allow: false
			}
		};

//		var form = new JsonForm(this.formContainer, this.requestUrl, handlers, options);
		var form = new Form(this.formContainer, options);

		// Add buttons
		var submitButton = new FormSubmitButton(form, this.attendButton, {showLoader: true});
		form.addButton(submitButton);

		// Save form
		this.form = form;
		this.form.submit = function()
		{
			this.log("SUBMIT JAAA");

			var status = 'attending';
			if(this.attendingStatus)
			{
				status = 'declined';
			}

			this.tryAttendEvent(status);
		}.bind(this);

//		this.form.addValue('facebook_event_id', this.eventFacebookId);

		/*
		this.form.addEvent('onSubmit', function() {

			this.log("onSubmit");

			this.tryAttendEvent();

		}.bind(this));
		*/
	},

	tryAttendEvent: function(status)
	{
		this.log("AttendForm::tryAttendEvent()");

		var handlers = {
			onSuccess: {
//				handler: this.setAttendStatus.bind(this),
				handler: this.checkEventStatus.bind(this),
				arguments: [status]
//				arguments: null
			},
			onFailure: {
				handler: function() {
					// Hide loader from button
					this.form.hideLoadState();
					// Enable button
					this.form.enable();
				}.bind(this),
				arguments: null
			}
		}
		var perms = 'rsvp_event';

		this.application.checkFacebookLoginStatus(handlers, perms);
	},

	checkEventStatus: function(status)
	{
		this.log("AttendForm::checkEventStatus(" + status + ")");

		this.log("this.eventFacebookId: " + this.eventFacebookId);

		//FB.api(this.eventFacebookId + '/attending/' + this.application.getFacebookUserId(), 'get', function(response) {
		FB.api(this.eventFacebookId + '/attending', 'get', function(response) {

			this.log("response: " + response);

			for(var i in response)
			{
				this.log("response[" + i + "]: " + response[i]);
			}
//			for(var i in response.data)
//			{
//				this.log("response.data[" + i + "]: " + response.data[i]);
//			}
			
			var userIds = [];
			if(response.data)
			{
				response.data.each(function(user, index) {

					this.log("user.id: " + user.id);
					userIds.include(user.id);

				}.bind(this));
				
				
				this.log("userIds.contains(this.application.getFacebookUserId()): " + userIds.contains(this.application.getFacebookUserId()));

	//			if(response.data[0])
				if(userIds.contains(this.application.getFacebookUserId()))
				{
					this.log("user is attending");

					if(status == 'attending')
					{
						this.log("status == attending");
						this.attendingStatus = true;
						this.attendButton.set('text', this.options.declinedText);

						this.form.enable();
					}
					else if(status == 'declined')
					{
						this.log("status == declined");
						this.setAttendStatus(status);
					}
				}
				else
				{
					this.log("user is NOT attending");

					this.setAttendStatus(status);
				}
			}
			
			if(response.error)
			{
				for(var j in response.error)
				{
					this.log("response.error[" + j + "]: " + response.error[j]);
				}
			}

			
		}.bind(this));
	},

	setAttendStatus: function(status)
	{
		this.log("AttendForm::setAttendStatus(" + status + ")");

		this.log(this.eventFacebookId + "/" + status);

		FB.api(this.eventFacebookId + '/' + status, 'post', function(response) {
			/*
			for(var i in response)
			{
				this.log("response[" + i + "]: " + response[i]);
			}
			if(response.error)
			{
				for(var j in response.error)
				{
					this.log("response.error[" + j + "]: " + response.error[j]);
				}
			}
			*/

			if(response)
			{
				//this.log(status + " success");
				var userId = this.application.getFacebookUserId();
				
				if(status == 'attending')
				{
					this.attendingStatus = true;
					this.attendButton.set('text', this.options.declinedText);
					
					this.addAttendee(userId);
				}
				else if(status == 'declined')
				{
					this.attendingStatus = false;
					this.attendButton.set('text', this.options.attendingText);
					
					this.removeAttendee(userId);
				}
				
				this.form.enable();
			}
			else
			{
				this.log("attending failed");

				this.form.enable();
			}
		}.bind(this));
	},

	addAttendee: function(userId)
	{
		this.log("AttendForm::addAttendee(" + userId + ")");

		var title = "Jij gaat ook!";
		var profile = "http://www.facebook.com/" + userId;
		var image = "https://graph.facebook.com/" + userId + "/picture";

		var attendee = new Element('div', {'class': 'attendee', 'id': 'attendee-' + userId});
		var link = new Element('a', {'href': profile, 'target': '_blank', 'title': title});
		attendee.adopt(link);

		// Show loader
		this.showImageLoadState(attendee);

		var loadedImage = new Asset.images([image], 
		{
			onProgress: function(counter, index) 
			{
				//this.log("onProgress: " + counter + ", " + index);
			}.bind(this),
			onComplete: function() 
			{
				var image = loadedImage[0];
				image.title = title;
				image.alt = title;
				image.width = 40;
				image.height = 40;

				// Insert image
				link.adopt(image);

				var imageElement = link.getElement('img').setStyle('opacity', 0);
				imageElement.fade('in');

				// Hide image loader
				this.hideImageLoadState(attendee);

				// Hide loader from button
				this.form.hideLoadState();
			}.bind(this),
			onAbort: function(counter, index)
			{
				//this.log("onAbort: " + counter + ", " + index);

				// Hide image loader
				this.hideImageLoadState(attendee);
			}.bind(this),
			onError: function(counter, index)
			{
				//this.log("onError: " + counter + ", " + index);

				// Hide image loader
				this.hideImageLoadState(attendee);
			}.bind(this)
		});

		// Rebuild attendees
		if(attendee) this.rebuildAttendees('add', attendee);
	},

	removeAttendee: function(userId)
	{
		this.log("AttendForm::removeAttendee(" + userId + ")");

		var attendee = this.attendingContainer.getElement('#attendee-' + userId);
		this.log("attendee: " + attendee);

		// Rebuild attendees
		if(attendee) this.rebuildAttendees('remove', attendee);
	},
	
	rebuildAttendees: function(action, attendee)
	{
		this.log("AttendForm::rebuildAttendees(" + action + ", " + attendee + ")");
	
		var attendees = this.attendingContainer.getElements('.attendee');

		if(action == 'add')
		{
			// Add to array
			attendees.splice(0, 0, attendee);
		}
		else if(action == 'remove')
		{
			var attendeeIndex = attendees.indexOf(attendee);
			
			// Remove from array
			attendees.splice(attendeeIndex, 1);
		}
	
		// Remove last attendee
		while(attendees.length > this.options.maxAttendees)
		{
			var lastIndex = attendees.length - 1;
			attendees.splice(lastIndex, 1);
		}

		// Clear attendees
		this.attendingContainer.empty();

		// Rebuild attendees
		var row;
		attendees.each(function(attendee, index) {

			//this.log(index + " " + attendee);

			// Remove classes
			attendee.removeClass('last-child');
			if(index % this.options.attendeesCols == (this.options.attendeesCols - 1)) attendee.addClass('last-child');
			if(index == 0) attendee.addClass('me');

			if(index % this.options.attendeesCols == 0)
			{
				row = new Element('div', {'class': 'row'});
				if(index > (this.options.maxAttendees - this.options.attendeesCols - 1)) row.addClass('last-child');

				this.attendingContainer.adopt(row);
			}

			row.adopt(attendee);

		}.bind(this));
	},

	/*
	 * Show image load state
	 */
	showImageLoadState: function(image)
	{
		this.log("AttendForm::showImageLoadState(" + image + ")");

		var loader = new Element('div', {'class': 'loader'});

		if(!image.getElement('.loader'))
		{
			image.adopt(loader);

			loader.fx = new Fx.Tween(loader, {
				duration: 250,
				transition: Fx.Transitions.Quad.easeOut,
				link: 'cancel',
				property: 'opacity'
			});
			loader.fx.addEvent('complete', function() {

				if(loader.getStyle('opacity').toInt() == 0)
				{
					loader.dispose();
				}
			}.bind(this));
			loader.fx.set(0);
		}

		loader.fx.start(1);
	},

	/*
	 * Hide image load state
	 */
	hideImageLoadState: function(image)
	{
		this.log("AttendForm::hideImageLoadState(" + image + ")");

		var loader = image.getElement('.loader');
		loader.fx.start(0);
	}


});
