//GENERIC POPUPWINDOW CLASS
var GenericPopupWindow = Class.create();
GenericPopupWindow.default_width = 600;
GenericPopupWindow.default_height = 500;
GenericPopupWindow.scrolling = false;
GenericPopupWindow.prototype = {
	initialize: function( el ){
		this.el = el;
		this.winCount = 0;
		//super fancy regular expression width and height for popup class. -James
		this.classes = this.el.readAttribute('class');
		if(this.classes.indexOf('pop_w') > 0){
			var myRe = /(pop_w_)[0-9]*/;
			var myRe2 = /(pop_h_)[0-9]*/;
			var tempRe = myRe.exec(this.classes);
			var tempRe2 = myRe2.exec(this.classes);
			if(tempRe != null && tempRe2 != null){
				this.width = tempRe[0].replace(tempRe[1],'');
				this.height = tempRe2[0].replace(tempRe2[1],'');
			} else {
				this.width = null;
				this.height = null;
			}
		}
		if(this.width == null){
			this.width = ( this.el.hasAttribute('win_width') ? this.el.attributes['win_width'].value : GenericPopupWindow.default_width );
		}
		if(this.height == null){
			this.height = ( this.el.hasAttribute('win_height') ? this.el.attributes['win_height'].value : GenericPopupWindow.default_height );
		}
		this.scrolling = ( this.el.hasAttribute('scrolling') ? this.el.attributes['scrolling'].value : GenericPopupWindow.scrolling );
		Event.observe( this.el, 'click', this.clicked.bindAsEventListener( this ) );
	},
	clicked: function( event ){
		if(this.scrolling == '1'){
			window.open(this.el.href, "win"+this.winCount++, "width="+this.width+",height="+this.height+",resizable=1,scrollbars=1");
		} else {
			window.open(this.el.href, "win"+this.winCount++, "width="+this.width+",height="+this.height+",resizable=1");
		}
		try{
			Event.stop( event );
		}catch( e ){
		}
	}
}
var checkboxManager = Class.create({
	initialize: function(element) {
		this.element = element;
		this.boxes = this.element.select('input');
		this.allbox = this.element.select('.checkbox_all')[0];
		this.initEventHandlers();
	},
	initEventHandlers: function() {
		this.boxes.each(function(elem){elem.observe('click',this.handleClick.bind(this))}.bind(this));
	},
	handleClick: function(e) {
		var ele = Event.element(e);
		if(ele.hasClassName('checkbox_all')) {
			this.boxes.each(function(elem){elem.checked = false});
			this.allbox.checked = true;
		}else{
			this.allbox.checked = false;
		}
	}
});
var tab_object = Class.create({
	initialize: function(container) {
		this.container = $(container);
		this.triggers = this.container.select('.tab_triggers li');
		this.triggersA = this.container.select('.tab_triggers li a');
		this.content = this.container.select('.tab_item');
		this.onLoad();
		this.startup();
	},
	onLoad: function() {
		var i = 0;
		this.triggers.each(function(elem){
			elem.writeAttribute('tab',i);
			elem.observe('click',this.handleToggle.bind(this));
			i++;
		}.bind(this));
		this.triggersA.each(function(elem){
			elem.observe('click',this.handleToggle.bind(this));
		}.bind(this));
		this.container.select('h2.removeHeading').each(function(elem){
			elem.hide();
		});
	},
	startup: function() {
		this.closeTabs();
		this.triggers[0].addClassName('active_tab');
		this.content[0].show();
	},
	openTabByID: function(id){
		var t = $(id);
		if(t != undefined){
			var tnum = null;
			try{
				tnum = parseInt(t.up('li').readAttribute('tab'));
			} catch (e){}
			if(tnum != null){			
				this.openTab(tnum);
			}
		}		
	},
	closeTabs: function(){
		this.content.each(function(elem){
			elem.hide();
		});
		this.resetTriggers();
	},
	openTab: function(num) {
		this.closeTabs();
		this.triggers[num].addClassName('active_tab');
		this.content[num].show();		
	},
	jumpToTab: function(id,num) {
		this.closeTabs();
		this.triggers[num].addClassName('active_tab');
		this.content[num].show();
		Effect.ScrollTo(id);
	},
	resetTriggers: function(){
		this.triggers.each(function(elem){
			elem.removeClassName('active_tab');
		});
	},
	handleToggle: function(e){
		var tab = Event.element(e);
		if(!tab.hasClassName('dontstop')){
			Event.stop(e);
		}
		if(tab.readAttribute('tab') == undefined) {
			tab = tab.up();
		}
		this.closeTabs();
		tab.addClassName('active_tab');
		var tmp = parseInt(tab.readAttribute('tab'));
		try {
			this.content[tmp].show();
		} catch(e) {
			this.openTab(0);
		};
	}
});
var formFocusHelpTxt = Class.create({
	initialize: function() {
		this.elements = $$('.replace_focus');
		if(this.elements.length > 0){
			this.elements.each(function(el) {
				el.observe('blur',this.checkFieldValueBlur.bind(this));
				el.observe('focus',this.checkFieldValueFocus.bind(this));
			}.bind(this));
		}
	},
	checkFieldValueFocus: function(e){
		var field = e.element();
		var helpTxt = field.readAttribute('title');
		if(helpTxt != null && field.value == helpTxt) {
			field.value = '';
		}
	},
	checkFieldValueBlur: function(e){
		var field = e.element();
		var helpTxt = field.readAttribute('title');
		if(helpTxt != null && field.value == '') {
			field.value = helpTxt;
		}
	}
});
var fancy_login = Class.create({
	initialize: function(options) {
		this.options = Object.extend({
			trigger: 'account_login_btn',
			formID: 'account_login_ajax',
			formWrapper: 'account_login_form',
			account_links: 'account_action_urls',
			welcome: 'welcome_txt',
			close: 'fancy_close',
			error_block: 'login_ajax_error',
			replace_html: '<span>WELCOME, {name}</span>',
			trigger_text: null,
			removeNode: 'signUpNode'
		}, options || {});
		this._trigger = $(this.options.trigger);
		this.formWrapper = $(this.options.formWrapper);
		this.loggedIn = true;
		this._error = $(this.options.error_block);
		this._account_links = $(this.options.account_links);
		this.onLoad();
	},
	onLoad: function() {
		if(this.formWrapper != undefined){
			this.loggedIn = false;
			Event.observe(this.options.formID, 'submit', this.sendRequest.bind(this));
		}
		$$('.'+this.options.close).each(function(element){element.observe('click',this.handleClickEvent.bind(this));}.bind(this));
		this._trigger.observe('click',this.handleClickEvent.bind(this));
	},
	handleClickEvent: function(e) {
		Event.stop(e);
		this.toggleView();
	},
	toggleView: function(){
		if(this.loggedIn){
			Effect.toggle(this._account_links, 'slide', {duration:0.4});
		}else{
			Effect.toggle(this.formWrapper, 'slide', {duration:0.4});
		}
	},
	sendRequest: function(e) {
		Event.stop(e);
		var el = Event.element(e);
        var ajaxRequest = new Ajax.Request(el.action, {
			method: el.method,
			parameters: Form.serialize(el), 
			asynchronous: true,
			onSuccess: this.showResponse.bind(this),
			onFailure: this.showError.bind(this)
        });
	},
	showResponse: function(data){
		if(data.headerJSON.status_code == 0) {
			this._error.show();
		} else if(data.headerJSON.status_code > 0) {
			this.toggleView();
			this.loggedIn = true;
			try{
				$(this.options.welcome).update(this.options.replace_html.replace('{name}', data.headerJSON.user.name));
				Event.observe(this.options.trigger, 'click',this.handleClickEvent.bind(this));
			} catch(e) {}			
			if( this.options.trigger_text != null ) {
				try{
					$(this.options.trigger).update(this.options.trigger_text);
				} catch(e) {}
				if($(this.options.removeNode)) {
					try{
						$(this.options.removeNode).remove();
					} catch(e) {}
				}
			}
		}
	},
	showError: function(data){
		this._error.show();
	}
});
var sidebarExpand = Class.create({
	initialize: function(element,options) {
		this.options = Object.extend({
			trigger: 'h3',
			trigger_active: 'active',
			content: 'sidebarItem',
			images: new Array('/images/sidebar_plus.gif','/images/sidebar_minus.gif')
		}, options || {});
		this.container = $(element);
		if(this.container != undefined) {
			if(document.images) {
				var image = new Image();
				for(var j = 0; j < this.options.images.length; j++) {
					image.src = this.options.images[j];
				}
			}
			this.triggers = this.container.select(this.options.trigger);
			this.content = this.container.select('.' + this.options.content);
			var i=0;
			this.triggers.each(function(el){
				el.writeAttribute('tab',i);
				el.observe('click',this.handleClickEvent.bind(this));
				i++;
			}.bind(this));
		} else {
			return;
		}
	},
	handleClickEvent: function(e){
		var el = Event.element(e);
		var tab = parseInt(el.readAttribute('tab'));
		if(el.hasClassName(this.options.trigger_active)) {
			el.removeClassName(this.options.trigger_active);
			try {
				this.content[tab].hide();
			} catch(e) {}
		} else {
			el.addClassName(this.options.trigger_active);
			try {
				this.content[tab].show();
				this.content[tab].fire("sidebar:expand", { opened: this.content[tab].readAttribute('opened') });
				this.content[tab].writeAttribute('opened','true');
			} catch(e) {}
		}
	}
});
function ajaxRequest(url,element){
	var ajaxRequest = new Ajax.Request(url, {
		method: 'get',
		asynchronous: true,
		onSuccess: function(data){
			element.update(data.responseText);
		}
	});
}
//observe sidbar events to load ajax components!!!!
/*
document.observe("sidebar:expand", function(event) {
	if(event.target.id != null && event.target.id != '' && event.memo.opened == null) {
		switch(event.target.id) {
			case 'sidebarFeaturedProperty':
				ajaxRequest('/render_component/FeaturedProperty/content?count=4', $(event.target.id).select('.ajaxContent')[0]);
				break;		
			case 'sidebarPropertySearch':
				ajaxRequest('/render_component/PropertySearch/content?search_url=/NewToMarket/1/&results=4', $(event.target.id).select('.ajaxContent')[0]);
				break;		
			case 'sidebarNewlyReduced':
				ajaxRequest('/render_component/dropin/NewlyReduced/content?count=4', $(event.target.id).select('.ajaxContent')[0]);
				break;		
		}	
	}  
});
*/
/*
	*lazyLoadComponent --function to lazy load components
	*onclick="lazyLoadComponent('NewlyReducedSearchContainer','NewlyReduced/content?count=4');"
	*@_elementID string id of wrapper for the component to load into
	*@_string string name of component used along with full query options in the switch within function
*/  
function lazyLoadComponent(_elementID, _string){
	var _componentContainer = $(_elementID);
	var _loadingWheelUrl = '/images/ajax-gold.gif';
	if(_componentContainer !== undefined && !_componentContainer.hasClassName('renderSuccess') && _string !== ''){
		$$('.lazyComponentErrorMessage').invoke('remove');
		_componentContainer.insert({bottom:'<img style="margin:15px;" class="lazyComponentLoadWheel" alt="loading..." src="' + _loadingWheelUrl + '" />'});
		var ajaxRequest = new Ajax.Request('/render_component/' + _string, {
			method: 'post',
			asynchronous: true,
			onSuccess: function(data){
				$$('.lazyComponentLoadWheel').invoke('remove');
				_componentContainer.insert({bottom:data.responseText});
				_componentContainer.addClassName('renderSuccess');
			},
			onFailure: function(data){
				$$('.lazyComponentLoadWheel').invoke('remove');
				_componentContainer.insert({bottom:'<p class="lazyComponentErrorMessage">Error retrieving search component. Please try again in a moment.</strong>'});
			}
		});
	}
}	
function slideRemarks(a, id){
	var remark = $(id);
	if(remark != undefined){
		Effect.toggle(remark, 'blind', {duration:0});		
		if(!remark.visible()){
			a.update(' Less');
		} else {
			a.update('...More');
		}
	}
	
}
function closeQuickSearch(ele){
	$(ele).hide();
}
function openQuickSearch(){
	var ele = $('quick_search_home_expand');
	if(!ele.visible()) {
		var eleHeight = 62;
		ele.setStyle({top:eleHeight+'px'});
		ele.show();
	} else {
		ele.hide();
	}
}
function expandSearchNarrowers(el){
	var searchDiv = $('MoreSearchOptionsBlock');
	Effect.toggle(searchDiv, 'blind', {duration:0.4, beforeStart: function(){
		if(!searchDiv.visible()){
			$('refineSubmit').hide();
			el.addClassName('closeNarrower')
			el.update('Less Search Options');
		}else{
			el.removeClassName('closeNarrower');
			$('refineSubmit').show();
			el.update('More Search Options');
		}
	}
	});
}
function SearchManageTypeSearchForm(){
	var _rent = $('pricingBlock2');
	var _normal = $('pricingBlock');
	var _el = $('propTypeID112');
	if(_el != undefined && _el.checked == true){
		try{$('as_Min_Price').name = 'null';} catch(e){};
		try{$('as_Max_Price').name = 'null';} catch(e){};
		try{$('as_Min_Price2').name = 'Min_Price';} catch(e){};
		try{$('as_Max_Price2').name = 'Max_Price';} catch(e){};
		try{_rent.show();}catch(e){};
		try{_normal.hide();}catch(e){};		
	} else {
		try{$('as_Min_Price2').name = 'null';} catch(e){};
		try{$('as_Max_Price2').name = 'null';} catch(e){};
		try{$('as_Min_Price').name = 'Min_Price';} catch(e){};
		try{$('as_Max_Price').name = 'Max_Price';} catch(e){};
		try{_rent.hide();}catch(e){};
		try{_normal.show();	}catch(e){};	
	}
}
function SearchManageTypeSearchNarrower(){
	var _rent = $('sn_rentalPrice');
	var _normal = $('sn_normalPrice');
	var _el = $('propTypeID112');
	if(_el != undefined && _el.checked == true){
		try{$('sn_Min_Price').name = 'null';} catch(e){};
		try{$('sn_Max_Price').name = 'null';} catch(e){};
		try{$('sn_Min_Price2').name = 'Min_Price';} catch(e){};
		try{$('sn_Max_Price2').name = 'Max_Price';} catch(e){};
		try{_rent.show();}catch(e){};
		try{_normal.hide();}catch(e){};		
	} else {
		try{$('sn_Min_Price2').name = 'null';} catch(e){};
		try{$('sn_Max_Price2').name = 'null';} catch(e){};
		try{$('sn_Min_Price').name = 'Min_Price';} catch(e){};
		try{$('sn_Max_Price').name = 'Max_Price';} catch(e){};
		try{_rent.hide();}catch(e){};
		try{_normal.show();	}catch(e){};	
	}
}

function quickSearchPriceWatch(el,rent,normal){
	var _rent = $(rent);
	var _normal = $(normal);
	if(el.value == '112'){
		try{$('qs_Min_Price').name = 'null';} catch(e){};
		try{$('qs_Max_Price').name = 'null';} catch(e){};
		try{$('qs_Min_Price2').name = 'Min_Price';} catch(e){};
		try{$('qs_Max_Price2').name = 'Max_Price';} catch(e){};
		try{_rent.show();}catch(e){};
		try{_normal.hide();}catch(e){};		
	} else {
		try{$('qs_Min_Price2').name = 'null';} catch(e){};
		try{$('qs_Max_Price2').name = 'null';} catch(e){};
		try{$('qs_Min_Price').name = 'Min_Price';} catch(e){};
		try{$('qs_Max_Price').name = 'Max_Price';} catch(e){};
		try{_rent.hide();}catch(e){};
		try{_normal.show();	}catch(e){};	
	}
}
function managePricesLX(el,rent,normal){
	var _rent = $(rent);
	var _normal = $(normal);
	if(el.value == '112'){
		try{$('luxury_Min_Price').name = 'null';} catch(e){};
		try{$('luxury_Min_Price2').name = 'Min_Price';} catch(e){};
		try{_rent.show();}catch(e){};
		try{_normal.hide();}catch(e){};		
	} else {
		try{$('luxury_Min_Price2').name = 'null';} catch(e){};
		try{$('luxury_Min_Price').name = 'Min_Price';} catch(e){};
		try{_rent.hide();}catch(e){};
		try{_normal.show();	}catch(e){};	
	}
}
// fire static map function
function runStaticMap() {
	if(!$('static_map_instance').hasClassName('StaticMap')){
		$('static_map_instance').addClassName('StaticMap');
		try{
			StaticMapInstance.run();
		} catch(e){}
	}
}
function selectJumpMenu(e) {
	var el = Event.element(e);
	if(el.value != '') {
		window.location = el.value;
	}
}
function expandSocialNetworks(e){
	Event.stop(e);
	var elm = Event.element(e);
	var myNetworks = $$('li.socialNetworksExtra');
	if(myNetworks[0].visible()){
		elm.update('View All');
		elm.title = 'View All';
	} else {
		elm.update('View Less');
		elm.title = 'View Less';
	}
	myNetworks.each(function(el){
		if(el.visible()){
			el.hide();
		} else {
			el.show();
		}
	});
}
function expandOpenHouse(trig,ele){
	var myDiv = $(ele);
	if(myDiv.visible()){
		Effect.BlindUp(myDiv,{duration:0.4});
		trig.removeClassName('activeOpenHouse');
	} else {
		Effect.BlindDown(myDiv,{duration:0.4});
		trig.addClassName('activeOpenHouse');
	}
}
function selectAll() {
	$$('.SelectAll').each(
		function(iter) {
			for(var i=0; i < iter.options.length; i++) {
				iter.options[i].selected = true;
			}
		}
	);
	return true;	
}
function companyonhack(e){
	var el = e.element();
	var agent_box = $('listing_agent_select_box');
	var hidden_owner_field = $('company_only_field');
	if(el.checked == true) {
		agent_box.hide();
		agent_box.selectedIndex = 0;
		hidden_owner_field.value = 'on';
		$$('.prop_listed_by_field').each(function(item){
			item.checked = false;
		});
		$('ASBottomSearchCompany').checked = true;
	} else {
		$('ASBottomSearchCompany').checked = false;
		hidden_owner_field.value = '';
	}
}
function refineCompanyHack(e){
	var el = e.element();
	if(el.checked == true) {
		var myElem = $$('input[name="Listing_Agent"]')[0];
		var myElem2 = $$('input[name="owner_only"]')[0];
		if(myElem != undefined) {
			myElem.value = '';	
		}
		if(myElem2 != undefined) {
			myElem2.value = '';
		}
	}
}
function  prop_listed(e){
	var el = e.element();
	var topCheck = $('ASCompany');
	var agent_box = $('listing_agent_select_box');
	var hidden_owner_field = $('company_only_field');
	if(el.value == '/company/on/') {
		topCheck.checked=true;
		agent_box.hide();
		agent_box.selectedIndex = 0;
		hidden_owner_field.value = 'on';
	} else if(el.value == 'choose_agent') {
		agent_box.show();
		topCheck.checked=false;
		hidden_owner_field.value = '';
	} else {
		agent_box.hide();
		topCheck.checked=false;
		agent_box.selectedIndex = 0;
		hidden_owner_field.value = '';
	}
}
function showWhatForm(){
	var element = $('natureOfContact');
	var formID = $('propDetailsForm1');
	var containers = $$('.form_section');
	containers.each(function(elem){elem.hide();});
	if(element.selectedIndex == 1){
		formID.action = requestInfo;
	}else if(element.selectedIndex == 2){
		formID.action = scheduleLocation;
	}else if(element.selectedIndex == 3){
		formID.action = similarAction;
	}else{
		formID.action = requestInfo;
	}
	try{
		containers[(element.selectedIndex - 1)].show();
	} catch(e){}
}
function handleGATrackForm(e) {
	var myFormElement = Event.element(e);
	var myFormAction = '/virtual/goal' + myFormElement.action.replace('http://' + window.location.host,'');
	try{
		pageTracker._trackPageview(myFormAction);					
	}catch(e){}	
}

if(parseFloat(Prototype.Version) >= 1.6) {
	//if we have prototype 1.6 than we use this event because it's faster!
	document.observe("dom:loaded", function() {
		//removes type hint text on form text fields
		new formFocusHelpTxt();
		//account login
		if($('account_login_btn')){
			var login_obj = new fancy_login({
				form: 'account_login_ajax',
				replace_html: 'WELCOME, {name}',
				trigger_text: 'My Account'
			});
		}
		//popup window script
		$$( "a.PopupWin" ).each(function(el){new GenericPopupWindow(el);});
		//search form observers
		if($('qs_AddressAndLoc')) {
			$('qs_AddressAndLoc').observe('focus',openQuickSearch);
		}
		if($('qsSb_AddressAndLoc')) {
			$('qsSb_AddressAndLoc').observe('focus',openQuickSearch);
		}
		if($('ASCompany')) {
			$('ASCompany').observe('click',companyonhack);
		}
		if($('snCompany')) {
			$('snCompany').observe('click',refineCompanyHack);
		}
		//sidebar community jump dropdown
		if($('communityJumpMenu')) {
			$('communityJumpMenu').observe('change',selectJumpMenu);
		}
		$$('form.goalTrack').each(function(formEl){
			formEl.observe('submit',handleGATrackForm);
		});
	});
} else {
	Event.observe(window, 'load', function() {
		$$( "a.PopupWin" ).each(function(el){new GenericPopupWindow(el);});
	});
	if($('communityJumpMenu')) {
		$('communityJumpMenu').observe('change',selectJumpMenu);
	}
	throw('Prototype 1.6 or greater is not loaded! Some features may not function with a lesser version.');
}
