var Comments = Comments || {};

(function () {

	/* RSF dependency copied into this namespace from rsf.js */
	   /* parseUri 1.2; MIT License
	   By Steven Levithan <http://stevenlevithan.com> 
	   http://blog.stevenlevithan.com/archives/parseuri
	   */
	   var parseUri = function (source) {
	      var o = parseUri.options,
	         value = o.parser[o.strictMode ? "strict" : "loose"].exec(source);
	      
	      for (var i = 0, uri = {}; i < 14; i++) {
	         uri[o.key[i]] = value[i] || "";
	      }
	      
	      uri[o.q.name] = {};
	      uri[o.key[12]].replace(o.q.parser, function ($0, $1, $2) {
	         if ($1) uri[o.q.name][$1] = $2;
	      });
	      
	      return uri;
	   }
	   parseUri.options = {
	      strictMode: false,
	      key: ["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"],
	      q: {
	         name: "queryKey",
	         parser: /(?:^|&)([^&=]*)=?([^&]*)/g
	      },
	      parser: {
	         strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,
	         loose: /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/
	      }
	   }
	
	 /** 
	  * Adapted from RSF.transformActionDomToAJAX.
	  * We only transform the action elements and pagination links (a elements with class="ajaxify").
	  *
	  * Transform all action and navigation elements inside a DOM block into AJAX action elements,
	  * This will keep the forms from submitting, the page from changing, and the links
	  * from causing navigation to proceed off the page
	  *
	  * parentNode: all action elements contained within this node will be transformed to having navigation transitions "decorated"
	  * targetNode: the effect of the decorated navigation will be to cause replacement of DOM contents of this target node.
	  * RETURN: the list of updated action elements
	  */
	Comments.transformActionDomToAJAX = function (parentNode, targetNode) {
		if (typeof(targetNode) == "undefined" || targetNode == null) {
			targetNode = parentNode;
		}
		var updatedElements = [];

		// define the callback function for the ajax response
		var callback = function(results) {
			var targetNodeRes = targetNode;
			if (typeof(targetNode) === "function") {
				targetNodeRes = targetNode.apply();
			}
			// specifically purge the existing items before putting in the new stuff
			while (targetNodeRes.childNodes[0])  {
				targetNodeRes.removeChild(targetNodeRes.childNodes[0]);
			}
			// now drop in the new xhtml result into this node
			targetNodeRes.innerHTML = results;
			RSF.getDOMModifyFirer().fireEvent();
			// rerun the dom transformer on the replacement xhtml
			Comments.transformActionDomToAJAX(targetNodeRes, targetNodeRes);
		}

		var inputs = parentNode.getElementsByTagName("input");
		for (var i = 0; i < inputs.length; ++ i) {
			var input = inputs[i];
			if (input.getAttribute("type").toLowerCase() != "submit") {
				continue;
			}
			var updater = RSF.getAJAXFormUpdater(input.form, callback, null, input);
			RSF.addEventToElement(input, "click", updater);
			updatedElements.push(input);
		}

		var links = parentNode.getElementsByTagName("a");
		for (var i = 0; i < links.length; i++) {
			var link = links[i];

			if (!link.href || link.href.length == 0) {
				continue;            
			}
			
			if (link.className.search("\\bajaxify\\b") == -1) {
				continue;
			}

			var parsed = parseUri(link.href);
			if (parsed.host == "" || parsed.host == document.domain) {
				var updater = RSF.getAJAXLinkUpdater(link, callback);

				RSF.addEventToElement(link, "click", updater);
				updatedElements.push(link);
			} else {
				RSF.log("link is not in this domain so skipping it: " + link.href);
				continue;
			}
		}
		RSF.evaluateScripts(parentNode);

		return updatedElements;
	};


	Comments.init_Comments = function (ahahURL) {
		var comments_box = document.getElementById("comments_box");
		comments_box.getElementsByTagName("form")[0].action = ahahURL;
		Comments.transformActionDomToAJAX(comments_box);
	};
	
})();

