var tagArray = new Array();
var filterList;
var ruleSet;

function openSearchForm() {
		$("searchForm").update("<input type='text' name='searchKey' id='searchKey' /><input type='button' name='searchBtn' id='searchBtn' value='>>' onclick=\"searchRules($('searchKey').value, 'moa', 1);\" />");
}
function translateControls(lang) {
    if (lang == "Spanish") {
        $("language").update("<a href=\"#\" onclick='getRules(\"English\"); return false'>Ingl&eacute;s</a> <span>Espa&ntilde;ol</span>");
    } else {
        $("language").update("<span>English</span> <a href=\"#\" onclick='getRules(\"Spanish\"); return false'>Spanish</a>");
    }
}

function showHide(element, depth) {
    // Get parent node of showhide link and change the display of the child div nodes
    var parent = element.parentNode;
    var el = parent.getElementsByTagName("div");
    for (var i=0; i<el.length; i++) {
    	//if (el[i].className == "d" + (depth+1)) {
    	    if (element.className == "show") {
    	    	el[i].style.display = "block";
    	    } else {
    	    	el[i].style.display = "none";
    	    }
    	//}
    }
    // Change the show-hide link state
    if (element.className == "show") {
    	element.className = "hide";
    	element.innerHTML = "hide";
    } else {
    	element.className = "show";
    	element.innerHTML = "show";
    }
}

function showTags() {
    $("tags").update("<div id='clearFilter'><a href=\"#\" id='nofilter' onclick=\"filterRules('', 'moa', 1); filterList(this.id); return false\">Clear Tags</a></div><strong>Tag List :</strong><div id='tagList'>");
    tagArray.sort();
    for (var i=0; i<tagArray.length; i++) {
        //$("tags").insert("<a href=\"#\" onclick=\"getRules('English', '" + tagArray[i] + "'); return false\">" + tagArray[i] + "</a> ");
        $("tagList").insert("<a href=\"#\" id='filter-" + tagArray[i] + "' onclick=\"filterRules('" + tagArray[i] + "', 'moa', 1); filterList(this.id); return false\">" + tagArray[i] + "</a> ");
    }
	$("tags").insert("</div>");
}
function checkTags(tags) {
    tags = tags.split(", ");
    for (var i=0; i<tags.length; i++) {
        if (tagArray.indexOf(tags[i]) == -1) {
            tagArray[tagArray.length] = tags[i];
        }
    }
    return true;
}

function matchTags(tags, tag) {
	// Match clicked tag to existing tags
	tags = tags.split(", ");
	tagMatch = false;
	for (var i=0; i<tags.length; i++) {
		if (tags[i] == tag) {
			tagMatch = true;
			break;
		}
	}
	return (tagMatch);
}

function filterList(tagID) {
	var tags = $("tags").getElementsBySelector("a");
	for (var i=0; i<tags.length; i++) {
		$(tags[i]).className = null;
	}
	if (tagID != "nofilter") {
		$(tagID).className = "filterTag";
	}
}

function filterRules(tag, parent, depth, rules) {
	// Recursively filter the rules tree based on tag
	if (!rules) rules = ruleSet;
	var tagFlag = false;
	for (var i=0; i<rules.length; i++) {
		// Set Rule Number
		var thisID = parent + "." + (i+1);
		// Reset style on node
		$(thisID).removeAttribute("style");
		
		if (rules[i].sections) {
			// Recursively filter child nodes
			filterRules(tag, thisID, (depth+1), rules[i].sections);
		}
		if (rules[i].tags && matchTags(rules[i].tags, tag)) {
			// Match
			// Mark node as tagged
			$(thisID).className = "tagged";
			//$(parent).className = "tagPath";
			tagFlag = true;
		} else {
			// Mismatch
			// Remove tagged mark if not tagged and previously tagged
			if ($(thisID).className == "tagged") {
				$(thisID).removeAttribute("class");
			}
		}
		if ($(thisID).className == "tagPath") {
			$(parent).className = $(thisID).className;
			tagFlag = true;
		}
		if (!tagFlag) {
			$(parent).removeAttribute("class");
		} else {
			$(parent).className = "tagPath";
		}
	}
	if ($("filteredOn")) {
		$("filteredOn").remove();
	}
	if (tag) {
		$("moa").className = "filtered";
		if (!$("filteredOn")) $("docTitle").insert("<span id='filteredOn'>(filtered by tag : " + tag + ")</span>");
		$("saveResults").update("<a href='./?t=" + tag + "'>Save filter results in URL</a>");
		var tagPair = window.location.search.substring(1);
		tagPair = tagPair.split("=");
		/*
		if (tagPair[1] != tag) {
			document.location.hash = "?t=" + tag;
		}
		*/
	}
}

function searchRules(keyword, parent, depth, rules) {
	// Recursively filter the rules tree based on tag
	if (!rules) rules = ruleSet;
	var searchFlag = false;
	for (var i=0; i<rules.length; i++) {
		// Set Rule Number
		var thisID = parent + "." + (i+1);
		// Reset style on node
		$(thisID).removeAttribute("style");
		
		if (rules[i].sections) {
			// Recursively search child nodes
			searchRules(keyword, thisID, (depth+1), rules[i].sections);
		}
		// Logic for separating keywords and searching rules by each
			if (rules[i].rule.indexOf(keyword) > -1) {
				// Match
				// Mark node as tagged
				$(thisID).className = "tagged";
				//$(parent).className = "tagPath";
				searchFlag = true;
			} else {
				// Mismatch
				// Remove tagged mark if not tagged and previously marked
				if ($(thisID).className == "tagged") $(thisID).removeAttribute("class");
			}
		// End logic for separating keywords and searching rules by each
		if ($(thisID).className == "tagPath") {
			$(parent).className = $(thisID).className;
			searchFlag = true;
		}
		if (!searchFlag) $(parent).removeAttribute("class");
		else $(parent).className = "tagPath";
	}
	if ($("filteredOn")) $("filteredOn").remove();
	if (keyword) {
		$("moa").className = "filtered";
		if (!$("filteredOn")) $("docTitle").insert("<span id='filteredOn'>(filtered by keyword : " + keyword + ")</span>");
		$("saveResults").update("<a href='./?s=" + keyword + "'>Save search results in URL</a>");
	}
}

function displayRules(rules, parent, depth) {
    // Recursively display the rules tree
    for (var i=0; i<rules.length; i++) {
    	var thisID = parent + "." + (i+1);
    	if (depth > 1) var nodeType = "p";
    	else var nodeType = "h2";
    	$(parent).insert("<div id='" + thisID + "'><" + nodeType + ">" + "<span class='ruleNum'>" + thisID.replace("moa.", "") + "</span> - " + rules[i].rule + "</" + nodeType + ">");
		if (rules[i].tags) checkTags(rules[i].tags);
        if (rules[i].table) {
                                var columns = rules[i].table.columns;
 //                               var tableVar = ("<table id='" + rules[i].table.id + "' summary='" + rules[i].table.summary + "' border='1'>");
 //                               var headVar = ("<thead><tr><th colspan='"+ columns+"'>" + rules[i].table.title + "</th></tr>");
 //                               for (var j=0;j<rules[i].table.header.length;j++) {
 //                                               headVar = (headVar + "<th>" + rules[i].table.header[j] + "</th>");
 //                               }
 //                               headVar = (headVar + "</thead>");
 //                               var bodyVar = "<tbody>";
 //                               for (var j=0;j<rules[i].table.body.length; j++) {
 //                                               bodyVar = (bodyVar + "<tr>");
 //                                               for(var k=0;j<rules[i].table.body[j].length;k++) {
 //                                                               if(k == 0)
 //                                                                               bodyVar = (bodyVar + "<th>" + rules[i].table.body[j][k] + "</th>");
 //                                                               else
 //                                                                               bodyVar = (bodyVar + "<td>" + rules[i].table.body[j][k] + "</td>");
 //                                               }
 //                                               bodyVar = (bodyVar + "</tr>");
 //                               }
 //                               bodyVar = (bodyVar + "</tbody>");
 //                               var footVar = ("<tfoot><tr><td colspan='" + columns +"'>");
 //                               for (var j=0;j<rules[i].table.foot.length;j++) {
 //                                               footVar = (footVar + "<sup>" + (j+1) + "</sup>" + rules[i].table.foot[j] + "<br />");
 //                               }
 //                               footVar = (footVar + "</tfoot>")
 //                               tableVar = (tableVar + headVar + bodyVar + footVar + "</table>");
  //                              $(thisID).insert( thisID + tableVar);
       	}
    	if (rules[i].sections) {
    	    $(thisID).innerHTML += "<span onclick='showHide(this, " + depth + ");' class='hide'>hide</span>";
    	    // Recursive call to self
    	    displayRules(rules[i].sections, thisID, (depth+1));
    	}
    }
}

function getRules(lang, tag) {
    // Determine which version of the MOA JSON file to retrieve
    var jsonFile = "DagRules" + lang + ".json?d=" + Date();
    $("content").update("Loading...<br />" + $("content").innerHTML);
    var rules = new Ajax.Request(jsonFile, {
    	method : 'get',
    	requestheaders : { Accept : 'application/json' },
    	onSuccess : function(xhr) {
    	    var rulesDoc = xhr.responseText.evalJSON(true);
			$("rulesWrapper").lang = rulesDoc.language;
            $("content").update("<h1 id='docTitle'>" + rulesDoc.title + "</h1><div>Updated " + rulesDoc.updated + "</div><br /><div id='preface'></div><div id='moa'></div>");
            $("preface").update("<div id='summary'>" + rulesDoc.preface.summary + "</div><br/><div id='caution'>" + rulesDoc.preface.caution + "</div><p id='ruleZero'>&ldquo;Rule Zero&rdquo;</p><div id='zero'>" + rulesDoc.preface.zero + "</div>");
			ruleSet = rulesDoc.rules;
			displayRules(ruleSet, "moa", 1);
			if (window.location.search.substring(1) && !tag) {
				var tagPair = window.location.search.substring(1);
				tagPair = tagPair.split("=");
				tag = tagPair[1];
				filterRules(tag.replace(/%20/," "), "moa", 1, ruleSet);
				
			} else if (tag) {
				filterRules(tag, "moa", 1, ruleSet);	
			}		
			
			//openSearchForm();
			//translateControls(lang);
			showTags();
		}
    });
}

function initLoad() {
    // Initial function calls
    getRules("English");
}

Event.observe( window, 'load', initLoad);
