//<![CDATA[
////////////////////////////////////////////////////////////////////////////////////////////////
// FUNCTIONS FOR INITIAL PAGE LOAD
////////////////////////////////////////////////////////////////////////////////////////////////
// used to identify and log in users
// loggedin is used to identify property tracker accounts
// signed is used to verify that user has completed manadatory registration form
var qs;
var userid = '';
var siusername = '';
var sipassword = '';
var loggedin = false;
var signedin = false;
var numSearches = 0;
var numListings = 0;

// used in save searches
var searchid;
var quicksearchid;
var newonly;
var favs;
var mls;
var mlsregionid;

// used for processing saved listing after login
var savelistingid = '';
var savemlsregionid = '';
var savefrom = '';
var savemarker = '';

// These are used in loading the login / register containers
var whichContainer_welcome = 'welcome';
var whichContainer_results = 'results';

var saveToFavs_map = 'map';
var saveToFavs_mls = 'mls';
var saveToFavs_detail = 'detail';
var saveToFavs_search = 'searchform';

// Animation Constants
var SAVETOFAVAPPEARDURATION = 1.2;
var SAVETOFAVFADEDURATION = 1.2;
var SAVETOFAVHIGHLIGHTDURATION = 4.0;
var REMFROMFAVAPPEARDURATION = 1.2;
var REMFROMFAVFADEDURATION = 1.2;
var REMFROMFAVHIGHLIGHTDURATION = 4.0;
var HIDELOGINBUTTONDURATION = 1.2;
var SHOWLOGINREGISTERFORMDURATION = 1.2;
var HIDELOGINREGISTERFORMDURATION = 1.2;
var PROCESSLOGINFADEDURATION = 1.2;
var PROCESSLOGINHIGHLIGHTDURATION = 4.0;
var PROCESSLOGINAPPEARDURATION = 1.2;
var PROCESSREGISTERHIGHLIGHTDURATION = 4.0;
var PROCESSREGISTERFADEDURATION = 1.2;
var PROCESSREGISTERAPPEARDURATION =  1.2;
var SHOWLOGINREGISTERBUTTONSFADEDURATION = 1.2;
var SHOWLOGINREGISTERBUTTONSAPPEARDURATION =  1.2;
var SHOWLOGINREGISTERBUTTONSHIGHLIGHTDURATION = 1.2;

//
// Loads user's information and login status via cookies
//
function loadUser() {	
	
	// Retrieve user info from cookies
	if (readCookie('siUserID')) {userid = readCookie('siUserID')} else {userid = ''}
	if (readCookie('siID')) {siusername = readCookie('siID');} else {siusername = '';}
	if (readCookie('siPW')) {sipassword = readCookie('siPW');} else {sipassword = '';}
	
	// Check if user is logged in
	if (readCookie('siLoggedIn')) {
		if (readCookie('siLoggedIn') == 'true') {
			if ((userid.length >= 1) && (siusername.length >= 1) && (sipassword.length >= 1)) {loggedin = true; signedin = true} else {loggedin = false}
		}
	}
	
	//if (signedin == false) {
	//	if (readCookie('siSignedIn') == 'true') {
	//		signedin = true;
	//	}
	//}
	
	signedin = true;
}
//
// Executes the full search function from favorites section of website
//
function full_search_from_favorites(searchType) {
	$('userid').value = userid;
	$('searchid').value = '';
	$('favs').value = 'true';
	full_search(searchType);	
}
//
// Executes the full search function from saved searches section of website
//
function run_saved_search(searchid, searchType) {
	$('userid').value = userid;
	$('searchid').value = searchid;
	$('favs').value = 'false';
	full_search(searchType);	
}
//
// Lists number of saved listings in the side bar
//
function sidebarUpdateSavedListingText(num) {
	var numSavedListings = $('numSavedListings');
	var showSavedListings = $('showSavedListings');
	var noSavedListings = $('noSavedListings');
	
	// if user has one saved listing
	if (num == 1) {
		numSavedListings.innerHTML = 'You currently have 1 saved listing.';
		$(showSavedListings).show();
		$(noSavedListings).hide();
	} 
	
	// if user has two saved listings
	else if (num >=2) {
		numSavedListings.innerHTML = 'You currently have ' + num + ' saved listings.';
		$(showSavedListings).show();
		$(noSavedListings).hide();
	} 
	
	// if user has no saved listings
	else {
		numSavedListings.innerHTML = 'You do not currently have any saved listings. <a href="javascript:newSearch();">Click here to search the area listings</a>.<br /><br />Once you save listings, you can email or request more information on all of your saved listings at once.';
		$(showSavedListings).hide();
		$(noSavedListings).show();
	}
}
//
// Lists number of saved searches in the side bar
//
function sidebarUpdateSavedSearchesText(num) {
	var numSavedSearches = $('numSavedSearches');
	var runSavedSearches = $('runSavedSearches');
	var viewAllSearches = $('viewAllSearches');
	var noSavedSearches = $('noSavedSearches');	

// if user has one saved search
	if (num == 1) {
		numSavedSearches.innerHTML = 'You have 1 saved search.';
		$(noSavedSearches).hide();
		$(runSavedSearches).show();
	} 
	
	// if user has two saved searches
	else if (num >=2) {
		numSavedSearches.innerHTML = 'You have ' + num + ' saved searches.';
		$(noSavedSearches).hide();
		$(runSavedSearches).show();
	} 
	
	// if user has no saved searches
	else {
		numSavedSearches.innerHTML = 'You do not currently have any saved searches.';
		$(noSavedSearches).show();
		$(runSavedSearches).hide();
	}
}
//
// Logs user out and clears information
//
function logout_automatic() {
		// clears cookie login information
		eraseCookie('siID');
		eraseCookie('siPW');
		eraseCookie('siUserID');
		eraseCookie('siLoggedIn');
		
		// clear user data from javascript variables
		userid = '';
		siusername = '';
		sipassword = '';
		
		// Also need to remove user id from search form hidden fields
		if ($('userid')) 
			$('userid').value = '';
		
		if ($('searchid')) 
			$('searchid').value = '';
		
		loggedin = false;
}
//
// Opens the virtual tour window
//
function showVirtualTour(theURL) {
	window.open(theURL, 'virtualtour', 'width=600, height=600, resizable=yes, scrollbars=yes, toolbar=no, menubar=no')
}

function showmoreOpenHouseInfo(mls,mlsregionid){

	
	if ((mls != '') && (mlsregionid != '')) {

		var open_house_loading = $('open_house_loading' + mls);
		var open_house_info = $('open_house_info' + mls);
		
		new Effect.Fade(open_house_info, {queue: 'end', duration: 0.2});
		new Effect.Appear(open_house_loading, {queue: 'end', duration: 0.2});
		
		var bindArgs = {
		method: 'post',
		parameters: 'mls='+mls+'&mlsregionid='+mlsregionid,			
		onFailure: function(){
			open_house_info.innerHTML = 'No additional Open Houses were found for this listing.';
			
			new Effect.Fade(open_house_loading, {queue: 'end', duration: 0.2});
			new Effect.BlindDown(open_house_info, {queue: 'end', duration: 0.2});
			new Effect.Highlight(open_house_info, {queue: 'end', duration: 0.7});

		},
		onSuccess: function(t){
			open_house_info.innerHTML = t.responseText;
			
			new Effect.Fade(open_house_loading, {queue: 'end', duration: 0.2});
			
			new Effect.BlindDown(open_house_info, {queue: 'end', duration: 0.2});
			new Effect.Highlight(open_house_info, {queue: 'end', duration: 0.7});
		}
		};	
	
		new Ajax.Request('/' + agent_folder + '/pages/open_houses.asp', bindArgs);
	
	}
}

function hideOpenHouseInfo(mls,mlsregionid){
	
	if ((mls != '') && (mlsregionid != '')) {

		var open_house_info = $('open_house_info' + mls);

		open_house_info.innerHTML = '<a href="javascript: showmoreOpenHouseInfo(\'' + mls + '\',\'' + mlsregionid + '\');">More upcoming open houses &gt;&gt;</a>';
	}
}
/**********************************************************************************************

 FULL SEARCH FUNCTIONS
 
***********************************************************************************************/
//
// Runs the search and populates search results and map results tabs
//
function full_search(searchType) {	
	// Put form data into querystring and form URL to pass to XML map results	
	var formAction;
	
	switch (searchType){
		case '1':
			formAction = 'search_form.asp';
			break;
		case '2': 
			formAction = 'mls.asp';
			break;
	    case '3':
			formAction = 'mls_maps.asp';
			break;
		case '4':
			formAction = 'mls_detail.asp';
			break;
		case '5':
			formAction = 'property_tracker.asp';
			break;
		default:
			formAction = '';
			break;
	}
	
	document.frmSearch.action = formAction;
	document.frmSearch.submit();
}
//
// Clears the quicksearchid form field and runs the full search
//
function full_search_from_form(searchType) {
	clearHiddenFieldsFromSearchForm();	
	full_search(searchType);
}
//
// roms the search form to run a new search
//
function newSearch() {
	$('userid').value = userid;
	$('searchid').value = '';	
	$('favs').value = 'false';
	$('hidaction').value = 'newsearch';
	full_search('1');
}
//
// Switches back to the search tab
//
function reviseSearch() {
	$('hidaction').value = '';
	$('searchid').value = '';
	full_search('1');
}
//
// Shows save for current search
//
function show_save_for_current_search() {
	$('userid').value = userid;
	$('favs').value = 'false';
	$('hidaction').value = 'currentsavedsearch';
	full_search('1');
}
//
// Loads Detail view for listing from Search Results or Map Results
//
function showDetailPage(detail_offset) {	
	$('detoffset').value=detail_offset;
	$('listingid').value='';
	full_search('4');	
}
//
// Processes user login from side bar
//
function processSidebarLogin(whichContainer) {
	
	var bindArgs = {
	asynchronous: false,
	method: 'post',
	parameters: 'email='+$('sidebarloginemail').value+'&password='+$('sidebarloginpassword').value+'&siteid='+siteid,
	onFailure: function(t){
		alert('An error occurred and we could not send your request.  Please try again.');	
	},
	onSuccess: function(t){
		var returnVal = parseFloat(t.responseText);
		
		// incorrect username or password
		if (returnVal <= 0)  
			$('sidebar_login_incorrect').show(); 
			
		// Login was successful
		else {  			
			//  set the javascript variables to logged in
			userid = returnVal;
			loggedin = true;
			siusername = $('sidebarloginemail').value;
			sipassword = $('sidebarloginpassword').value;
			if ($('userid')) 
				$('userid').value = userid;			
			
			// If they checked the Remember Me box, then set cookies
			if (document.frmSidebarLogin.sidebarloginremember.checked) {
				createCookie('siUserID',userid,365);
				createCookie('siID',siusername,365);
				createCookie('siPW',sipassword,365);
				createCookie('siLoggedIn','true',365);
			} 
			else {
				createCookie('siUserID',userid,1);
				createCookie('siID',siusername,1);
				createCookie('siPW',sipassword,1);
				createCookie('siLoggedIn','true',1);				
			}
			
			// If we started on the list results page, then reload that page to
			//  show any existing favorites
			switch (savefrom){
				case saveToFavs_mls:
					full_search('2');
					break;
				case saveToFavs_map:
					full_search('3');				
					break;
				case saveToFavs_search:
					full_search('1');
					break;
				default:
					full_search('0');
					break;
			}
		}
	}
	};	
	
	// Validate the form contents before submitting
	var email = IsValidEmail($('sidebarloginemail'));
	var pass = IsEmpty($('sidebarloginpassword'));
	if (email && !pass)	
		new Ajax.Request('/' + agent_folder + '/pages/login_process.asp',bindArgs);
	else if (pass) {
		alert('Please enter your password.');
		$('sidebarloginpassword').focus();
	} 
	else if (!email) {
		alert('Please enter a valid email address.');
		$('sidebarloginemail').focus();	
	}	
}
//
// Processes user login
//
function processLogin(whichContainer) {
	
	$('loginsubmit').value = 'Please Wait...';
	$('loginsubmit').style.width = '120px';		
	
	var bindArgs = {
	asynchronous: false,
	method: 'post',
	postBody: 'email='+$('email').value+'&password='+$('password').value+'&siteid='+siteid,
	onFailure: function(t){
		alert('An error occurred and we could not send your request.  Please try again.');
		$('loginsubmit').value = 'Login';
		$('loginsubmit').style.width = '80px';			
	},		
	onSuccess: function(t){
		var returnVal = parseFloat(t.responseText);

		// Login unsuccessful
		if (returnVal <= 0) { // incorrect username or password
			$('login_incorrect').show();
			$('loginsubmit').value = 'Login';
			$('loginsubmit').style.width = '80px';				
		} 
		
		// Login successful
		else { 			
			//  set the javascript variables to logged in
			userid = returnVal;
			loggedin = true;
			siusername = $('email').value;
			sipassword = $('password').value;
			
			// set userid if available, else userid is set to returnVal
			if ($('userid')) 
				$('userid').value = userid;
			
			//alert('userid: ' + userid);
			//alert('logged in: ' + loggedin);
			//alert('username: ' + siusername);
			//alert('password: ' + sipassword);
			//alert('dojo user id: ' + $('userid').value);
			
			// If they checked the Remember Me box, then set cookies
			if (document.frmLogin.loginremember.checked) {
				createCookie('siUserID',userid,365);
				createCookie('siID',siusername,365);
				createCookie('siPW',sipassword,365);
				createCookie('siLoggedIn','true',365);
			} 
			else {
				createCookie('siUserID',userid,2);
				createCookie('siID',siusername,2);
				createCookie('siPW',sipassword,2);
				createCookie('siLoggedIn','true',2);				
			}
			
			//alert('cookie userid: ' + readCookie('siUserID'));
			//alert('cookie logged in: ' + readCookie('siLoggedIn'));
			//alert('cookie username: ' + readCookie('siID'));
			//alert('cookie password: ' + readCookie('siPW'));
			
			// Now, it gets tricky
			// If they started the login process by clicking a Save to Favorites button,
			// we need to go back to the search results and show that listing as saved.
			// BUT, we also need to update the search results and map results pages to 
			// show ALL of their saved listings.
			
			// They started from the property tracker home page
			if (whichContainer != 'results') {
				savelistingid = '';
				savemlsregionid = '';
				savefrom = '';
				
				loadHomePage();
			} 
			
			// otherwise....
			else { 
			
				// If there is a listing to save, save it
				if ((savelistingid != '') && (savemlsregionid != '')) {
					//alert('saving listing: ' + savelistingid + ', region: ' + savemlsregionid);
					
					var returnVal = saveListing(savelistingid, savemlsregionid, 'save');
					//alert('save returned: ' + returnVal);
				}
				
				// If we started on the list results page, then reload that page, and, once it's
				// been reloaded, scroll down to the just-saved listing.
				switch (savefrom) {
				
					case saveToFavs_mls:
						$('listingid').value = savelistingid;
						full_search('2');
						break;
						
					case saveToFavs_map:
						//alert('save to favs map');
						if (returnVal >= 1) {
							$('listingid').value = savelistingid;
							//alert('saved successfully');
							
							//reload the page to load favorites
							full_search('3');						
						} 
						else {
							var coords = cumulativeOffset($('map'));
							window.scrollTo(0, coords[1]-20);							
							$('map_message').innerHTML = "An error occurred (" + returnVal + ") and the listing could not be saved. Please try again.";
							new Effect.Highlight($('map_message'), {queue: 'end', duration: PROCESSLOGINHIGHLIGHTDURATION});
							new Effect.BlindUp($('map_message'), {queue: 'end', duration: PROCESSLOGINFADEDURATION});
						}						
	
						// reset values to null
						savelistingid = '';
						savemlsregionid = '';
						savefrom = '';
						break;
						
					case saveToFavs_detail: 
						var coords = cumulativeOffset($('detail_message'));
						window.scrollTo(0, coords[1]-220);
						
						if (returnVal >= 1) {
							// change the button from Save Listing to Listing Saved
							$('detSaveListing').innerHTML = "<a href=\"javascript:removeFromFavorites('" + savelistingid + "', '" + savemlsregionid + "', 'detail',0);\"><img src=\"res/images/listings/det_listing_saved.gif\" border=\"0\" alt=\"Listing Saved - click to un-save\"></a>";
							$('login_register_results').innerHTML = '<fieldset><legend>Success!</legend><strong>This listing has been saved.</strong> To view your Favorites, click the Property Tracker tab at the top.</fieldset>';
						} 
						else {							
							$('detail_message').hide();
							$('detail_message').innerHTML = '<fieldset><legend>Save Listing</legend><strong>This listing could not be saved.</strong> Please make sure that you are logged in and try again.</fieldset>';
							new Effect.BlindDown($('detail_message'), {duration: PROCESSLOGINAPPEARDURATION});				
						}
						
						// wipe in the notice and then fade it out
						new Effect.Highlight($('detail_message'), {queue: 'end', duration: PROCESSLOGINHIGHLIGHTDURATION});
						new Effect.BlindUp($('detail_message'), {queue: 'end', duration: PROCESSLOGINFADEDURATION});
						
						// reset values to null
						savelistingid = '';
						savemlsregionid = '';
						savefrom = '';			
						break;
						
					case 'searchform': 
						$('searchform_message').innerHTML = '<fieldset><legend>Login</legend><strong>Success!</strong> You are now logged in.  Please wait a moment while we load the form so that you can save the search.</fieldset><br /><br />';
						new Effect.Highlight($('searchform_message'), {queue: 'end', duration: PROCESSLOGINHIGHLIGHTDURATION});
						new Effect.BlindUp($('searchform_message'), {queue: 'end', duration: PROCESSLOGINFADEDURATION});
						new Effect.BlindDown($('savethissearch'), {queue: 'end', duration: PROCESSLOGINAPPEARDURATION});
						new Effect.Highlight($('savethissearch'), {queue: 'end', duration: PROCESSLOGINHIGHLIGHTDURATION});
						
						// reset values to null
						savelistingid = '';
						savemlsregionid = '';
						savefrom = '';	
						break;
					 
					case 'unsubscribe':
						$('searchform_message').innerHTML = '<fieldset><legend>Login</legend><strong>Success!</strong> You are now logged in.  Please wait a moment while we unsubcribe you from listing alerts for this search.</fieldset>';
						new Effect.Highlight($('searchform_message'), {duration: PROCESSLOGINHIGHLIGHTDURATION});
						setTimeout('unsubscribeSavedSearch()',4000);
						
						// reset values to null
						savelistingid = '';
						savemlsregionid = '';
						savefrom = '';			
					default:
						break;
				}// end switch/case
			}
		}
	}
	};	
	
	// Validate the form contents before submitting
	var email = IsValidEmail($('email'));
	var pass = IsEmpty($('password'));
	
	if (email && !pass) {	
		$('loginsubmit').value = 'Please Wait...';
		$('loginsubmit').style.width = '120px';	
		new Ajax.Request('/' + agent_folder + '/pages/login_process.asp',bindArgs);
	} 
	else if (!pass) {
		alert('Please enter your password.');
		$('password').focus();
	} 
	else if (valResults.isInvalid('email')) {
		alert('Please enter a valid email address.');
		$('email').focus();	
	}	
}
//
// Allows user to retrieve lost password
//
function retrievePassword() {
		
	var lost_password_container = $('lost_password_container');
	var orig_contents = lost_password_container.innerHTML;
	
	var params = $H({
		email: $('forgotemail').value,
		siteid: parentsiteid,
		agentsiteid: siteid
		}).toQueryString();
	
	var bindArgs = {
	method: 'post',
	parameters: params,
	onFailure: function(){
		alert('An error occurred and we could not retrieve your password.  Please try again.');
		$('retrievesubmit').value = 'Retrieve Password';
		$('retrievesubmit').style.width = '140px';	
	},
	onSuccess: function(t){
		var returnVal = parseFloat(t.responseText);
		if (returnVal == -2) {
			$('retrieve_not_found').show();
			$('retrievesubmit').value = 'Retrieve Password';
			$('retrievesubmit').style.width = '140px';			
		} 
		else if (returnVal <= 0) {
			$('retrieve_error').show();
			$('retrievesubmit').value = 'Retrieve Password';
			$('retrievesubmit').style.width = '140px';			
		} 
		else {
			$(lost_password_container).hide();
			$('retrieve_success').show();
		}
		
	}
	};	
	
	// Validate the form contents before submitting

	var email = IsValidEmail($('forgotemail'));
	
	if (email) {
		$('retrievesubmit').value = 'Please Wait...';
		new Ajax.Request('/' + agent_folder + '/pages/retrieve_password.asp', bindArgs);
	} 
	else {
		alert('Please enter a valid email address.');
		$('forgotemail').focus();
	}	
}
//
// Registers new user's to the website
//
function processRegister(whichContainer) {
	$('register_already_taken').style.display = 'none';
	$('register_error').style.display = 'none';	
	
	var bindArgs = {
		method: 'post',
		parameters: Form.serialize($('frmRegister')),
		onFailure: function(){
			alert('An error occurred and we could not complete your registration.  Please try again.');
			$('registersubmit').value = 'Submit';
			$('registersubmit').style.width = '80px';	
		},
		onSuccess: function(t){
		var returnVal = parseFloat(t.responseText);
		if (returnVal == -2) {
			$('register_already_taken').style.display = '';
			$('registersubmit').value = 'Submit';
			$('registersubmit').style.width = '80px';				
		} 
		else if (returnVal <= 0) {
			$('register_error').style.display = '';
			$('registersubmit').value = 'Submit';
			$('registersubmit').style.width = '80px';				
		} 
		else {
			userid = returnVal;
			loggedin = true;
			siusername = $('registeremail').value;
			sipassword = $('registerpassword').value;
			if ($('userid')) 
				$('userid').value = userid;			
			
			// If they checked the Remember Me box, then set cookies
			createCookie('siUserID',userid,365);
			createCookie('siID',siusername,365);
			createCookie('siPW',sipassword,365);
			createCookie('siLoggedIn','true',365);


			// Now, it gets tricky
			// If they started the login process by clicking a Save to Favorites button,
			// we need to go back to the search results and show that listing as saved.
			// BUT, we also need to update the search results and map results pages to 
			// show ALL of their saved listings.
			if (whichContainer != 'results') { // they started from the property tracker page
				loadHomePage();
				savelistingid = '';
				savemlsregionid = '';
				savefrom = '';			
			} 
			else { // otherwise....
				// If there is a listing to save, save it
				if ((savelistingid != '') && (savemlsregionid != '')) {
					var returnVal = saveListing(savelistingid, savemlsregionid, 'save');
				}
				
				// If we started on the list results page, then change the listing to saved.
				if (savefrom == saveToFavs_mls) 
					if (returnVal >= 1) {
						$('savelisting' + savelistingid).innerHTML = '<a href="javascript: removeFromFavorites(\'' + savelistingid + '\', \'' + savemlsregionid + '\', \'mls\',0);" class="summary"><img src="/agent_site/res/images/listings/button_listingsaved.gif" border="0" alt="Listing Saved - Click to Remove" /></a>';
						$('listing_message' + savelistingid).innerHTML = '<fieldset><legend>Success!</legend><strong>You are now registered and this listing has been saved.</strong><br />To view your Favorites, click the Property Tracker tab at the top.</fieldset>';
						new Effect.Highlight($('listing_message' + savelistingid), {queue: 'end',duration: PROCESSREGISTERHIGHLIGHTDURATION});
						new Effect.BlindUp($('listing_message' + savelistingid), {queue: 'end', duration: PROCESSREGISTERFADEDURATION});
					} 
					else {
						$('listing_message' + savelistingid).innerHTML = '<fieldset><legend>Save to Favorites</legend><strong>You are now registered, but an error occurred (\'' + returnVal + '\') and the listing could not be saved. Please try again.'
						new Effect.Highlight($('savelistingid' + savelistingid), {queue: 'end',duration: PROCESSREGISTERHIGHLIGHTDURATION});
						new Effect.BlindUp($('savelistingid' + savelistingid), {queue: 'end', duration: PROCESSREGISTERFADEDURATION});		
					}
					
				else if (savefrom == saveToFavs_map) {
					if (returnVal >= 1) {
						// Show the favorites icon
						if (savemarker != '') {showFavIcon(savemarker)};
						savemarker = '';
						
						//Update the Save To Favorites text in the popup
						$('maplisting' + savelistingid).innerHTML = '<a href="javascript: removeFromFavorites(' + savelistingid + ', ' + mlsregionid + ', saveToFavs_map, ' + whichMarker + ');" class="popup_link">Listing Saved</a>|';
						
						//Scroll back up to view the map
						var coords = cumulativeOffset($('map'));
						window.scrollTo(0, coords[1]-20);	
						
						// Change the map message to show them that they've registered successfully and the
						// listing has been saved
						$('map_message').innerHTML = '<fieldset><legend>Success!</legend><strong>Your registration is complete, and this listing has been saved.</strong> To view your Favorites and access all your Property Tracker features, click the Property Tracker tab at the top.</fieldset>';
						new Effect.Highlight($('map_message'), {queue: 'end',duration: PROCESSREGISTERHIGHLIGHTDURATION});
						new Effect.BlindUp($('map_message'), {queue: 'end', duration: PROCESSREGISTERFADEDURATION});
						
						// increment the number of saved listings on the property tracker home page
						numListings++;
					} 
					else {
						$('map_message').innerHTML = "An error occurred (" + returnVal + ") and the listing could not be saved. Please try again."
						new Effect.Highlight($('map_message'), {queue: 'end',duration: PROCESSREGISTERHIGHLIGHTDURATION});
						new Effect.BlindUp($('map_message'), {queue: 'end', duration: PROCESSREGISTERFADEDURATION});			
					}					
					
					savelistingid = '';
					savemlsregionid = '';
					savefrom = '';					
					
				} 
				else if (savefrom == saveToFavs_detail) {
					if (returnVal >= 1) {
						var coords = cumulativeOffset($('detail_message'));
						window.scrollTo(0, coords[1]-220);
						
						// change the button from Save Listing to Listing Saved
						$('detSaveListing').innerHTML = "<a href=\"javascript:removeFromFavorites('" + savelistingid + "', '" + savemlsregionid + "', 'detail',0);\"><img src=\"res/images/listings/det_listing_saved.gif\" border=\"0\" alt=\"Listing Saved - click to un-save\"></a>";
		
						// wipe in the notice that the listing has been saved, and then fade it out
						$('login_register_results').innerHTML = '<fieldset><legend>Success!</legend><strong>You are now registered, and this listing has been saved to your Favorites.</strong><br />To view your Favorites, click the Property Tracker tab at the top.</fieldset>';
						new Effect.Highlight($('detail_message'), {queue: 'end',duration: PROCESSREGISTERHIGHLIGHTDURATION});
						new Effect.BlindUp($('detail_message'), {queue: 'end', duration: PROCESSREGISTERFADEDURATION});
						
						
						if ($('savelisting' + savelistingid))
							$('savelisting' + savelistingid).innerHTML = '<a href="javascript: removeFromFavorites(\'' + savelistingid + '\', \'' + savemlsregionid + '\', \'mls\',0);" class="summary"><img src="/agent_site/res/images/listings/button_listingsaved.gif" border="0" alt="Listing Saved - Click to Remove" /></a>';
						
					} 
					else {
						var coords = cumulativeOffset($('detail_message'));
						window.scrollTo(0, coords[1]-220);						
						
						// wipe in the notice that the listing could not be saved, and then fade it out
						$('detail_message').hide();
						$('detail_message').innerHTML = '<fieldset><legend>Save Listing</legend><strong>This listing could not be saved.</strong><br />Please make sure that you are logged in and try again.</fieldset>';
						new Effect.BlindDown($('detail_message'), {queue: 'end',duration: PROCESSREGISTERAPPEARDURATION});
						new Effect.Highlight($('detail_message'), {queue: 'end', duration: PROCESSREGISTERHIGHLIGHTDURATION});
						new Effect.Fade($('detail_message'), {queue: 'end', duration: PROCESSREGISTERFADEDURATION});					
					}
					
					savelistingid = '';
					savemlsregionid = '';
					savefrom = '';
				} 
				else if (savefrom == 'searchform') {
					$('searchform_message').innerHTML = '<fieldset><legend>Restier for Property Tracker</legend><strong>Success!</strong> You are now registered -- just click the Property Tracker tab at the top to access the full features.  Please wait a moment while we load the form so that you can save the search.</fieldset>';
					new Effect.Highlight($('searchform_message'), {queue: 'end',duration: PROCESSREGISTERHIGHLIGHTDURATION});
					new Effect.Fade($('searchform_message'), {queue: 'end', duration: PROCESSREGISTERFADEDURATION});
					new Effect.BlindDown($('savethissearch'), {queue: 'end', duration: PROCESSREGISTERAPPEARDURATION});
					new Effect.Highlight($('savethissearch'), {queue: 'end', duration: PROCESSREGISTERHIGHLIGHTDURATION});

					savelistingid = '';
					savemlsregionid = '';
					savefrom = '';					
				}
			}			
		}
	}
	};	
	
	// Validate the form contents before submitting
	var email = IsValidEmail($('registeremail'));	
	var first = IsEmpty($('registerfirstname'));
	if (!first)
		$('registerfirstname').value = ucFirst($('registerfirstname'));
	var last = IsEmpty($('registerlastname'));
	if (!last)
		$('registerlastname').value = ucFirst($('registerlastname'));
	var pass = IsEmpty($('registerpassword'));	
	var passConf = IsEmpty($('registerpasswordconfirm'));
	
	if (email && !first && !last && !pass && !passConf) {
		if ($('registerpassword').value == $('registerpasswordconfirm').value) {
			$('registersubmit').value = 'Processing Info...';
			$('registersubmit').style.width = '145px';	
			new Ajax.Request('/' + agent_folder + '/pages/register_process.asp', bindArgs);
		} 
		else {
			alert('The passwords did not match.');
			$('registerpasswordconfirm').focus();
		}
	} 
	else if (!(email && !first && !last && !pass && !passConf))
		alert('Please enter all of the required fields.');
	else if (!email) {
		alert('Please enter a valid email address.');
		$('registeremail').focus();
	}
}
//
// Handles Save to Favorites for list results, map results, and detail pages
// Because must take into account content in all three areas when making changes to any one
//
function saveToFavorites(listingid, mlsregionid, whichPage, whichMarker) {
	var returnVal;
	var displayMessage = null;
	
	savemarker = whichMarker;
		
	// Checks if user is logged in. If not, displays login options
	if (!(loggedin)) {
		showLoginRegisterButtons(listingid, mlsregionid, whichPage);
		
	// continues if user is logged in
	} else {
		// Determine which page we came from: listing results, map results, or detail page.
		// We will need to update listing markers across all pages at one time.
		switch (whichPage){
		
			case saveToFavs_mls:
				// saves listing
				returnVal = saveListing(listingid, mlsregionid, 'save');
				//$('listing_message' + listingid).innerHTML = '<img src="/agent_site/res/images/loading.gif" align="absmiddle"> Saving Listing Info...';
				
				// if the save was successful
				if (returnVal >= 1){
					$('savelisting' + listingid).innerHTML = '<a href="javascript: removeFromFavorites(\'' + listingid + '\', \'' + mlsregionid + '\', \'mls\',0);" class="summary"><img src="/agent_site/res/images/listings/button_listingsaved.gif" border="0" alt="Listing Saved - Click to Remove" /></a>';
					$('listing_message' + listingid).innerHTML = '<fieldset><legend>Success!</legend><strong>This listing has been saved.</strong> To view your Favorites, click the Property Tracker tab at the top.</fieldset>';
					
					// increment the number of saved listings on the property tracker home page
					numListings++;
				} 
				
				// if save failed
				else 
					$('listing_message' + listingid).innerHTML = "An error occurred (" + returnVal + ") and the listing could not be saved. Please try again.";
				
				// sets message to display
				displayMessage = $('listing_message' + listingid);
				break;
				
			case saveToFavs_map:		
				// saves listing
				returnVal = saveListing(listingid, mlsregionid, 'save');
				
				// if the save was successful
				if (returnVal >= 1) {
				
					// change display icon
					if (whichMarker != '') 
						showFavIcon(whichMarker);
					else 
						showFavIcon(0);	
					
					// set location coordinates
					var coords = cumulativeOffset($('map'));
					window.scrollTo(0, coords[1]-20);				
					
					$('maplisting' + listingid).innerHTML = '<a href="javascript: removeFromFavorites(' + listingid + ', ' + mlsregionid + ', saveToFavs_map, ' + whichMarker + ');" class="popup_link">Listing Saved</a>|';
					$('map_message').innerHTML = '<fieldset><legend>Success!</legend><strong>This listing has been saved.</strong> To view your Favorites, click the Property Tracker tab at the top.</fieldset>';
	
					// increment the number of saved listings on the property tracker home page
					numListings++;
				} 
				
				// if save failed
				else 
					$('map_message').innerHTML = "An error occurred (" + returnVal + ") and the listing could not be saved. Please try again."			
				
				// sets message to display
				displayMessage = $('map_message');
				break;
				
			case saveToFavs_detail:
				// saves listing
				returnVal = saveListing(listingid, mlsregionid, 'save');
				$('detail_message').style.display = 'none';
				
				// if the save was successful
				if (returnVal >= 1) {
					// change the button from Save Listing to Listing Saved
					$('detSaveListing').innerHTML = '<a href="javascript:removeFromFavorites(\'' + listingid + '\', \'' + mlsregionid + '\', \'detail\',0);"><img src="/agent_site/res/images/listings/det_listing_saved.gif" border="0" alt="Listing Saved - click to un-save"></a>';
					$('detail_message').innerHTML = '<fieldset><legend>Success!</legend><strong>This listing has been saved.</strong> To view your Favorites, click the Property Tracker tab at the top.</fieldset>';
	
					// increment the number of saved listings on the property tracker home page			
					numListings++;
				} 
				
				// if save failed
				else
					$('detail_message').innerHTML = '<fieldset><legend>Save Listing</legend><strong>This listing could not be saved.</strong> Please make sure that you are logged in and try again.</fieldset>';
				
				// sets message to display	
				displayMessage = $('detail_message');	
				break;
				
			default:
				break;
		}
		
		// Fades in message and fades back out
		new Effect.BlindDown(displayMessage, {queue: 'end', duration: SAVETOFAVAPPEARDURATION});
		new Effect.Highlight(displayMessage, {queue: 'end', duration: SAVETOFAVHIGHLIGHTDURATION});
		new Effect.Fade(displayMessage, {queue: 'end', duration: SAVETOFAVFADEDURATION});
	}
}
//
// Handles Remove from Favorites for list results, map results, and detail pages
//
function removeFromFavorites(listingid, mlsregionid, whichPage, whichMarker) {
	var returnVal = null;
	var displayMessage = null;
		
	if (!(loggedin))
		showLoginRegisterButtons(listingid, mlsregionid, whichPage); 
	else {
		
		// Determine which page we came from: listing results, map results, or detail page.
		//   We will need to update listing markers across all pages at one time.
		if (whichPage == saveToFavs_mls) {
			returnVal = saveListing(listingid, mlsregionid, 'remove');
			if (returnVal >= 1) {
				$('savelisting' + listingid).innerHTML = '<a href="javascript: saveToFavorites(\'' + listingid + '\', \'' + mlsregionid + '\', \'mls\',0);" class="summary"><img src="/agent_site/res/images/listings/button_savelisting.gif" border="0" alt="Save This Listing to Your Favorites" /></a>';
				$('listing_message' + listingid).innerHTML = '<fieldset><legend>Success!</legend><strong>This listing has been removed from your Favorites.</strong>&nbsp;&nbsp;To view your Favorites, click the Property Tracker tab at the top.</fieldset>';
				
				// decrement the number of saved listings on the property tracker home page
				numListings--;
			} 
			else 
				$('listing_message' + listingid).innerHTML = "An error occurred (" + returnVal + ") and the listing could not be removed. Please try again.";		
				
			// sets message to display
			displayMessage = $('listing_message' + listingid);

		} 
		else if (whichPage == saveToFavs_map) {
			returnVal = saveListing(listingid, mlsregionid, 'remove');
			if (returnVal >= 1) {
				
				if (whichMarker != '') 
					removeFavIcon(whichMarker);
				else 
					removeFavIcon(0);	
				
				var coords = cumulativeOffset($('map'));
				window.scrollTo(0, coords[1]-20);				
				
				$('maplisting' + listingid).innerHTML = '<a href="javascript: saveToFavorites(' + listingid + ', ' + mlsregionid + ', saveToFavs_map, ' + whichMarker + ');" class="popup_link">Save to Favorites</a>|';
				$('map_message').innerHTML = '<fieldset><legend>Success!</legend><strong>This listing has been removed from your Favorites.</strong> To view your Favorites, click the Property Tracker tab at the top.</fieldset>';
				
				// decrement the number of saved listings on the property tracker home page
				numListings--;
			} 
			else 
				$('map_message').innerHTML = "An error occurred (" + returnVal + ") and the listing could not be removed. Please try again.";
			
			// sets message to display
			displayMessage = $('map_message');
			
		} 
		else if (whichPage == saveToFavs_detail) {
			returnVal = saveListing(listingid, mlsregionid, 'remove');
			if (returnVal >= 1) {
				// change the button from Save Listing to Listing Saved
				$('detSaveListing').innerHTML = '<a href="javascript:saveToFavorites(\'' + listingid + '\', \'' + mlsregionid + '\', \'detail\',0);"><img src="/agent_site/res/images/listings/next_steps_buttons_23.gif" border="0" alt="Save Listing to Your Favorites"></a>';

				// wipe in the notice that the listing has been saved, and then fade it out
				$('detail_message').style.display = 'none';
				$('detail_message').innerHTML = '<fieldset><legend>Success!</legend><strong>This listing has been removed from your Favorites.</strong>&nbsp;&nbsp;To view your Favorites, click the Property Tracker tab at the top.</fieldset>';
	
			} 
			else {
				// wipe in the notice that the listing could not be saved, and then fade it out
				$('detail_message').style.display = 'none';
				$('detail_message').innerHTML = '<fieldset><legend>Save Listing</legend><strong>This listing could not be removed.</strong> Please make sure that you are logged in and try again.</fieldset>';
					
			}

			// sets message to display
			displayMessage = $('detail_message');
		}
		
		// Fades in message and fades back out
		new Effect.BlindDown(displayMessage, {queue: 'end', duration: REMFROMFAVAPPEARDURATION});
		new Effect.Highlight(displayMessage, {queue: 'end', duration: REMFROMFAVHIGHLIGHTDURATION});
		new Effect.Fade(displayMessage, {queue: 'end', duration: REMFROMFAVFADEDURATION});
	}
}
//
// Saves the listings
//
function saveListing(listingid, mlsregionid, action) {
	var returnVal;
	returnVal = -2;
	
	if (action != 'remove') 
		action = 'save';
		
	var params = $H({
		action: action, 
		listingid: listingid,
		mlsregionid: mlsregionid,
		userid: userid,
		siteid: parentsiteid,
		agentsiteid: siteid
		}).toQueryString();
	
	var bindArgs = {
	method: 'post',
	asynchronous: false,
	parameters: params,
	onFailure: function(){
		returnVal = -1;
	},
	onSuccess: function(t){
		returnVal = parseFloat(t.responseText);
	}
	};
	
	// Run the XHR Requests
	new Ajax.Request('/' + agent_folder + '/pages/save_listing.asp', bindArgs);		
	return returnVal;
}
//
// Shows or hides Log in and Register buttons
//
function showLoginRegisterButtons(listingid, mlsregionid, whichPage) {
	
	var divContainer;
	
	//alert('showing buttons: ' + whichPage);
	
	// Need to see which content div we're dealing with so that we know where
	// to load the login / register buttons
	switch (whichPage){
		// List Results Page
		case 'mls':
			divContainer = $('listing_message' + listingid);
			break;
		// Detail Page
		case 'detail':
			divContainer = $('detail_message');				
			break;
		// Map Results Page
		case 'map':
			divContainer = $('map_message');
			break;
		// Search form page
		case 'searchform':
			divContainer = $('searchform_message');
			break;
		// Search form page
		case 'unsubscribe':
			divContainer = $('searchform_message');
			break;			
		default:
			break;
	} 
	
	// If the login / register buttons are already open, then hide them
	if ((savelistingid == listingid) && (savemlsregionid == mlsregionid) && (savefrom == whichPage)) {
		new Effect.BlindUp(divContainer, {duration: SHOWLOGINREGISTERBUTTONSFADEDURATION});
		savelistingid = '';
		savemlsregionid = '';
		savefrom = '';
		return;
	} 
	else if ((savelistingid.length != 0) && (savemlsregionid.length != 0)) {
		hideLoginRegisterButtons(savelistingid, savemlsregionid);
	}
	
	// Store the listing ID so that we can still add the listing to favorites after
	//  login or register
	savelistingid = listingid;
	savemlsregionid = mlsregionid;
	savefrom = whichPage;
	
	//divContainer.style.display = '';
	
	if (whichPage == 'mls') {
		var coords = cumulativeOffset($('listing'+listingid));
		divContainer.style.display = 'none';
		window.scrollTo(0, coords[1]-140);
		divContainer.innerHTML='<img src="/agent_site/res/images/loading_big.gif" align="absmiddle"> <span style="font-size: 12px; font-weight: bold;">Loading...</span>';
	} 
	else if (whichPage == 'map') {
		var coords = cumulativeOffset($('map'));
		new Effect.ScrollTo('map', {queue: 'end', offset: 75});
		window.scrollTo(0, coords[1]+75);		
		divContainer.innerHTML='<img src="/agent_site/res/images/loading_big.gif" align="absmiddle"> <span style="font-size: 12px; font-weight: bold;">Loading...</span>';
	} 
	else if (whichPage == 'detail') {
		divContainer.innerHTML='<img src="/agent_site/res/images/loading_big.gif" align="absmiddle"> <span style="font-size: 12px; font-weight: bold;">Loading Form...</span>';
		var coords = cumulativeOffset($(divContainer));
		divContainer.style.display = 'none';
		window.scrollTo(0, coords[1]-140);
	} 
	else if ((whichPage == 'searchform') || (whichPage == 'unsubscribe')) 
		divContainer.innerHTML='<img src="/agent_site/res/images/loading.gif" align="absmiddle"> <span style="font-size: 12px; font-weight: bold;">Loading, please wait...</span>';
	
	new Effect.Opacity(divContainer);
	
	var params = $H({
		page: whichPage
		}).toQueryString();
	
	var bindArgs = {
	method: 'get',	
	parameters: params,
	onFailure: function(){
		alert('An error occurred and we could not retrieve the login / register form.  Please try again.');
		divContainer.innerHTML='';
		divContainer.style.display = 'none';
		savelistingid = '';
		savemlsregionid = '';		
	},
	onSuccess: function(t){
		divContainer.innerHTML=t.responseText;
		new Effect.BlindDown(divContainer, {queue: 'end', duration: SHOWLOGINREGISTERBUTTONSAPPEARDURATION});
		new Effect.Highlight(divContainer, {queue: 'end', duration: SHOWLOGINREGISTERBUTTONSHIGHLIGHTDURATION});	
	}
	};
	
	new Ajax.Request('/' + agent_folder + '/pages/choose_login_register.asp',bindArgs);	
}
//
// Hides the Login and Register button from user
//
function hideLoginRegisterButtons(listingid, mlsregionid){
	savelistingid = '';
	savemlsregionid = '';
	savefrom = '';

	// Load the div asking user to log in or register
	if ($('listing_message'+listingid)) {
		new Effect.BlindUp($('listing_message'+listingid), {duration: HIDELOGINBUTTONDURATION});
		$('listing_message'+listingid).innerHTML = '';
	}
}
//
// Displays Login/Registration Form to user
//
function showLoginOrRegisterForm(actionType, whichContainer) {	
	// Need this first part to distinguish between the Property Tracker Welcome page 
	// and the search results pages.  We don't want to have the login form open on both 
	// pages at once, because of overlapping div names.
	
	var buttons_container = $('buttons_container_' + whichContainer);
	var login_register = $('login_register_' + whichContainer);
	var whichPage;
	
	if (actionType == 'login') {whichPage = '/' + agent_folder + '/pages/login.asp';} else {whichPage = '/' + agent_folder + '/pages/register.asp'}
	
	//Reset opacity from having been faded out before.
	//new Effect.Opacity(login_register);
	
	var params = $H({
		container: whichContainer
		}).toQueryString();
	
	// Set the bind arguments to retrieve map data
	var bindArgs = {
		parameters: params,
		onFaiure: function(){
			alert('An error occurred and we could not load the Login Form . \n\n Please make sure that you are using an up-to-date browser and that you have javascript and cookies fully enabled.');
		},
		onSuccess: function(t){
			login_register.innerHTML=t.responseText;	
			$(buttons_container).hide();
			new Effect.BlindDown(login_register, {duration: SHOWLOGINREGISTERFORMDURATION});	
		}
	};

	// Run the XHR Requests
	new Ajax.Request(whichPage, bindArgs);		
}
//
// Hides Login/Registration Form from user
//
function hideLoginOrRegisterForm(whichContainer) {
	// For the welcome page, whichContainer is empty string.
	// For the mls, maps and detail pages, it's set to _2 -- this prevents overlapping div names.
	var buttons_container = $('buttons_container_' + whichContainer);
	var login_register = $('login_register_' + whichContainer);	
	
	if (buttons_container && login_register) {
		new Effect.Opacity(buttons_container);
		new Effect.BlindUp(login_register, {duration: HIDELOGINREGISTERFORMDURATION});
		$(buttons_container).show();
	}
}
//
// Opens a new window
//
function MM_openBrWindow(theURL,winName,features) { //v2.0
  window.open(theURL,winName,features);
}
//
// Sets the email string
//
function noSpam(user,domain) {
locationstring = "mailto:" + user + "@" + domain;
window.location = locationstring;
}
//
// Page offset setup
//
function cumulativeOffset(element) {

	var valueT = 0, valueL = 0;
	
	do {
	  valueT += element.offsetTop  || 0;
	  valueL += element.offsetLeft || 0;
	  element = element.offsetParent;
	} while (element);
	
	return [valueL, valueT];
}
////////////////////////////////////////////////////////////////////////////////////////////////
// QUERYSTRING FUNCTIONS
////////////////////////////////////////////////////////////////////////////////////////////////
//
// Returns the string result of a Query String
//
function getQuerystring() {
  FORM_DATA = new Object();
  separator = ',';
  query = '' + this.location;
  qu = query
  query = query.substring((query.indexOf('?')) + 1);
  
    // Keep everything after the question mark '?'.
  if (query.length < 1) { return false; }  // Perhaps we got some bad data?
  keypairs = new Object();
  numKP = 1;
  
  while (query.indexOf('&') > -1) {
    keypairs[numKP] = query.substring(0,query.indexOf('&'));
    query = query.substring((query.indexOf('&')) + 1);
    numKP++;
  }
  
  keypairs[numKP] = query;
  
  for (i in keypairs) {
    keyName = keypairs[i].substring(0,keypairs[i].indexOf('='));
      // Left of '=' is name.
    keyValue = keypairs[i].substring((keypairs[i].indexOf('=')) + 1);
      // Right of '=' is value.
    while (keyValue.indexOf('+') > -1) {
      keyValue = keyValue.substring(0,keyValue.indexOf('+')) + ' ' + keyValue.substring(keyValue.indexOf('+') + 1);
        // Replace each '+' in data string with a space.
    }
	
    keyValue = unescape(keyValue);
	// Unescape non-alphanumerics
	
	if (keyValue.length == 0) keyValue = '';
	
    if (FORM_DATA[keyName]) 
      FORM_DATA[keyName] = FORM_DATA[keyName] + separator + keyValue;
        // Object already exists, it is probably a multi-select input,
        // and we need to generate a separator-delimited string
        // by appending to what we already have stored.
     
	else 
      FORM_DATA[keyName] = keyValue;
        // Normal case: name gets value.
    
  }
  return FORM_DATA;
}
////////////////////////////////////////////////////////////////////////////////////////////////
// COOKIE FUNCTIONS
////////////////////////////////////////////////////////////////////////////////////////////////
//
//
//
function createCookie(name,value,days) {
	if (days)
	{
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}
//
//
//
function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++)
	{
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return '';
}
//
//
//
function eraseCookie(name) {
	createCookie(name,"",-1);
}
//]]>
