/* ocms-listSplitter.js */

(function () {
	if (typeof OCMS === "undefined") {
		/* OCMS becomes a global var */
		OCMS = {};
	}	
	
	if (OCMS.listSplitter === undefined) {
		OCMS.listSplitter = function (args) {

			function breakAndAppend () {
				// traversing backwards, find a {break}
				// cut li's from there to the end
				// paste those li's into new list created as new sibling to original list
				// repeat with original list until no {break}'s encountered

				// note: list__Col0 will always be added to the list, even if it does not have
				//	a {break} item within it

				function isBreak ($item) {
					var bBreak = $item.html().toLowerCase() === "{break}",
						$a;
					
					if (!bBreak) {
						$a = $item.find("a");
						if ($a.size() === 1 ) {
							bBreak = $a.html().toLowerCase() === "{break}";
						}
					}
					return bBreak;
				}

				var listTag = this.tagName.toLowerCase();
				
				if ("ulol".indexOf(listTag) >= 0) {
					var $originalList = $(this),
						$listItems = $originalList.find("li"),
						originalClass = "",
						nIt,
						$newListItems,
						newList;

					originalClass = $originalList.attr('class');

					if (settings.wrapWithDiv) {
						$originalList.wrap("<div class='list__Container'></div>");
					}
					
					for (nIt = $listItems.size() - 1; nIt >= 0; --nIt) {
						$thisItem = $listItems.eq(nIt);
						if (isBreak($thisItem)) {
							$newListItems = $thisItem.nextAll();
							$thisItem.remove();
							
							newList = document.createElement(listTag);
							// note: prepend performs a move
							$(newList).prepend($newListItems).addClass(originalClass);
							$originalList.after(newList);
						}
					}

					$originalList.siblings().andSelf().each(function (nCol) {
						$(this).addClass("list__Col" + nCol);
					});		
				}
			}	// breakAndAppend


			/* begin listSplitter */

			var defaults = {
					selector: null,			// selector is expected to specify one or more ul or ol, NOT their container
					wrapWithDiv: true
				},
				ignoreMe = {},
				settings = {},
				$sourceLists = null,
				testRE =	/<li((\n|.)(?!<\/li>))+?>{break}(\n|.)+?<\/li>/i,
				replaceRE = /<li((\n|.)(?!<\/li>))+?>{break}(\n|.)+?<\/li>/gi;
				
			if (typeof args === "string") {
				settings = $.extend(settings, defaults);
				settings.selector = args;
			} else {
				settings = $.extend(true, ignoreMe, defaults, args);
			}
			
			$sourceLists = $(settings.selector);
			if ($sourceLists.size()) {
				$sourceLists.each(breakAndAppend);				
			}
			
			return;
		}	// listSplitter
	}	// OCMS.listSplitter === undefined
})();
