﻿var g_strCurrentTerm = "";
var g_aTerms = null;
var g_aRegulationIndex = {
	"191": { "Accident": "3", "Incident": "3" },
	"192": { "AbandonedPipeline": "727", "ClassLocation": "5", "Gas": "top",
	  "GatheringLine": "3", "HighPressureDistributionSystem": "3",
	  "InactivePipeline": "top", "LineMarkers": "707", "MainlineValves": "179",
	  "MaximumAllowableOperatingPressure": "top", "Operator": "3",
	  "Pipeline": "3", "PipelineFacility": "3", "TransmissionLine": "top" },
	"194": { "Barrel": "5", "BreakoutTank": "5" },
	"195": { "AbandonedPipeline": "59", "Accident": "50", "Barrel": "2",
	  "BaselineAssessmentPlan": "452", "BreakoutTank": "2", "CarbonDioxide": "2",
	  "EnvironmentallySensitiveAreas": "2", "GatheringLine": "2",
	  "HazardousLiquid": "2", "ImmediateRepairCondition": "452",
	  "InactivePipeline": "top", "Incident": "50", "IntegrityAssessment": "452",
	  "IntegrityManagementProgram": "452", "LineMarkers": "410",
	  "MainlineValves": "260", "Operator": "2", "Pipeline": "2",
	  "PipelineFacility": "2", "RepairConditions": "452",
	  "UnusuallySensitiveAreas": "6" }
}
var g_aRegulationURLs = {
	"191": { "Base": "http://ecfr.gpoaccess.gov/cgi/t/text/text-idx?c=ecfr;sid=196ad72e288144d04645108c2906ec7a;rgn=div5;view=text;node=49%3A3.1.1.1.2;idno=49;cc=ecfr", "3": "http://ecfr.gpoaccess.gov/cgi/t/text/text-idx?c=ecfr;sid=196ad72e288144d04645108c2906ec7a;rgn=div5;view=text;node=49%3A3.1.1.1.2;idno=49;cc=ecfr#49:3.1.1.1.2.0.9.2" },
	"192": { "Base": "http://ecfr.gpoaccess.gov/cgi/t/text/text-idx?c=ecfr&sid=196ad72e288144d04645108c2906ec7a&rgn=div5&view=text&node=49:3.1.1.1.3&idno=49", "3": "#49:3.1.1.1.3.1.9.2", "5": "#49:3.1.1.1.3.1.9.3", "179": "#49:3.1.1.1.3.4.9.22", "707": "#49:3.1.1.1.3.13.9.5", "727": "#49:3.1.1.1.3.13.9.15" },
	"194": { "Base": "http://ecfr.gpoaccess.gov/cgi/t/text/text-idx?c=ecfr;sid=c40f96ec07d5302f8c75efbd80ce54fb;rgn=div5;view=text;node=49%3A3.1.1.1.5;idno=49;cc=ecfr", "5": "#49:3.1.1.1.5.1.19.3" },
	"195": { "Base": "http://ecfr.gpoaccess.gov/cgi/t/text/text-idx?c=ecfr&sid=c40f96ec07d5302f8c75efbd80ce54fb&rgn=div5&view=text&node=49:3.1.1.1.6&idno=49", "2": "#49:3.1.1.1.6.1.21.4", "6": "#49:3.1.1.1.6.1.21.8", "50": "#49:3.1.1.1.6.2.21.2", "59": "#49:3.1.1.1.6.2.21.9", "260": "#49:3.1.1.1.6.4.21.25", "410": "#49:3.1.1.1.6.6.21.9", "452": "#49:3.1.1.1.6.6.22.27" }
}

Event.observe(window, 'load', function() {
	Event.observe('txtPhrase', 'keyup', OnWordChange);
	new Ajax.Request('js/data2.js', {
		method:'get',
		onSuccess: function(transport) {
		  var obj = transport.responseText.evalJSON(true);
			g_aTerms = obj["Terms"];
			PopulateTerms(g_aTerms);
			// make back button work on Firefox
			if (Prototype.Browser.Gecko) {
				setInterval(function() {
					var strHash = StripPound(window.location.hash);
					if (strHash != g_strCurrentTerm)
						DisplayTerm(strHash);
				}, 500);
			}
		}
	});
});

function OnWordChange() {
	PopulateTerms(GetMatchingTerms($F("txtPhrase")));
}

function escParens(str) {
  return str.replace("(", "\\(").replace(")", "\\)");
}

function GetMatchingTerms(phrase) {
  var regex = new RegExp(escParens(phrase), "gi");
  return g_aTerms.findAll(function(term) {
    if (term.desc.match(regex))
      return true;
    else if (term.keys.any(function(key) {
      // strip regex marks from the key b/c we can't use it as a regex
      // b/c Javascript's regex engine doesn't support partial matching
      return key.replace('?', '').match(regex);
    }))
      return true;
	});
}

function OnChooseTerm() {
  var selected_text = $("selTerms").options[$("selTerms").selectedIndex].text;
	DisplayTerm($F("selTerms"), selected_text);
}

function GetTermById(id, default_term) {
	return g_aTerms.find(function(term) {
	  return term.id == id;
	}) || default_term;
}

function PopulateTerms(terms) {
	$("spanNumMatchingTerms").innerHTML = terms.length;
	var astrHTML = terms.collect(function(objTerm) {
	  return ["<option value='", objTerm.id, "'>", objTerm.desc,
	    "</option>"].join("");
	 });
	astrHTML.unshift("<select id='selTerms' size='20'>"); 
	astrHTML.push("</select>");
	$("divTerms").innerHTML = astrHTML.join("");
  Event.observe('selTerms', 'change', OnChooseTerm);
  
	if (terms.length > 0) {
		$("selTerms").selectedIndex = 0;
		var hash_id = StripPound(window.location.hash);
		var displayed_term;
		if (hash_id && terms.pluck('id').include(hash_id))
		  displayed_term = GetTermById(hash_id, terms[0]);
		else
		  displayed_term = terms[0];
		DisplayTerm(displayed_term.id, displayed_term.desc);
	}
}

function DisplayTerm(strTermID, strTitle) {
	var strURL;
	if (!strTitle) strTitle = GetTermById(strTermID, g_aTerms[0]).Title;
	if (strTermID.length >= 3 && strTermID.substr(0, 3) == "Ref") {
		strURL = GetRef(strTermID.substr(3, 3), strTermID.substr(6, strTermID.length - 6));
		window.location.href = strURL;
	} else {
		var selTerms = $("selTerms");
		if (selTerms.options[selTerms.selectedIndex].text != strTitle) {
			var nTerms = selTerms.options.length;
			for (var nTerm = 0; nTerm < nTerms; ++nTerm)
				if (selTerms.options[nTerm].text == strTitle)
					selTerms.selectedIndex = nTerm;
		}
		strURL = strTermID + ".htm";
		new Ajax.Updater("entry", strURL, { method: "get",
			onComplete: AddImageCaptions });
		//$("title").innerHTML = strTitle;
		g_strCurrentTerm = strTermID;
		window.location.hash = strTermID;
	}
}

// removes leading "#" from a string (usually the Hash part of a URL)
function StripPound(str) {
	return str && str.substr(0, 1) == '#' ? str.substr(1) : str;
}

function GetRef(nRegulationCode, strName) {
	var nMinorCode = g_aRegulationIndex[nRegulationCode][strName];
	return g_aRegulationURLs[nRegulationCode].Base + (nMinorCode == "top" ? "" : g_aRegulationURLs[nRegulationCode][nMinorCode]);
}
