/// <Reference Path="/CustomSource/JavaScript/jquery-1.4.1-vsdoc.js"/>
//Function to round numbers, changing the rlength variable indicates the number of decimal places to round to
function roundNumber(theNumber) {
	var rnum = theNumber;
	var rlength = 0;
	if (rnum > 8191 && rnum < 10485) {
		rnum = rnum - 5000;
		var newnumber = Math.round(rnum * Math.pow(10, rlength)) / Math.pow(10, rlength);
	}
	else {
		var newnumber = Math.round(rnum * Math.pow(10, rlength)) / Math.pow(10, rlength);
	}
	return newnumber;
}

//Function that converts words in a string to the proper case
function PCase(STRING) {
	var strReturn_Value = "";
	var iTemp = STRING.length;
	if (iTemp == 0) {
		return "";
	}
	var UcaseNext = false;
	strReturn_Value += STRING.charAt(0).toUpperCase();
	for (var iCounter = 1; iCounter < iTemp; iCounter++) {
		if (UcaseNext == true) {
			strReturn_Value += STRING.charAt(iCounter).toUpperCase();
		}
		else {
			strReturn_Value += STRING.charAt(iCounter).toLowerCase();
		}
		var iChar = STRING.charCodeAt(iCounter);
		if (iChar == 32 || iChar == 45 || iChar == 46) {
			UcaseNext = true;
		}
		else {
			UcaseNext = false
		}
		if (iChar == 99 || iChar == 67) {
			if (STRING.charCodeAt(iCounter - 1) == 77 || STRING.charCodeAt(iCounter - 1) == 109) {
				UcaseNext = true;
			}
		}
	}
	return strReturn_Value;
}

//Function that returns an object having .x and .y properties which are the coordinates of the named anchor, relative to the page.
function getAnchorPosition(anchorname) {
	var useWindow = false;
	var coordinates = new Object();
	var x = 0, y = 0;
	var use_gebi = false, use_css = false, use_layers = false;
	if (document.getElementById) { use_gebi = true; }
	else if (document.all) { use_css = true; }
	else if (document.layers) { use_layers = true; }
	if (use_gebi && document.all) {
		x = AnchorPosition_getPageOffsetLeft(document.all[anchorname]);
		y = AnchorPosition_getPageOffsetTop(document.all[anchorname]);
	}
	else if (use_gebi) {
		var o = document.getElementById(anchorname);
		x = AnchorPosition_getPageOffsetLeft(o);
		y = AnchorPosition_getPageOffsetTop(o);
	}
	else if (use_css) {
		x = AnchorPosition_getPageOffsetLeft(document.all[anchorname]);
		y = AnchorPosition_getPageOffsetTop(document.all[anchorname]);
	}
	else if (use_layers) {
		var found = 0;
		for (var i = 0; i < document.anchors.length; i++) {
			if (document.anchors[i].name == anchorname) { found = 1; break; }
		}
		if (found == 0) {
			coordinates.x = 0; coordinates.y = 0; return coordinates;
		}
		x = document.anchors[i].x;
		y = document.anchors[i].y;
	}
	else {
		coordinates.x = 0; coordinates.y = 0; return coordinates;
	}
	coordinates.x = x;
	coordinates.y = y;
	return coordinates;
}

// Function getting the page offset left position
function AnchorPosition_getPageOffsetLeft(el) {
	var ol = el.offsetLeft;
	while ((el = el.offsetParent) != null) { ol += el.offsetLeft; }
	return ol;
}

// Function getting the page offset top position
function AnchorPosition_getPageOffsetTop(el) {
	var ot = el.offsetTop;
	while ((el = el.offsetParent) != null) { ot += el.offsetTop; }
	return ot;
}

// HTML to display for varying states of the sorting arrows.
function sortGraphics() {
	this.Descending = "<img alt='Sort ascending' src='/AM/CustomSource/ASPCode/img/down_arrow.gif' title='Sort ascending' />";
	this.DescendingSelected = "<img alt='Current sort descending/Sort ascending?' src='/AM/CustomSource/ASPCode/img/arrow_g_down.gif' title='Current sort descending/Sort ascending?' />";
	this.Ascending = "<img alt='Sort descending' src='/AM/CustomSource/ASPCode/img/up_arrow.gif' title='Sort descending' />";
	this.AscendingSelected = "<img alt='Current sort ascending/Sort descending?' src='/AM/CustomSource/ASPCode/img/arrow_g_up.gif' title='Current sort ascending/Sort descending?' />";
}

// Determine which of four graphics to display, based on currentSort ASC or DESC and selected true or false
function determineSortGraphic(currentSort, selected) {
	var sortingGraphics = new sortGraphics();
	if (currentSort == "DESC") {
		if (selected == true) {
			return sortingGraphics.DescendingSelected;
		} else {
			return sortingGraphics.Descending;
		}
	} else {
		if (selected == true) {
			return sortingGraphics.AscendingSelected;
		} else {
			return sortingGraphics.Ascending;
		}
	}
}

// Return the opposite ordering to what's passed.
function oppositeSortOrder(currentSort) {
	return (currentSort == "DESC" ? "ASC" : "DESC");
}

//Function that loads the year drop down when the page is initially loaded by calling the import year drop down function that takes in the value of the court or agency drop down and the year drop down.  Before the year drop down is loaded, a message is displayed informing the user that the drop down is being loaded.
function loadYearDropDown(CourtOrAgency, YearJump) {
	if ($) {
		$('#YearDisplay').html("<div id='YearJump'>Loading&nbsp;...</div>");
		importYearDropDown(CourtOrAgency, YearJump);
	}
}

//Function that imports the year drop down data from the xml document by receiving the value of the court or agency drop down and the year drop down, creating an xml document object, calling the display year 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 court or agency value, the year value and the particular request (getting the year drop down), so therefore, the server knows what to process.
function importYearDropDown(CourtOrAgency, YearJump) {
	if ($) {
		$.ajax({
			url: '/AM/CustomSource/ASPCode/caseindexprocess.asp?CourtOrAgency=' + CourtOrAgency + '&YearJump=' + YearJump + '&theRequest=getYearDropDown',
			success: function (data) {
				var htmlContent = "";
				htmlContent += "<select id='YearJump' name='YearJump' style='width:240px;'>";
				$(data).find('year').each(function () {
					htmlContent += "<option value='" + $(this).attr('value') + "'" + ($(this).attr('value') == YearJump ? " selected='selected'" : "") + ">" + $(this).text() + "</option>";
				});
				htmlContent += "</select>";
				$('#YearDisplay').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/caseindexprocess.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 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 particular request (getting the alert message), so therefore, the server knows what to process.
function importAlertMessage() {
	if ($) {
		$.ajax({
			url: '/AM/CustomSource/ASPCode/caseindexprocess.asp?theRequest=getAlertMessage',
			success: function (data) {
				var newHeadTitle = $(data).find('alertmessage').text();
				$('#AlertMessageDisplay').html("<p class='error'>" + newHeadTitle + "</p>");
			}
		});
	}
}

//Function that validates the form to make sure the user selected a court or agency.  If the user did not select a court or agency an alert is displayed.  If the user did select a court or agency then the import database records function is called.
function validateForm() {
	if (document.form1.CourtOrAgency.selectedIndex == 0) {
		importAlertMessage();
	} else {
		importPageTitle(document.form1.CourtOrAgency.value);
		importDatabaseRecords(document.form1.OrdMode.value, document.form1.OrdModeFiling.value, document.form1.OrdModePetitioner.value, document.form1.OrdModeDocket.value, document.form1.OrdModeEmployer.value, document.form1.OrdModeCaseName.value, document.form1.OrdModeCitation.value, document.form1.PreviousSortColumnIndex.value, document.form1.SortColumnIndex.value, document.form1.Page.value, document.form1.LastRecordToDisplay.value);
	}
}

//Function that imports the database records from the xml document by receiving the order modes (ascending/descending), the sort column index (the default is set to 1 which is in reference to the filing date column), 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, the year 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 order modes for sorting functionality, the sort column index (used to indicate what column to sort by), the page that the user is on, the last record to be displayed on the page, the court or agency, the year, the number of cases per page and the particular request (getting the database records), so therefore, the server knows what to process
function importDatabaseRecords(OrdMode, OrdModeFiling, OrdModePetitioner, OrdModeDocket, OrdModeEmployer, OrdModeCaseName, OrdModeCitation, PreviousSortColumnIndex, SortColumnIndex, Page, LastRecordToDisplay, CourtOrAgency, YearJump, NumLines) {
	if (CourtOrAgency == null) {
		CourtOrAgency = document.getElementById('CourtOrAgency').value;
	}
	if (YearJump == null) {
		YearJump = document.getElementById('YearJump').value;
	}
	if (NumLines == null) {
		NumLines = document.getElementById('NumLines').value;
	}

	if ($) {
		$('#AlertMessageDisplay').html('');
		$('#RecordDisplay').html("<div align='center'><h2>Searching&nbsp;...</h2><br /><img src='/AM/Graphics/bigrotation.gif'></div>");

		$.ajax({
			url: '/AM/CustomSource/ASPCode/caseindexprocess.asp?OrdMode=' + OrdMode + '&OrdModeFiling=' + OrdModeFiling + '&OrdModePetitioner=' + OrdModePetitioner + '&OrdModeDocket=' + OrdModeDocket + '&OrdModeEmployer=' + OrdModeEmployer + '&OrdModeCaseName=' + OrdModeCaseName + '&OrdModeCitation=' + OrdModeCitation + '&PreviousSortColumnIndex=' + PreviousSortColumnIndex + '&SortColumnIndex=' + SortColumnIndex + '&Page=' + Page + '&LastRecordToDisplay=' + LastRecordToDisplay + '&CourtOrAgency=' + CourtOrAgency + '&YearJump=' + YearJump + '&NumLines=' + NumLines + '&theRequest=getDatabaseRecords',
			success: function (data) {
				var htmlContent = "";
				var resultSet = $(data);
				var recordsReturned = Number($(data).find('records').attr('recordcount'));

				if (recordsReturned > 1) {
					var firstResult = Number($(data).find('records').attr('firstrecordtodisplay'));
					var lastResult = Number($(data).find('records').attr('lastrecordtodisplay'));
					var currentPage = Number($(data).find('records').attr('page'));
					var agencyId = Number($(data).find('records').attr('courtoragency'));

					// Display the results.
					htmlContent += "<table id='sortedtable' style='width:99%;' summary=''>";
					htmlContent += "<thead><tr>";
					htmlContent += "<th>#</th>";
					var recordsRoot = resultSet.find('records');
					var currentSortingColumn = Number(recordsRoot.attr('sortcolumnindex'));
					htmlContent += "<th>Filing <a href='#' onclick=\"importDatabaseRecords('" + oppositeSortOrder(OrdModeFiling) + "', '" + oppositeSortOrder(OrdModeFiling) + "', '" + OrdModePetitioner + "', '" + OrdModeDocket + "', '" + OrdModeEmployer + "', '" + OrdModeCaseName + "', '" + OrdModeCitation + "', '" + SortColumnIndex + "', 1, 1, 0, " + CourtOrAgency + ", " + YearJump + ", " + NumLines + ");return false;\">" + determineSortGraphic(recordsRoot.attr('ordmodefiling'), (currentSortingColumn == 1)) + "</a></th>";
					if (agencyId == 1 || agencyId == 2) {
						htmlContent += "<th>Case name <a href='#' onclick=\"importDatabaseRecords('" + oppositeSortOrder(OrdModeCaseName) + "', '" + OrdModeFiling + "', '" + OrdModePetitioner + "', '" + OrdModeDocket + "', '" + OrdModeEmployer + "', '" + oppositeSortOrder(OrdModeCaseName) + "', '" + OrdModeCitation + "', '" + SortColumnIndex + "', 2, 1, 0, " + CourtOrAgency + ", " + YearJump + ", " + NumLines + ");return false;\">" + determineSortGraphic(recordsRoot.attr('ordmodecasename'), (currentSortingColumn == 2)) + "</a></th>";
					} else if (agencyId == 4) {
						htmlContent += "<th>Petitioner <a href='#' onclick=\"importDatabaseRecords('" + oppositeSortOrder(OrdModePetitioner) + "', '" + OrdModeFiling + "', '" + oppositeSortOrder(OrdModePetitioner) + "', '" + OrdModeDocket + "', '" + OrdModeEmployer + "', '" + OrdModeCaseName + "', '" + OrdModeCitation + "', '" + SortColumnIndex + "', 3, 1, 0, " + CourtOrAgency + ", " + YearJump + ", " + NumLines + ");return false;\">" + determineSortGraphic(recordsRoot.attr('ordmodepetitioner'), (currentSortingColumn == 3)) + "</a></th>";
					} else if (agencyId == 5 || agencyId == 6) {
						htmlContent += "<th>Employer <a href='#' onclick=\"importDatabaseRecords('" + oppositeSortOrder(OrdModeEmployer) + "', '" + OrdModeFiling + "', '" + OrdModePetitioner + "', '" + OrdModeDocket + "', '" + oppositeSortOrder(OrdModeEmployer) + "', '" + OrdModeCaseName + "', '" + OrdModeCitation + "', '" + SortColumnIndex + "', 4, 1, 0, " + CourtOrAgency + ", " + YearJump + ", " + NumLines + ");return false;\">" + determineSortGraphic(recordsRoot.attr('ordmodeemployer'), (currentSortingColumn == 4)) + "</a></th>";
					}
					htmlContent += "<th>Docket&nbsp;# <a href='#' onclick=\"importDatabaseRecords('" + oppositeSortOrder(OrdModeDocket) + "', '" + OrdModeFiling + "', '" + OrdModePetitioner + "', '" + oppositeSortOrder(OrdModeDocket) + "', '" + OrdModeEmployer + "', '" + OrdModeCaseName + "', '" + OrdModeCitation + "', '" + SortColumnIndex + "', 5, 1, 0, " + CourtOrAgency + ", " + YearJump + ", " + NumLines + ");return false;\">" + determineSortGraphic(recordsRoot.attr('ordmodedocket'), (currentSortingColumn == 5)) + "</a></th>";
					if (agencyId == 1 || agencyId == 2) {
						htmlContent += "<th class='caseTableCitation'>Citation <a href='#' onclick=\"importDatabaseRecords('" + oppositeSortOrder(OrdModeCitation) + "', '" + OrdModeFiling + "', '" + OrdModePetitioner + "', '" + OrdModeDocket + "', '" + OrdModeEmployer + "', '" + OrdModeCaseName + "', '" + oppositeSortOrder(OrdModeCitation) + "', '" + SortColumnIndex + "', 6, 1, 0, " + CourtOrAgency + ", " + YearJump + ", " + NumLines + ");return false;\">" + determineSortGraphic(recordsRoot.attr('ordmodecitation'), (currentSortingColumn == 6)) + "</a></th>";
					}

					htmlContent += "</tr></thead>";
					htmlContent += "<tbody>";
					var currentResult = firstResult;
					$(data).find('record').each(function () {
						var currentCase = $(this);
						htmlContent += "<tr>";
						htmlContent += "<td>" + currentResult + "</td>";
						htmlContent += "<td>" + currentCase.find('filingdate').text() + "</td>";
						htmlContent += "<td><a href='" + currentCase.attr('link') + "' onclick='window.open(this.href);return false;'>";
						if (agencyId == 1 || agencyId == 2) {
							htmlContent += currentCase.find('casename').text();
						} else if (agencyId == 4) {
							htmlContent += currentCase.find('petitioner').text();
						} else if (agencyId == 5 || agencyId == 6) {
							htmlContent += currentCase.find('employer').text();
						}
						htmlContent += "</a></td>";
						htmlContent += "<td>" + currentCase.find('docketnumber').text() + "</td>";
						if (agencyId == 1 || agencyId == 2) {
							htmlContent += "<td>" + currentCase.find('citation').text() + "</td>";
						}
						htmlContent += "</tr>";
						currentResult++;
					});
					htmlContent += "</tbody></table>";

					// Display paging controls, if necessary.
					if (recordsReturned > NumLines) {
						var totalPages = roundNumber(recordsReturned / NumLines);

						htmlContent += "<div id='Pagination' style='text-align:center;'><p>More results:<br />";

						if (currentPage != 1) {
							var previousPage = currentPage - 1;
							htmlContent += "<a href='#' onclick=\"importDatabaseRecords('" + OrdMode + "', '" + OrdModeFiling + "', '" + OrdModePetitioner + "', '" + OrdModeDocket + "', '" + OrdModeEmployer + "', '" + OrdModeCaseName + "', '" + OrdModeCitation + "', '" + PreviousSortColumnIndex + "', '" + SortColumnIndex + "', " + previousPage + ", " + (previousPage * NumLines) + ");return false;\">Previous</a> | ";
						}

						var pagesStartCount = 1;
						var pagesEndCount = 10;
						if (currentPage > 10) {
							if (currentPage % 10 > 0) {
								pagesStartCount = currentPage - (currentPage % 10 - 1);
							} else {
								pagesStartCount = currentPage - 9;
							}
							pagesEndCount = pagesStartCount + 9;
							var previousPageSet = pagesStartCount - 10;
							htmlContent += "<a href='#' onclick=\"importDatabaseRecords('" + OrdMode + "', '" + OrdModeFiling + "', '" + OrdModePetitioner + "', '" + OrdModeDocket + "', '" + OrdModeEmployer + "', '" + OrdModeCaseName + "', '" + OrdModeCitation + "', '" + PreviousSortColumnIndex + "', '" + SortColumnIndex + "', " + previousPageSet + ", " + (previousPageSet * NumLines) + ");return false;\">" + (pagesStartCount - 10) + "-" + (pagesStartCount - 1) + "</a> | ";
						}
						if (pagesEndCount > totalPages || totalPages <= 10) {
							pagesEndCount = totalPages;
						}

						for (w = pagesStartCount; w <= pagesEndCount; w++) {
							if (currentPage == w) {
								htmlContent += "" + w + "";
							} else {
								htmlContent += "<a href='#' onclick=\"importDatabaseRecords('" + OrdMode + "', '" + OrdModeFiling + "', '" + OrdModePetitioner + "', '" + OrdModeDocket + "', '" + OrdModeEmployer + "', '" + OrdModeCaseName + "', '" + OrdModeCitation + "', '" + PreviousSortColumnIndex + "', '" + SortColumnIndex + "', " + w + ", " + (w * NumLines) + ");return false;\">" + w + "</a>";
							}

							if (w != pagesEndCount) {
								htmlContent += " | ";
							}
						}

						if ((pagesEndCount - pagesStartCount == 9) && pagesEndCount < totalPages) {
							var nextPageSet = pagesStartCount + 10;
							htmlContent += " | <a href='#' onclick=\"importDatabaseRecords('" + OrdMode + "', '" + OrdModeFiling + "', '" + OrdModePetitioner + "', '" + OrdModeDocket + "', '" + OrdModeEmployer + "', '" + OrdModeCaseName + "', '" + OrdModeCitation + "', '" + PreviousSortColumnIndex + "', '" + SortColumnIndex + "', " + nextPageSet + ", " + (nextPageSet * NumLines) + ");return false;\">" + (pagesEndCount + 1) + "-" + (pagesEndCount + 10) + "</a>";
						}
						if (lastResult < recordsReturned) {
							var nextPage = currentPage + 1;
							htmlContent += " | <a href='#' onclick=\"importDatabaseRecords('" + OrdMode + "', '" + OrdModeFiling + "', '" + OrdModePetitioner + "', '" + OrdModeDocket + "', '" + OrdModeEmployer + "', '" + OrdModeCaseName + "', '" + OrdModeCitation + "', '" + PreviousSortColumnIndex + "', '" + SortColumnIndex + "', " + nextPage + ", " + (nextPage * NumLines) + ");return false;\">Next</a>";
						}

						htmlContent += "</p></div>";

					}
				} else {
					htmlContent += "<p class='error'>No results were found for your search.</p>";
				}
				$('#RecordDisplay').html(htmlContent);
				$('#RecordDisplay tbody tr:even').addClass('rowalt2');
			}
		});
	}
}
