//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 formExtra = Class.create({
	initialize: function(options){
		this.options = Object.extend({
			input: null,
			extra: null,
			button: null
		}, options || {});
		this.input = $(this.options.input);
		this.pop = $(this.options.extra);
		this.btn = $(this.options.button);
		this.close = this.pop.select('.exitBTTN')[0];
		this.propTypes = this.pop.select('.qsPropType');
		this.commercial = this.pop.select('.commercialSearchParams')[0];
		this.residential = this.pop.select('.residentialSearchParams')[0];
		this.lot_land = this.pop.select('.lotLandFarmSearchParams')[0];
		this.multiFamily = this.pop.select('.multiFamilySearchParams')[0];
		this.propSections = this.pop.select('.propTypeSection');
		this.priceRange = this.pop.select('.priceRangeField')[0];
		this.buildEvents();
	},
	buildEvents: function(){
		this.propTypes.each(function(el){
			el.observe('click',this.togglePropTypes.bind(this));
			el.observe('focus',this.togglePropTypes.bind(this));
		}.bind(this));
		this.input.observe('focus', this.togglePop.bind(this));
		this.btn.observe('click', this.togglePop.bind(this));
		this.close.observe('click', this.closePop.bind(this));
	},
	togglePropTypes: function(e){
		var el = Event.element(e);
		this.propSections.each(function(t){
			t.hide();
		});
		if(el.checked == true){
			if(el.hasClassName('t-res')){
				this.priceRange.show();
				this.residential.show();
			} else if(el.hasClassName('t-ll')){
				this.lot_land.show();
				this.priceRange.show();
			} else if(el.hasClassName('t-com')){
				this.commercial.show();
				this.priceRange.show();
			} else if(el.hasClassName('t-mf')){
				this.priceRange.show();
				this.multiFamily.show();
			}
		}		
	},
	closePop: function(e){
		this.pop.removeClassName('activePop');
		this.pop.hide();
		this.closeAllPops();
	},
	closeAllPops: function(){
		$$('.activePop').each(function(el){
			el.removeClassName('activePop');
			el.hide();
		});
	},
	togglePop: function(e){
		if(this.pop.hasClassName('activePop')){
			this.closeAllPops();
		}else{
			this.closeAllPops();
			this.pop.addClassName('activePop');
			this.pop.show();
		}
	}	
});
var keywordRotator = Class.create({
	initialize: function(element,options) {
	   this.options = Object.extend({
		   speed: 0.4,
		   timeout: 3000,
		   div: 'slideDiv',
		   inactive: 'inactiveSlide',
		   pause: true,
		   effects: 'blind' //fade
	   }, options || {});
	   this.container = $(element);
	   this.terms = this.container.select('.'+this.options.div);
	   this.paused = false;
	   this.timer = null;
	   this.busy = false;
	   this.currTerm = 0;
	   this.totalTerms = this.terms.length;
	   this.nextTerm = 0;
	   this.lastTerm = 0;
	   var i = 0;
	   this.terms.each(function(el){
		if(i > 0){
			 el.hide();
			 el.removeClassName(this.options.inactive);
		}
		i++;
	   }.bind(this));
	   if(this.options.pause){
		   this.container.observe('mouseover', this.pause.bind(this));
		   this.container.observe('mouseout', this.unpause.bind(this));
	   }
	   this.startup();
	},
	pause: function(e){
	   this.paused = true;
	   this.clearTimer();
	},
	unpause: function(e){
	   this.paused = false;
	   this.setTimer();		
	},
	startup: function(){
	   this.setTimer();
	},
	setTimer: function(){
	   if(!this.paused){
			 this.timer = setTimeout(this.getNextTerm.bind(this), this.options.timeout);
	   }
	},
	clearTimer: function(){
	   clearTimeout(this.timer);
	},
	animate: function(){
	   this.clearTimer();
	   if(this.options.effects == 'fade'){
			 this.terms[this.currTerm].fade({ duration:this.options.speed });
			 this.terms[this.nextTerm].appear({ duration:this.options.speed, afterFinish:function(){ this.setTimer(); }.bind(this) });
	   }else if(this.options.effects == 'blind'){
			 Effect.BlindLeft(this.terms[this.currTerm], {
				    duration:this.options.speed,
				    afterFinish: function(){
						  Effect.BlindRight(this.terms[this.nextTerm], {
								duration:this.options.speed,
								afterFinish:function(){ this.setTimer(); }.bind(this)
						  });
				    }.bind(this)
			 });
	   }
	},
	getNextTerm: function(){
	   this.clearTimer();
	   this.lastTerm = this.currTerm;
	   var roll = (this.nextTerm + 1) == this.totalTerms;
	   this.nextTerm = roll ? 0 : this.nextTerm+1;
	   this.currTerm = roll ? this.totalTerms-1 : this.nextTerm-1;
	   this.animate();
	}
});
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 handleGATrackForm(e) {
	var myFormElement = Event.element(e);
	var myFormAction = '/virtual/goal' + myFormElement.action.replace('http://' + window.location.host,'');
	try{
		pageTracker._trackPageview(myFormAction);					
	}catch(e){}	
}
function selectAll() {
	$$('.SelectAll').each(
		function(iter) {
			for(var i=0; i < iter.options.length; i++) {
				iter.options[i].selected = true;
			}
		}
	);
	return true;	
}
function openLightbox(url){
	   Lightview.show({
		href:url,
		options:{
			 autosize:true
		}
	   });	   
}
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('.removeHeading').each(function(elem){
			elem.hide();
		});
	},
	startup: function() {
		this.closeTabs();
		this.triggers[0].addClassName('active_tab');
		this.content[0].show();
	},
	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 listedByObject = Class.create({
	initialize: function(element){
		this.element = element;				
		this.radios = this.element.select('.prop_listed_by_field');
		this.hidden = this.element.select('.company_only_field')[0];
		this.list = this.element.select('.listing_agent_select_box')[0];
		this.getEvents();
	},
	getEvents: function(){
		this.radios.each(function(el){
			el.observe('click',this.handleClick.bind(this));
			el.observe('focus',this.handleClick.bind(this));
		}.bind(this));
	},
	handleClick: function(e){
		var input = Event.element(e);
		if(input.value == '/company/on/') {
			this.list.hide();
			this.list.selectedIndex = 0;
			this.hidden.value = 'on';
		} else if(input.value == 'choose_agent') {
			this.list.show();
			this.hidden.value = '';
		} else {
			this.list.hide();
			this.list.selectedIndex = 0;
			this.hidden.value = '';
		}
	}
});
function communityJumpMenu(e) {
	if(e.value != '') {
		window.location = e.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 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 onboardJumpMenu(field){
	var zip = field.value;
	var state = 'IA';
	var onboardID = '444-90c0702d320f';
	if(zip != undefined && zip != ''){
		if(Lightview != undefined) {
			Lightview.show({
			  href: "http://www.onboardnavigator.com/webcontent/OBWC_Results.aspx?&AID=" + onboardID + "&Zip=" + zip + "&State=" + state + "&DataType=1",
			  rel: 'iframe',
			  options:{
				width:700,
				height:600,
				topclose:true,
				autosize:true
			  }
			});		
		} else {
			window.location.href = "http://www.onboardnavigator.com/webcontent/OBWC_Results.aspx?&AID=" + onboardID + "&Zip=" + zip + "&State=" + state + "&DataType=1";
		}
	}	
}
function getOnboardData(zip,state){
	var onboardID = '444-90c0702d320f';
	if(Lightview != undefined) {
		Lightview.show({
		  href: "http://www.onboardnavigator.com/webcontent/OBWC_Results.aspx?&AID=" + onboardID + "&Zip=" + zip + "&State=" + state + "&DataType=1",
		  rel: 'iframe',
		  options:{
			width:700,
			height:600,
			topclose:true,
			autosize:true
		  }
		});		
	} else {
		window.location.href = "http://www.onboardnavigator.com/webcontent/OBWC_Results.aspx?&AID=" + onboardID + "&Zip=" + zip + "&State=" + state + "&DataType=1";
	}
}
Effect.BlindRight = function(element) {
  element = $(element);
  var elementDimensions = element.getDimensions();
  return new Effect.Scale(element, 100, Object.extend({    
    scaleContent: false,
    scaleY: false,
    scaleFrom: 0,
    scaleMode: {originalHeight: elementDimensions.height, originalWidth: elementDimensions.width},
    restoreAfterFinish: true,
    afterSetup: function(effect) {
    effect.element.makeClipping().setStyle({width: '0px'}).show();
    },  
    afterFinishInternal: function(effect) {
      effect.element.undoClipping();
    }
  }, arguments[1] || { }));
};
Effect.BlindLeft = function(element) {
  element = $(element);
  element.makeClipping();
  return new Effect.Scale(element, 0,
    Object.extend({ scaleContent: false,
      scaleY: false,
      restoreAfterFinish: true,
      afterFinishInternal: function(effect) {
        effect.element.hide().undoClipping();
      }
    }, arguments[1] || { })
  );
};
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(){
		var w = document.viewport.getWidth() / 2;
		if(this.loggedIn){
			this._account_links.setStyle({
				left: (w + 280) + 'px'
			});
		}else{
			this.formWrapper.setStyle({
				left: (w + 280) + 'px'
			});
		}
		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();
	}
});
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() {
		//popup window script
		$$( "a.PopupWin" ).each(function(el){new GenericPopupWindow(el);});
		//var sliderInstance = new slides();
		$$('form.goalTrack').each(function(formEl){
			formEl.observe('submit',handleGATrackForm);
		});
		if($('account_login_btn')){
			var login_obj = new fancy_login({
				form: 'account_login_ajax',
				replace_html: 'WELCOME, {name}',
				trigger_text: 'My Account'
			});
		}
	});
} else {
	throw('Prototype 1.6 or greater is not loaded! Some features may not function with a lesser version.');
}