dojo.provide("ecnext.manta.asktheexpert.AskTheExpertController");

dojo.require("ecnext.JsonService");
dojo.require("ecnext.manta.ScreennamePopupController");

dojo.declare("ecnext.manta.asktheexpert.AskTheExpertController", null , {
	widgets: null,
	jsonService: null,
	screennameController: null,
	subId: null,
	categoryName: null,
	
	constructor: function(kwArgs) {
		this.subId = 'subId' in kwArgs ? kwArgs.subId : '';
		this.categoryName = 'categoryName' in kwArgs ? kwArgs.categoryName : '';

		this.screennameController = new ecnext.manta.ScreennamePopupController();

		this.widgets = {
			myQuestionForm: dojo.byId('my-question-form'),
			myQuestion: dojo.byId('my-question'),
			myQuestionScreenname: dojo.byId('my-question-screenname'),
			myQuestionTxt: dojo.byId('my-question-txt'),

			commentTemplateContainer: dojo.byId('comment-template-container-'),
			commentTemplateTxt: dojo.byId('comment-template-txt'),
			commentTemplateCreatedTimestamp: dojo.byId('comment-template-created_timestamp'),
			commentTemplateAuthorScreenname: dojo.byId('comment-template-author_screenname'),
			newCommentsContainer: dojo.byId('new-comments-container'),

			commentForm: dojo.byId('comment-form'),

			screennameForm: dojo.byId('screenname-form'),
			screennameFormError: dojo.byId('screenname-form-error')
		};

		this.jsonService = new ecnext.JsonService({uri: '/api/ask_the_expert'});
	},

	createWidgets: function(kwArgs) {
		this.screennameController.createWidgets(kwArgs);

		this.listen();

		var uri = window.location.href;
		if (uri.indexOf('action=addQuestion') != - 1) {
			this.submitQuestion();
		}
		else if (uri.indexOf('action=addComment') != -1) {
			this.submitComment();
		}
	},

	listen: function() {
		if (this.widgets.myQuestionForm) {
			dojo.connect(this.widgets.myQuestionForm.question_submit,
				"onclick", dojo.hitch(this, "submitQuestion"));
		}

		if (this.widgets.commentForm) {
			dojo.connect(this.widgets.commentForm.comment_submit,
				"onclick", dojo.hitch(this, "submitComment"));
		}

		dojo.subscribe("ecnext-screenname-popup-success", this, "_continueOnScreennameSuccess");

		dojo.subscribe("ecnext-ask_the_expert-delete-comment",
			dojo.hitch(this, "deleteComment"));
	},

	deleteComment: function(event) {
		var id = event.args.id;

		var dResult = this.jsonService.sendMessage({msg: {
			action: 'deleteComment',
            id: id
		}});

		dResult.addCallback(function(result) {
			if (result) {
				var node = dojo.byId('comment-container-' + id);
				if (node) {
					node.style.display = 'none';
				}
			}
			return result;
		});

		dResult.addErrback(function(error) {
			alert("there was an error deleting comment (" + id + ")");
			return error;
		});
	},

	submitQuestion: function(event) {
		if (this.subId) {
			var screenname = this.getScreenname();
			if (screenname) {
				this._submitQuestion();
			}
			else {
				this.addScreenname(dojo.hitch(this, "_submitQuestion"),
					event, {positionCallback: mkPositionLeftCb(300)});
			}
		}
		else {
			var questionTxt = this.widgets.myQuestionForm.question.value;
			var categoryName = this.categoryName;
			this._redirectToLogin(
				'/api/ask_the_expert?action=addQuestion&txt=' + encodeURIComponent(questionTxt) + '&categoryName=' + encodeURIComponent(categoryName),
				'question');
		}
	},

	_submitQuestion: function() {
		var prevSubmitValue = this.widgets.myQuestionForm.question_submit.value;
		this.widgets.myQuestionForm.question_submit.value = 'Saving...';
		this.widgets.myQuestionForm.question_submit.disabled = true;

		var categoryName = this.categoryName;
		var questionTxt = this.widgets.myQuestionForm.question.value;
		var dResult = this.jsonService.sendMessage({
			msg: {
				action: 'addQuestion',
				categoryName: categoryName,
				txt: questionTxt
			}
		});

		//this.widgets.myQuestion.style.display = '';
		//this.widgets.myQuestionForm.style.display = 'none';

		var _this = this;
		var questionTxtNode = this.widgets.myQuestionTxt;
		dResult.addBoth(function(response) {
			_this.widgets.myQuestionForm.question_submit.value = prevSubmitValue;
			_this.widgets.myQuestionForm.question_submit.disabled = false;
			return response;
		});
		dResult.addCallback(function(result) {
			ecnext.textContent(questionTxtNode, questionTxt);
			_this.widgets.myQuestionForm.question.value = '';
			_this.widgets.myQuestion.style.display = '';
			return result;
		});
		dResult.addErrback(function(error) {
			alert("there was an error submitting your question");
			return error;
		});
	},

	submitComment: function(event) {
		if (this.subId) {
			var screenname = this.getScreenname();
			if (screenname) {
				this._submitComment();
			}
			else {
				this.addScreenname(dojo.hitch(this, "_submitComment"),
					event, {positionCallback: mkPositionLeftCb(300)});
			}
		}
		else {
			var commentTxt = this.widgets.commentForm.comment.value;
			var questionId = this.widgets.commentForm.questionId.value;
			this._redirectToLogin(
				'/api/ask_the_expert?action=addComment&txt='
				+ encodeURIComponent(commentTxt)
				+ '&questionId=' + encodeURIComponent(questionId),
				'comment');
		}
	},

	_submitComment: function() {
		var commentTxt = this.widgets.commentForm.comment.value;
		var questionId = this.widgets.commentForm.questionId.value;

		var prevSubmitValue = this.widgets.commentForm.comment_submit.value;
		this.widgets.commentForm.comment_submit.value = 'Saving...';
		this.widgets.commentForm.comment_submit.disabled = true;

		var dResult = this.jsonService.sendMessage({
			msg: {
				action: 'addComment',
				txt: commentTxt,
				questionId: questionId
			}
		});

		var _this = this;
		dResult.addBoth(function(response) {
			_this.widgets.commentForm.comment_submit.value = prevSubmitValue;
			_this.widgets.commentForm.comment_submit.disabled = false;
			return response;
		});

		dResult.addCallback(function(result) {
			_this.widgets.commentForm.comment.value = '';
			ecnext.textContent(_this.widgets.commentTemplateTxt, result.txt);
			ecnext.textContent(_this.widgets.commentTemplateCreatedTimestamp, result.created_timestamp);
			ecnext.textContent(_this.widgets.commentTemplateAuthorScreenname, result.author_screenname);

			var newComment = _this.widgets.commentTemplateContainer.cloneNode(true);
			var ncc = _this.widgets.newCommentsContainer;
			ncc.insertBefore(newComment, ncc.firstChild);
			newComment.style.display = '';

			return result;
		});

		dResult.addErrback(function(error) {
			alert("there was an error submitting your comment");
			return error;
		});

		return dResult;
	},

	_continueOnScreennameSuccess: function() {
		this._addScreennameContinuation();
	},

	getScreenname: function(next) {
		return this.screennameController.getScreenname();
	},

	_addScreennameContinuation: null,
	addScreenname: function(continuation, event, showTooltipArgs) {
		this._addScreennameContinuation = continuation;
		this.screennameController.showPopup(event, showTooltipArgs);
	},

	_redirectToLogin: function(rld, redirectType) {
		var finalDestination = window.location.href;
		rld += "&atefd=" + encodeURIComponent(finalDestination);

		var newLocation = "https://www.manta.com/member/register/?rl=asktheexpert" + redirectType + "&view=asktheexpert&rld=" + encodeURIComponent(rld);

		window.location = newLocation;
	},

	zLastFunction: function() {}
});

