/*
 * TaxInquiry.js - Site specific script file
 */

/*
 * Create the TaxInquiry namespace
 */
var TaxInquiry;
if (typeof TaxInquiry == 'undefined') {
	TaxInquiry = {};
}

/*
 * Any nasty-dirty globals we need
 */
var sidebarTop = null;
var sidebarScrolledOutOfView = false;

/*
 * Code to be run when the document is ready
 */
TaxInquiry.onready = function() {
	/*
	 * 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 :-( )
	 */
	$("#sidebar .ajax a")
	.click(function() {
		var offset = $(this).position();
		if( !$("#sidebar-throbber").length > 0 ) { 
			$("#sidebar .box").append("<div id='sidebar-throbber'></div>"); 
		} else {
			$("#sidebar-throbber").show();
		}
		$("#sidebar-throbber").css({
			'width': '16px',
			'height': '16px',
			'position': 'absolute',
			'left': (offset.left - 15) + 'px',
			'top': offset.top + 'px',
			'z-index': '90'
		});
		/* Return false to continue processing eg: element onclick */
		return false;
	})
	.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, .headerDetail-header")
	.live('mouseover', function(){ 
		$(this).addClass("ui-state-highlight");
		$(this).css("cursor", "pointer");
	})
	.live('mouseout', function(){ 
		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");
		});
		$(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
	 */
	$(".fg-button:not(.ui-state-disabled)")
	.hover(
		function(){ 
			$(this).addClass("ui-state-hover"); 
			$(this).css("cursor", "pointer");
		},
		function(){ 
			$(this).removeClass("ui-state-hover"); 
			$(this).css("cursor", "auto");
		}
	)
	.mousedown(function(){
			$(this).parents('.fg-buttonset-single:first').find(".fg-button.ui-state-active").removeClass("ui-state-active");
			if( $(this).is('.ui-state-active.fg-button-toggleable, .fg-buttonset-multi .ui-state-active') ){ $(this).removeClass("ui-state-active"); }
			else { $(this).addClass("ui-state-active"); }	
	})
	.mouseup(function(){
		if(! $(this).is('.fg-button-toggleable, .fg-buttonset-single .fg-button,  .fg-buttonset-multi .fg-button') ){
			$(this).removeClass("ui-state-active");
		}
	})
	.mouseout(function(){
		if(! $(this).is('.fg-button-toggleable, .fg-buttonset-single .fg-button,  .fg-buttonset-multi .fg-button') ){
			$(this).removeClass("ui-state-active");
		}
	});
	
	/*
	 * 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
	 */
	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: '800px',
		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 + ":hidden").length > 0) {
			//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 = "/propertyinquiry.pl?rm=view_ajax&amp;viewpage=detail/" + $(this).attr("id").match(/\[(.*?)\]/)[1];
		
		//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 determinig 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' ).checked ) {
		document.getElementById('rm').value = 'search_process';
        document.getElementById('criteria').submit();
    } else {
    	document.getElementById('rm').value = 'search_ajax';

    	TaxInquiry.waitDlg();

    	$.post('/propertyinquiry.pl', DEVNET.formToJSON( '#criteria' ), function(data){ 
    		if(TaxInquiry.handleJSON(data, '#resultDiv') != -1){
        		$("#resultDiv").dialog("open");
    		}
    	}, 'json');
    }
}
 
 /*
  * View cached search results
  */
 TaxInquiry.viewResults = function() {
 	TaxInquiry.waitDlg();
 	$.getJSON('/propertyinquiry.pl?rm=results&ajax=1&', function(data){
 		if(TaxInquiry.handleJSON(data, '#resultDiv') != -1){
     		$("#resultDiv").dialog("open");
 		}
 	})
 }

 /*
  * View text as a text balloon
  */
 TaxInquiry.viewText = function( page ) {
 	$.getJSON('/pages.pl?&rm=display_ajax&page=' + page, function(data){
 		if(TaxInquiry.handleJSON(data, '#balloonDiv') != -1){
     		$("#balloonDiv").dialog("open");
 		}
 	})
 }

/*
 * Respond to JSON received from server
 */
TaxInquiry.handleJSON = function(data, contentDiv) {
	$.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>'
		$("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>'
		$("body").append(html);
	});
	
	if(data.errors.length > 0)
		return -1;
	
	if(data.replace_content == 1) {
		/* in case of something like a major error, replace all of the content div */
		$("#content").html(data.content);
		return -1;
	} else {
		$(contentDiv).html(data.content);
	}
	return 1;
}
 
/*
 * Use the view_ajax runmode to grab parcel data
 */
TaxInquiry.viewPage = function(location, contentDiv, animate){
	if(animate == true){
		$(contentDiv).animate({opacity: 0}, 300, function() {
			$.getJSON(location, function(data){
				TaxInquiry.handleJSON(data, contentDiv); 
				$(contentDiv).stop();
				$(contentDiv).animate({opacity: 1}, 300);
			});
		});
	} else {
		$.getJSON(location, function(data){
			TaxInquiry.handleJSON(data, contentDiv);
		});
	}
	
}
 
TaxInquiry.waitDlg = function(){
	$("html, body").animate({scrollTop: 0}, {duration: 500, 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");
		}
	}});
}

