(function($) {
	var user = {},
		auth = false;
		
	var maxSearches,
		maxListings,
		maxHoods;
	
	var getUrlVars = function () {
		var vars = {};
		var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
			vars[key] = value;
		});
		return vars;
	};
	
	// Turn object to string
	var stringify = function (obj) {
		var str = '';
		for(var i in obj) {
			if (obj.hasOwnProperty(i)) {
				str += '&' + i + '=' + obj[i];
			}
		}
		// Removed first ampersand
		str = str.substring(1);
		return str;
	};
		
	/////////////////////////
	// Over Labels
	/////////////////////////
	$.initOverLabels = function () {
  		if (!document.getElementById) return;  	

  		var labels, id, field;

  		// Set focus and blur handlers to hide and show 
  		// LABELs with 'overlabel' class names.
  		labels = document.getElementsByTagName('label');
  		for (var i = 0; i < labels.length; i++) {
	
    		if (labels[i].className == 'overlabel') {

      			// Skip labels that do not have a named association with another field.
      			id = labels[i].htmlFor || labels[i].getAttribute('for');
      			if (!id || !(field = document.getElementById(id))) {
        			continue;
      			}

      			// Change the applied class to hover the label over the form field.
      			labels[i].className = 'overlabel-apply';

      			// Hide any fields having an initial value.
      			if (field.value !== '') {
        			hideLabel(field.getAttribute('id'), true);
      			}

      			// Set handlers to show and hide labels.
      			field.onfocus = function () {
        			hideLabel(this.getAttribute('id'), true);
      			};
      			field.onblur = function () {
        			if (this.value === '') {
          				hideLabel(this.getAttribute('id'), false);
        			}
      			};

      			// Handle clicks to LABEL elements (for Safari).
      			labels[i].onclick = function () {
        			var id, field;
        			id = this.getAttribute('for');
        			if (id && (field = document.getElementById(id))) {
          				field.focus();
        			}
      			};
    		}
  		}
	};
	
	$.openPopup = function(content) {
    	// Make sure existing window is closed
    	$("#popup").dialog('close');

    	$("#popupContent").html(content);
    	// Reset the dialog box
    	$("#popup").dialog('option', 'width', 'auto')
    			   .dialog('option', 'height', 'auto')
    	 		   .dialog('option', 'position', 'center')
    	 		   .dialog('open');
    };
    
    var signInPopup = function () {
		var html = '<div class="required-top">Registration required to use this feature.</div>';
		html 	+= '<div class="required-sub-top">Included with your FREE account &gt;</div>';
		html 	+= '<div class="signin-details">';
		html 	+= '  <div class="title">Welcome Back</div>';
		html 	+= '  <div class="notice"></div>';
		html 	+= '  <input type="text" id="portalHide" name="portalHide" value="" tabindex="9" />';
		html 	+= '  <div class="left">';
		html 	+= '    <div class="input-box">';
		html 	+= '    <label class="overlabel" for="portalUsername">Email</label>';
		html 	+= '    <input type="text" id="portalUsername" name="portalUsername" value="" tabindex="10" />';
		html 	+= '    </div>';
		html 	+= '    <div class="input-box">';
		html 	+= '    <label class="overlabel" for="portalPassword">Password</label>';
		html 	+= '    <input type="password" id="portalPassword" name="portalPassword" value="" tabindex="11" />';
		html 	+= '    </div>';
		html 	+= '    <div id="linkForgot" class="forgot">Forgot your password?</div>';
		html 	+= '  </div>';
		html 	+= '  <div class="right">';
		html 	+= '    <div id="btnLogin" class="btn-login">Login</div>';
		html 	+= '  </div>';
		html 	+= '  <div id="linkRegister" class="register">Not Registered?</div>';
		html 	+= '</div>';
		
		$.openPopup(html);
		
		$.initOverLabels();
		
		$('#linkForgot').click(function () {
			forgotPopup();
		});
		
		$('#linkRegister').click(function () {
			registerPopup();
		});
		
		$('#btnLogin').click(function () {
			var post = { username: $('#portalUsername').val(), password: $('#portalPassword').val() };
			$.post('/ajax/account/login', post, function(data) {
				if (data.success == false) {
					$('.signin-details .notice').html('<span>' + data.message + '</span>');
				} else {
					user = data.user;
					auth = true;
					
					$("#popup").dialog('close');
					
					buildAccountBox();
					
					// check for boundaries function to update
					if ($.isFunction($.updateBoundaries)) {
						$.updateBoundaries();
					}
				}
			});
		});
	};
    
    var forgotPopup = function () {
		var html = '<div class="required-top">Enter your email below for a reset link.</div>';
		html 	+= '<div class="forgot-details">';
    	html    += '  <form id="forgotForm" method="post">';
		html 	+= '  <div class="title">Welcome Back</div>';
		html 	+= '  <div class="notice"></div>';
		html 	+= '  <input type="text" id="portalHide" name="portalHide" value="" tabindex="29" />';
		html 	+= '  <div class="left">';
		html 	+= '    <div class="input-box">';
		html 	+= '    <label class="overlabel" for="portalForgotEmail">Email</label>';
		html 	+= '    <input type="text" id="portalForgotEmail" name="portalForgotEmail" value="" tabindex="30" />';
		html 	+= '    </div>';
		html 	+= '    <div id="linkSignIn" class="signin">Sign in to your account?</div>';
		html 	+= '  </div>';
		html 	+= '  <div class="right">';
		html 	+= '    <div id="btnSend" class="btn-send">Send</div>';
		html 	+= '  </div>';
		html    += '  </form>';
		html 	+= '  <div id="linkRegister" class="register">Not Registered?</div>';
		html 	+= '</div>';
		
		$.openPopup(html);
		
		$.initOverLabels();
		
		$('#linkSignIn').click(function () {
			signInPopup();
		});
		
		$('#linkRegister').click(function () {
			registerPopup();
		});
		
		// Forgot Form Validator
    	var valid = $("#forgotForm").validate({
    		rules: {
    			portalForgotEmail: {
    				required: true,
    				email: true
    			}
    		},
    		errorPlacement: function(error, element) { 	     	
    	   	},
    		success: function(label) {
    		}
    	});
		
		$('#btnSend').click(function () {
			// Remove existing errors
			$('.forgot-details input').removeClass('error');
			
			if (valid.form()) {
				$.post('/ajax/account/forgot', { username: $('#portalForgotEmail').val() }, function(data) {
					if (data.success == false) {
						$('.forgot-details .notice').html('<span>' + data.message + '</span>');
					} else {
						$('.forgot-details .notice').html('<span>You should receive an email shortly</span>');
						$('#portalForgotEmail').val('');
					}
				});
			} else {
				$('.forgot-details .notice').html('<span>Please enter a valid email address</span>');
			}
		});
	};
    
    var resetPopup = function () {
		var html = '<div class="required-top">Change your password below.</div>';
		html 	+= '<div class="reset-details">';
    	html    += '  <form id="resetForm" method="post">';
		html 	+= '  <div class="title">Reset Password</div>';
		html 	+= '  <div class="notice"></div>';
		html 	+= '  <input type="text" id="portalHide" name="portalHide" value="" tabindex="39" />';
		html 	+= '  <input type="hidden" id="portalCode" name="portalCode" value="" />';
		html 	+= '  <div class="left">';
		html 	+= '    <div class="input-box">';
		html 	+= '    <label class="overlabel" for="portalResetPass">New Password</label>';
		html 	+= '    <input type="password" id="portalResetPass" name="portalResetPass" value="" tabindex="40" />';
		html 	+= '    </div>';
		html 	+= '    <div class="input-box">';
		html 	+= '    <label class="overlabel" for="portalConfirmPass">Confirm Password</label>';
		html 	+= '    <input type="password" id="portalConfirmPass" name="portalConfirmPass" value="" tabindex="41" />';
		html 	+= '    </div>';
		html 	+= '  </div>';
		html 	+= '  <div class="right">';
		html 	+= '    <div id="btnReset" class="btn-reset">Reset</div>';
		html 	+= '  </div>';
		html    += '  </form>';
		html 	+= '  <div id="linkRegister" class="register">Not Registered?</div>';
		html 	+= '</div>';
		
		$.openPopup(html);
		
		$.initOverLabels();
		
		$('#linkRegister').click(function () {
			registerPopup();
		});
		
		// Forgot Form Validator
    	var valid = $("#resetForm").validate({
    		rules: {
    			portalResetPass: {
    				required: true,
    				minlength: 4
    			},
    			portalConfirmPass: {
    				required: true,
    				minlength: 4,
    				equalTo: "#portalResetPass"
    			}
    		},
    		errorPlacement: function(error, element) { 	     	
    	   	},
    		success: function(label) {
    		}
    	});
		
		$('#btnReset').click(function () {
			// Remove existing errors
			$('.reset-details input').removeClass('error');
			
			if (valid.form()) {
			
				var post = { code: $('#portalCode').val(), 
					 	 	 password: $('#portalResetPass').val(), 
					 	 	 confirm: $('#portalConfirmPass').val() };
			
				$.post('/ajax/account/reset', post, function(data) {
					if (data.success == false) {
						$('.reset-details .notice').html('<span>' + data.message + '</span>');
					} else {
						user = data.user;
						auth = true;
					
						$("#popup").dialog('close');
						buildAccountBox();
						
						// check for boundaries function to update
						if ($.isFunction($.updateBoundaries)) {
							$.updateBoundaries();
						}
					}
				});
			} else {
				$('.reset-details .notice').html('<span>Please enter matching passwords</span>');
			}
		});
	};
	
	var settingsPopup = function () {
    	var html = '<div class="account-popup settings-popup">';
    	html += '<ul id="accountTabs">';
    	html += '  <li class="tab-settings"></li>';
    	html += '  <li class="tab-searches"></li>';
    	html += '  <li class="tab-hoods"></li>';
    	html += '  <li class="tab-homes"></li>';
    	html += '</ul>';
    	html += '<div class="account">';
    	html += '  <form id="settingsForm" method="post">';
    	html += '  <input type="hidden" id="settingsId" name="settingsId" value="' + user['id'] + '" />';
    	html += '  <div class="settings-input">';
    	html += '    <label>First Name:</label>';
    	html += '    <input type="text" id="settingsFirstName" name="settingsFirstName" tabindex="1" maxlength="32" value="' + user['first_name'] + '" />';
    	html += '  </div>';
    	html += '  <div class="settings-input">';
    	html += '    <label>Last Name:</label>';
    	html += '    <input type="text" id="settingsLastName" name="settingsLastName" tabindex="2" maxlength="32" value="' + user['last_name'] + '" />';
    	html += '  </div>';
    	html += '  <div class="settings-input">';
    	html += '    <label for="settingsUsername">Email Address (username):</label>';
    	html += '    <input type="text" id="settingsUsername" name="settingsUsername" tabindex="3" value="' + user['username'] + '" />';
    	html += '  </div>';
    	html += '  <div class="settings-input">';
    	html += '    <label for="settingsPassword">Password:</label>';
    	html += '    <input type="password" id="settingsPassword" name="settingsPassword" tabindex="4" value="******" />';
    	html += '  </div>';
    	html += '  <div class="settings-input">';
    	html += '    <label for="confirmPassword">Confirm Password:</label>';
    	html += '    <input type="password" id="settingsConfirm" name="settingsConfirm" tabindex="5" value="******" />';
    	html += '  </div>';
    	html += '  <div class="settings-input">';
    	html += '    <label for="settingsStreetAddress">Street Address:</label>';
    	html += '    <input type="text" id="settingsStreetAddress" name="settingsStreetAddress" tabindex="6" maxlength="100" />';
    	html += '  </div>';
    	html += '  <div class="settings-input">';
    	html += '    <label for="settingsCity">City:</label>';
    	html += '    <input type="text" id="settingsCity" name="settingsCity" tabindex="7" maxlength="50" />';
    	html += '  </div>';
    	html += '  <div class="settings-input">';
    	html += '    <label for="settingsZip">Zip Code:</label>';
    	html += '    <input type="text" id="settingsZip" name="settingsZip" tabindex="8" maxlength="5" />';
    	html += '  </div>';
    	html += '  <div class="settings-input">';
    	html += '    <label for="settingsEmail2">Additional Email:</label>';
    	html += '    <input type="text" id="settingsEmail2" name="settingsEmail2" tabindex="9" maxlength="50" />';
    	html += '  </div>';
    	html += '  <div class="settings-input">';
    	html += '    <label for="settingsEmail3">Additional Email:</label>';
    	html += '    <input type="text" id="settingsEmail3" name="settingsEmail3" tabindex="10" maxlength="50" />';
    	html += '  </div>';
    	html += '  <div class="settings-input">';
    	html += '    <label for="settingsPhoneNum1">Phone Number (preferred):</label>';
    	html += '    <div class="settings-left">';
    	html += '      <select id="settingsPhoneType1" name="settingsPhoneType1" tabindex="11">';
    	html += '      <option value=""></option><option value="Cell">Cell</option><option value="Home">Home</option>';
    	html += '      <option value="Work">Work</option><option value="Fax">Fax</option></select>';
    	html += '    </div>';
    	html += '    <div class="settings-right"><input type="text" id="settingsPhoneNum1" name="settingsPhoneNum1" tabindex="12" maxlength="16" /></div>';
    	html += '  </div>';
    	html += '  <div class="settings-input">';
    	html += '    <label for="settingsPhoneNum2">Phone Number:</label>';
    	html += '    <div class="settings-left">';
    	html += '      <select id="settingsPhoneType2" name="settingsPhoneType2" tabindex="13">';
    	html += '      <option value=""></option><option value="Cell">Cell</option><option value="Home">Home</option>';
    	html += '      <option value="Work">Work</option><option value="Fax">Fax</option></select>';
    	html += '    </div>';
    	html += '    <div class="settings-right"><input type="text" id="settingsPhoneNum2" name="settingsPhoneNum2" tabindex="14" maxlength="16" /></div>';
    	html += '  </div>';
    	html += '  <div class="settings-input">';
    	html += '    <label for="settingsPhoneNum3">Phone Number:</label>';
    	html += '    <div class="settings-left">';
    	html += '      <select id="settingsPhoneType3" name="settingsPhoneType3" tabindex="15">';
    	html += '      <option value=""></option><option value="Cell">Cell</option><option value="Home">Home</option>';
    	html += '      <option value="Work">Work</option><option value="Fax">Fax</option></select>';
    	html += '    </div>';
    	html += '    <div class="settings-right"><input type="text" id="settingsPhoneNum3" name="settingsPhoneNum3" tabindex="16" maxlength="16" /></div>';
    	html += '  </div>';
	    html += '  <div id="btnSettings" class="btn-sprite"></div>';
    	html += '  </form>';
    	html += '  <div class="cl"></div>';
    	html += '</div>';
    	html += '</div>';
    	
		$.openPopup(html);

    	$('.tab-searches').click(favSearchesPopup);
    	$('.tab-homes').click(favListingsPopup);
    	$('.tab-hoods').click(favHoodsPopup);	
    	
    	// Make sure optional values are set
    	if (user['street_address'] != '') {
    		$('#settingsStreetAddress').val(user['street_address']);
    	}
    	if (user['city'] != '') {
    		$('#settingsCity').val(user['city']);
    	}
    	if (user['zip'] != '') {
    		$('#settingsZip').val(user['zip']);
    	}
    	if (user['email_2'] != '') {
    		$('#settingsEmail2').val(user['email_2']);
    	}
    	if (user['email_3'] != '') {
    		$('#settingsEmail3').val(user['email_3']);
    	}
    	if (user['phone_type_1'] != '') {
    		$('#settingsPhoneType1').val(user['phone_type_1']);
    	}
    	if (user['phone_num_1'] != '') {
    		$('#settingsPhoneNum1').val(user['phone_num_1']);
    	}
    	if (user['phone_type_2'] != '') {
    		$('#settingsPhoneType2').val(user['phone_type_2']);
    	}
    	if (user['phone_num_2'] != '') {
    		$('#settingsPhoneNum2').val(user['phone_num_2']);
    	}
    	if (user['phone_type_3'] != '') {
    		$('#settingsPhoneType3').val(user['phone_type_3']);
    	}
    	if (user['phone_num_3'] != '') {
    		$('#settingsPhoneNum3').val(user['phone_num_3']);
    	}
    		
    		
    	    	// Create Form Validator
    	var valid = $("#settingsForm").validate({
    		rules: {
    			settingsUsername: {
    				required: true,
    				email: true,
    				remote: {
    					url: '/ajax/account/validuser',
    					type: 'post',
    					data: { 
    						'userId': function() { return $("#settingsId").val(); },
    						'username': function() { return $("#settingsUsername").val(); }
    					}
    				}
    			},
    			settingsPassword: {
    				required: true,
    				minlength: 4
    			},
    			settingsConfirm: {
    				required: true,
    				minlength: 4,
    				equalTo: "#settingsPassword"
    			},
    			settingsFirstName: {
    				required: true,
    				minlength: 2
    			},
    			settingsLastName: {
    				required: true,
    				minlength: 2
    			},
    			settingsEmail2: {
    				email: true
    			},
    			settingsEmail3: {
    				email: true
    			}
    		},
    		messages: {
    			settingsUsername: {
    				required: "Please enter a valid email address",
    				email: "Please enter a valid email address",
    				remote: "This email address is already in use"
    			},
    			settingsPassword: {
    				required: "Enter an alpha numeric password",
    				minlength: jQuery.format("Enter at least {0} characters")
    			},
    			settingsConfirm: {
    				required: "Enter the same password as above",
    				minlength: jQuery.format("Enter at least {0} characters"),
    				equalTo: "Enter the same password as above"
    			},
    			settingsFirstName: {
    				required: "Enter the your first name",
    				minlength: jQuery.format("Enter at least {0} characters")
    			},
    			settingsLastName: {
    				required: "Enter the your last name",
    				minlength: jQuery.format("Enter at least {0} characters")
    			},
    			settingsEmail2: {
    				email: "Please enter a valid email address"
    			},
    			settingsEmail3: {
    				email: "Please enter a valid email address"
    			}
    		},
    		errorPlacement: function(error, element) {
    	     	
    	   	},
    		success: function(label) {
    			
    		}
    	});
    	
		$('#btnSettings').click(function() {
			// Remove existing errors
			$('.settings-popup input').removeClass('error');
			
			if (valid.form()) {
				updateAccount();
			} else {			
				$('.notice').slideUp('fast', function() { $(this).remove(); });
				// Show error message
				var html = '<div class="notice"><span style="display: none;">Correct the errors below</span></div>';
				$('#settingsId').after(html);
				$('.notice').delay(100).slideDown(300, function() { $('.notice span').fadeIn(); });
			}
		});	
	};
	
    var updateAccount = function() {
    	// Clear phone type if number is empty
    	if ($('#settingsPhoneNum1').val() == '') {
    		$('#settingsPhoneType1').val('');
    	}
    	if ($('#settingsPhoneNum2').val() == '') {
    		$('#settingsPhoneType2').val('');
    	}
    	if ($('#settingsPhoneNum3').val() == '') {
    		$('#settingsPhoneType3').val('');
    	}
    	
		var postValues = {
			'username': $('#settingsUsername').val(),
			'password': $('#settingsPassword').val(),
			'confirm': $('#settingsConfirm').val(),
			'firstName': $('#settingsFirstName').val(),
			'lastName': $('#settingsLastName').val(),
			'streetAddress': $('#settingsStreetAddress').val(),
			'city': $('#settingsCity').val(),
			'zip': $('#settingsZip').val(),
			'email2': $('#settingsEmail2').val(),
			'email3': $('#settingsEmail3').val(),
			'phoneType1': $('#settingsPhoneType1').val(),
			'phoneNum1': $('#settingsPhoneNum1').val(),
			'phoneType2': $('#settingsPhoneType2').val(),
			'phoneNum2': $('#settingsPhoneNum2').val(),
			'phoneType3': $('#settingsPhoneType3').val(),
			'phoneNum3': $('#settingsPhoneNum3').val()
		};
				
		$.post('/ajax/account/edit', postValues,
			function(data) {
				if (data.success == false) {
				 
					$('.notice').slideUp('fast', function() { $(this).remove(); });
					// Show error message
					var html = '<div class="notice"><span style="display: none;">' + data.message + '</span></div>';
					$('#settingsId').after(html);
					$('.notice').delay(100).slideDown(300, function() { $('.notice span').fadeIn(); });

				} else {
					// Set global variables
					user = data.user;
					
					$('.notice').slideUp('fast', function() { $(this).remove(); });
					// Show error message
					var html = '<div class="notice"><span class="success" style="display: none;">Account has been updated</span></div>';
					$('#settingsId').after(html);
					$('.notice').delay(100).slideDown(300, function() { $('.notice span').fadeIn(); });
				}						
			}, 'json');		
    };	
	
	var favSearchesPopup = function () {
    	var html = '<div class="account-popup fav-searches-popup">';   
    	html += '<ul id="accountTabs">';
    	html += '  <li class="tab-settings"></li>';
    	html += '  <li class="tab-searches"></li>';
    	html += '  <li class="tab-hoods"></li>';
    	html += '  <li class="tab-homes"></li>';
    	html += '</ul>';
    	html += '<div class="account">'; 
		html += '  <div class="fav-bar">';
		html += '    <span class="fav-name">Name</span>';
		html += '    <span class="fav-actions">Actions</span>';
		html += '  </div>';	
		html += '  <div class="fav-acc">';
		for (var i=0; i<user['searches'].length; i++) {
			html += '<div id="favsearch_' + user['searches'][i]['id'] + '" class="acc-item">';	
			html += '  <div id="viewsearch_' + user['searches'][i]['id'] + '" class="acc-name">' + user['searches'][i]['name'];
			if (user['searches'][i]['email'] == 1 && user['searches'][i]['freq'] == 'd') {
				html += ' - <i>Daily Email</i>';
			} else if (user['searches'][i]['email'] == 1 && user['searches'][i]['freq'] == 'w') {
				html += ' - <i>Weekly Email</i>';
			} else {
				html += ' - <i>No Email</i>';
			}
			html += '  </div>';	
			html += '  <div class="acc-view">View</div>';	
			html += '  <div class="acc-edit">Edit</div>';		
			html += '  <div class="acc-delete">Delete</div>';		
			html += '</div>';	
		}
		html += '  </div>';	
		
    	html += '</div>';
    	html += '</div>';
    	
		$.openPopup(html);
    	
    	$('.tab-settings').click(settingsPopup);
    	$('.tab-homes').click(favListingsPopup);	
    	$('.tab-hoods').click(favHoodsPopup);	
    	
    	$('.fav-searches-popup .acc-view').live('click', function () {
	    	// Make sure existing window is closed
	    	$("#popup").dialog('close');
	    	
    		var par = this.parentNode.id;
    		var id  = par.substring(par.lastIndexOf('_')+1);
			
			for (var i=0; i<user['searches'].length; i++) {
				if (user['searches'][i]['id'] == id) {
					location.href = '/arlington-va-real-estate#' + escape(user['searches'][i]['criteria']);
					break;
				}
			}
		});
    	
    	// Add edit button
    	$('.fav-searches-popup .acc-edit').click(function () {
    		var par = this.parentNode.id;
    		var id  = par.substring(par.lastIndexOf('_')+1);

    		// See if current open item is click on.. just close
    		var open = true;
    		if ($('#favsearch_' + id).hasClass('acc-item-edit')) {
    			open = false;
    		}
    		
    		// Close existing content boxes before opening new one
    		$('.fav-content').delay(200).slideUp('slow', function() { 
    			$(this).prev().removeClass('acc-item-edit'); 	
    			$(this).remove();
    		});
    		
    		if (open) {
    			// Get search info
    			for (var i=0; i<user['searches'].length; i++) {
    				if (user['searches'][i]['id'] == id) {
    					var favSearch = user['searches'][i];
    					break;
    				}
    			}
    			
        		// Open box directly underneath
        		var html = '<div id="favcontent_' + id + '" class="fav-content fav-search-content">';
        		html += '  <input type="hidden" id="favSearchId" name="favSearchId" value="' + favSearch.id + '" />';
        		html += '  <div class="fav-content-item">';
        		html += '    <label>Saved Search Name</label>';
        		html += '    <input type="text" id="favSearchName" name="favSearchName" maxlength="45" value="' + favSearch.name + '" />';
        		html += '  </div>';
        	    html += '  <div class="fav-content-check">';
        	    html += '    <label><input type="checkbox" id="favSearchEmail" name="favSearchEmail" tabindex="2" value="1" />Email me new listings and price changes</label>';
        	    html += '  </div>';
        	    html += '  <div class="fav-content-check">';
        	    html += '    <label class="freq-left"><input type="radio" id="favSearchFreqDaily" name="favSearchFreq" tabindex="3" value="d" checked />Daily</label>';
        	    html += '    <label class="freq-right"><input type="radio" id="favSearchFreqWeekly" name="favSearchFreq" tabindex="4" value="w" />Weekly (Friday Morning)</label>';
        		html += '    <div class="save-content">Save</div>';
        		html += '    <div class="close-content">Close</div>';
        	    html += '  </div>';
        		html += '</div>';
        		
        		$('#favsearch_' + id).after(html).delay(200).addClass('acc-item-edit');
        		$('#favcontent_' + id).delay(200).slideDown('slow', function () {
            		// Set values
            		if (favSearch.email == 1) {
                		$('#favSearchEmail').attr('checked', true);
                		if (favSearch.freq == 'w') {
                    		$('#favSearchFreqWeekly').attr('checked', true);
                		} else {
                    		$('#favSearchFreqDaily').attr('checked', true);
                		}
            		}
        		});
        		
        		// Add close and save events	
        		$('#favcontent_' + id + ' .save-content').click(function () {
        			updateSearch();
        		});
        		$('#favcontent_' + id + ' .close-content').click(function () {
            		$('#favcontent_' + id).delay(200).slideUp('slow', function() { 
            			$(this).prev().removeClass('acc-item-edit'); 	
            			$(this).remove();
            		});
        		});
    		}
    	});
    	// Delete button click event
    	$('.fav-searches-popup .acc-delete').click(function () {
    		var par = this.parentNode.id;
    		var id  = par.substring(par.lastIndexOf('_')+1);
    		
    		$.post('/ajax/account/deletesearch', { 'id': id },
    			function(data) {
    				if (data.success === true) {
    					var searches = [];
    					for (var i=0; i<user['searches'].length; i++) {
    						if (user['searches'][i]['id'] != data['id']) {
    							searches.push(user['searches'][i]);
    						}
    					}
    					user['searches'] = searches;
    					// Remove item from manager and drop down
    					if (searches.length > 1) {
    						$('#search_' + id).remove();
    					} 
    					$('#favsearch_' + id).slideUp('slow', function() { $(this).remove(); });
    					$('#favcontent_' + id).slideUp('slow', function() { $(this).remove(); });
    				} 						
    			}, 'json');	
    	});    	
	};
	
    var saveSearch = function () {
    	if (user['searches'] == false || user['searches'].length < maxSearches) {
    		
    		var email = 0;
        	if ($('#saveSearchEmail').attr('checked')) {
        		email = 1;
        	}
        	
        	var criteria = stringify($.getSearchValues());
    		
			var postValues = {
				'name': $('#saveSearchName').val(),
				'criteria': criteria,
				'email': email,
				'freq': $('input[name="saveSearchFreq"]:checked').val()
			};
				
			$.post('/ajax/account/addsearch', postValues,
				function(data) {
					if (data.success !== false) {
						// Add new values
						if (user.searches == false) {
							user.searches = [];
						}
						user['searches'].push({'id': data.success, 
											   'client_id': user.id, 
											   'criteria': postValues['criteria'],
											   'name': postValues['name'],
											   'email': email,
											   'freq': postValues['freq']});

        				
						$('.notice').slideUp('fast', function() { $(this).remove(); });
						// Show error message
						var html = '<div class="notice"><span class="success">This search has been saved</span></div>';
						$('.top-input').before(html);
						$('.notice').delay(100).slideDown(300).delay(1500).fadeOut(200, function () {
        					$("#popup").dialog('close');	
						});	
					}						
				}, 'json');	
    	}
    };
	
    var updateSearch = function () {
		var email = 0;
    	if ($('#favSearchEmail').attr('checked')) {
    		email = 1;
    	}
		
		var postValues = {
	        'id': $('#favSearchId').val(),
			'name': $('#favSearchName').val(),
			'email': email,
			'freq': $('input[name="favSearchFreq"]:checked').val()
		};
			
		$.post('/ajax/account/editsearch', postValues,
			function(data) {
				if (data.success !== false) {
        			// Update user listings array
            		for (var i=0; i<user['searches'].length; i++) {
            			if (user['searches'][i]['id'] == postValues['id']) {
            				user['searches'][i]['name']  = postValues['name'];
            				user['searches'][i]['email'] = postValues['email'];
            				user['searches'][i]['freq']  = postValues['freq'];
            			}
            		}
        			// Update manager favorites title and rebuild drop down menu
        			var html = postValues['name'];
        			
        			if (postValues['email'] == 1 && postValues['freq'] == 'd') {
        				html += ' - <i>Daily Email</i>';
        			} else if (postValues['email'] == 1 && postValues['freq'] == 'w') {
        				html += ' - <i>Weekly Email</i>';
        			} else {
        				html += ' - <i>No Email</i>';
        			}

        			$('#viewsearch_' + postValues['id']).html(html);
				}						
			}, 'json');	    	
    };
    
	var favHoodsPopup = function () {
    	var html = '<div class="account-popup fav-hoods-popup">';   
    	html += '<ul id="accountTabs">';
    	html += '  <li class="tab-settings"></li>';
    	html += '  <li class="tab-searches"></li>';
    	html += '  <li class="tab-hoods"></li>';
    	html += '  <li class="tab-homes"></li>';
    	html += '</ul>';
    	html += '<div class="account">'; 
		html += '  <div class="fav-bar">';
		html += '    <span class="fav-name">Name</span>';
		html += '    <span class="fav-actions">Actions</span>';
		html += '  </div>';	
		html += '  <div class="fav-acc">';
		for (var i=0; i<user['hoods'].length; i++) {
			html += '<div id="favhood_' + user['hoods'][i]['id'] + '" class="acc-item">';	
			html += '  <div id="viewhood_' + user['hoods'][i]['id'] + '" class="acc-name">' + user['hoods'][i]['name'];
			if (user['hoods'][i]['email'] == 1 && user['hoods'][i]['freq'] == 'd') {
				html += ' - <i>Daily Email</i>';
			} else if (user['hoods'][i]['email'] == 1 && user['hoods'][i]['freq'] == 'w') {
				html += ' - <i>Weekly Email</i>';
			} else {
				html += ' - <i>No Email</i>';
			}
			html += '  </div>';	
			html += '  <div class="acc-edit">Edit</div>';		
			html += '  <div class="acc-delete">Delete</div>';		
			html += '</div>';	
		}
		html += '  </div>';	
		
    	html += '</div>';
    	html += '</div>';
    	
		$.openPopup(html);
    	
    	$('.tab-settings').click(settingsPopup);
    	$('.tab-homes').click(favListingsPopup);
    	$('.tab-searches').click(favSearchesPopup);	
    	
    	// Add edit button
    	$('.fav-hoods-popup .acc-edit').click(function () {
    		var par = this.parentNode.id;
    		var id  = par.substring(par.lastIndexOf('_')+1);

    		// See if current open item is click on.. just close
    		var open = true;
    		if ($('#favhood_' + id).hasClass('acc-item-edit')) {
    			open = false;
    		}
    		
    		// Close existing content boxes before opening new one
    		$('.fav-content').delay(200).slideUp('slow', function() { 
    			$(this).prev().removeClass('acc-item-edit'); 	
    			$(this).remove();
    		});
    		
    		if (open) {
    			// Get search info
    			for (var i=0; i<user['hoods'].length; i++) {
    				if (user['hoods'][i]['id'] == id) {
    					var favHood = user['hoods'][i];
    					break;
    				}
    			}
    			
        		// Open box directly underneath
        		var html = '<div id="favcontent_' + id + '" class="fav-content fav-hood-content">';
        		html += '  <input type="hidden" id="favHoodId" name="favHoodId" value="' + favHood.id + '" />';
        		html += '  <div class="fav-content-item">';
        		html += '    <label>Saved Search Name</label>';
        		html += '    <input type="text" id="favHoodName" name="favHoodName" maxlength="45" value="' + favHood.name + '" />';
        		html += '  </div>';
        	    html += '  <div class="fav-content-check">';
        	    html += '    <label><input type="checkbox" id="favHoodEmail" name="favHoodEmail" tabindex="2" value="1" />Email me new listings and price changes</label>';
        	    html += '  </div>';
        	    html += '  <div class="fav-content-check">';
        	    html += '    <label class="freq-left"><input type="radio" id="favHoodFreqDaily" name="favHoodFreq" tabindex="3" value="d" checked />Daily</label>';
        	    html += '    <label class="freq-right"><input type="radio" id="favHoodFreqWeekly" name="favHoodFreq" tabindex="4" value="w" />Weekly (Friday Morning)</label>';
        		html += '    <div class="save-content">Save</div>';
        		html += '    <div class="close-content">Close</div>';
        	    html += '  </div>';
        		html += '</div>';
        		
        		$('#favhood_' + id).after(html).delay(200).addClass('acc-item-edit');
        		$('#favcontent_' + id).delay(200).slideDown('slow', function () {
            		// Set values
            		if (favHood.email == 1) {
                		$('#favHoodEmail').attr('checked', true);
                		if (favHood.freq == 'w') {
                    		$('#favHoodFreqWeekly').attr('checked', true);
                		} else {
                    		$('#favHoodFreqDaily').attr('checked', true);
                		}
            		}
        		});
        		
        		// Add close and save events	
        		$('#favcontent_' + id + ' .save-content').click(function () {
        			updateHood();
        		});
        		$('#favcontent_' + id + ' .close-content').click(function () {
            		$('#favcontent_' + id).delay(200).slideUp('slow', function() { 
            			$(this).prev().removeClass('acc-item-edit'); 	
            			$(this).remove();
            		});
        		});
    		}
    	});
    	// Delete button click event
    	$('.fav-hoods-popup .acc-delete').click(function () {
    		var par = this.parentNode.id;
    		var id  = par.substring(par.lastIndexOf('_')+1);
    		
    		$.post('/ajax/account/deletehood', { 'id': id },
    			function(data) {
    				if (data.success === true) {
    					var hoods = [];
    					for (var i=0; i<user['hoods'].length; i++) {
    						if (user['hoods'][i]['id'] != data['id']) {
    							hoods.push(user['hoods'][i]);
    						}
    					}
    					user['hoods'] = hoods;
    					// Remove item from manager and drop down
    					if (hoods.length > 1) {
    						$('#hood_' + id).remove();
    					} 
    					$('#favhood_' + id).slideUp('slow', function() { $(this).remove(); });
    					$('#favcontent_' + id).slideUp('slow', function() { $(this).remove(); });
    				} 						
    			}, 'json');	
    	});    	
	};  
	
    var updateHood = function () {
		var email = 0;
    	if ($('#favHoodEmail').attr('checked')) {
    		email = 1;
    	}
		
		var postValues = {
	        'id': $('#favHoodId').val(),
			'name': $('#favHoodName').val(),
			'email': email,
			'freq': $('input[name="favHoodFreq"]:checked').val()
		};
			
		$.post('/ajax/account/edithood', postValues,
			function(data) {
				if (data.success !== false) {
        			// Update user listings array
            		for (var i=0; i<user['hoods'].length; i++) {
            			if (user['hoods'][i]['id'] == postValues['id']) {
            				user['hoods'][i]['name']  = postValues['name'];
            				user['hoods'][i]['email'] = postValues['email'];
            				user['hoods'][i]['freq']  = postValues['freq'];
            			}
            		}
        			// Update manager favorites title and rebuild drop down menu
        			var html = postValues['name'];
        			
        			if (postValues['email'] == 1 && postValues['freq'] == 'd') {
        				html += ' - <i>Daily Email</i>';
        			} else if (postValues['email'] == 1 && postValues['freq'] == 'w') {
        				html += ' - <i>Weekly Email</i>';
        			} else {
        				html += ' - <i>No Email</i>';
        			}

        			$('#viewhood_' + postValues['id']).html(html);
				}						
			}, 'json');	    	
    };  
	
	var favListingsPopup = function () {
    	var html = '<div class="account-popup fav-listings-popup">';   
    	html += '<ul id="accountTabs">';
    	html += '  <li class="tab-settings"></li>';
    	html += '  <li class="tab-searches"></li>';
    	html += '  <li class="tab-hoods"></li>';
    	html += '  <li class="tab-homes"></li>';
    	html += '</ul>';
    	html += '<div class="account">'; 	
		html += '  <div class="fav-bar">';
		html += '    <span class="fav-name">Name</span>';
		html += '    <span class="fav-actions">Actions</span>';
		html += '  </div>';
		html += '  <div class="fav-acc">';
		for (var i=0; i<user['listings'].length; i++) {
			html += '<div id="favlisting_' + user['listings'][i]['id'] + '" class="acc-item">';	
			html += '  <div id="viewlisting_' + user['listings'][i]['id'] + '" class="acc-name">' + user['listings'][i]['name'];
			if (user['listings'][i]['notes'] != '') {
				html += ' - <i>Notes Available</i>';
			}
			html += '  </div>';	
			html += '  <div class="acc-view">View</div>';	
			html += '  <div class="acc-edit">Notes</div>';		
			html += '  <div class="acc-delete">Delete</div>';		
			html += '</div>';		
		}
		html += '  </div>';	
		
    	html += '</div>';
    	html += '</div>';
    	
		$.openPopup(html);
    	
    	$('.tab-settings').click(settingsPopup);
    	$('.tab-searches').click(favSearchesPopup);	
    	$('.tab-hoods').click(favHoodsPopup);	
    	
    	$('.fav-listings-popup .acc-view').live('click', function () {
	    	// Make sure existing window is closed
	    	$("#popup").dialog('close');
	    	
    		var par = this.parentNode.id;
    		var id  = par.substring(par.lastIndexOf('_')+1);
			
			for (var i=0; i<user['listings'].length; i++) {
				if (user['listings'][i]['id'] == id) {
					location.href = '/arlington-va-real-estate/redirect/key/' + user['listings'][i]['listing_key'] + '/';
					break;
				}
			}
		});
    	
    	// Add edit button
    	$('.fav-listings-popup .acc-edit').click(function () {
    		var par = this.parentNode.id;
    		var id  = par.substring(par.lastIndexOf('_')+1);

    		// See if current open item is click on.. just close
    		var open = true;
    		if ($('#favlisting_' + id).hasClass('acc-item-edit')) {
    			open = false;
    		}
    		
    		// Close existing content boxes before opening new one
    		$('.fav-content').delay(200).slideUp('slow', function() { 
    			$(this).prev().removeClass('acc-item-edit'); 	
    			$(this).remove();
    		});
    		
    		if (open) {
    			// Get listing info
    			for (var i=0; i<user['listings'].length; i++) {
    				if (user['listings'][i]['id'] == id) {
    					var favListing = user['listings'][i];
    					break;
    				}
    			}
    			
        		// Open box directly underneath
        		var html = '<div id="favcontent_' + id + '" class="fav-content fav-listing-content">';
        		html += '  <input type="hidden" id="favListingId" name="favListingId" value="' + favListing.id + '" />';
        		html += '  <div class="fav-content-item">';
        		html += '    <label>Saved Home Name</label>';
        		html += '    <input type="text" id="favListingName" name="favListingName" maxlength="45" value="' + favListing.name + '" />';
        		html += '  </div>';
        		html += '  <div class="fav-content-ta">';
        		html += '    <label>Notes</label>';
        		html += '    <textarea id="favListingNotes">' + favListing.notes + '</textarea>';
        		html += '    <div class="save-content">Save</div>';
        		html += '    <div class="close-content">Close</div>';
        		html += '  </div>';
        		html += '</div>';
        		
        		$('#favlisting_' + id).after(html).delay(200).addClass('acc-item-edit');
        		$('#favcontent_' + id).delay(200).slideDown('slow');
        		
        		
        		// Add close and save events	
        		$('#favcontent_' + id + ' .save-content').click(function () {
        			updateListing();
        		});
        		$('#favcontent_' + id + ' .close-content').click(function () {
            		$('#favcontent_' + id).delay(200).slideUp('slow', function() { 
            			$(this).prev().removeClass('acc-item-edit'); 	
            			$(this).remove();
            		});
        		});
    		}
    	});
    	// Delete button click event
    	$('.fav-listings-popup .acc-delete').click(function () {
    		var par = this.parentNode.id;
    		var id  = par.substring(par.lastIndexOf('_')+1);
    				
    		$.post('/ajax/account/deletelisting', { 'id': id },
    			function(data) {
    				if (data.success === true) {
    					var listings = [];
    					for (var i=0; i<user['listings'].length; i++) {
    						if (user['listings'][i]['id'] != data['id']) {
    							listings.push(user['listings'][i]);
    						}
    					}
    					user['listings'] = listings;
    					// Remove item from manager and drop down
    					if (listings.length > 1) {
    						$('#listing_' + id).remove();
    					}
    					$('#favlisting_' + id).slideUp('slow', function() { $(this).remove(); });
    					$('#favcontent_' + id).slideUp('slow', function() { $(this).remove(); });
    				} 						
    			}, 'json');	
    	});
	};
	
	var updateListing = function () {    		
    	// Confirm both name and key are set on page
        var postValues = {
            'id': $('#favListingId').val(),
        	'name': $('#favListingName').val(),
        	'notes': $('#favListingNotes').val()
        };
        				
        $.post('/ajax/account/editlisting', postValues,
        	function(data) {
        		if (data.success !== false) {
        			// Update user listings array
            		for (var i=0; i<user['listings'].length; i++) {
            			if (user['listings'][i]['id'] == postValues['id']) {
            				user['listings'][i]['name']  = postValues['name'];
            				user['listings'][i]['notes'] = postValues['notes'];
            			}
            		}
        			// Update manager favorites title and rebuild drop down menu
        			var html = postValues['name'];
        			if (postValues['notes'] != '') {
        				html += ' - <i>Notes Available</i>';
        			}
        			$('#viewlisting_' + postValues['id']).html(html);
        		}						
        	}, 'json');	
    };
    
    var saveListing = function () {
    	if (user['listings'] == false || user['listings'].length < maxListings) {
    		// Confirm both name and key are set on page
        	var postValues = {
        		'name': $('#saveListingName').val(),
        		'key': $('#saveListingKey').val(),
        		'notes': $('#saveListingNotes').val()
        	};
        				
        	$.post('/ajax/account/addlisting', postValues,
        		function(data) {
        			if (data.success !== false) {
        				// Add new values
        				if (user.listings == false) {
        					user.listings = [];
        				}
        				user['listings'].push({'id': data.success, 
        									   'client_id': user.id, 
        									   'name': postValues['name'],
        									   'notes': postValues['notes'],
        									   'listing_key': postValues['key']});
        				       				
						$('.notice').slideUp('fast', function() { $(this).remove(); });
						// Show error message
						var html = '<div class="notice"><span class="success">This listing has been saved</span></div>';
						$('.top-input').before(html);
						$('.notice').delay(100).slideDown(300).delay(1500).fadeOut(200, function () {
        					$("#popup").dialog('close');	
						});				
        			} else {
						$('.notice').slideUp('fast', function() { $(this).remove(); });
						// Show error message
						var html = '<div class="notice"><span>This listing has already been saved</span></div>';
						$('.top-input').before(html);
						$('.notice').delay(100).slideDown(300).delay(1500).fadeOut(200, function () {
        					$("#popup").dialog('close');	
						});			
        			}						
        		}, 'json');	
    	}		
    };
    
    var saveHood = function () {
    	if (user['hoods'] == false || user['hoods'].length < maxHoods) {
    		// Confirm both name and key are set on page
	    	var postValues = {
	    		'minPrice':   $('#saveHoodMinPrice').val().replace(/[^0-9]/g, ''),
				'maxPrice':   $('#saveHoodMaxPrice').val().replace(/[^0-9]/g, ''),
				'beds': 	  $('#saveHoodBeds').val(),
				'baths': 	  $('#saveHoodBaths').val(),
				'single':     ($('#saveHoodSingle').is(':checked') ? 1 : 0),
				'townhome':   ($('#saveHoodTownhome').is(':checked') ? 1 : 0),
				'condo':      ($('#saveHoodCondo').is(':checked') ? 1 : 0),
				'email':      ($('#saveEmail').is(':checked') ? 1 : 0),
				'freq': 	  $('input[name="saveFreq"]:checked').val(),
				'name': 	  $('#saveName').val(),
				'hoodId': 	  $('#saveHoodId').val()
	    	};
        				
        	$.post('/ajax/account/addhood', postValues,
        		function(data) {
        			if (data.success !== false) {
        				// Add new values
        				if (user.hoods == false) {
        					user.hoods = [];
        				}
        				user['hoods'].push({'id': data.success, 
        									'client_id': user.id, 
        									'name': postValues['name'],
        									'email': postValues['email'],
        									'freq': postValues['freq'],
        									'neighborhood_id': postValues['hoodId']});
        				       				
						$('.notice').slideUp('fast', function() { $(this).remove(); });
						// Show error message
						var html = '<div class="notice"><span class="success">This neighborhood has been saved</span></div>';
						$('.email-bottom').before(html);
						$('.notice').delay(100).slideDown(300).delay(1500).fadeOut(200, function () {
        					$("#popup").dialog('close');	
						});				
        			} else {
						$('.notice').slideUp('fast', function() { $(this).remove(); });
						// Show error message
						var html = '<div class="notice"><span>This neighborhood has already been saved</span></div>';
						$('.email-bottom').before(html);
						$('.notice').delay(100).slideDown(300).delay(3000).fadeOut(200, function () {
        					$("#popup").dialog('close');	
						});			
        			}						
        		}, 'json');	
    	}		
    };
	
	var registerPopup = function () {
		var html = '<div class="required-top">Registration required to use this feature.</div>';
		html 	+= '<div class="required-sub-top">Included with your FREE account &gt;</div>';
		html 	+= '<div class="register-details">';
		html 	+= '  <div id="registerInput">';
    	html    += '  <form id="registerForm" method="post">';
		html 	+= '  <div class="title">Create Free Account</div>';
		html 	+= '  <div class="notice"></div>';
		html 	+= '  <input type="text" id="portalHide" name="portalHide" value="" tabindex="9" />';
		html 	+= '  <div class="left">';
		html 	+= '    <div class="input-box">';
		html 	+= '    <label class="overlabel" for="portalFirstName">First Name</label>';
		html 	+= '    <input type="text" id="portalFirstName" name="portalFirstName" value="" tabindex="20" />';
		html 	+= '    </div>';
		html 	+= '    <div class="input-box">';
		html 	+= '    <label class="overlabel" for="portalEmail">Email Address</label>';
		html 	+= '    <input type="text" id="portalEmail" name="portalEmail" value="" tabindex="22" />';
		html 	+= '    </div>';
		html 	+= '    <div class="input-box">';
		html 	+= '    <label class="overlabel" for="portalPass">Password</label>';
		html 	+= '    <input type="password" id="portalPass" name="portalPass" value="" tabindex="24" />';
		html 	+= '    </div>';
		html 	+= '    <div class="terms">By clicking Join, I agree to the <span id="linkTerms">Terms of Use</span>.</div>';
		html 	+= '  </div>';
		html 	+= '  <div class="right">';
		html 	+= '    <div class="input-box">';
		html 	+= '    <label class="overlabel" for="portalLastName">Last Name</label>';
		html 	+= '    <input type="text" id="portalLastName" name="portalLastName" value="" tabindex="21" />';
		html 	+= '    </div>';
		html 	+= '    <div class="input-box">';
		html 	+= '    <label class="overlabel" for="portalPhone">Phone Number</label>';
		html 	+= '    <input type="text" id="portalPhone" name="portalPhone" value="" tabindex="23" />';
		html 	+= '    </div>';
		html 	+= '    <div class="input-box">';
		html 	+= '    <label class="overlabel" for="portalPass2">Confirm Password</label>';
		html 	+= '    <input type="password" id="portalPass2" name="portalPass2" value="" tabindex="25" />';
		html 	+= '    </div>';
		html 	+= '    <div id="btnJoin" class="btn-join">Login</div>';
		html 	+= '  </div>';
		html 	+= '  <div id="linkSignin" class="signin">Returning Members &gt</div>';
		html    += '  </form>';
		html 	+= '  </div>';
	    html    += '  <div id="registerTerms">';
	    html 	+= '    <b>Terms of Use</b><br /><br />';
	    html 	+= '    By registering for a Century 21 Redwood Realty account you are agreeing to the following terms and ';
	    html 	+= '    conditions. Your agreement to these terms does not require you to work with Century 21 Redwood Realty. ';
	    html 	+= '    <ul>';
	    html 	+= '      <li>You are entering into a lawful consumer-broker relationship with Century 21 Redwood  as may be defined by state law. </li>';
	    html 	+= '      <li>Any information you obtain from the Century 21 Redwood Realty website is intended for your personal, non-commercial use. </li>';
	    html 	+= '      <li>You have a bona fide interest in the purchase, sale, or lease of real estate on the Century 21 Redwood Realty website. </li>';
	    html 	+= '      <li>You will not copy, redistribute, or retransmit any of the information provided except in connection with your consideration of the purchase or sale of an individual property. </li>';
	    html 	+= '      <li>You acknowledge that the individual multiple listing service (MLS), which supplies the listing data, owns such data and you acknowledge the validity or the MLSs copyright to such data.</li>';
	    html 	+= '    </ul>';
	    html 	+= '    <br /><b>Metropolitan Regional Information Systems, Inc. (MRIS)</b><br /><br />';
	    html 	+= '    &copy; Metropolitan Regional Information Systems, Inc. All rights reserved. Listings provided by MRIS from various';
	    html 	+= '    brokers who participate in IDX (Internet Data Exchange). Information deemed reliable but not guaranteed.<br /><br />';
	    html 	+= '    Last Updated: 9 March, 2011<br /><br />';
	    html 	+= '    <span id="linkBack" class="link">Back to "Create Account" page</span>';
	    html 	+= '  </div>';
		html 	+= '</div>';
		
		$.openPopup(html);
		
		$.initOverLabels();
		
		$('#linkSignin').click(function () {
			signInPopup();
		});
		$('#linkTerms').click(function () {
			$('#registerInput').css('display', 'none');
			$('#registerTerms').css('display', 'block');
		});
		$('#linkBack').click(function () {
			$('#registerTerms').css('display', 'none');
			$('#registerInput').css('display', 'block');
		});
		
		// Create Form Validator
    	var valid = $("#registerForm").validate({
    		rules: {
    			portalEmail: {
    				required: true,
    				email: true,
    				remote: {
    					url: '/ajax/account/validuser',
    					type: 'post',
    					data: { 'userId': null }
    				}
    			},
    			portalPass: {
    				required: true,
    				minlength: 4
    			},
    			portalPass2: {
    				required: true,
    				minlength: 4,
    				equalTo: "#portalPass"
    			},
    			portalFirstName: {
    				required: true,
    				minlength: 2
    			},
    			portalLastName: {
    				required: true,
    				minlength: 2
    			}
    		},
    		errorPlacement: function(error, element) { 	     	
    	   	},
    		success: function(label) {
    		}
    	});
    	
    	$('#btnJoin').click(function() {
			// Remove existing errors
			$('.register-details input').removeClass('error');
			
			if (valid.form()) {

				var post = { username: $('#portalEmail').val(), 
					 	 	 password: $('#portalPass').val(), 
					 	 	 confirm: $('#portalPass2').val(), 
					 	 	 firstName: $('#portalFirstName').val(), 
					 	 	 lastName: $('#portalLastName').val(), 
					 	 	 phone: $('#portalPhone').val() };
				$.post('/ajax/account/add', post, function(data) {
					if (data.success == false) {
						$('.register-details .notice').html('<span>' + data.message + '</span>');
					} else {
						user = data.user;
						auth = true;
					
						$("#popup").dialog('close');
					
						buildAccountBox();
						
						// check for boundaries function to update
						if ($.isFunction($.updateBoundaries)) {
							$.updateBoundaries();
						}
					}
				});
			} else {
				$('.register-details .notice').html('<span>Please fill in the fields below</span>');
			}
		});
	};
	
	var buildAccountBox = function () {
		if (auth) {
			var html = '<b>Welcome, ' + user.first_name + '</b> <a id="myAccount" href="#">My Account</a> <a id="logout" href="#">Logout</a>';
		} else {
			var html = 'Want to experience more? <a id="signIn" href="#">Sign-In Here</a>';					
		}
		$('#account').html(html);
	};
	
	var logout = function () {
		$.post('/ajax/account/logout', null, function() {
			auth = false;
			user = {};
					
			buildAccountBox();
			// check for boundaries function to update
			if ($.isFunction($.resetBoundaries)) {
				$.resetBoundaries();
			}
		});
	};

	var hideLabel = function (fieldId, hide) {
  		var fieldFor, labels = document.getElementsByTagName('label');
  		for (var i = 0; i < labels.length; i++) {
    		fieldFor = labels[i].htmlFor || labels[i].getAttribute('for');
    		if (fieldFor == fieldId) {
      			labels[i].style.textIndent = (hide) ? '-1000px' : '0px';
      			return true;
    		}
  		}
	};
	
	$.saveListingPopup = function (name, key) {

    	var html = '<div class="save-listing-popup">';
    	html += '  <div class="save-listing-top btn-sprite title-save-listing">Save This Listing</div>';
    	html += '  <div class="save-listing-bottom">';
		html += '  <div id="saveListingInput">';
    	if (user['listings'] == false || user['listings'].length < maxListings) {
    		html += '  <form id="saveListingForm" method="post">';
			html += '  <input type="text" id="portalHide" name="portalHide" value="" tabindex="99" />';
			html += '  <input type="hidden" id="saveListingKey" name="saveListingKey" value="' + key + '" />';
			html += '  <div class="full top-input">';
			html += '    <div class="input-box">';
			html += '    <label class="overlabel" for="saveListingName">Name</label>';
			html += '    <input type="text" id="saveListingName" name="saveListingName" value="' + name + '" tabindex="111" />';
			html += '    </div>';
			html += '  </div>';
			html += '  <div class="comment">';
			html += '  <label class="overlabel" for="saveListingNotes">Listing Notes</label>';
			html += '    <textarea id="saveListingNotes" name="saveListingNotes" tabindex="112"></textarea>';
			html += '  </div>';
			html += '  <div id="btnSave" class="btn-save">Save</div>';
			html += '  </form>';
		} else {
			html += '  <div class="notice"><span>You currently have the maximum saved listings.</span></div>';
			html += '  <div class="full">';
			html += '    <div class="input-box"></div>';
			html += '  </div>';
		}
		html += '  <div class="cl"></div>';
		html += '  </div>';
    	html += '  </div>';
	    html += '</div>';
	    
		$.openPopup(html);
		
		$.initOverLabels();
    	
    	if (user['listings'] == false || user['listings'].length < maxListings) {
			$('#btnSave').click(function() {
				if ($('#saveListingName').val() != '') {
					saveListing();
				} else {
					$('.notice').slideUp('fast', function() { $(this).remove(); });
					// Show error message
					var html = '<div class="notice"><span style="display: none;">Enter a name for this listing</span></div>';
					$('.top-input').before(html);
					$('.notice').delay(100).slideDown(300, function() { $('.notice span').fadeIn(); });
				}
			});
    	} else {
    		$('.manage-listing').click(favListingsPopup);
    	}
    };
    
    $.saveHoodPopup = function (id, name, values) {

		var html = '<div class="email-popup">';
    	html += '  <div class="email-top">';
    	html += '    <div class="filter-title">Filter:</div>';
    	html += '    <div class="filter-type">';
		html += '      <input type="text" id="portalHide" name="portalHide" value="" tabindex="99" />';
		html += '      <input type="hidden" id="saveHoodId" name="saveHoodId" value="' + id + '" />';
    	html += '      <div class="radio-box">';
    	html += '        <label><input type="checkbox" id="saveHoodSingle" name="saveHoodSingle" class="checkbox" value="1" tabindex="150" />';
    	html += '        Single Family Homes</label>';
    	html += '      </div>';
    	html += '      <div class="radio-box">';
    	html += '        <label><input type="checkbox" id="saveHoodTownhome" name="saveHoodTownhome" class="checkbox" value="1" tabindex="151" />';
    	html += '        Townhomes</label>';
    	html += '      </div>';
    	html += '      <div class="radio-box">';
    	html += '        <label><input type="checkbox" id="saveHoodCondo" name="saveHoodCondo" class="checkbox" value="1" tabindex="152" />';
    	html += '        Condo Style</label>';
    	html += '      </div>';
    	html += '    </div>'; 
    	html += '    <div class="filter-input filter-min-price">';
    	html += '      <div class="title">Price Range</div>';
    	html += '      <label class="overlabel" for="saveHoodMinPrice">Min</label>';
    	html += '      <input id="saveHoodMinPrice" name="saveHoodMinPrice" type="text" value="' + values.minPrice + '" maxlength="12" tabindex="155" />';
    	html += '      <div class="to">to</div>';
    	html += '    </div>';
    	html += '    <div class="filter-input filter-max-price">';
    	html += '      <div class="title">&nbsp;</div>';
    	html += '      <label class="overlabel" for="saveHoodMaxPrice">Max</label>';
    	html += '      <input id="saveHoodMaxPrice" name="saveHoodMaxPrice" type="text" value="' + values.maxPrice + '" maxlength="12" tabindex="156" />';
    	html += '    </div>';
    	html += '    <div class="filter-input filter-beds">';
    	html += '      <div class="title">Beds</div>';
    	html += '      <select tabindex="4" id="saveHoodBeds" name="saveHoodBeds" tabindex="160">';
    	html += '        <option value="0">All</option>';
    	html += '        <option value="1">1 +</option>';
     	html += '        <option value="2">2 +</option>';
    	html += '        <option value="3">3 +</option>';
    	html += '        <option value="4">4 +</option>';
    	html += '        <option value="5">5 +</option>';
    	html += '        <option value="6">6 +</option>';
    	html += '      </select>';
    	html += '    </div>';
    	html += '    <div class="filter-input filter-baths">';
    	html += '      <div class="title">Baths</div>';
    	html += '      <select tabindex="4" id="saveHoodBaths" name="saveHoodBaths" tabindex="161">';
    	html += '        <option value="0">All</option>';
    	html += '        <option value="1">1.5 +</option>';
    	html += '        <option value="2">2 +</option>';
    	html += '        <option value="3">3 +</option>';
    	html += '        <option value="4">4 +</option>';
    	html += '        <option value="5">5 +</option>';
    	html += '      </select>';
    	html += '    </div>';  	   	
    	html += '  </div>';
    	html += '  <div class="email-bottom">';  
    	html += '    <div class="email-left">Saved Search Name</div>';
    	html += '  	 <div class="email-middle">';  	
    	html += '      <div class="email-item">';
    	html += '      	<input type="text" id="saveName" name="saveName" maxlength="45" value="' + name + '" tabindex="165" />';
    	html += '      </div>';
    	html += '      <div class="email-check">';
    	html += '      	<label><input type="checkbox" id="saveEmail" name="saveEmail" tabindex="166" checked />Email me new listings and price changes</label>';
    	html += '      </div>';
    	html += '      <div class="email-check">';
    	html += '      	<label class="email-check-left"><input type="radio" id="saveFreqDaily" name="saveFreq" value="d" tabindex="167" checked />Daily</label>';
    	html += '      	<label class="email-check-right"><input type="radio" id="saveFreqWeekly" name="saveFreq" value="w" tabindex="168" />Weekly (Friday Morning)</label>';
    	html += '      </div>'; 
    	html += '    </div>';
    	html += '    <div class="email-right"><div id="btnSave" class="btn-save btn-sprite"></div></div>'; 		
    	html += '  </div>';
		html += '</div>';
		
		$.openPopup(html);	
    	
    	$.initOverLabels();
    	
		$("#saveHoodMinPrice").autoNumeric();
		$("#saveHoodMaxPrice").autoNumeric();
		$("#saveName").focus();
		
		$("#saveHoodBeds").val(values.beds);
		$("#saveHoodBaths").val(values.baths);
		
		var toBool = function (value) {
			if (value == 1 || value == "1" || value == "true" || value == true) {
				return true;
			} else {
				return false;
			}
		};
		// Set checkboxes
		$('input#saveHoodSingle').attr('checked', toBool(values.single));
		$('input#saveHoodTownhome').attr('checked', toBool(values.townhome));
		$('input#saveHoodCondo').attr('checked', toBool(values.condo));

		if (user['hoods'] == false || user['hoods'].length < maxHoods) {
			$('#btnSave').click(function() {
				if ($('#saveName').val() != '') {
					saveHood();
				} else {
					
					$('.notice').slideUp('fast', function() { $(this).remove(); });
					// Show error message
					var html = '<div class="notice"><span style="display: none;">Enter a name for this neighborhood email alert</span></div>';
					$('.email-bottom').before(html);
					$('.notice').delay(100).slideDown(300, function() { $('.notice span').fadeIn(); });
				}
			});
    	}
	};    
    
    $.saveSearchPopup = function () {

    	var html = '<div class="save-search-popup">';
    	html += '  <div class="save-search-top btn-sprite title-save-search">Save This Listing</div>';
    	html += '  <div class="save-search-bottom">';
		html += '  <div id="saveSearchInput">';
    	html += '  <form id="saveSearchForm" method="post">';
		html += '  <input type="text" id="portalHide" name="portalHide" value="" tabindex="99" />';
		html += '  <div class="full top-input">';
		html += '    <div class="input-box">';
		html += '    <label class="overlabel" for="saveSearchName">Name</label>';
		html += '    <input type="text" id="saveSearchName" name="saveSearchName" value="" tabindex="111" />';
		html += '    </div>';
		html += '  </div>';
	    html += '  <div class="save-check">';
	    html += '    <label><input type="checkbox" id="saveSearchEmail" name="saveSearchEmail" tabindex="2" value="1" checked />Email me new listings and price changes</label>';
	    html += '  </div>';
	    html += '  <div class="save-check freq-email">';
	    html += '    <label class="freq-left"><input type="radio" id="saveSearchFreqDaily" name="saveSearchFreq" tabindex="3" value="d" checked />Daily</label>';
	    html += '    <label class="freq-right"><input type="radio" id="saveSearchFreqWeekly" name="saveSearchFreq" tabindex="4" value="w" />Weekly (Friday Mornings)</label>';
	    html += '  </div>';
		html += '  <div id="btnSave" class="btn-save">Save</div>';
		html += '  </form>';
		html += '  <div class="cl"></div>';
		html += '  </div>';
    	html += '  </div>';
	    html += '</div>';
	    
		$.openPopup(html);
		
		$.initOverLabels();

		$('#btnSave').click(function() {
			if ($('#saveSearchName').val() != '') {
				saveSearch();
			} else {
				$('.notice').slideUp('fast', function() { $(this).remove(); });
				// Show error message
				$('.top-input').before('<div class="notice"><span style="display: none;">Enter a name for this search</span></div>');
				$('.notice').delay(100).slideDown(300, function() { $('.notice span').fadeIn(); });
			}
		});
    };
	
	$.signInPopup = function () {
		registerPopup();
	}
	
	$.settingsPopup = function () {
		settingsPopup();
	}
	
	$.userSettings = function (data) {
		user = data;
		auth = true;
	};
	
    $.isLoggedIn = function () {
    	return auth;
    };
    
    $.getUserInfo = function (field) {
    	if (user[field] != undefined) {
    		return user[field];
    	} else {
    		return '';
    	}
    };
    
    $.setMaxFavorites = function (searches, listings, hoods) {
    	maxSearches = searches;
    	maxListings = listings;
    	maxHoods	= hoods;
    };

	$(document).ready(function() {
		// Run over-label script to location and sub loc search
		$.initOverLabels();
		
    	// Get map details
		$("#popup").dialog({
			autoOpen: false,
			width: 'auto',
			height: 'auto',
			modal: true,
			closeText: '',
			resizable: false
		});

		// Initialize close button for popup
		$('#popupClose').click(function() {
			$("#popup").dialog('close');
		});
		$('#signIn').live('click', function() {
			registerPopup();
		});
		$('#logout').live('click', function() {
			logout();
		});
		$('#myAccount').live('click', function() {
			settingsPopup();
		});
		
		var get = getUrlVars();
		if (auth == false && get.passcode != null) {

			$.post('/ajax/account/validate', { 'code': get.passcode }, function(data) {
				if (data.success !== false) {
					// Open password reset form
					resetPopup();
					$('#portalCode').val(data.code);
				} else {
					// Open password email from and set error
					forgotPopup();
					$('.forgot-details .notice').html('<span>' + data.message + '</span>');
				}						
			}, 'json');		
		}
	});
})($);
