/*
 * TaxInquiry.js - Site specific script file
 */

/*
 * Create the TaxInquiry namespace
 */
var TaxInquiry;
if (typeof TaxInquiry === 'undefined') {
	TaxInquiry = {};
}

if (typeof TaxInquiry.Parcel === 'undefined') { TaxInquiry.Parcel = {}; }
if (typeof TaxInquiry.Parcel.Location  === 'undefined') { TaxInquiry.Parcel.Location = {}; }
if (typeof TaxInquiry.Account === 'undefined') { TaxInquiry.Account = {}; }
if (typeof TaxInquiry.Search === 'undefined') { TaxInquiry.Search = {}; }
if (typeof TaxInquiry.Search.Current === 'undefined') { TaxInquiry.Search.Current = {}; }
if (typeof TaxInquiry.Search.Cached === 'undefined') { TaxInquiry.Search.Cached = {}; }
if (typeof TaxInquiry.Search.Results === 'undefined') {
	TaxInquiry.Search.Results = {
		AutoWidth: false
	};
}

/*
 * Any nasty-dirty globals we need
 */
var sidebarTop = null;
var sidebarScrolledOutOfView = false;

/*
 * Code to be run when the document is ready
 */
TaxInquiry.onready = function() {
    var client = {};
    if( typeof Client !== 'undefined' ) {
        client = Client;
    }
    else {    
        client.resultWidth = function() {
            return "800px";
        }
    }

	//TaxInquiry.Storage
	//Provides safe wrappers to HTML5 localStorage and compresses values to save space
	//Usage: DEVNET.Storage("SomeKey") will return the value of SomeKey
	//	 DEVNET.Storage("SomeKey", "New Value") will set the value of SomeKey to New Value
	TaxInquiry.Storage = function (key, value) {

		if (!TaxInquiry.Storage.Enabled) { return false; }

		//return current value if user new value is not passed in
		if (value == null) {
			if (localStorage.getItem(key) == null) { return null; }
			if (TaxInquiry.Storage.CompressionEnabled) {
				var ret = RawDeflate.inflate(JSON.parse(localStorage.getItem(key)));
				//depending on browser implementation, JSON.parse will unescape
				//and also parse the string. IE8 does this, the other major browsers
				//don't seem to, so we parse again
				if (typeof ret == "string") {
					ret = JSON.parse(ret);
				}
				return ret;
			} else {
				var ret = JSON.parse(localStorage.getItem(key));
				return ret;
			}
		}

		//try to update value
		try {
			//have to use setItem/getItem syntax due to IE not treating it as a regular array
			//IE also seems to have an issue with the UTF16 returned by RawDeflate, so escape it
			//using JSON.stringify
			if (TaxInquiry.Storage.CompressionEnabled) {
				var zipped = JSON.stringify(RawDeflate.deflate(value));
				localStorage.setItem(key, zipped);
			} else {
				localStorage.setItem(key, value);
			}
			return true;
		}
		catch (e) {
			log(e);
			//clear out cache and try again
			log("localStorage error, possibly quota exceeded, trying again.");
			try {
				log("Clearing out TaxInquiry localStorage to make more room");
				//Probably don't need to alert the user...it might just confuse them if we can recover
				//alert("We're sorry, something went wrong and we have to delete old cached search results. If you were trying to search, please resubmit your search. If this problem persists please contact the site administrator.");
				//clear out TaxInquiry storage
				for (var item in localStorage) {
					//use toString because of IE
					var sitem = item.toString();
					if (sitem.startsWith("TaxInquiry") && sitem != key) {
						log("Removing: " + sitem);
						localStorage.removeItem(sitem);
					}
				}

				//we need to keep these
				var cgiSess = $.cookies.get("CGISESSID");
				var appVer = $.cookies.get("appVer");
				var dbVer = $.cookies.get("dbVer");

				localStorage.setItem('TaxInquiry.DBVer', dbVer);

				localStorage.setItem('TaxInquiry.AppVer', appVer);

				localStorage.setItem('TaxInquiry.SessionID', cgiSess);

				//have to use setItem/getItem syntax due to IE not treating it as a regular array
				//IE also seems to have an issue with the UTF16 returned by RawDeflate, so escape it
				//using JSON.stringify
				if (TaxInquiry.Storage.CompressionEnabled) {
					var zipped = JSON.stringify(RawDeflate.deflate(value));
					localStorage.setItem(key, zipped);
				} else {
					localStorage.setItem(key, value);
				}
				return true;
			}
			catch (e) {
				log(e);
				log("Unable to recover, disabling TaxInquiry.Storage for now.");
				$.cookies.set("TaxInquiry.Storage.Enabled", false);
				//alert("We're sorry, due to limitations of your browser we have to disable cached search results. If you were trying to search, please resubmit your search. If this problem persists please contact the site administrator.");
				return false;
			}
			return false;
		}
	}

	//Closure to determine if TaxInquiry.Storage is enabled
	TaxInquiry.Storage.Enabled = (function() {
		if ($.cookies.get("TaxInquiry.Storage.Enabled") == null) { $.cookies.set("TaxInquiry.Storage.Enabled", true); }
		return Modernizr.localstorage && $.cookies.get("TaxInquiry.Storage.Enabled");
	})();

	TaxInquiry.Storage.CompressionEnabled = (function() {
		log("TaxInquiry.Storage.CompressionEnabled = " + !(jQuery.browser.msie && parseInt(jQuery.browser.version) < 9));
		if (jQuery.browser.msie && parseInt(jQuery.browser.version) < 9)
			return false;
		return true;
	})();


	//Initialize offline storage
	if (TaxInquiry.Storage.Enabled) {
		//check/update application version and dbversion variables
		var cgiSess = $.cookies.get("CGISESSID");
		var appVer = $.cookies.get("appVer");
		var dbVer = $.cookies.get("dbVer");

		if (dbVer != localStorage.getItem('TaxInquiry.DBVer') || localStorage.getItem('TaxInquiry.DBVer') == null) {
			//clear out TaxInquiry storage
			for (var item in localStorage) {
				//use toString because of IE
				var sitem = item.toString();
				if (sitem.startsWith("TaxInquiry")) {
					localStorage.removeItem(sitem);
				}
			}
			localStorage.setItem('TaxInquiry.DBVer', dbVer);
		}

		if (appVer != localStorage.getItem('TaxInquiry.AppVer') || localStorage.getItem('TaxInquiry.AppVer') == null) {
			localStorage.setItem('TaxInquiry.AppVer', appVer);
		}

		if (cgiSess != localStorage.getItem('TaxInquiry.SessionID') || localStorage.getItem('TaxInquiry.SessionID') == null) {
			localStorage.setItem('TaxInquiry.SessionID', cgiSess);
		}

		//Click tracking in sessionStorage for debugging UI (this is per browser tab)
		//namespace the event so that we don't step on anything else that
		//may bind to body at some point on the click event
		$("body").bind("click.debug", function(eventData) {
			//refer to http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html for event details
			//also http://api.jquery.com/category/events/event-object/
			var click = {
				X: eventData.pageX,
				Y: eventData.pageY,
				timestamp: (new Date).getTime(),
				page: eventData.target.baseURI,
				tag: eventData.target.localName,
				id: eventData.target.id,
				classes: eventData.target.className,
				innerHTML: eventData.target.innerHTML,
				innerText: eventData.target.innerText
			};

			//store in localStorage
			var clicks = [];
			if (sessionStorage.getItem("TaxInquiry.ClickTracking") != null) {
				clicks = JSON.parse(sessionStorage.getItem("TaxInquiry.ClickTracking"));
			}

			clicks.push(click);
			try {
				sessionStorage.setItem("TaxInquiry.ClickTracking", JSON.stringify(clicks));
			} catch(e) {
				log("Session Storage limit reached.");
				log(e);
				log("Resetting debug click tracking storage.");
				sessionStorage.removeItem("TaxInquiry.ClickTracking");
				clicks = [];
				clicks.push(click);
				//recover?
				try {
					log("Retrying...");
					sessionStorage.setItem("TaxInquiry.ClickTracking", JSON.stringify(clicks));
				} catch(e) {
					log("Session Storage limit reached.");
					log(e);
					log("Disabling debug click tracking. Giving up.");
					sessionStorage.removeItem("TaxInquiry.ClickTracking");
					//unbind event from within to prevent further errors
					$("body").unbind(eventData);
					return;
				}
			}
		});
	}


	/*
	 * Accordian
	 * Dont animate in FF or IE, they have trouble doing animation with a large number of elements within
	 * the accordian divs (there is a noticeable lag). Webkit and Opera seem ok.
	 * Also note that according to docs, jQuery.browser is deprecated as of 1.3, however they dont have
	 * a replacment method for getting browser name, only features. So this will have to stay for the moment.
	 */

	if(jQuery.browser.mozilla == true || jQuery.browser.msie == true) {
		$(".accordian").accordion({ header: ".head3", autoHeight: false, animated: false });
		$(".accordian-small").livequery(function(){
			$(this).accordion({
				header: ".head4",
				autoHeight: false,
				animated: false,
				collapsible: true,
				active: false
			});
		});
	} else {
		$(".accordian").accordion({ header: ".head3", autoHeight: false });
		$(".accordian-small").livequery(function(){
			$(this).accordion({
				header: ".head4",
				autoHeight: false,
				animated: true,
				collapsible: true,
				active: false
			});
		});
	}

	/*
	 * Set up datepicker
	 */
	$(".date_input").datepicker();

	/*
	 * show warning/info dialogs
	 */
	/* Show animation fail: http://dev.jqueryui.com/ticket/4892 */
	$(".fg-dialog").livequery(function() {
		$(this).dialog({
			modal: true,
			draggable: false,
			resizable: false,
			/*show: 'puff',*/
			hide: 'puff',
			buttons: {
				Ok: function() {
					$(this).dialog('close');
				}
			},
			open: function() {
				$(".waitDlg").dialog("close");
			}
		});
	});

	/*
	 * Set up Throbber plugin for sidebar (sorry, no encapsulation here :-( )
	 */
	if( !$("#sidebar-throbber").length > 0 ) {
		$("#sidebar .box").append("<div id='sidebar-throbber'></div>");
	}

	$("#sidebar .ajax a")
	.bind("ajax-click", function(e) {
		//don't mess with the throbber if the link loaded cached data
		if ($(this).is(".page-cached")) {
			$("#sidebar-throbber").hide();
			return false;
		} else {
			$("#sidebar-throbber").show();
		}

		var offset = $(this).position();

		$("#sidebar-throbber").css({
			'width': '16px',
			'height': '16px',
			'position': 'absolute',
			'left': (offset.left - 15) + 'px',
			'top': offset.top + 'px',
			'z-index': '90'
		});
		return true;
	});

	$("#sidebar .ajax a")
	.throbber({
		image: "/common/images/indicator.gif",
		ajax: true,
		parent: "#sidebar-throbber"
	});


	/*
	 * all hover and click logic for sidebar links
	 */
	$("#sidebar dd")
	.hover(
		function(){
			$(this).addClass("ui-state-highlight");
			$(this).addClass("ui-corner-all");
			$(this).css("cursor", "pointer");
		},
		function(){
			if( !$(this).is(".fg-link-active") ){
				$(this).removeClass("ui-state-highlight");
				$(this).removeClass("ui-corner-all");
			}
			$(this).css("cursor", "auto");
		}
	)
	.mouseup(function(){
		$("#sidebar dd").each( function() {
			$(this).removeClass("ui-state-highlight");
			$(this).removeClass("ui-corner-all");
			$(this).removeClass("fg-link-active");
		});
		$(this).addClass("ui-state-highlight");
		$(this).addClass("ui-corner-all");
		//ajax links need to stay highlighted
		if( $(this).is(".ajax") ) { $(this).addClass("fg-link-active"); }
	});

	/*
	 * all hover and click logic for result links
	 */
	$("#results tbody tr, #parcel_list tbody tr, .headerDetail-header")
	.live('mouseover', function(){
		if($( this ).is(".ui-state-checked")) return;
		$(this).addClass("ui-state-highlight");
		$(this).css("cursor", "pointer");
	})
	.live('mouseout', function(){
		if($(this).is(".ui-state-checked")) return;
		if(!$(this).is(".fg-link-active")){
			$(this).removeClass("ui-state-highlight");
		}
		$(this).css("cursor", "auto");
	})
	.live('mouseup', function(){
		$(this).parent().children(".headerDetail-header").each( function() {
			$(this).removeClass("ui-state-highlight");
			$(this).removeClass("fg-link-active");
		});

	    if( $( this ).hasClass( "ui-state-checked" )) {
			$(this).removeClass("ui-state-highlight");
			$(this).removeClass("fg-link-active");
	    }
	    else {
            $(this).addClass("ui-state-highlight");
            $(this).addClass("fg-link-active");
        }
	});

	/*
	 * all hover and click logic for page nav links
	 */
	$(".pagenav")
	.live('mouseover', function(){
		$(this).addClass("ui-state-highlight");
		$(this).addClass("ui-corner-all");
	})
	.live('mouseout', function(){
		if( !$(this).is(".fg-link-active") ){
			$(this).removeClass("ui-state-highlight");
			$(this).removeClass("ui-corner-all");
		}
	})
	.live('mouseup', function(){
		$(this).addClass("ui-state-active");
		$(this).addClass("ui-corner-all");
		$(this).addClass("fg-link-active");
	});

	/*
	 * all hover and click logic for buttons
	 */
	$(":button, .buttonlink").livequery(function(){ $(this).button(); });

	/*
	 * Default enter key to form submit, escape key to clear
	 */
	$("#criteria").keypress(function (e) {
		if((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
			$("#criteria .ui-priority-primary:first").click();
			return false
		} else if((e.which && e.which == 27) || (e.keyCode && e.keyCode == 27)) {
			$("#criteria .ui-priority-secondary:first").click();
			return false
		} else {
			return true;
		}
	});

	/*
	 * Handle sidebar scrolling
	 */
	if( $("#sidebar").length > 0 ) {
        sidebarTop = parseInt($("#sidebar").offset().top);

        $(window).scroll(function() {
            var offset = $(document).scrollTop() + "px";
            if ($(document).scrollTop() > sidebarTop){
                sidebarScrolledOutOfView = true
                $("#sidebar").animate({top: offset},{duration: 500, queue: false});
            } else {
                /* using hacky method to avoid unnecessary jumping in webkit/IE */
                /* never set it back, this just skips over things that aren't initialized the first time */
                if (sidebarScrolledOutOfView){
                    $("#sidebar").animate({top: sidebarTop},{duration: 500, queue: false});
                }
            }
        });
    }

	/*
	 * Results Dialog box
	 */
	$("#resultDiv").dialog({
		dialogClass: "resultsDlg",
		draggable: false,
		modal: true,
		resizable: false,
		/* http://dev.jqueryui.com/ticket/4437 */
		//width: function() {
			//if( typeof Client === 'undefined' ) {
				//return Client.resultWidth();
			//}
			//else {
				//return '750px';
			//}
		//},
		width: client.resultWidth(),
		title: "Step 3: Select a Property",
		autoOpen: false,
		open: function() {
			$(".waitDlg").dialog("close");
		}
	});

	/*
	 * Search radio buttons
	 */
	$("input[name='search_method']").click(function() {
		var crit = $("input:radio[name='search_method']:checked").val() + "-criteria";
		//don't reshow, use selector rather than style.display as style.display doesn't inherit from class styles
		if($("#" + crit).is(":hidden")) {
			//show main criteria selection div if hidden
			$("#search-criteria:hidden").show();
			//hide any visible criteria divs
			$(".search-criteria:visible").hide();
			//show the requested search criteria div
			DEVNET.showFade(crit, 500);
			//set focus to first input
			$("#" + crit).find(":input:first").focus();
		}
	});

	/*
	 * Trigger default view load on page load
	 */
	$(".defaultView:first").trigger("mouseup").trigger("click");

	/*
	 * Trigger detail load on header-detail load (selecting first)
	 */
	$(".headerDetail-header:first").livequery(function() {
		$(this).trigger("mouseup").trigger("click");
	});


	/*
	* Handle header-detail behavior (needs to be broken out into a library function at some point so that we can call $.headerDetail() )
	*/
	$(".headerDetail-header").live("click", function(){
		var tagType = this.tagName;

		//Pull detail template from id of header
		var url = "/wedge/ajax/parcel/" + TaxInquiry.Parcel.Number + "/" + TaxInquiry.Parcel.Year + "/detail-" + $(this).attr("id").match(/\[(.*?)\]/)[1] + "?detail=true";

		//Build rest of url
		$(this).children(".headerDetail-join").each(function() {
			url += "&amp;" + $(this).attr("id").match(/\[(.*?)\]/)[1] + "=" + $(this).text().trim();
		});

		//it's cheaper to remove and recreate
		$(this).parent().find('.headerDetail-detail').remove();

		var html = "<" + tagType + " class = 'headerDetail-detail'>";

		//we need a generic way of determining if we need a helper child element (like needing a TD for TR)
		if(tagType == 'TR'){
			var numberOfCols = 0;
			//colspan=0 doesn't work on all browsers, add up all colSpans in current row to find total number of columns (ignoring special headerDetail-join columns)
			for(var i = 0; i < this.cells.length; i++) {
				if (!this.cells[i].className.match(/headerDetail-join/))
					numberOfCols += this.cells[i].colSpan;
			}
			html += "<td colspan='" + numberOfCols + "'>";
		}
		html += "<div class='head4' style='text-align: center; width: 100%'>Please Wait...</div>"
			 +  "<image src='/images/candybar.gif' style='margin-left: auto; margin-right: auto; display: block;'/>";
		if(tagType == 'TR'){ html += "</td>"; }
		html += "</" + tagType + ">";

		$(this).parent().append(html);

		if(tagType == 'TR')
			TaxInquiry.viewPage(url, ".headerDetail-detail:first>td:first", false);
		else
			TaxInquiry.viewPage(url, ".headerDetail-detail:first", false);

		return false;
	});

}

/*
 * Code to be run after the page loads
 */
TaxInquiry.onload = function() {
	 return;
}

/*
 * Code to run a search
 */

TaxInquiry.search = function() {

	if (document.getElementById('parcel_search') != null) {
		if(document.getElementById('parcel_search').checked) {
			document.getElementById('rm').value = 'search_process';
			document.getElementById('criteria').submit();
			return;
		}
	}

	if (document.getElementById('pp_search') != null) {
		if(document.getElementById('pp_search').checked) {
			document.getElementById('rm').value = 'search_process';
			document.getElementById('criteria').submit();
			return;
		}
	}

	document.getElementById('rm').value = 'search_ajax';

	TaxInquiry.waitDlg();

	var cachedSearch = false;

	//store search in local cache
	if (TaxInquiry.Storage.Enabled) {
		log("Grabbing search criteria");
		var criteria = JSON.stringify($("#criteria").serializeArray());
		TaxInquiry.Search.Current = {
			key: Crypto.SHA1(criteria),
			criteria: criteria,
			parcelResults: null,
			nameResults: null
		}

		log("Looking for cached searches for key: " + TaxInquiry.Search.Current.key);
		//check to see if this cache key exists in the recent searches cache
		if (TaxInquiry.Storage("TaxInquiry.Search." + TaxInquiry.Search.Current.key) != null) {
			log("Found: " + TaxInquiry.Search.Current.key);
			//TaxInquiry.Search.Cached = JSON.parse(TaxInquiry.Storage("TaxInquiry.Search." + TaxInquiry.Search.Current.key));
			TaxInquiry.Search.Cached = TaxInquiry.Storage("TaxInquiry.Search." + TaxInquiry.Search.Current.key);
			TaxInquiry.Search.Current.parcelResults = TaxInquiry.Search.Cached.parcelResults;
			TaxInquiry.Search.Current.nameResults = TaxInquiry.Search.Cached.nameResults;
			cachedSearch = true;
		}

		log("Storing current search");
		//store current search
		TaxInquiry.Storage("TaxInquiry.Search.Current", JSON.stringify(TaxInquiry.Search.Current));
	}
	log("Posting to server");

	var criteria = DEVNET.formToJSON( '#criteria' );
	criteria.push({
		name: "cached_search",
		value: cachedSearch.toString()
	});

	$.post('/wedge/search/process/ajax', criteria, function(data){
		if(TaxInquiry.handleJSON(data, '#resultDiv')){
			$("#resultDiv").dialog("open");
		}
	}, 'json');

}

/*
 * Return current cached search results in property_key order
 */
TaxInquiry.getCurrentCachedSearch = function() {
	if (TaxInquiry.Storage.Enabled) {
		if (TaxInquiry.Storage("TaxInquiry.Search.Current") != null) {
			//fetch from local storage
			var results = TaxInquiry.Storage("TaxInquiry.Search.Current");
			//sort parcel results
			if (results != null && results.parcelResults != null && results.parcelResults.results != null) {
				//instead of using a comparison function, override the toString of the object
				//We do this because when using a comparison function the function is called n log n times
				//overriding the toString means we only call toString n times.
				var toStringOrig = Object.prototype.toString;
				Object.prototype.toString = function() { return this.property_key; };

				results.parcelResults.results.sort();

				Object.prototype.toString = toStringOrig;

				return results;
			}

			return null;
		}
	}

	return null;
}

/*
 * Redirect to search results (handles search cookie and blocking the UI)
 * Does not build the proper url itself
 */
TaxInquiry.searchRedirect = function(url) {
	//set cookie
	$.cookies.set("goSearchResults", 1);
	//block UI
	$.blockUI({
		message: "<h1>Retrieving your selection...</h1>",
		baseZ: 3000,
		theme: true
	 });
	location.href = url;
}

 /*
  * View cached search results
  */
 TaxInquiry.viewResults = function() {
	log("Opening cached results.");
 	TaxInquiry.waitDlg();
 	$.getJSON('/wedge/search/results/ajax/', function(data){
 		if(TaxInquiry.handleJSON(data, '#resultDiv')){
			$("#resultDiv").dialog("open");
 		}
 	})
 }

/*
 * Check JSON response for errors
 */
TaxInquiry.checkJSON = function(data) {
	$.each(data.errors, function(i, err) {
		var html = '<div title="Error" class="fg-dialog ui-widget ui-helper-reset" id="warning' + i + '"><div class="para"><span class="ui-icon ui-icon-alert" style="float:left; margin:0 7px 50px 0;"></span>' + err + '</div></div>'
		log(err);
		$("body").append(html);
	});
	$.each(data.messages, function(i, msg) {
		var html = '<div title="Information" class="fg-dialog ui-widget ui-helper-reset" id="info' + i + '"><div class="para"><span class="ui-icon ui-icon-info" style="float:left; margin:0 7px 50px 0;"></span>' + msg + '</div></div>'
		log(msg);
		$("body").append(html);
	});

	if(data.errors.length > 0) {
		log("Errors ocurred during AJAX request. Bailing out.");
		return false;
	}
	return true;
}

/*
 * Respond to JSON received from server
 */
TaxInquiry.handleJSON = function(data, contentDiv, location) {

	if (!TaxInquiry.checkJSON(data)) { return false; }

	if (TaxInquiry.Storage.Enabled && location != null && data.replace_content != 1) {
		log("Storing AJAX request for: " + location);
		TaxInquiry.Storage('TaxInquiry.Ajax.' + location, JSON.stringify(data));
	}

	if(data.replace_content == 1) {
		/* in case of something like a major error, replace all of the content div */
		log("Major error ocurred. Replacing page content with error information.");
		$("#content").html(data.content);
		return false;
	} else {
		log("Inserting retrieved content.");
		$(contentDiv).html(data.content);
	}
	return true;
}

/*
 * Use the view_ajax runmode to grab parcel data
 */
TaxInquiry.viewPage = function(location, contentDiv, animate, caller){
	var pageData = null;

	if (TaxInquiry.Storage.Enabled) {
		log("Checking for page data in cache for url: " + location);
		var cached = TaxInquiry.Storage('TaxInquiry.Ajax.' + location)
		if ( cached != null) {
			log("Found cached page data");
			pageData = cached;
			//set a class on the calling element to signify that the data
			//it loaded into the page was cached.
			//if this class is present in the other event handlers for the
			//calling element they will act appropriately (like not activating the throbber)
			$(caller).addClass("page-cached");
		}
	}

	$(caller).trigger("ajax-click");

	if (pageData != null) {
		log("Loading page data from cache");
		if (animate == true) {
			$(contentDiv).animate({opacity: 0}, 300, function() {
				$(contentDiv).html(pageData.content);
				$(contentDiv).stop();
				$(contentDiv).animate({opacity: 1}, 300);
			});
		} else {
			$(contentDiv).html(pageData.content);
		}
	} else {
		log("Requesting page data from server");
		if(animate == true){
			$(contentDiv).animate({opacity: 0}, 300, function() {
				$.getJSON(location, function(data){
					TaxInquiry.handleJSON(data, contentDiv, location);
					$(contentDiv).stop();
					$(contentDiv).animate({opacity: 1}, 300);
				});
			});
		} else {
			$.getJSON(location, function(data){
				TaxInquiry.handleJSON(data, contentDiv, location);
			});
		}
	}


}

TaxInquiry.waitDlg = function(){
	$("html, body").animate({scrollTop: 0}, {duration: 50, queue: false, complete: function() {
		if(!$("#resultWait").length > 0) {
			$("body").append("<div id='resultWait' class='waitDlg'><div class='head3' style='text-align: center; width: 100%'>Please Wait...</div><br /><image src='/images/candybar.gif' style='margin-left: auto; margin-right: auto; display: block;'/></div>");
			$("#resultWait").dialog({
				draggable: false,
				modal: true,
				resizable: false,
				width: '260px',
				height: 'auto'
			});
		} else {
			$("#resultWait").dialog("open");
		}
	}});
}

TaxInquiry.openRedemptionEstimate = function(id, source, propertyKey) {
	var location = "/wedge/ajax/parcel/" + TaxInquiry.Parcel.Number + "/" + TaxInquiry.Parcel.Year
			+ "/redemption_estimate?rd_id=" + id + "&amp;source=" + source + "&amp;property_key=" + propertyKey;

	var d = new Date();
	var today = d.getMonth() + 1 + "/" + d.getDate() + "/" + d.getFullYear();

	$.getJSON(location, function(data){
		var win = window.open("about:blank", "redemptionEstimate", "location=0,scrollbars=1,resizable=1,width=800,height=600");
		var html = "<html><body><div id='content'></div></body></html>";
		//create new doc in new window
		win.document.open();
		win.document.write(html);
		win.document.title='Estimate of Redemption';
		win.document.close();

		if (TaxInquiry.checkJSON(data) != -1) {
			win.document.getElementById("content").innerHTML = data.content;
		}

		//since javascript won't run inside the new document, and jquery won't work on external windows,
		//set up anything marked with the 'today' class with today's date formatted as a string
		for (var i = 0; i < win.document.getElementsByTagName('*').length; i++) {
			if (win.document.getElementsByTagName('*')[i].className == 'today') {
				win.document.getElementsByTagName('*')[i].innerHTML = today;
			}
		}
	});
}

TaxInquiry.Search.showCriteria = function( theElement ) {
    log( "Element length " + $("#" + theElement).length );

    // Make sure we have criteria to work with
    criteria = TaxInquiry.getCurrentCachedSearch();
    criteria = criteria["criteria"];
    if (criteria == null) { log("criteria null"); return; }

    // Parse out the criteria, skip items that aren't really criteria.
    var crit = JSON.parse(criteria);
    if( crit.length == 0 ) { log("crit len 0"); }
    for (var i = 0; i < crit.length; i++) {
        switch (crit[i]["name"]) {
            case "rm":
            case "search_method":
            case "name_type":
            case "addr_type":
                continue;
        }
        if (crit[i]["value"] != "") {
            var desc = $("#criteria").find("label[for='" + crit[i]["name"] + "']").text();
            var html = (desc == "") ? crit[i]["name"] : desc;
            html += ": " + crit[i]["value"] + "<br />";
            $("#" + theElement).append(html);
        }
    }
};

