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

	// Variables
	element: null,
	requestUrl: null,
	eventId: null,
	form: null,
	application: null,
	commentsContainer: null,

	// Class instances
	
	initialize: function( element, requestUrl, eventId )
	{
		this.enableLog();
		//this.disableLog();
		this.log("CommentForm::initialize()");

		// Set variables
		this.element = element;
		this.requestUrl = requestUrl;
		this.eventId = eventId;
		this.application = new Application();

		this.commentsContainer = this.element.getElement('.comments');

		this.initForm();

		this.application.initFacebook();
	},

	/*
	 * Init form
	 */
	initForm: function()
	{
		this.log("CommentForm::initForm()");

		// Succes message
		this.succesMessage = this.element.getElement('.success-message');
		this.succesMessage.fx = new Fx.Tween(this.succesMessage, {
			duration: 500,
			transition: Fx.Transitions.Quad.easeOut,
			property: 'opacity',
			link: 'cancel'
		});
		this.succesMessage.fx.set(0);

		this.succesMessage.fx.addEvent('start', function() {

			if(this.succesMessage.getStyle('opacity').toInt() == 0)
			{
				this.succesMessage.show();
			}
		}.bind(this));

		this.succesMessage.fx.addEvent('complete', function() {
			
			if(this.succesMessage.getStyle('opacity').toInt() == 0)
			{
				this.succesMessage.hide();
			}
		}.bind(this));

		this.succesMessage.getElement('.another-comment').addEvent('click', function(event) {
			event.preventDefault();

			this.succesMessage.fx.start(0);
			this.form.reset();

		}.bind(this));

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

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

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

					this.succesMessage.fx.start(1);

					this.removeEmptyState();
					this.addComment(response);

					// Post on users wall
					var wallPost = this.form.elements[2].element.checked;
					if(wallPost && response.event) this.tryPostMessageOnWall(response.event);
					
					// Track event
					this.application.trackEvent('comment', 'success', this.application.page.name);
				}
				else
				{
					this.log("error!");

					this.form.formErrorMessage.clear();
					this.form.formErrorMessage.addMessage('message', 0, response.error);
					this.form.formErrorMessage.show();
					
					// Track event
					this.application.trackEvent('comment', 'error', this.application.page.name);
				}
			}.bind(this),
			onFailure: function(xhr)
			{
				this.log("onFailure");
				
				this.form.formErrorMessage.clear();
				this.form.formErrorMessage.addMessage('message', 0, "Je bericht kan niet worden verstuurd. Probeer het nogmaals.");
				this.form.formErrorMessage.show();
				
				// Track event
				this.application.trackEvent('comment', 'fail', this.application.page.name);
			}.bind(this)
		};

		var options = {
			showLoader: true,
			allowStatus: true,
			formErrorMessage: {
				allow: true,
				container: this.element.getElement('.form-message-container'),
				allowClose: false
			}
		};

		var elementOptions = {};

		var form = new JsonForm($('comment-form'), this.requestUrl, handlers, options);

		var messageElement = new FormElement(form, 'message', elementOptions);
		messageElement.addValidation(Form.REGEX_TEXT, 'Vul een reactie in');
		form.addElement(messageElement);
		
		var nameElement = new FormElement(form, 'name', elementOptions);
		nameElement.addValidation(Form.REGEX_NAME, 'Vul je naam in');
		form.addElement(nameElement);

		var wallPostElement = new FormElement(form, 'wall-post', {optional: true});
		form.addElement(wallPostElement);

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

		// Save form
		this.form = form;

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

			this.log("onSubmit");
			
			this.form.formErrorMessage.clear();
			
			// Track event
			this.application.trackEvent('comment', 'submit', this.application.page.name);

		}.bind(this));


		this.form.onSubmit = function()
		{
			this.log("CommentForm::form.onSubmit()");

			// Add event id
			this.form.addValue('event-id', this.eventId);

			var validate = this.form.validate();

			this.form.showStatus(validate);

			if(validate === true)
			{
				this.form.disable();
				this.form.showLoadState();

				var wallPost = this.form.elements[2].element.checked;

				if(wallPost)
				{
					this.tryFacebookLogin();
				}
				else
				{
					this.form.submit();
				}
			}
		}.bind(this);

	},

	addComment: function(data)
	{
		this.log("CommentForm::initForm(" + data + ")");

//		this.log("data.name: "+ data.name);
//		this.log("data.message: "+ data.message);
//		this.log("data.date: "+ data.date);
//		this.log("data.time: "+ data.time);
//		this.log("data.employee: "+ data.employee);

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

		if(data.employee)
		{
			comment.addClass('employee');
		}

		var message = new Element('div', {'class': 'message', 'html': '<p>' + data.message + '</p>'});
		var user = new Element('div', {'class': 'user'});
		user.adopt( new Element('p', {'class': 'name', 'html': data.name}) );
		user.adopt( new Element('p', {'html': 'Geplaatst op <strong>' + data.date + '</strong> om <strong>' + data.time + '</strong>'}) );

		comment.adopt(message);
		comment.adopt(user);

		comment.inject(this.commentsContainer, 'top');
		comment.hide();

		// Animation
		comment.fx = new Fx.Reveal(comment, {
			duration: 400,
			transitionOpacity: true
		});

		comment.fx.reveal();
		comment.fx.addEvent('show', function()
		{
			comment.highlight('#ff6c00');
		}.bind(this));
	},

	removeEmptyState: function()
	{
		this.log("CommentForm::removeEmptyState()");

		var emptyState = this.element.getElement('.empty-state');

		if(emptyState)
		{
			// Animation
			emptyState.fx = new Fx.Reveal(emptyState, {
				duration: 400,
				transitionOpacity: true
			});

			emptyState.fx.dissolve();
			emptyState.fx.addEvent('hide', function()
			{
				emptyState.dispose();
			}.bind(this));
		}
	},

	tryFacebookLogin: function()
	{
		this.log("CommentForm::tryFacebookLogin()");

		//this.form.submit();

		var handlers = {
			onSuccess: {
				handler: function() {
					this.log("onSuccess handler");
					this.form.submit();
				}.bind(this),
				arguments: null
			},
			onFailure: {
				handler: function() {
					this.log("onFailure handler");
				}.bind(this),
				arguments: null
			}
		}
		var perms = 'publish_stream';

		this.application.checkFacebookLoginStatus(handlers, perms);
		
		// Track event
		this.application.trackEvent('comment', 'facebook login - try', this.application.page.name);
	},

	tryPostMessageOnWall: function(event)
	{
		this.log("CommentForm::tryPostMessageOnWall(" + event + ")");

		//this.postMessageOnWall(event);

		var handlers = {
			onSuccess: {
				handler: this.postMessageOnWall.bind(this),
				arguments: [event]
			},
			onFailure: {
				handler: null,
				arguments: null
			}
		}
		var perms = 'publish_stream';

		this.application.checkFacebookLoginStatus(handlers, perms);
		
		// Track event
		this.application.trackEvent('comment', 'facebook post - try', this.application.page.name);
	},

	postMessageOnWall: function(event)
	{
		this.log("CommentForm::postMessageOnWall(" + event + ")");

		var comment = this.form.elements[0].element.value;
		var user = this.form.elements[1].element.value;
		// Remove employee tag and trim spaces
		user = user.split('$Mezz$')[0].trim();

		var message = user + ' schreef: "' + comment + '" over ' + event.title;

		FB.api(
			{
				method: 'stream.publish',
				message: message,
				attachment:
				{
					name: event.title,
					caption: event.venue + ' / ' + event.time,// + ' / ' + event.price,
					description: event.description,
					media: [
					{
						type: "image",
						src: event.image,
						href: event.link
					}],
					href: event.link
				}
			},
			function(response)
			{
				if(!response || response.error)
				{
					this.log('Error occured');

					if(response.error)
					{
						for(var j in response.error)
						{
							this.log("response.error[" + j + "]: " + response.error[j]);
						}
					}
					
					// Track event
					this.application.trackEvent('comment', 'facebook post - error', this.application.page.name);
				}
				else
				{
					this.log('response: ' + response);
					
					// Track event
					this.application.trackEvent('comment', 'facebook post - success', this.application.page.name);
				}
			}.bind(this)
		);
	}

});
