if (typeof SvD == 'undefined') {
	throw('SvD.article.comments.js kräver SvD.js');
}

if (typeof jQuery != 'undefined') {

	/*** Artikelkommentering ***/
	SvD.article.comments = function ($) {

		return  {

			abuseID : null,
			alias : null,

			init : function () {
				if ($("#articlecomments").length === 0 || !SvD.enableAjax) { return; }

				this.articleComments = $("#articlecomments");
				this.addCommentButton = $("#addcommentbutton");
				this.abuseFormContainer = $("#reportcommentabuse");
				this.abuseForm = $("#articlecomments_abuseform");
				this.commentFormContainer = $("#commentthisarticle");
				this.commentForm = $("#articlecomments_postform");
				this.commentWrapper = $("#articlecomments_commentwrapper");
				this.commentFormAlias = $("#articlecomments_alias");

				this.setCommentFormBehaviours();
				this.setButtonBehaviours();
				this.setPagingBehaviours();
			},

			setButtonBehaviours : function () {
				var _this = this;

				this.addCommentButton.live("click", function(){
					_this.abuseFormContainer.hide();
		      		_this.commentFormContainer.slideToggle("fast");
		      		return false;
		   		 });

				this.commentWrapper.find(".buttons .abuse").live("click", function(){
					var path = $(this).attr("href");
					path = path.split("#")[0] + "&service=ajax";
					var comment = $(this).parents(".comment");
					var cid = comment.attr("id");
					cid = cid.replace(/articlecomment_/,"");
					_this.commentFormContainer.hide();

					if ((_this.abuseForm.length === 0 || cid != _this.abuseID)) {
						_this.abuseFormContainer.html('<p class="loading">Laddar...</p>').load(path, function() {
							_this.abuseID = cid;
							_this.setAbuseFormBehaviours(cid);
						});
					}

					_this.abuseFormContainer.show();
					SvD.utils.smoothScroll(_this.abuseFormContainer, 30, 500);
					return false;
				});

				this.commentWrapper.find(".buttons .reply").live("click", function(){
					var comment = $(this).parents(".comment");
					var replyName = comment.find(".name").text();
					var replyDate = comment.find(".date").text();
					var replyHeader = "Re: " + replyName + replyDate;
					$("#articlecomments_headline").val(replyHeader);
					_this.commentFormContainer.show();
					_this.abuseFormContainer.hide();
					SvD.utils.smoothScroll(_this.commentFormContainer, 10, 400);
					return false;
				});
			},

			setCommentFormBehaviours: function () {
				var _this = this;
				//_this.commentFormContainer.hide();

				var aliasFromCookie = $.cookie('SvD_CommentAlias');
				_this.commentFormAlias.val(aliasFromCookie);

				_this.commentForm.validate({
					event: "keyup",
					rules: {
						"field(alias)": "required",
						title: "required",
						body: { required: true, minlength: 1, maxlength: 500 },
						rules: "required"
					},
					messages: {
						"field(alias)": "Fyll i ditt alias",
						title: "Fyll i en rubrik",
						body: {
							required: "Skriv en kommentar",
							maxlength: "Max 500 tecken"
						},
						rules: "Du måste godkänna reglerna"
					},
					success: function(label) {
						label.html('Ok').addClass("valid");
					},

					submitHandler: function(form) {
						var debug = true;
						var url = location.href;
						var commentCount = _this.commentWrapper.find(".comment").length;

						url = url.split("#")[0];
						url = url.split("?")[0];
						url += "?service=ajax&component=commentDone";

						var targetUrl = url;

						/* if (commentCount < 1) {
							targetUrl = _this.commentForm.find("input[name=targetUrl]").val();
							targetUrl = targetUrl.split("=")[0];
							targetUrl += "=" + escape(url);
						} */

						_this.commentForm.find("input[name=customTargetUrl]").val(targetUrl);
						_this.commentForm.find("input[name=forward-failure]").val(url);

						var options = {
							type: 'POST',
							beforeSubmit: function() {
								_this.commentForm.find("input:submit").attr("disabled", "disabled").after('<p class="loading">Sparar din kommentar...</p>');
								var aliasFromForm = _this.commentFormAlias.val();
								_this.alias = aliasFromForm;
								$.cookie('SvD_CommentAlias', aliasFromForm);
								_this.commentFormContainer.find(".posterror").remove();
							},
		   					success: function(responseText, statusText) {
		   						_this.commentForm.find(".loading").remove();
								_this.commentForm.find(".error").remove();

		   						var response = responseText;
		   						if (response.indexOf("posterror") != -1) {
		   							_this.commentForm.before(responseText);
		   							if ($(".posterror .secondsleft").length !== 0) { _this.countdownUntilNextPost(); }
		   						} else {
									_this.commentForm.clearForm();
									_this.commentForm.find("input:submit").removeAttr("disabled");
									_this.addCommentButton.click();
									_this.commentFormAlias.val(_this.alias);
									_this.update('');

			   						if (typeof s_gi == "function") {
			   							var s = s_gi('svdsvdseprod,svdglobal');
			   							s.linkTrackVars='eVar16,events';
			   							s.linkTrackEvents='event16';
			   							s.events='event16';
			   							s.tl(this,'c','Comment posted');
			   						}
								}
							},
							error: function() {
								if (debug) {
									if (window.console && window.console.error) {
										console.error(arguments);
									}
								} else {
									alert("Ett fel har uppstått. Vänligen ladda om sidan och prova igen");
								}
							}
						};
						$(form).ajaxSubmit(options);
						return false;
					}
				});

				$("#articlecomments_comment").keyup( function() {
					var maxlength = 500;
					var comment = $.trim(this.value);
					var charsleft = maxlength - comment.length;
					var currentlength = ", " + charsleft + " tecken kvar";
					if (charsleft < 0) { currentlength = ", <strong>FEL:</strong> texten är för lång"; }
					_this.commentForm.find(".currentlength").html(currentlength);
				});

			},

			setAbuseFormBehaviours: function (cid) {
				_this = this;

				if (_this.abuseForm.length === 0) {
					_this.abuseForm = $("#articlecomments_abuseform");
				}

				_this.abuseForm.validate({
					event: "keyup",

					rules: {
						email: {
							required: true,
							email: true
						},
						body: { required: true, minlength: 1, maxlength: 500 }
					},
					messages: {
						email: "Fyll i din e-postadress",
						body: {
							required: "Fyll i en motivering",
							maxLength: "Din motivering får max vara 500 tecken lång"
						}
					},

					submitHandler: function(form) {
						var debug = true;
						var url = location.href;
						url = url.split("#")[0];
						url = url.split("?")[0];
						url += "?service=ajax&component=reportDone";

						_this.abuseForm.find("input[name=targetUrl]").val(url);
						_this.abuseForm.find("input[name=forward-failure]").val(url);
						_this.abuseForm.find("input[name=errorUrl]").val(url);

						var options = {
							type: 'POST',
							target: _this.abuseFormContainer,
							beforeSubmit: function() {
								_this.abuseForm.find("input:submit").attr("disabled", "disabled");
								_this.abuseForm.find("input:reset").attr("disabled", "disabled").after('<p class="loading">Sparar din anmälan...</p>');
							},
		   					success: function() {
								_this.abuseDoneBox();
							},
							error: function() {
								if (debug) {
									if (window.console && window.console.error) {
										console.error(arguments);
									}
								} else {
									alert("Ett fel har uppstått. Vänligen ladda om sidan och prova igen");
								}
							}
						};
						$(form).ajaxSubmit(options);
						return false;
					}
				});

				$("#articlecomments_abuse_cancel").click(function() {
					var anchor = "#articlecomment_";
					anchor += cid;
					_this.abuseFormContainer.slideUp("fast");
					SvD.utils.smoothScroll($(anchor), 30, 500);
				});
			},

			setPagingBehaviours: function () {
				_this = this;

				var paging = _this.articleComments.find(".articlecomments_paging_links");
				var pagingForm = $("#articlecomments_usersettings");

				paging.find("a").live("click", function(){
					paging.prepend('<p class="loading">Uppdaterar...</p>');
					_this.update(this.href);
					return false;
				});

				if (pagingForm.length === 0) { return; }
				var url = pagingForm.attr("action");
				url = url.split("#")[0];
				var options = {
					type: 'POST',
					url: url,
					target: _this.articleComments.find(".container"),
					beforeSubmit: function(formData) {
						formData.push({name: 'component', value: 'commentList'});
						formData.push({name: 'service', value: 'ajax'});
						pagingForm.find("input:submit").attr("disabled", "disabled").after('<p class="loading">Uppdaterar...</p>');
					},
					success: function() {
						SvD.utils.smoothScroll(_this.articleComments, 30, 500);
					}
				};
				pagingForm.live("submit", function(){
					$(this).ajaxSubmit(options);
					return false;
				});
			},

			update: function (url) {
				_this = this;
				var isNewComment = false;
				var noCacheDate = new Date();
				var timestamp = noCacheDate.getMinutes();

				if (url.length === 0) {
					var pagingUrl = _this.articleComments.find(".firstpage");
					if (pagingUrl.length !== 0) {
						url = pagingUrl.attr("href");
					} else {
						url = location.href;
					}
					url = url.split("#")[0];
					url = url.split("?")[0];
					isNewComment = true;
				} else {
					url = url.split("#")[0];
					url += "&";
				}
				if (url.indexOf("&") == -1) { url += "?"; }
				url += "component=commentList&service=ajax&ts=" + timestamp;

				_this.articleComments.find(".container").load(url, function() {
					SvD.utils.smoothScroll(_this.articleComments, 10, 400);
					if (isNewComment) { _this.highlightLatestComment(); }
				});
			},

			highlightLatestComment : function () {
				_this = this;
				var comment = _this.commentWrapper.find(".comment:first");
				comment.hide().fadeIn('slow').animate({opacity: 1.0}, 800);
			},

			abuseDoneBox : function () {
				_this = this;
				var box = _this.abuseFormContainer.find(".abuseresult");
				var button = box.find(".button");
				button.click(function() {
					box.slideUp("fast", function(){
					   box.remove();
					   SvD.utils.smoothScroll(_this.articleComments, 10, 400);
					});
				});
			},

			countdownUntilNextPost : function () {
				_this = this;
				var counter = _this.articleComments.find(".posterror .secondsleft");
				if (counter.length !== 0) {
					var currentVal = counter.text();
					if (currentVal > 0) {
						currentVal--;
						counter.text(currentVal);
						setTimeout('SvD.article.comments.countdownUntilNextPost()',1000);
					} else {
						counter.parents("p").text("Nu kan du posta din kommentar.");
						$("#articlecomments_submitbutton").removeAttr("disabled");
					}
				}
			}
		};
	}(jQuery);
}

if (typeof jQuery != 'undefined') {
	jQuery(document).ready(function() {
		SvD.article.comments.init();
	});
}