/**
 * Define application namespaces
 */
var Monroe = {
	Page: {},
	Prop: {},
	ClientId: {},
	Callback: {}
};

/**
 * Base JavaScript class.
 * 
 * All other pages classes should extend from this one. 
 */
Monroe.Page.MonroePage = Class.create({
	initialize: function(){
		Monroe.Page = this;
	
		new sidebarSeach();
		new login();
		
		this.mlsTextInput = $(Monroe.ClientId.MlsAutoComplete);
		this.mlsGoButton = $(Monroe.ClientId.MlsGoActiveButton);
		
		var self = this;
		
		if (this.mlsTextInput){
			this.mlsTextInput.observe('keyup', function(){
				self.mlsTextInput_OnKeyUp();
			});
		}
	},
	mlsTextInput_OnKeyUp: function(){
		//Enable the MLS Go button only if we have 7 characters in the text field.
		this.mlsGoButton.disabled = !(this.mlsTextInput.value.length > 6);
	}
});

/**
 * TODO: These classes and functions below should be merged into the
 * Monroe.Page.MonroePage class above.
 */


//Handles login controls (for both logon and logout).
var login = Class.create({
	initialize: function(){
		this.loginEl = $('login-links');
		
		if (!this.loginEl) return;
		
		this.realtorLoginEl = this.loginEl.down('a[href="#realtor-login"]');
		this.realtorLogoutEl = this.loginEl.down('a[href="#realtor-logout"]');
		this.loginFormEl = $('login-form');
		this.submitFormEl = this.loginFormEl.down('a[href="#submit-login"]');
		this.userNameEl = $('user-name');
		this.passwordEl = $('password');
		this.loginErrorEl = $('login-error');

		var self = this;

		//Watch realtor-login link for toggling form.
		if (this.realtorLoginEl){
			this.realtorLoginEl.observe('click', function(event){
				self.formToggle();
				event.stop();
			});
		}

		//Watch submit-logout link.
		if (this.realtorLogoutEl){
			this.realtorLogoutEl.observe('click', function(event){
				self.logout();
				event.stop();
			});
		}

		//Watch submit-login link.
		if (this.submitFormEl){
			this.submitFormEl.observe('click', function(event){
				self.submitLogin();
				event.stop();
			});
		}

		//Watch for ENTER press while in username and textbox controls.
		if (this.userNameEl){
			[this.userNameEl, this.passwordEl].each(function(inputEl){
				inputEl.observe('keypress', function(event){
					if (event.keyCode==Event.KEY_RETURN){
						self.submitLogin();
						event.stop();
					}
				});
			});
		}
	},
	formToggle: function(){
		Effect.toggle(this.loginFormEl, 'appear', {duration:.5});
	},
	submitLogin: function(){
		var self = this;

		//Init error.
		this.loginErrorEl.update('');

		//Required fields
		if (self.userNameEl.value==''){
			this.loginErrorEl.update('Error: Username is required.');
			return;
		}
		if (self.passwordEl.value==''){
			this.loginErrorEl.update('Error: Password is required.');
			return;
		}

		new Ajax.Request(Monroe.Prop.AppUrl + 'index2.php?json=Login', {
			method: 'Get',
			parameters: {
				username: self.userNameEl.value,
				password: self.passwordEl.value
			},
			onSuccess: function(transport){
				if (transport.responseText.charAt(0)==1) document.location.href = 'http://www.homesplusmonroe.com/profile/';
				else self.loginErrorEl.update('Error: Login failed.');
			}
		});
	},
	logout: function(){
		if (confirm('Are you sure you want to log out?')){
			document.location.href = Monroe.Prop.AppUrl + 'logout';
		}
	}
});

//Functionality for overall search pane.
var sidebarSeach = Class.create({
	initialize: function(){
		this.element = $('quick-search');
		this.cityEl = null;
		this.zipEl = null;

		//Bail early if there is no sidebar.
		if (!this.element) return;

		//Get ref to city and zip fields.
		this.cityEl = $(Monroe.ClientId.City);
		this.zipEl = $(Monroe.ClientId.Zip);

		//Hook up panel behavior.
		var i = 0;
		this.element.select('.quick-search-expand').each(function(divEl){
			new sidebarSeachPanel(divEl, i);
			i++;
		});

		//Hook up Clear button.
		$('btn-search-clear').observe('click', function(){
			this.clear();
		}.bind(this));

		//Watch city and zip for changes.
		this.cityEl.observe('change', function(){
			this.cityChanged();
		}.bind(this));
		this.zipEl.observe('change', function(){
			this.zipChanged();
		}.bind(this));
	},
	cityChanged: function(){
		if (this.cityEl.value != 0) this.zipEl.value = 0;
	},
	zipChanged: function(){
		if (this.zipEl.value != 0) this.cityEl.value = 0;
	},
	clear: function(){
		this.element.select('select').each(function(selectEl){
			selectEl.value = 0;
		});
		this.element.select('input[type=checkbox]').each(function(inputEl){
			inputEl.checked = false;
		});
	}
});
//Functionality for a single div expando control (in the search sidebar).
var sidebarSeachPanel = Class.create({
	initialize: function(divEl, elementNum){
		this.divHeadEl = divEl;
		this.elementNum = elementNum;
		this.linkEl = divEl.down('a');
		this.divBodyEl = divEl.next();
		this.hiddenFieldEl = $(Monroe.ClientId.ExpandedPanels);

		//Attach click behavior to
		this.linkEl.observe('click', function(event){
			this.toggle();
			event.stop();
		}.bind(this));

		//Restore panel state (all hidden initially).
		var ar = this.getPanelStates();
		if (ar[this.elementNum]==1){
			this.divBodyEl.show();
		}
	},
	toggle: function(){
		Effect.toggle(this.divBodyEl, 'Blind', {duration:.25});

		this.savePanelState();
	},
	savePanelState: function(){
		//Get current panel states from hidden field.
		var ar = this.getPanelStates();

		//1 means it expanded. 0 means contracted.
		ar[this.elementNum] = (this.divBodyEl.visible()) ? 0 : 1;

		//Write current panel states to hidden field.
		this.setPanelStates(ar);
	},
	getPanelStates: function(){
		return this.hiddenFieldEl.value.split(',');
	},
	setPanelStates: function(ar){
		this.hiddenFieldEl.value = ar.join(',');
	}
});

Event.observe(window, 'beforeunload', function(){
	try{GUnload()} catch(er){}; //Prevent Google Maps API memory leaks.
});

function setGoogleMap(location){
	if (GBrowserIsCompatible()) {
		var map = new GMap2($('gmap-api'));
		map.addControl(new GSmallMapControl());

		var geocoder = new GClientGeocoder();
		geocoder.getLatLng(
			location,
			function(point){
				if (!point){
					//No Google map found. Hide it!
					$('gmap-api').hide();
				}
				else{
					map.setCenter(point, 13);
					var marker = new GMarker(point);
					map.addOverlay(marker);
				}
			}
		);
	}
}
