//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;
		this.width = ( this.el.hasAttribute('win_width') ? this.el.attributes['win_width'].value : GenericPopupWindow.default_width );
		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 ){
			return false;
		}
	}
}
//CLASS DEFINITIONS
var viewSwap = Class.create({
	initialize: function(element) {
		this.element = element;
		this.containerID = $(this.element.attributes['rel'].nodeValue);
		this.initEventHandlers();
		this.addStyles();
	},
	initEventHandlers: function() {
		this.element.observe('click',this.handleClick.bind(this));
		
	},
	addStyles: function() {
		$$('img.viewTrigger').each(function(elem){
			elem.setStyle({
				cursor:'pointer'
			})
		});
	},
	handleClick: function(e) {
		var currentVisibleIcon = $$('img.selected')[0];
		var currentVisibleView = $(currentVisibleIcon.attributes['rel'].nodeValue);
		if(currentVisibleIcon != this.element){
			this.fixPagingLinks(this.element.attributes['rel'].nodeValue);
			currentVisibleIcon.removeClassName('selected');
			this.element.addClassName('selected');
			currentVisibleView.fade({ duration: .5});
			this.containerID.appear({ duration: 1});
		}
	},
	fixPagingLinks: function(viewname) {
		$$('a.resultsLink').each(function(elem){
			if(elem.href.match(/useView=\w+/) != null){
				elem.href = elem.href.replace(/useView=\w+/, 'useView=' + viewname);
			}else{
				elem.href = elem.href + '?useView=' + viewname;	
			}
		});
	}	
});
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') && ele.checked== true) {
			this.boxes.each(function(elem){elem.checked = false});
			this.allbox.checked = true;
		}else{
			this.allbox.checked = false;
		}
	}
});
var quickSearchElement = Class.create({
	initialize: function(element) {
		this.element = $(element);
		this._buttons = this.element.select('.quickHubButton');
		this._containers = this.element.select('.quickSearchContentSection');
		this.initEventHandlers();
	},
	initEventHandlers: function() {
		this._buttons.each(function(elem){
			elem.observe('click',this.handleClick.bind(this));
		}.bind(this));
	},
	handleClick: function(e) {
		this.closeElements();
		var ele = Event.element(e);
		try{
			ele.up('.quickHubButton').addClassName('quickHubButtonActive');
		}catch(e){
			//console.log(e)
		}
		try{
			$(ele.up('.quickHubButton').readAttribute('rel')).show();
		}catch(e){
			//console.log(e);
		}
	},
	closeElements: function() {
		this._containers.each(function(elem){
			elem.hide();
		});
		this._buttons.each(function(elem){
			elem.removeClassName('quickHubButtonActive');
		});	
	}
});
var jo_tooltip = Class.create({
	initialize: function(_useclass,options) {
		this.options = Object.extend({
			openDelay:8,
			skinID: 'jo_tooltipCont',
			tipContentID: 'jo_tooltipDynamicContent',
			stemID: 'jo_tooltip_stem',
			tipTopID: 'jo_tooltipTop',
			tipInnerID: 'jo_tooltipInnerContainer',
			tipBottomID: 'jo_tooltipBottom',
			onOpen: Prototype.emptyFunction,
			effect:false,
			onEvent:'mouseover',
			offEvent:'mouseout',
			useStem:false,
			stemHeight: 0,
			stemBuffer: 0,
			offset:{x:0,y:0},
			hook:{tipPosition:'middleRight'},
			stemClasses: ['tl','tr','br','bl']
		}, options || {});
		this.hook = this.options.hook.tipPosition;
		this.timer = null;
		this.tipIDExtended = null;
		this._stemID = null
		this._top = null;
		this._left = null;
		this._dynamicContentID = null;
		this._viewportDimensions = null;
		this._elementViewport = null;
		this._viewportScroll = null;
		this.isOpen = false;
		this.buildTip();
		var tooltip = $$('.' + _useclass);
		tooltip.each(function(elem){
			elem.observe(this.options.onEvent,this.handleOpenEvent.bind(this))
			elem.observe(this.options.offEvent,this.handleCloseEvent.bind(this))
		}.bind(this));
	},
	buildTip: function(){
		var lw = document.createElement('div');
		var bodyElement = document.getElementsByTagName('body')[0];
		var skin = 
			'<div id="' + this.options.skinID + '">'
				+	'<div id="' + this.options.tipInnerID + '">'
					+	'<div id="' + this.options.tipTopID + '">&nbsp;</div>'
					+ 	'<div id="' + this.options.tipContentID + '">&nbsp;</div>'
					+	'<div id="' + this.options.tipBottomID + '">&nbsp;</div>'
		if(this.options.useStem == true){
			skin += '<div id="' + this.options.stemID + '" class="' + this.options.stemClasses[3] + '">&nbsp;</div>';
		}
		skin += 	'</div>'	
			+'</div>';
		lw.innerHTML = skin;
		bodyElement.appendChild(lw);
		this.tipIDExtended = $(this.options.skinID);
		this._dynamicContentID = $(this.options.tipContentID);
		if(this.options.useStem == true){
			this._stemID = $(this.options.stemID);
		}
		try{
			bodyElement.observe('click',this.handleCloseEvent.bind(this));
			bodyElement.observe('mouseover',this.handleCloseEvent.bind(this));
		}catch(e){
			document.body.onclick = function(e){
				this.handleCloseEvent(e);
			}.bind(this);
			document.body.mouseover = function(e){
				this.handleCloseEvent(e);
			}.bind(this);
		}
	},
	makeCalculations: function(tip,target){
		var _max_y = this._viewportDimensions.height + this._viewportScroll.top;
		var _max_x = this._viewportDimensions.width + this._viewportScroll.left;
		this.stemClassReset();
		var bumpup = false;
		var bumpside = false;
		var oldheight = null;
		var stemTop = null;
		switch(this.hook){
			case 'topLeft': 
				this._top = this.options.offset.y + ( ( -1 * ( tip.height - target.height ) ) + this._elementViewport.top + this._viewportScroll.top );
				this._left = this.options.offset.x + (-1 * tip.width) + this._elementViewport.left + this._viewportScroll.left;
				if( this._left < 0){
					this._left = this.options.offset.x + (target.width) + this._elementViewport.left + this._viewportScroll.left;
				}
				break;
			case 'topRight':
				this._top = this.options.offset.y + ( ( -1 * ( tip.height - target.height ) ) + this._elementViewport.top + this._viewportScroll.top );
				this._left = this.options.offset.x + target.width + this._elementViewport.left + this._viewportScroll.left;
				if( ( this._left + tip.width ) > _max_x){
					this._left = this._elementViewport.left + this._viewportScroll.left + ( -1 * tip.width ) - this.options.offset.x;
				}
				break;
			case 'bottomLeft':
				this._top = this.options.offset.y + target.height + this._elementViewport.top + this._viewportScroll.top;
				this._left = this.options.offset.x + (-1 * tip.width) + this._elementViewport.left + this._viewportScroll.left;
				if( this._left < 0){
					this._left = this.options.offset.x + (target.width) + this._elementViewport.left + this._viewportScroll.left;
				}
				if( ( this._top + tip.height ) > _max_y){
					this._top = _max_y - tip.height;
				}
				break;
			case 'bottomRight':
				this._top = this.options.offset.y + (-1 * target.height) + this._elementViewport.top + this._viewportScroll.top;
				this._left = this.options.offset.x + target.width + this._elementViewport.left + this._viewportScroll.left;
				if( ( this._left + tip.width ) > _max_x){
					this._left = this._elementViewport.left + this._viewportScroll.left + ( -1 * tip.width ) - this.options.offset.x;
				}
				if( ( this._top + tip.height ) > _max_y){
					this._top = _max_y - tip.height;
				}
				break;
			case 'middleRight':
				this._top = this.options.offset.y + ( target.height + ( -1 * ( tip.height / 2 ) ) + this._elementViewport.top + this._viewportScroll.top );
				this._left = this.options.offset.x + target.width + this._elementViewport.left + this._viewportScroll.left;
				if( ( this._top + tip.height ) > _max_y){
					oldheight = this._top;
					this._top = _max_y - tip.height;
					bumpup = true;
				}
				if( ( this._left + tip.width ) > _max_x){
					this._left = this._elementViewport.left + this._viewportScroll.left + ( -1 * tip.width ) - this.options.offset.x + 14;
					bumpside = true;
				}
				if(this.options.useStem == true){
					if(bumpup == true && bumpside == false){
						stemTop = (tip.height / 2) + (oldheight - this._top) - (this.options.stemHeight / 2);
						if(stemTop > tip.height - this.options.stemBuffer - (this.options.stemHeight / 2)){
							stemTop = tip.height - this.options.stemBuffer - (this.options.stemHeight / 2);
						}
						this.positionStem( stemTop , 3);
					}else if(bumpup == false && bumpside == true){
						this.positionStem((tip.height / 2) - (this.options.stemHeight / 2) , 2);
					}else if(bumpup ==true && bumpside == true){
						stemTop = (tip.height / 2) + (oldheight - this._top) - (this.options.stemHeight / 2);
						if(stemTop > tip.height - this.options.stemBuffer - (this.options.stemHeight / 2)){
							stemTop = tip.height - this.options.stemBuffer - (this.options.stemHeight / 2);
						}
						this.positionStem(stemTop , 2);
					}else{
						this.positionStem((tip.height / 2) - (this.options.stemHeight / 2) , 3);
					}
				}
				break;
			case 'middleLeft':
				this._top = this.options.offset.y + ( target.height + ( -1 * ( tip.height / 2 ) ) + this._elementViewport.top + this._viewportScroll.top );
				this._left = this.options.offset.x + (-1 * tip.width) + this._elementViewport.left + this._viewportScroll.left;
				if( ( this._top + tip.height ) > _max_y){
					this._top = _max_y - tip.height;
				}
				if( this._left < 0){
					this._left = this.options.offset.x + (target.width) + this._elementViewport.left + this._viewportScroll.left;
				}
				break;
		}
	},
	stemClassReset: function(){
		if(this.options.useStem == true){
			this.options.stemClasses.each(function(elem){
				this._stemID.removeClassName(elem);
			}.bind(this));
		}
		return;
	},
	positionStem: function(theY,theclass){
		this._stemID.addClassName(this.options.stemClasses[theclass]);
		this._stemID.setStyle({
			top: theY + 'px'
		});
		return;
	},
	getWindow: function(element){
		this._viewportDimensions = document.viewport.getDimensions();
		this._elementViewport = element.viewportOffset();
		this._viewportScroll = document.viewport.getScrollOffsets();		
	},
	handleOpenEvent: function(e){
		var elem = Event.element(e);
		if(this.options.onEvent == 'click'){
			Event.stop(e);
		}
		if(this.timer != null){
			clearTimeout(this.timer);
			this.timer = null;
		}
		this.timer = setTimeout(function(){
			this.timer = null;
			if(this.isOpen == false){
				this.isOpen = true;
				var tipDim = this.tipIDExtended.getDimensions();
				var triggerDim = elem.getDimensions();			
				this.getWindow(elem);		
				this.makeCalculations(tipDim,triggerDim);
				this.tipIDExtended.setStyle({
					top:this._top + 'px',
					left:this._left + 'px',
					display:'block'
				});
				this.options.onOpen(elem,this._dynamicContentID);		
			}
		}.bind(this),800);
	},
	handleCloseEvent: function(e){
		if(this.options.offEvent == 'click'){
			Event.stop(e);
		}
		if(this.isOpen == true || this.tipIDExtended.visible()){
			this.isOpen = false;
			this.tipIDExtended.hide();
		}
	}
});
var sidebarAccordion = Class.create({
	initialize: function(element,options) {
		this.element = $(element);
		this.options = Object.extend({
			resizeSpeed : 8,
			classNames:{
				toggle:'sidebar_accordion_toggle',
				toggleActive:'sidebar_accordion_toggle_active',
				content:'sidebar_accordion_content',
				contentActive:'sidebar_accordion_content_active',
				onlyOneOpen: 'onlyOneOpen'
			},
			defaultSize:{
				height:null,
				width:null
			},
			onEvent : 'click'
		}, options || {});			
		this.duration = ((11-this.options.resizeSpeed)*0.15);
		this.inTransition = false;
		if(this.element.hasClassName(this.options.classNames.onlyOneOpen)){
			this.onlyOneOpen = true;
		}else{
			this.onlyOneOpen = false;
		}
		var accordions = this.element.select('.' + this.options.classNames.toggle);
		accordions.each(function(elem){
			var t = elem.next();
			if(!t.hasClassName(this.options.classNames.contentActive)){
				t.setStyle({
					height: '0px',
					display: 'none'
				});
			}
			elem.observe(this.options.onEvent,this.handleToggle.bind(this))
		}.bind(this));
	},
	activate: function(elem) {
		var cont = elem.up('h2').next('.' + this.options.classNames.content);
		var trig = elem.up('h2');
		var imgElem = trig.down();
		imgElem.src = imgElem.readAttribute('openedImg');
		cont.setStyle({display: 'block'});
		this.inTransition = true;
		trig.addClassName(this.options.classNames.toggleActive);
		new Effect.Scale(
			cont,
			100,
			{
				duration:this.duration,
				scaleContent:false,
				scaleFrom:0,
				scaleX:false,
				scaleY:true,
				scaleMode:
				{
					originalHeight: this.options.defaultSize.height ? this.options.defaultSize.height : cont.scrollHeight,
					originalWidth: this.options.defaultSize.width ? this.options.defaultSize.width : cont.scrollWidth
				},
				afterFinish: function(){
					this.inTransition = false
					cont.addClassName(this.options.classNames.contentActive)
					cont.setStyle({
						height:'auto'
					})
				}.bind(this)
				
			}
		);
		return true;
	},
	deActivate: function(elem) {
		var cont = elem.up('h2').next('.' + this.options.classNames.content);
		var trig = elem.up('h2');
		var imgElem = trig.down();
		imgElem.src = imgElem.readAttribute('closedImg');
		trig.removeClassName(this.options.classNames.toggleActive);	
		new Effect.Scale(
			cont,
			0,
			{
				duration:this.duration,
				scaleContent:false,
				scaleFrom:100,
				scaleX:false,
				scaleY:true,
				scaleMode:
				{
					originalHeight: this.options.defaultSize.height ? this.options.defaultSize.height : cont.scrollHeight,
					originalWidth: this.options.defaultSize.width ? this.options.defaultSize.width : cont.scrollWidth
				},
				afterFinish: function(){
					cont.removeClassName(this.options.classNames.contentActive)
					cont.setStyle({
						height:'0px',
						display:'none'
					})
				}.bind(this)
			}
		);
		return true;
	},
	handleToggle: function(e) {
		var ele = Event.element(e);
		if(this.inTransition == false){
			if(this.onlyOneOpen == true){
				var openelem = $$('.' + this.options.classNames.contentActive);
				openelem.each(function(elem){
					this.deActivate(elem.previous('h2').down());
				}.bind(this));
			}	
			if(!ele.up('h2').next('.' + this.options.classNames.content).visible()){
				this.activate(ele);
			}else{
				this.deActivate(ele);
			}
		}
	}	
});
var fancyLogin = Class.create({
	initialize: function(triggerID,formID) {
		this.trigger = $(triggerID);
		this.formID = $(formID);
		this.initEventHandlers();
	},
	initEventHandlers: function() {
		this.trigger.select('a')[0].observe('click',this.handleToggle.bind(this));
		$('fancyCloseBtn').observe('click',this.handleToggle.bind(this));
	},
	handleToggle: function(e) {
		Event.stop(e);
		Effect.toggle(this.formID, 'appear',{duration:.4});
	}	
});
var tabsManager = Class.create({
	initialize: function(options) {
		this.options = Object.extend({
			containerClass: 'tabboxInfoContent',
			tabClass: 'tabboxButton',
			activeTabClass: 'tabboxButton_active',
			triggerEvent: 'click' 
		}, options || {});
		this._tabs = $$('.' + this.options.tabClass);
		this._containers = $$('.' + this.options.containerClass);
		this.initEventHandlers();
	},
	initEventHandlers: function() {
		this.openFirst();
		this._tabs.each(function(elem){
			elem.setStyle({cursor:'pointer'});
			elem.observe(this.options.triggerEvent,this.handleToggle.bind(this))
		}.bind(this));
	},
	openFirst: function() {
		this._tabs[0].addClassName(this.options.activeTabClass);
		this._containers[0].show();
	},
	closeAllBoxes: function() {
		this._containers.each(function(elem){elem.hide();});
	},
	removeActiveClasses: function() {
		this._tabs.each(function(elem){elem.removeClassName( this.options.activeTabClass )}.bind(this));
	},
	handleToggle: function(e) {
		var ele = Event.element(e);
		this.closeAllBoxes();
		this.removeActiveClasses();
		try{
			ele.up('.' + this.options.tabClass).addClassName(this.options.activeTabClass);
		}catch(e){
			//console.log(e)
		}
		try{
			$(ele.up('.' + this.options.tabClass).attributes['rel'].nodeValue).show();
		}catch(e){
			//console.log(e);
		}
	}	
});
var advancedSearchNinja = Class.create({
	initialize: function(){
		this.triggers = $$('input.property_type_triggger_js');
		this.containers = $$('.property_type_js');
		this.initEventHandlers();
	},
	initEventHandlers: function() {
		this.triggers.each(function(elem){
			elem.observe('click',this.handleToggle.bind(this));
		}.bind(this));
	},
	handleToggle: function(e) {
		var ele = Event.element(e);
		if(ele.checked == true){
			var temp = $(ele.readAttribute('rel'));
			this.closeContainers();
			temp.show();
			Effect.ScrollTo(temp);
		}
	},
	closeContainers: function(){
		this.containers.each(function(elem){
			elem.hide();
		});
	}
});
var SAFormManagerWidget = Class.create({
	initialize: function(options) {
		this.options = Object.extend({
			formElementClass: '.clearFocus',
			elementEvent: 'focus'
		}, options || {});
		this._defaultValues = new Array();
		this._fields = $$(this.options.formElementClass);
		this.initEventHandlers();
	},
	initEventHandlers: function() {
		this._fields.each(function(elem){
			this._defaultValues.push(elem.value);
			elem.observe(this.options.elementEvent,this.handleFocus.bind(this));
		}.bind(this));
	},
	handleFocus: function(e) {
		this.fixBlanks();
		var ele = Event.element(e);
		if(this._defaultValues.indexOf(ele.value) != -1){
			ele.value = '';
		}
	},
	fixBlanks: function(k) {
		this._fields.each(function(elem){
			if(elem.value == ''){
				elem.value = this._defaultValues[this.getIndex(elem)];
			}			
		}.bind(this));
	},
	getIndex: function(k) {
		for(var i = 0; i < this._fields.length; i++){
			if(k == this._fields[i]){
				return i;
			}
		}
	}
});
var fancy_listing_agent = Class.create({
	initialize: function(elem,_hidden,_div){
		this.elem = $(elem);
		this._hidden = $(_hidden);
		this._div = $(_div);
		this.setup();
		this.listen();
	},
	setup: function(){
		if(this.elem.value == 'company' || this.elem.value == 'owner_only'){
			this._hidden.name = this.elem.value;
			this._hidden.value = 'on';
		}else{
			this._hidden.value = '';
		}
	},
	listen: function(){
		this.elem.observe('change',this.handleChange.bind(this));
	},
	handleChange: function(e){
		if(this.elem.value == 'company' || this.elem.value == 'owner_only'){
			this._hidden.name = this.elem.value;
			this._hidden.value = 'on';
		}else{
			this._hidden.value = '';
		}
		if(this.elem.value == 'do_agents'){
			this._div.show();
		}else{
			this._div.hide();
			var list = this._div.select('.agent_list_selectbox')[0];
			var _len = list.length;
			for(var i = 0; i < _len; i++){
				list.options[i].selected = false;
			}
		}
	}
})
var liveChatNotice = Class.create({
	initialize: function(){
		this.element = $$('a.liveChatClosed');
		this.block = $('liveChatIsClosed');
		if(this.element.length > 0){
			this.element.each(function(elem){
				try{
					this.block.select('.CloseBtn')[0].observe('click',this.handleEffect.bind(this));
				}catch(e){}
				elem.observe('click',this.handleClick.bind(this));
			}.bind(this));
			this.positionBlock();
		}
	},
	positionBlock: function(){
		var w = document.viewport.getDimensions().width;
		var w2 = this.block.getWidth();
		this.block.setStyle({
			left: ((w/2) - (w2/2)) + 'px'
		});
	},
	handleEffect: function(e){
		Effect.toggle(this.block, 'appear',{duration:.4});
	},
	handleClick: function(e){
		Event.stop(e);
		var ele = Event.element(e);
		if(!this.block.visible()){
			this.block.setStyle({
				top: (ele.positionedOffset().top - (this.block.getHeight()/2)) + 'px'
			});
		}
		this.handleEffect();
	}
});




var liveChatNoticeCHRISTMASinstance = Class.create({
	initialize: function(){
		this.element = $$('a.liveChatIsClosedCHRISTMAS');
		this.block = $('liveChatIsClosedCHRISTMAS');
		if(this.element.length > 0){
			this.element.each(function(elem){
				try{
					this.block.select('.CloseBtn')[0].observe('click',this.handleEffect.bind(this));
				}catch(e){}
				elem.observe('click',this.handleClick.bind(this));
			}.bind(this));
			this.positionBlock();
		}
	},
	positionBlock: function(){
		var w = document.viewport.getDimensions().width;
		var w2 = this.block.getWidth();
		this.block.setStyle({
			left: ((w/2) - (w2/2)) + 'px'
		});
	},
	handleEffect: function(e){
		Effect.toggle(this.block, 'appear',{duration:.4});
	},
	handleClick: function(e){
		Event.stop(e);
		var ele = Event.element(e);
		if(!this.block.visible()){
			this.block.setStyle({
				top: (ele.positionedOffset().top - (this.block.getHeight()/2)) + 'px'
			});
		}
		this.handleEffect();
	}
});

// DOM READY TRIGGER
Event.observe(window, 'load', function() {
	$$( "a.PopupWin" ).each(function(el){new GenericPopupWindow(el);});
	$$('img.viewTrigger').each(function(elem){new viewSwap(elem);}); //results page view swap
});