$(document).ready(function(){
	    $("#tabs").tabs();
	window.scrollTo(0,0);
	$("#tabs > ul > li > a").bind("click", function() {
		var scrollTop = document.body.scrollTop;
		if (scrollTop == 0)
		{
		    if (window.pageYOffset)
			scrollTop = window.pageYOffset;
		    else
			scrollTop = (document.body.parentElement) ? document.body.parentElement.scrollTop : 0;
		}
		window.location.hash = $(this).attr('href');
		window.scrollTo(0,scrollTop);
		//$.noticeAdd( { text: 'click' } );
	});

	$("a[href=\\"+window.location.hash+"]").trigger("click");

	$("body").append( "<div style='display:none;'><table id='submitMessageBox' width='100%' height='100%'><tr><td align='center' id='submitMessage'>Searching Lodging</td></tr></table></div>");

		function saveResults()
		{
			var html = $("div#canvases").html();
			var saveResultsVar = $.getUrlVar('saveResults');
			var deleteVar = $.getUrlVar('delete')+"";
			if ( (typeof saveResultsVar == "string") && (saveResultsVar.length > 0) ) {
				$.ajax( {
					async		: false,
					type		: 'POST',
					url		: "saveResults.php",
					success		: function() { 
								//$.noticeAdd( { text: "Back from saveResults.php" } ) 
					},
					data		: {
						file		: 'savedResults',
						key		: saveResultsVar,
						'delete'	: deleteVar,
						contents	: html
					}
				});
			}
		}

		var tabs = [
			"#typeAll",
			"#typeBnB",
			"#typeCabin",
			"#typeMotel",
			"#typeInn",
			"#typeRV",
			"#typeRental"
		]

		/*
			When the reset 'button' is clicked we need to wait for the browser to clear the form, then re-submit the form to get the 
			results from the 'normal' non-optional mode.  After clicking the reset-form button, we wait 100ms for the browser to 
			actually finish resetting the form - FIXME is needed for correct operation.  How to trigger on form reset-completion?
			The 100ms timeout works, but a trigger would be best.
		*/
		$("input.resetButton").bind("click", function(){
			setTimeout(function(){$("form#lodgingSearch").submit();}, 100);
		});

		/*
			Code for submitting the form
		*/
		var u;
	    	$("form#lodgingSearch").ajaxForm({
				type		: "POST",
				dataType	: 'json',
				//url		: u="apx.php?app=findLodging&" + $.param( {'gssUrl':"http://spreadsheets.google.com/pub?key=taaCdOjRU_3Mir3ArzQvLJg&single=true%26gid=0&output=csv"} ),
				//url		: u="apx.php?app=findLodging&" + $.param( {'gssUrl':"http://spreadsheets.google.com/pub?key=taaCdOjRU_3Mir3ArzQvLJg&single=true%26gid=0&output=csv"} ),
				beforeSubmit: function(formData, jqForm, opts) {
					$("#submitMessage").html("Searching Lodging");
					//$.noticeAdd( { text: "beginning search" } );
					$.fn.colorbox( {open:true, inline: true, href:'#submitMessageBox', width: "300px", height:"200px" } );

					$("#canvases > div > ul").html("");				// Clears each tab canvas before search

					$.each(tabs, function(i,hash){
						$("a[href=\\"+hash+"]").next().html("");		// Clears totals in tab before search
					});

					
					return true;
				},
				success: function(results) {
					$("#lodgingLists ul").html("");
					var ulIdBaseName = "#lodgingList_";
					var x=0;
					var dbg = "";
					var totals = {};
					//$.noticeAdd( { text: "search completed" } );

					if (results.entries > 0) {
						var totals = {};
						setTimeout(function(){$("#submitMessage").html("Search Results Updated");}, 1000);
						setTimeout(function(){$.fn.colorbox.close();}, 2000);

						// Go through each of the spreadsheet rows that matched the search criteria
						// if no criteria was selected, then all rows in the spreadsheet are returned
						$.each(results.data, function(i,row){
							// Go through each column in the spreadsheet row
							// columns are, for example: name, email, website, typeLodge, typeBnB,..., amenPool, amenInternet, ...
							var canvases = {};
							$.each(row, function(name,value) {
								if ((name.substr(0, 4)=='type') && (value=='x')) {
									canvases[name] = name;
									if ( typeof totals[name] == "undefined" ) {
										totals[name] = 0;
									}
									totals[name]++;
								}
							});

							$.each(canvases, function(name, value) {
								var sel = "#"+name + " > ul";

								$(sel).append( 
									$("<li>")
									.append(
										$("<h3/>")
										.addClass("head")
										.append( 
											$("<a/>")
											.attr('href','#')
											.html(row.name)
										)
									)
									.append( 
										$("<div/>")
										.addClass('content')
										.html( 
											"<table><tr>"+
											"<td>"
												+row.address+"<br />"
												+"Phone:"+row.phone+"<br />"
												+"Email: <a href='mailto:"+row.email+"'>"+row.email+"</a><br />"
												+"Website: <a href='http://"+row.website+"'>"+row.website+"</a>"
											+"</td>"+
											"<td>"+row.blurb+"</td>"+
											"</tr></table>"
										)
									)
								);
							});
						});

						$.each(totals, function(name,total){
							var $obj = $("a[href=\\#"+name+"]").next();
							$obj.html( "("+total+")" );
						});
						
						saveResults();					// Do this before running the randomRotate() 
						randomRotate();
					} else {
						$.each(tabs, function(i,hash){
							$("a[href=\\"+hash+"]").next().html("");
						});
						setTimeout(function(){$("#submitMessage").html("No matching results");}, 1000);
						setTimeout(function(){$.fn.colorbox.close();}, 2000);
					}
					//$("#dbg").html( $.dump(results) );
				}
		});



    });

