// SCRIPTS FOR THE SAVE SEARCH FUNCTIONALITY - USED BY RESULTS AND MAP SEARCH PAGES


// OPERATIONAL FUNCTIONS

// toggles save search menu
function toggleSaveSearchMenu() {
	if(!$("SaveSearchMenu").visible()) {
		showSaveSearchMenu();
	} else {
		hideSaveSearchMenu();
	}
}

// shows menu and hides select boxes so that they don't pop through the menu
function showSaveSearchMenu() {
	$("SaveSearchMenu").show();
	$("search_name").focus();
	$$("select.submit_on_change").invoke("hide");
}

// hides menu and shows selects again
function hideSaveSearchMenu() {
	$("SaveSearchMenu").hide();
	$$("select.submit_on_change").invoke("show");
}

// saves a search - makes ajax call
// includes validation
function saveSearch(overwrite) {
	if (!overwrite) {overwrite = false;} // by default we don't overwrite
	
	// while validating/saving, disable the submit button and make it show that it is saving
	$("BtnSaveSearchSubmit").update("Saving...");
	$("BtnSaveSearchSubmit").disabled = true;
	
	var json_url = "?";

	// use ajax to save the search
	new Ajax.Request(json_url,
	{
		method:'post',
		parameters: {
			product: 'Web',
			controller: 'ListingSearch',
			action: 'save_this_search',
			acnt: ACNT,
			save_search_overwrite: overwrite, // if true, skip validation and save anyway - used when overwriting an old search with the same name
			search_name: $("search_name").getValue(),
			email_notification: $("email_notification").getValue(),
            IDXSESS: SESSION_ID
		},
		onSuccess: function(transport) { // if ajax worked
			// validation happens in the Search controller
			// it will return one of four values as a string:
			// 'success', 'empty', 'duplicate', or 'no search params'

			// it returns a value of 'success' if it has successfully saved.
			var search_status = transport.responseJSON;
			//alert(search_status);

			switch(search_status) {
				// search name must not be an empty string
				case 'empty':
					// display the error message
					$("SaveSearchMsg").className = "error_msg";
					$("SaveSearchMsg").update("Please give a name to your saved search");
					$("SaveSearchMsg").show();
					// reset the button so it can submit again
					$("BtnSaveSearchSubmit").update("Save Search");
					$("BtnSaveSearchSubmit").disabled = false;
				break;
				
				// if there is already a saved search with this name, prompt them - do they want to overwrite it?
				case 'duplicate':
					// display the error message
					$("SaveSearchMsg").className = "error_msg";
					$("SaveSearchMsg").update("There is already a saved search with this name. Overwrite it?");
					$("SaveSearchMsg").show();
					// show buttons for overwrite
					$("SaveSearchOverwrite").show();
				break;
				
				// 
				case 'missing search params':
					// display the error message
					alert("missing search parameters");
					saveSearchReset();
				break;
				
				
				// when the search is successfully saved:
				case 'success':
					$("SaveSearchOverwrite").hide(); // hide the overwrite buttons
					// reset the submit button text
					$("BtnSaveSearchSubmit").update("Saved");
					// show the confirmation message
					$("SaveSearchMsg").className = "conf_msg";
					$("SaveSearchMsg").update("Your search: <strong>" + $F("search_name") + "</strong> has been saved");
					$("SaveSearchMsg").show();
					// hide and reset the save search menu after 3 seconds
					// function to reset the form...
					var resetSaveSearchForm = function() {
						hideSaveSearchMenu();
						saveSearchReset();
					}
					var resetSoon = setTimeout(resetSaveSearchForm, 3000);
				break;
				
				default:
					alert("not getting the right return value: "+search_status);
					saveSearchReset();
				
			}
		},
		onFailure: function() {
			alert('The ajax request failed - was trying to save a search.');
			saveSearchReset();
		}
	});
}


// resets the save search form to it's initial state (but doesn't close the menu)
function saveSearchReset() {
	$("SaveSearchOverwrite").hide(); // hide the overwrite buttons
	// reset the form inputs and button text
	$("search_name").value = '';
	if (!isIE6) { // IE6 gets an error when you try to focus on a hidden element
		$("search_name").focus();
	}
	// default has been changed to true - but we'll leave it the same as they last used
	$("BtnSaveSearchSubmit").update("Save Search");
	$("BtnSaveSearchSubmit").disabled = false;
	$("SaveSearchMsg").hide(); // hide any error messages that used to be open
}




// SAVE SEARCH EVENTS
// these get attached to the page elements on page load
function attachSaveSearchEvents() {
	
	// only allow them to save a search if they are logged in
	// check status of hidden input
	if (AUTHENTICATED != "") {
		// save search menu opens onclick
		$('BtnSaveSearch').observe('click', function(event) {
			Event.stop(event);
			toggleSaveSearchMenu();
		});
		// the button inside the menu should post via an ajax call and then display a confirmation message
		$('BtnSaveSearchSubmit').observe('click', function(event) {
			Event.stop(event); // stops from from posting
			saveSearch(); // validate/save the search 
		});
		// cancel button
		$('BtnSaveSearchCancel').observe('click', function(event) {
			Event.stop(event);
			saveSearchReset();
			toggleSaveSearchMenu();
		});
		// yes, overwrite the old search
		$('BtnOverwriteYes').observe('click', function(event) {
			saveSearch(true); // save search - overwriting the old record with the same search name
		});
		// no, don't overwrite
		$('BtnOverwriteNo').observe('click', function(event) {
			saveSearchReset();
		});
		// override Return key to be consistent across browsers
		$('search_name').observe('keypress', function(event) {
			if (event.keyCode == Event.KEY_RETURN) {
				Event.stop(event); // stops form from posting
				saveSearch(); // validate/save the search
			}
		});
	}
	// else no one is logged in - we need to redirect to the register page - 
	// the href of the button is set to the correct url in the smarty code
	
}

Event.observe(window, 'load', function() {
	attachSaveSearchEvents();
});

