/// <Reference Path="/CustomSource/JavaScript/jquery-1.4.1-vsdoc.js"/>

//Function that loads the court or agency drop down when the page is initially loaded by calling the import court or agency drop down function that takes in the area (court/agency) indicated.  Before the court or agency drop down is loaded, a message is displayed informing the user that the drop down is being loaded.
function loadCourtOrAgencyDropDown(Area) {
	if ($) {
		$('#CourtOrAgencyDisplay').html("<div id='CourtOrAgency'>Loading&nbsp;...</div>");
		importCourtOrAgencyDropDown(Area);
	}
}

//Function that imports the court or agency drop down data from the xml document by receiving the area (court/agency) indicated, creating an xml document object, calling the display court or agency drop down function and loading the url which creates an xml document for the pertinent information using server side processing.  The server side process page receives the area (court/agency) indicated and the particular request (getting the court or agency drop down), so therefore, the server knows what to process.
function importCourtOrAgencyDropDown(Area) {
	if ($) {
		$.ajax({
			url: '/AM/CustomSource/ASPCode/caseindexprocess.asp?Area=' + Area + '&theRequest=getCourtOrAgencyDropDown',
			success: function (data) {
				var htmlContent = "";
				htmlContent += "<select id='CourtOrAgency' name='CourtOrAgency' style='width:240px;'>";
				$(data).find('courtoragency').each(function () {
					htmlContent += "<option value='" + $(this).attr('value') + "'" + ($(this).attr('selected') == 'yes' ? " selected='selected'" : "") + ">" + $(this).text() + "</option>";
				});
				htmlContent += "</select>";
				$('#CourtOrAgencyDisplay').html(htmlContent);
			}
		});
	}
}

//Function that loads the number of cases per page drop down when the page is initially loaded by calling the import number of cases per page drop down function that takes in the value of the number of cases per page drop down.  Before the number of cases per page drop down is loaded, a message is displayed informing the user that the drop down is being loaded.
function loadNumberOfCasesPerPageDropDown(NumLines) {
	if ($) {
		$('#NumberOfCasesPerPageDisplay').html("<div id='NumLines'>Loading&nbsp;...</div>");
		importNumberOfCasesPerPageDropDown(NumLines);
	}
}

//Function that imports the number of cases per page drop down data from the xml document by receiving the value of the number of cases per page drop down, creating an xml document object, calling the display number of cases per page drop down function and loading the url which creates an xml document for the pertinent information using server side processing.  The server side process page receives the number of cases per page value and the particular request (getting the number of cases per page drop down), so therefore, the server knows what to process.
function importNumberOfCasesPerPageDropDown(NumLines) {
	if ($) {
		$.ajax({
			url: '/AM/CustomSource/ASPCode/caselawsearchprocesssimple.asp?NumLines=' + NumLines + '&theRequest=getNumberOfCasesPerPageDropDown',
			success: function (data) {
				var htmlContent = "";
				htmlContent += "<select id='NumLines' name='NumLines' style='width:240px;'>";
				$(data).find('numberofcasesperpage').each(function () {
					htmlContent += "<option value='" + $(this).attr('value') + "'" + ($(this).attr('selected') == 'yes' ? " selected='selected'" : "") + ">" + $(this).text() + "</option>";
				});
				htmlContent += "</select>";
				$('#NumberOfCasesPerPageDisplay').html(htmlContent);
			}
		});
	}
}

//Function that imports the page title data from the xml document by receiving the current value of the court or agency drop down, creating an xml document object, calling the display page title function and loading the url which creates an xml document for the pertinent information using server side processing.  The server side process page receives the value of the court or agency drop down and the particular request (getting the page title), so therefore, the server knows what to process.
function importPageTitle(CourtOrAgency) {
	if ($) {
		$.ajax({
			url: '/AM/CustomSource/ASPCode/caselawsearchprocesssimple.asp?CourtOrAgency=' + CourtOrAgency + '&theRequest=getPageTitle',
			success: function (data) {
				var newHeadTitle = $(data).find('pagetitle').text();
				$('#indexTitle').text(newHeadTitle);
			}
		});
	}
}

//Function that imports the alert message data from the xml document by receiving the message to display, creating an xml document object, calling the display alert message function and loading the url which creates an xml document for the pertinent information using server side processing.  The server side process page receives the message to display and the particular request (getting the alert message), so therefore, the server knows what to process.
function importAlertMessage(TheMessage)
{

  if (document.implementation && document.implementation.createDocument)
  {
	xmlDoc4 = document.implementation.createDocument("", "", null);
	xmlDoc4.onload = displayAlertMessage;
  }
  else if (window.ActiveXObject)
  {
	xmlDoc4 = new ActiveXObject("Microsoft.XMLDOM");
	xmlDoc4.onreadystatechange = function () {
		if (xmlDoc4.readyState == 4) displayAlertMessage()
	};
  }
  else
  {
	alert('Your browser can\'t handle this script');
	return;
  }
  xmlDoc4.load("/AM/CustomSource/ASPCode/caselawsearchprocesssimple.asp?Message=" + TheMessage + "&theRequest=getAlertMessage");	
}

//Function that reads through the xml document alert message tag and pulls the information into the web page for display
function displayAlertMessage()
{
  var x = xmlDoc4.getElementsByTagName('alertmessages');
  var divTag = document.createElement('div');
  divTag.setAttribute('id','AlertMessage');
  divTag.id = 'AlertMessage';
  divTag.setAttribute('style','margin-left:15px');
  divTag.style.margin='15px';
  var fontTag = document.createElement('font');
  var bTag = document.createElement('b');
  fontTag.setAttribute('style','color:red');  
  fontTag.style.color = 'red';  
  for (j=0;j<x[0].childNodes.length;j++)
  {
	if (x[0].childNodes[j].nodeType != 1) continue;
	var tagValue = document.createTextNode(x[0].childNodes[j].firstChild.nodeValue);
	var tagValue2 = x[0].childNodes[j].firstChild.nodeValue;
  }
  bTag.appendChild(tagValue);
  fontTag.appendChild(bTag);  
  divTag.appendChild(fontTag);
  if (tagValue2 == 'No results found for your search.  Please try again.')
  {
    var pTag = document.createElement('p');
    divTag.appendChild(pTag);
	var theText = document.createTextNode('The following suggestions may assist you:');
	divTag.appendChild(theText);
	var pTag = document.createElement('p');
	divTag.appendChild(pTag);
	var ulTag = document.createElement('ul');
	var liTag = document.createElement('li');
	theText = document.createTextNode('Our system does not support the Boolean operator Not.');
	liTag.appendChild(theText);
	ulTag.appendChild(liTag);
	var liTag = document.createElement('li');
	theText = document.createTextNode('Boolean operators cannot be used at the end of a phrase.');
	liTag.appendChild(theText);
	ulTag.appendChild(liTag);
	var liTag = document.createElement('li');
	theText = document.createTextNode('Check spelling.');
	liTag.appendChild(theText);
	ulTag.appendChild(liTag);
	var liTag = document.createElement('li');
	var theLink = document.createElement('a');
	var theHREF = 'javascript:;';
	theLink.setAttribute('href',theHREF);
	theLink.href = theHREF;
	theLink.setAttribute('className','morelink');
	theLink.className = 'morelink';
	var theClickEvent = "document.getElementById('thelinks1').style.display='none';;document.getElementById('thelinks2').style.display='block';;document.getElementById('simplesearchtips').style.display='block';";
	theLink.setAttribute('onClick',theClickEvent);
	var functionName = "displaySimpleSearchTips";
  	var theFunction = "theLink.onclick = function " + functionName + "() { " + theClickEvent + "};";		
	theLink.onclick = eval(theFunction);
	theText = document.createTextNode('Search Tips');
	theLink.appendChild(theText);
	liTag.appendChild(theLink);
	ulTag.appendChild(liTag);
	divTag.appendChild(ulTag);	
  }
  if (document.getElementById('AlertMessageDisplay').hasChildNodes())
  {
	document.getElementById('AlertMessageDisplay').removeChild(document.getElementById('AlertMessage'));
	document.getElementById('AlertMessageDisplay').appendChild(divTag);
  }
  else
  {
	document.getElementById('AlertMessageDisplay').appendChild(divTag);
  }
  if (document.getElementById('RecordDisplay').hasChildNodes()) 
  {
	document.getElementById('RecordDisplay').removeChild(document.getElementById('sortedtable'));
	document.getElementById('RecordDisplay').removeChild(document.getElementById('Pagination'));	
  }
}

//Function that validates the form to make sure the user selected a court or agency and that they entered search criteria in the keywords field.  If the user did not select a court or agency or they did not enter search criteria in the keywords field, the appropriate alert message is displayed on the web page by calling the import alert message function that passes through the message to display.  If the user did select a court or agency and they did enter search criteria in the keywords field, then the import database records function is called.
function validateForm()
{
  if (document.form1.CourtOrAgency.selectedIndex == 0)
  {
  	importAlertMessage('Please select one of the court or agency options');
  } else if (document.form1.Keywords.value == "") {
  	//importAlertMessage('Please type a search criteria in the Keywords field');
	importPageTitle(document.form1.CourtOrAgency.value);
	importDatabaseRecords("+", document.form1.Page.value, document.form1.LastRecordToDisplay.value);
  } else {
	importPageTitle(document.form1.CourtOrAgency.value);
  	importDatabaseRecords(document.form1.Keywords.value.replace(/'/, "\'"), document.form1.Page.value, document.form1.LastRecordToDisplay.value);
  }
}

//Function that imports the database records from the xml document by receiving the keywords, the order by specification (date or case name), the page that the user is on (the default is set to 1 for the first page of cases), the last record to display on the page, the court or agency, and the number of cases per page to display.  The function creates an xml document object, calls the display database records function and loads the url which creates an xml document for the pertinent information using server side processing.  The server side process page receives the keywords, the order by specification (date or case name), the page that the user is on, the last record to be displayed on the page, the court or agency, the number of cases per page and the particular request (getting the database records), so therefore, the server knows what to process
function importDatabaseRecords(Keywords, Page, LastRecordToDisplay, CourtOrAgency,  NumLines, OrderBy) {
	if (CourtOrAgency == null) {
		CourtOrAgency = document.getElementById('CourtOrAgency').value;
	}
	if (NumLines == null) {
		NumLines = document.getElementById('NumLines').value;
	}
	if (OrderBy == null) {
		OrderBy = getSortOrder();
	}

	if ($) {
		$('#AlertMessageDisplay').html('');
		$('#RecordDisplay').html("<div align='center'><h2>Searching&nbsp;...</h2><br /><img src='/AM/Graphics/bigrotation.gif'></div>");

		//todo

		$.ajax({
			url: '/AM/CustomSource/ASPCode/caselawsearchprocesssimple.asp?Keywords=' + escape(Keywords) + '&Page=' + Page + '&LastRecordToDisplay=' + LastRecordToDisplay + '&CourtOrAgency=' + CourtOrAgency + '&NumLines=' + NumLines + '&OrderBy=' + OrderBy + '&theRequest=getDatabaseRecords',
			success: function (data) {
				var recordsReturned = $(data).find('records').attr('recordcount');
				$('#RecordDisplay').html('');

				// Determine whether there are results.
				if (recordsReturned > 1) {
					// Output the number of records found.
					if (recordsReturned < 500) {
						$('#RecordDisplay').append("<p>The search found <strong>" + recordsReturned + "</strong> documents in our library.</p>");
					} else {
						$('#RecordDisplay').append("<p>The search exceeded the maximum threshold. Listed below are the first <strong>" + recordsReturned + "</strong> documents that match your criteria.</p>");
					}

					// Display the results.
					var recordsHtml = "";
					var currentRecord = $(data).find('records').attr('firstrecordtodisplay');
					$(data).find('record').each(function () {
						recordsHtml += "<div style='border-top:1px solid black;margin:1em;padding:.5em 0;'>";
						recordsHtml += "<strong>" + currentRecord + ".</strong>";
						recordsHtml += " <a href='" + $(this).attr('link') + "' onclick='window.open(this.href);return false;'>";
						if (CourtOrAgency == 1 || CourtOrAgency == 2) {
							recordsHtml += $(this).find('casename').text();
						} else if (CourtOrAgency == 4) {
							recordsHtml += PCase($(this).find('petitioner').text());
						} else {
							recordsHtml += PCase($(this).find('employer').text());
						}
						recordsHtml += ", No. " + $(this).find('docketnumber').text() + "</a><br />";
						recordsHtml += "<span style='font-style:italic;'><span style='font-weight:bold;'>Filed:</span> " + $(this).find('filingdate').text() + ", " + getAgencyName(Number(CourtOrAgency)) + "</span><br />";
						if ($(this).find('citation').text() != '') {
							recordsHtml += "<span style='font-style:italic;'><span style='font-weight:bold;'>Public Citation:</span> " + $(this).find('citation').text() + "</span><br />";
						}
						if (CourtOrAgency == 4 && $(this).find('petitioner').text() != '') {
							recordsHtml += "<span style='font-style:italic;'><span style='font-weight:bold;'>Petitioner:</span> " + $(this).find('petitioner').text() + "</span><br />";
						}
						if (CourtOrAgency == 5 && $(this).find('arbitrator').text() != '') {
							recordsHtml += "<span style='font-style:italic;'><span style='font-weight:bold;'>Arbitrator:</span> " + $(this).find('arbitrator').text() + "</span><br />";
						}
						if (CourtOrAgency == 6 && $(this).find('examiner').text() != '') {
							recordsHtml += "<span style='font-style:italic;'><span style='font-weight:bold;'>Examiner:</span> " + $(this).find('examiner').text() + "</span><br />";
						}
						if ($(this).find('summary').text() != '') {
							recordsHtml += "<span style='font-style:italic;font-weight:bold;'>Summary:</span> " + $(this).find('summary').text() + "<br />";
						}

						// Display instances of finds
						if ($(this).find('casetextq11').text() != '') {
							recordsHtml += "<ul style='margin-top:1em;'>";
							for (var i = 1; i < 3; i++) {
								if ($(this).find('casetextq1' + i).text() != '' && $(this).find('casetextoriginalterm' + i).text() != '') {
									recordsHtml += "<li style='margin-bottom:1em;'>";
									recordsHtml += $(this).find('casetextq1' + i).text();
									recordsHtml += "<a href='/AM/CustomSource/ASPCode/caseshow.asp?Hig=on&amp;SearchTerm=" + $(this).find('casetextoriginalterm' + i).text() + "&amp;urlpath=" + $(this).find('casetextoriginalterm' + i).attr('urlloc') + "#L" + i + "'>" + $(this).find('casetextoriginalterm' + i).text() + "</a>";
									recordsHtml += $(this).find('casetextq2' + i).text();
									recordsHtml += "</li>";
								}
							}
							recordsHtml += "</ul>";
						}

						recordsHtml += "</div>";
						currentRecord++;
					});

					// Display paging controls, if necessary.
					if (recordsReturned > NumLines) {
						var totalPages = roundNumber(recordsReturned / NumLines);

						var theCoordinates = getAnchorPosition('RecordDisplay');
						var scrollFunction = "scroll(" + theCoordinates.x + "," + (theCoordinates.y - 130) + ");";

						recordsHtml += "<div id='Pagination' style='text-align:center;'>";
						recordsHtml += "<p>More results:<br />";
						if (Page != 1) {
							var PreviousPage = (Page * 1) - 1;
							LastRecordToDisplay = PreviousPage * NumLines;
							recordsHtml += "<a href='#' onclick=\"importDatabaseRecords('" + Keywords.replace(/'/, "\'") + "', '" + PreviousPage + "', '" + LastRecordToDisplay + "', '" + CourtOrAgency + "', '" + NumLines + "', '" + OrderBy + "');" + scrollFunction + "return false;\">Previous</a> | ";
						}

						var StartNumber = 1;
						var EndNumber = 10;
						if (Page > 10) {
							if (Page % 10 > 0) {
								StartNumber = Page - (Page % 10 - 1);
								EndNumber = StartNumber + 9;
							} else {
								StartNumber = Page - 9;
								EndNumber = StartNumber + 9;
							}
							var PreviousPageSet = StartNumber - 10;
							LastRecordToDisplay = PreviousPageSet * NumLines;

							recordsHtml += "<a href='#' onclick=\"importDatabaseRecords('" + Keywords.replace(/'/, "\'") + "', '" + PreviousPageSet + "', '" + LastRecordToDisplay + "', '" + CourtOrAgency + "', '" + NumLines + "', '" + OrderBy + "');" + scrollFunction + "return false;\">" + (StartNumber - 10) + "-" + (StartNumber - 1) + "</a> | ";
						}
						if (EndNumber > totalPages) {
							EndNumber = totalPages;
						}
						if (totalPages <= 10) {
							EndNumber = totalPages;
						}

						for (w = StartNumber; w <= EndNumber; w++) {
							if (w <= totalPages) {
								if (Page == w) {
									recordsHtml += "" + w + "";
								} else {
									LastRecordToDisplay = w * NumLines;
									recordsHtml += "<a href='#' onclick=\"importDatabaseRecords('" + Keywords.replace(/'/, "\'") + "', '" + w + "', '" + LastRecordToDisplay + "', '" + CourtOrAgency + "', '" + NumLines + "', '" + OrderBy + "');" + scrollFunction + "return false;\">" + w + "</a>";
								}
								if (w != EndNumber) {
									recordsHtml += " | ";
								}
							}
						}

						if ((EndNumber - StartNumber == 9) && EndNumber < totalPages) {
							var NextPageSet = StartNumber + 10;
							LastRecordToDisplay = NextPageSet * NumLines;
							recordsHtml += " | <a href='#' onclick=\"importDatabaseRecords('" + Keywords.replace(/'/, "\'") + "', '" + NextPageSet + "', '" + LastRecordToDisplay + "', '" + CourtOrAgency + "', '" + NumLines + "', '" + OrderBy + "');" + scrollFunction + "return false;\">" + (StartNumber + 10) + "-" + ((StartNumber + 19 > totalPages) ? totalPages : (StartNumber + 19)) + "</a>";
						}

						if (Page < totalPages) {
							var NextPage = (Page * 1) + 1;
							LastRecordToDisplay = NextPage * NumLines;
							recordsHtml += " | <a href='#' onclick=\"importDatabaseRecords('" + Keywords.replace(/'/, "\'") + "', '" + NextPage + "', '" + LastRecordToDisplay + "', '" + CourtOrAgency + "', '" + NumLines + "', '" + OrderBy + "');" + scrollFunction + "return false;\">Next</a>";
						}
						recordsHtml += "</p></div>";
					}

					$('#RecordDisplay').append(recordsHtml);
				} else {
					// No data was returned.
					importAlertMessage('No results found for your search. Please try again.');
				}
			}
		});
	}
}
