var lastHash = '';
$(document).ready(function() {

	if($('#img-container1').length > 0 && $('#img-container2').length > 0) {
		ResizeImgContainers('img-container1','img-container2');
	}
	
	PrepareAJAXNavigation();
	ReceiveCredit();
	$('#registration #plan').change(ReceiveCredit);
	
	// Search History
	SearchHistoryInit();
	
	if($('#SearchName').length > 0) {
		focusForm('SearchName');
	}
	if($('#featured_feature').length > 0) {
		SetupSiteAd('featured_feature');
	}
});

function ReceiveCredit() {
	var div =  $('#registration #receive_credit');
	var tdElem =  $('#registration #receive_credit').parent();
	var planCode = $('#registration #plan').val();
	if(!tdElem || !planCode) return;
	if(planCode == 8) {
		div.html('You have chosen the Daily Plan! To use your credits please choose a different plan.');
		return;
	}
}

function EmailImage(Url)
{
  var email = prompt('Plese enter the email address:','');
  if (email == '') return (false);

  validRegExp = /^[^@]+@[^@]+.[a-z]{2,}$/i;
  if (email.search(validRegExp) == -1) {
     alert('This is an invalid email address'); 
	 return (false);
  }

  $.get(Url+"&Email="+escape(email));
  alert('This will be emailed shortly!');
  return (true);
}

function hasTiffViewer(cookie_check)
{
   var found=false;
   if (cookie_check == undefined) cookie_check = true;
   if (cookie_check) {
	var tiffCookieValue = $.cookie('tiffCheck') || '';
	if (tiffCookieValue == '1') return (true);
   }
  

   var L = navigator.plugins.length;
   for(var i=0; i<L && !found; i++) {
     if (navigator.plugins[i].name.toLowerCase().indexOf('tiff') != -1) {
	found = true;
     }
     if (navigator.plugins[i].description.toLowerCase().indexOf('tiff') != -1) {
	found = true;
     }	
   }
   return (found);
}

  function TiffCookieBypass()
  {
	$.cookie('tiffCheck', '1', {expires: 366});
	window.location.reload();
  }

  function InstallWindow(cookieBypass) {
	
	if (cookieBypass == undefined) cookieBypass = true;
	
	document.write('<div id="notice">You appear not to have a TIFF viewer installed.<br><br>');
	if (cookieBypass) {
	   document.write('If you would like to skip this check; click <a href="#" onClick="TiffCookieBypass();">here</a><br><br>');
	}

	if (navigator.userAgent.indexOf('MSIE') !=-1)
	{
		 document.write('<object width=300 height=130 id=kpt1\n' +
		' classid="CLSID:106E49CF-797A-11D2-81A2-00E02C015623"\n' +
		' codebase="/tiffviewers/alttiff.cab#version=1,8,4,1">\n' +
		' <param name=toolbar value=off>\n' +
		' <param name=src value="/images/tiffinstall.tif"></object>\n');
	} else if (navigator.userAgent.indexOf('Mac') != -1) {
		document.write('On your Macintosh browser, you should download and install <a href="http://www.acordex.com/browseProd/VTpluginb.html">Accel ViewTIFF</a>');
//                document.write('<br><center><embed name="EmbedImage" toolbar=off alt="You need a Tiff Plugin" width=300px height=170px src="/images/tiffinstall.tif" id="Image" type="image/tiff"></center>');


	} else if (navigator.userAgent.indexOf('Linux') != -1) {
		document.write('On your Linux browser, You should download and install <a href="http://fredrik.hubbe.net/plugger.html">Plugger</a>');
//                document.write('<br><center><embed name="EmbedImage" toolbar=off alt="You need a Tiff Plugin" width=300px height=170px src="/images/tiffinstall.tif" id="Image" type="image/tiff"></center>');
	} else {
		document.write('You should download and install <a href="/tiffviewers/alternatiff-1_8_5.exe">Alternatiff</a>');
//                document.write('<br><center><embed name="EmbedImage" toolbar=off alt="You need a Tiff Plugin" width=300px height=170px src="/images/tiffinstall.tif" id="Image" type="image/tiff"></center>');
	}
	document.write('<br><br>Click <a href="#" onclick="TiffCookieBypass(); navigator.plugins.refresh(false); window.location.reload();">here to <b>Reload</b> the page</a>.  On some browsers you might have to restart them.<br>');

	document.write('</div>');
	
  }



function CheckMembershipReturned(Data, Status)
{
   Error = document.getElementById('error-display');
   if (Data.error != undefined) 
   {
	Error.innerHTML = '<ul id="form-registration-errorlist"><li>'+Data.error+'</li></ul>';
   } else {
	Error.innerHTML = '';
   }
   Additional = document.getElementById('additional-data');
   if (Data.html != undefined) {
	Title = document.getElementById('additional-data-title');
	Title.innerHTML = Data.title;
	HTML = document.getElementById('additional-data-html');
	HTML.innerHTML = Data.html;
	Additional.style.display='';
   } else {
	Additional.style.display='none';
   }
  var regbut = $("input[name='registration-submit-1']");
  if (regbut == undefined) {
    regbut = $("input[name='registration-submit']");
  }
  regbut[0].disabled = false;


}


function CheckMembership()
{
  var email = $("input[name='emailaddress']").attr("value");
  var oba = $("input[name='oba']").attr("value");
  var obapin = $("input[name='obapin']").attr("value");
  var regbut = $("input[name='registration-submit-1']");
  if (regbut == undefined) {
    regbut = $("input[name='registration-submit']");
  }
  regbut[0].disabled = true;

  $.post("/register.php", {emailaddress: email, oba: oba, obapin: obapin, CheckMembership: 1}, CheckMembershipReturned, 'json'); 

}

function WriteImageLink(Link)
{
	var headHeight = $('#site_header').height();
	var footerHeight = $('#footer').height();
	var headHeight = headHeight + $('#navigation').height();
	
	var height = (($(document).height() - headHeight) - footerHeight) - 16;
      document.write('<embed name="EmbedImage" alt="You need a Tiff Plugin" width=100% height='+height+'px src="'+Link+'" id="Image" type="image/tiff">');
	
}

function WritePDFLink(Link)
{
	var headHeight = $('#site_header').height();
	var footerHeight = $('#footer').height();
	var headHeight = headHeight + $('#navigation').height();
	
	var height = (($(document).height() - headHeight) - footerHeight) - 16;

        document.write('<iframe name="EmbedImage" alt="You need a PDF viewer" width=100% height='+height+'px src="'+Link+'" id="Image">');
	
}



function ResizeImgContainers(container, container2) {
	var headHeight = $('#site_header').height();
	var footerHeight = $('#footer').height();
	var headHeight = headHeight + $('#navigation').height();
	
	var height = (($(document).height() - headHeight) - footerHeight) - 16;
      $('#' + container2).height(height);
	$('#' + container).height(height);
}

var inRotation=false;
function ImgRotate(imgID)
{
  if (inRotation) return;
  inRotation = true;
  var activeImage = $('#Image')[0];
  var CurrentWidth = $('#Image').width();
  var CurrentHeight = $('#Image').height();
  if (zoomResetWidth == 0) zoomResetWidth = CurrentWidth;
  if (zoomResetHeight == 0) zoomResetHeight = CurrentHeight;

  var src = activeImage.src;

  $('#Image').width(33);
  $('#Image').height(33);
  activeImage.src = "/images/thinking.gif";

  $.get("/image.php", { i: imgID, Rotate: 'Y'}, function(data) {
	CurrentHeight = zoomResetWidth;
	zoomResetWidth = zoomResetHeight;
	zoomResetHeight = CurrentHeight;
      activeImage.onLoad = ImgRotateOnLoad();
	activeImage.src = src;
      inRotation = false;
    });
}

function ImgRotateOnLoad()
{
  var activeImage = $('#Image')[0];
  activeImage.onLoad = null;
  self.setTimeout('ImgZoomReset()', 1500);
  // ImgZoomReset();
}


var zoomResetWidth=0;
var zoomResetHeight=0;
function ImgZoomOut()
{
	var CurrentWidth = $('#Image').width();
	var CurrentHeight = $('#Image').height();
      if (zoomResetWidth == 0) zoomResetWidth = CurrentWidth;
      if (zoomResetHeight == 0) zoomResetHeight = CurrentHeight;

	ScaleWidth = CurrentWidth / 10
	ScaleHeight = CurrentHeight / 10

	CurrentWidth = CurrentWidth -= ScaleWidth;
	CurrentHeight = CurrentHeight -= ScaleHeight;
	if (CurrentWidth < 100) return;
	$('#Image').width(CurrentWidth);
      $('#Image').height(CurrentHeight);
}


function ImgZoomIn()
{
	var CurrentWidth = $('#Image').width();
	var CurrentHeight = $('#Image').height();
      if (zoomResetWidth == 0) zoomResetWidth = CurrentWidth;
      if (zoomResetHeight == 0) zoomResetHeight = CurrentHeight;


	ScaleWidth = CurrentWidth / 10
	ScaleHeight = CurrentHeight / 10

	CurrentWidth = CurrentWidth += ScaleWidth;
	CurrentHeight = CurrentHeight += ScaleHeight;
	$('#Image').width(CurrentWidth);
      $('#Image').height(CurrentHeight);
}

function ImgPrint()
{
  var CurrentWidth = $('#Image').width();
  var CurrentHeight = $('#Image').height();
  ImgZoomFull();
  window.print();
  $('#Image').width(CurrentWidth);
  $('#Image').height(CurrentHeight);
}

function ImgZoomReset()
{
  if (zoomResetWidth == 0) return;


  var CurrentWidth = zoomResetWidth;
  var CurrentHeight = zoomResetHeight;

  $('#Image').width(CurrentWidth);
  $('#Image').height(CurrentHeight);  
}

function ImgZoomFull()
{
  var tempImage = new Image();
  var activeImage = $('#Image')[0];

  if (zoomResetWidth == 0) zoomResetWidth = $('#Image').width();
  if (zoomResetHeight == 0) zoomResetHeight = $('#Image').height();

  tempImage.src = activeImage.src;
  var CurrentWidth = tempImage.width;
  var CurrentHeight = tempImage.height;

  $('#Image').width(CurrentWidth);
  $('#Image').height(CurrentHeight);  

}

function showwindow(x1) {
	window.open(x1,"_blank","toolbar=no,location=no,directories=no,status=no,scrollbars=yes,menubar=no,resizable=yes,width=600,height=400");
}
function search_load() {
	var Results = 'results.php#/results.php?Page=0'//&'+SessionID;
	
	if(isAppleWebKit()) {
		// WebKit doesn't work right when using replace.
		location.href = Results;
	} else {
		location.replace(Results);
	}
}

var currentTab = '';
function SelectThisTab(tab) {
	if(hasClass(document.getElementById(tab), 'selected')) {
		currentTab = tab;
	}
	items = getElementsByClass('selected');
	itemsTotal = items.length;
	for (i = 0; i < itemsTotal; i++) {
		removeClass(items[i], 'selected');
	}
	
	if(currentTab == tab) {
		document.getElementById('countystatus_data').innerHTML = '';
		currentTab = '';
	} else {
		addClass(document.getElementById(tab), 'selected');	
		ShowCourtTable(tab);
		currentTab = tab;
	}
	SetCookie(currentTab);
}

function ShowCourtTable(court) {
	var ajax = new sack();
	ajax.requestFile = "countystatus.php?court=" + court;
	ajax.element = 'countystatus_data';
	ajax.onLoading = function() { document.getElementById(ajax.element).innerHTML = 'loading...'; };
	ajax.onLoaded = function() {};
	ajax.onCompletion = function() { tooltip.init(); };
	ajax.runAJAX();
}
function SetCookie(tab) {
	var cookieAjax = new sack();
	cookieAjax.requestFile = "ajax.cookie.countystatus.php?tab=" + tab;
	cookieAjax.runAJAX();
}

// Focus on a form field when the page has loaded.
// Must be placed BELOW the form for it to work properly.
function focusForm(field){
   if(document.getElementById(field)){
      document.getElementById(field).focus();
   }
}

function SubmitForm(form) {
	form = document.getElementById(form);
	form.submit();
}
function HideObject (object) {
	document.getElementById(object).style.display = 'none';
}
function ShowObject (object) {
	document.getElementById(object).style.display = 'block';
}

function HideAllWithClass(ClassName) {
	Questions = getElementsByClass(ClassName);
	QuestionTotal = Questions.length;
	for (i = 0; i < QuestionTotal; i++) {
		HideObject(Questions[i].id);
	}
}

function hasClass(ele,cls) {
	return ele.className.match(new RegExp('(\\s|^)'+cls+'(\\s|$)'));
}

function addClass(ele,cls) {
	if (!this.hasClass(ele,cls)) ele.className += " "+cls;
}

function removeClass(ele,cls) {
	if (hasClass(ele,cls)) {
    	var reg = new RegExp('(\\s|^)'+cls+'(\\s|$)');
		ele.className=ele.className.replace(reg,' ');
	}
}

function getElementsByClass(searchClass, node, tag) {
	var classElements = new Array();
	if ( node == null )
		node = document;
	if ( tag == null )
		tag = '*';
	var els = node.getElementsByTagName(tag);
	var elsLen = els.length;
	var pattern = new RegExp('(^|\\s)'+searchClass+'(\\s|$)');
	for (i = 0, j = 0; i < elsLen; i++) {
		if ( pattern.test(els[i].className) ) {
			classElements[j] = els[i];
			j++;
		}
	}
	return classElements;
}

// Handles ODCR Results Paging
function results(link)
{
	var path = $(link).attr('href');
	results_page_load(path);
	return (false);
}

function results_page_load(url){
	$.get(url, {
		Partial: 1
	}, function(data){
		var odcr = document.getElementById("results-box");
		if (odcr == undefined) 
			return;
		odcr.innerHTML = data;
		location.hash = url;
		lastHash = location.hash;
	}, "html");
	return false;
}

// Handles OCIS Results
function results_load(fromLink)
{
	if (fromLink)
	{
		$.cookie("ocis_results_show", 'true', { expires: 90 });
	}
	
	var ocisLoad = document.getElementById("ocis-loading");
	var url = document.getElementById("ocis-url").getAttribute("href");
	var ocis = document.getElementById("ocis-results");
	ocisLoad.innerHTML = 'Loading OCIS Results...'
	var newurl = "/php/php_proxy.php?url=" + escape(url);

	$.get(newurl, function(data)
		{
			if (ocis == undefined) return;
			ocis.innerHTML = data;
			ocisLoad.innerHTML = 'OCIS Search Results <a id="ocis-hide" OnClick="javascript:hide_ocis(); return false;" href="' + url + '">(Hide Results)</a>';
		}
		, "html");
}

function hide_ocis()
{
	$.cookie("ocis_results_show", 'false', { expires: 90 });
	
	var ocisLoad = document.getElementById("ocis-loading");
	var url = document.getElementById("ocis-hide").getAttribute("href");
	var ocis = document.getElementById("ocis-results");

	ocis.innerHTML = "";
	ocisLoad.innerHTML = '<a id="ocis-url" OnClick="javascript:results_load(true); return false;" href="' + url + '">Check for OCIS Results</a>';
}

function getcase2(D,X,XX,C) // for OCIS support.
{
	var url = "http://www.oscn.net/applications/ocisweb/GetCaseInformation.asp?submitted=true&viewtype=caseGeneral&casemasterID="+C+"&db="+D;
	window.open(url, "_blank");
}

// AJAX Navigation
function PrepareAJAXNavigation() {
	if(location.hash) {
		lastHash = location.hash;
	}
	setInterval('pollHash()', 100);
	changeHashLocation();
}

function pollHash() {
    if(lastHash !== location.hash) {
        lastHash = location.hash;
		changeHashLocation();
    }
}

function changeHashLocation() {
	if (location.hash) {
		results_page_load(location.hash.substring(1));
	}
}
function isAppleWebKit(){
	var str = navigator.userAgent.toLowerCase();
	if(str.search(/applewebkit/) > -1 ) {
		return true;
	}
	return false;
}

// Search History
SearchHistoryMenuToggle = 0;
function SearchHistoryInit() {	
	$('#navigation #navigation-user-container #search_history').click(function(){
		if(SearchHistoryMenuToggle == 0) {
			SearchHistoryOpen();
		} else {
			SearchHistoryClose();
		}
		return false;
	});
	$(document).click(SearchHistoryClose);
}

function SearchHistoryOpen() {
	var url = '/user/search.history.php';
	var div = $('#navigation #navigation-user-container #search_history_data');
	if(div.html().search('Loading...') > -1){
		$.get(url, function(data){
			div.html(data);
		});
	}
	$('#navigation #navigation-user-container #search_history').addClass('selected');
	div.slideDown('fast');
	SearchHistoryMenuToggle = 1;
}

function SearchHistoryClose(){
	$('#navigation #navigation-user-container #search_history').removeClass('selected');
	$('#navigation #navigation-user-container #search_history_data').slideUp('fast');
	SearchHistoryMenuToggle = 0;
}

// Import Additional JS files Code.
if (typeof(JavascriptObject) == 'undefined') var JavascriptObject = new Object();

function JavascriptFileImport(jsFile) {
	if (JavascriptObject[jsFile] != null) return;
	var scriptElt = document.createElement('script');
	scriptElt.type = 'text/javascript';
	scriptElt.src = jsFile;
	document.getElementsByTagName('head')[0].appendChild(scriptElt);
	JavascriptObject[jsFile] = jsFile;
}