﻿/*globals window,document,alert,confirm,jQuery,unescape*/
if (typeof jQuery.isJson !== "function") {
	jQuery.isJson = function (str) {
		if (typeof str === "string") {
			if (jQuery.trim(str) === "") {
				return false;
			} else {
				str = str.replace(/\\./g, '@').replace(/"[^"\\\n\r]*"/g, "");
				return (/^[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]*$/).test(str);
			}
		} else {
			return true;
		}
	};
}
(function ($) {
	$.fn.cjBokoComments = function (options) {

		var settings = {
			// user editable settings
			base_url: "",
			top_base_url: "",
			author_ID: 0,
			entry_ID: 0,
			version_ID: 0
		};

		var sys = {
			elem: null,
			timer: null
		};
		
		function doEvalJSON(r) {
			try {
				if (typeof r === "string") {
					return JSON.parse(jQuery.trim(r));
				} else if (typeof r === "object") {
					return r;
				} else {
					return {
						"ERROR": true,
						"ERROR_MSG": "Error parsing JSON object."
					};
				}
			} catch(err) {
				if (typeof console !== "undefined") {
					console.debug(err);
				}
				console.debug(r);
			}
		}

		/*
			plugin functions
		----------------------------- */
		function doShowError(msg, flds) {
			var i, more, err;
			// handle adding the error class to the fields
			if (typeof flds === "string" && flds.length > 0) {
			
			}
			// handle alert window
			err = '<div class="ui-widget"><div class="ui-state-error ui-corner-all" style="padding:0 .7em;"><p style="padding:2px;margin:0"><span class="ui-icon ui-icon-alert" style="float:left;margin-right:.3em;"><\/span><strong>Oops! Something went wrong!<\/strong><br \/>The following errors were detected while processing the last request.<\/p>';
			if (typeof msg === 'object') {
				err += '<ul style="padding:2px;margin:0">';
				for (i = 0; i < msg.length; i++) {
					err += '<li style="padding:2px;margin:0">' + unescape(msg[i]) + '<\/li>';
					if (i > 3) {
						more = (msg.length - 3 > 0) ? true : false;
						break;
					}
				}
				err += '<\/ul>';
				if (more) {
					err += '<p style="padding:2px;margin:0">... There\'s <strong>' + (msg.length - 3 > 0) + '</strong> other problem' + (msg.length - 3 > 1 ? 's' : '') + ' not listed. (Error' + (msg.length - 3 > 1 ? 's' : '') + ' highlighted below)<\/p>';
				}
			} else if (typeof msg === 'string') {
				err += '<p>' + msg + '<\/p>';
			}
			err += '<\/div><\/div><br \/>';
			$('#cj_comment_form_error_wrapper').append(err);
			$('#cj_comment_form_error_wrapper').effect('shake', {},
			100);
			return;
		}

		function doFormPostEval(result) {
			var r = doEvalJSON(result);
			$('#cj_comment_form_error_wrapper').html("");
			try {
				if (jQuery.isJson(r)) {
					if (typeof r === "object" && typeof r.X_ERROR_TYPE === "string" && r.X_ERROR_TYPE === "error" && typeof r.X_ERROR_MSGS === "object" && typeof r.X_ERROR_FIELDS === "string") {
						$(sys.elem).find("button[type=submit]").attr("disabled", false);
						doShowError(r.X_ERROR_MSGS, r.X_ERROR_FIELDS);
					} else if (typeof r === "object" && typeof r.ERROR === "boolean" && r.ERROR === true && typeof r.ERROR_MSG === "string") {
						$(sys.elem).find("button[type=submit]").attr("disabled", false);
						doShowError(r.ERROR_MSG);
					} else if(typeof r.ERROR === "boolean" && r.ERROR === false) {
						// everyting groovy... reload the page?
						window.location.reload();
					} else {
						// we got something else? unknown error?!
						doShowError("An unexpected error was encountered attempting to post your comment.");
					}
				} else {
					// unknown result or length is 0 (Old problem, iFrame did not receive the ajax callback)
					if (typeof console !== "undefined") {
						console.debug("Unknown result type: " + typeof result + " Length: " + result.legth);
					}
					return;
				}
			} catch (err) {	
				if (typeof console !== "undefined") {
					console.debug(err);
				}
			}
		}

		function init() {

			// setup our comment display
			$("#boko_comments div.comment-options").show();
			$("#boko_comments a.boko_icon_reply").bind("click", function () {
				$("#boko_comments div.comment-options").css("display", "none");
				$("#boko_comments #butCommentPost").css("display", "none");
				$("#boko_comments_header_desc").hide();
				$("#boko-comment-form").show("slide", {
					direction: "up",
					duration: "fast"
				});
				$("#boko-comment-form input#parentID").val(($(this).attr("id")).replace("reply_", ""));
				$("#boko-comment-form textarea#comment_content").val($(this).attr("rel") + " - ");
				window.scrollTo(0, $("#boko_comments #butCommentCancel").offset().top);
			});
			$("#boko_comments #butCommentPost").bind("click", function () {
				$("#boko_comments div.comment-options").css("display", "none");
				$("#boko_comments #butCommentPost").css("display", "none");
				$("#boko_comments_header_desc").hide();
				$("#boko-comment-form").show("slide", {
					direction: "up",
					duration: "fast"
				});
				window.scrollTo(0, $("#boko_comments #butCommentCancel").offset().top);
			});
			$("#boko_comments #butCommentCancel").bind("click", function () {
				$("#boko-comment-form").hide("slide", {
					direction: "up",
					duration: "fast"
				});
				$("#boko_comments #butCommentPost").show();
				$("#boko_comments_header_desc").show();
				$("#boko_comments div.comment-options").show();
				$("#boko-comment-form input#parentID").val("");
				$("#boko-comment-form textarea#comment_content").val("");
				$('#cj_comment_form_error_wrapper').html("");
			});
			
			$("#boko_comments a.link_login_comment").bind("click", function(e) {
				if($("#loginbox").css("display") !== "block") {
					$("#loginbox").show("slide", { direction: "up", duration: "fast" });
					document.location.href = $(this).attr("href");
				}
				return true;
			});

			// setup our form
			$(sys.elem).submit(function () {
				var ifrmName = "uploader" + new Date().getTime();
				var ifrm = $("<iframe name=\"" + ifrmName + "\" id=\"" + ifrmName + "\" src=\"about:blank\" />");
				$(sys.elem).find("button[type=submit]").attr("disabled", true);
				$('#cj_comment_form_error_wrapper').html("");
				ifrm.css({
					"display": "none",
					"width": "1px",
					"height": "1px"
				});
				$(ifrm).load(function (e) {
					var objUploadBody = $(this).contents().find("body").html();
					var f = function() {
						$(ifrm).remove();
					};
					if ($.trim(objUploadBody) !== "") {
						doFormPostEval($.trim(objUploadBody));
						sys.timer = window.setTimeout(f, 100);
					}
				});
				$(sys.elem).before(ifrm);
				$(sys.elem).attr("action", settings.base_url + "assets/cfcs/boko/comment.cfc?method=doFormPostComment&returnFormat=JSON").attr("method", "post").attr("enctype", "multipart/form-data").attr("encoding", "multipart/form-data").attr("target", ifrmName);
			});

		}

		/* 
			set up any user passed variables
		***************************************/
		if (options) {
			$.extend(settings, options);
		}

		/* 
			begin
		***************************************/
		return this.each(function () {
			sys.elem = $(this);
			if (settings.base_url !== "" && settings.top_base_url !== "" && settings.section !== "") {
				if (typeof JSON === "undefined") {
					$.getScript(settings.base_url + 'assets/js/json2.js');
				}
				if (typeof JSON !== "undefined") {
					init();
				} else {
					if(typeof console !== "undefined") {
						console.debug("Error! Could not load the json2.js library.");
					}
				}
			}
		});
	};
})(jQuery);