var AdvertsAutoRefresh = function()
{
	var lastActionTime;
	var lastRefreshTime;
	var refreshInterval;
	
	return {
		bootstrap : function(interval)
		{
			if (interval == null) { interval = 30; } // default
			AdvertsAutoRefresh.refreshInterval = interval;
			
			AdvertsAutoRefresh.lastRefreshTime = new Date();
			AdvertsAutoRefresh.lastActionTime = null;
			
			AdvertsAutoRefresh.registerStandardEvents();
		},

		registerStandardEvents : function()
		{
			Event.observe(document, 'click', AdvertsAutoRefresh.registerUserAction);			
		},

		registerUserAction : function()
		{
			AdvertsAutoRefresh.lastActionTime = new Date();
			var differenceInSeconds = Math.round((AdvertsAutoRefresh.lastActionTime.getTime()-AdvertsAutoRefresh.lastRefreshTime.getTime()) / 1000);
			if (differenceInSeconds >= AdvertsAutoRefresh.refreshInterval)
			{
				AdvertsAutoRefresh.refreshAllAdverts();
			}
		},

		refreshAllAdverts : function()
		{
			$$('iframe.iframeAdvert').each(function(iframe)
			{
				var newOrd = Math.floor(Math.random()*999999);
				iframe.src = iframe.src.replace(/ord=[^&]*/, "ord="+newOrd);
			});		
			$$('iframe.integratedAdvert').each(function(iframe)
			{
				var rand = Math.floor(Math.random()*999999);
				iframe.src = iframe.src + "&" + rand;
			});
			AdvertsAutoRefresh.lastRefreshTime = new Date();
			AdvertsAutoRefresh.lastActionTime = null; 			
		}
	}
}();

var MainNavigation = function() {
	return {
		bootstrap : function(event) {
			new Array('home', 'fmn', 'homes_and_property', 'local_area', 'home_finance').each(function(name) {
				if ($(name+'_dropdown') != null)
				{				
					if ($(name+'_rollover').hasClassName(name+'_selected') == false) {
						$(name+'_dropdown').observe('mouseover', function() { $(name+'_rollover').removeClassName(name+'_rollover').addClassName('activated'); });
						$(name+'_dropdown').observe('mouseout', function() { $(name+'_rollover').removeClassName('activated').addClassName(name+'_rollover'); });
					}
					// for IE6
					$(name+'_nav').observe('mouseenter', function(event) {
						$(name+'_dropdown').setStyle({visibility: 'visible'});
					});
					$(name+'_nav').observe('mouseleave', function(event) {
						$(name+'_dropdown').setStyle({visibility: 'hidden'}); 
					});
				}
			});
		}
	}
}();

var SmallLocationBar = function() {
	return {
		bootstrap : function(event) {
			$('smallLocationBarLocation').observe('click', function(event) { event.element().clear(); });
		}
	}
}();

var LargeLocationBar = function() {
	return {
		bootstrap : function(event) {
			$('largeLocationBarLocation').observe('click',
				function(event) {
					event.element().clear();
					$('largeLocationBarLocation').style.color = '#383E4A';
				}
			);
		}
	}
}();

var ProfileForm = function() {
	return {
		clearProfileForm : function(event) {
			var element = event.element();
			if (element.value == 'Enter County, City, Area, or Post Code')
				element.clear();
		}
	}
}();

var FmnPropertyPanelTabs = function() {

	return {
		bootStrap: function() {
			if ($('fmnpropertypaneltabs')) {
				var tabs = new tabset('fmnpropertypaneltabs');
				tabs.autoActivate($('tab_mostexpensive'));
			}
		}
	};
}();

var FmnPropertyPanel = function() {

	return {
	
		bootStrap: function() {
			if ($('fmnpropertypanellocation')) $('fmnpropertypanellocation').observe('click', FmnPropertyPanel.clearLocation);
		},
	
		clearLocation : function(event) {
			var element = event.element();
			if (element.value == 'Enter County, City, Area, or Post Code')
				element.clear();
		}
	};

}();

var HomeFmnSearchForm = function() {
	return {
		clearHomeSearchFieldBusiness : function(event) {
			var element = event.element();
			// note - if you change this default value, be sure to change them in the searchBar view too
			if (element.value == 'and/or type in a company name')
				element.clear();
		},

		clearHomeSearchFieldCategory : function(event) {
			var element = event.element();
			// note - if you change this default value, be sure to change them in the searchBar view too
			if (element.value == 'type in a business, service or keyword')
				element.clear();
		}
	}
}();

var EditLocation = function() {
	var originalTitleHtml; // to put back if user clicks cancel

	var editButtonText = 'Edit';
	var updateButtonText = 'Save';
	var cancelButtonText = 'Cancel';
	
	var redirectUrl;
	var controller;

	return {
		bootStrapEditLocation : function() {
			if ($('locationEditUpdateButton')) {
				originalTitleHtml = $('locationEditLocation').innerHTML;
				$('locationEditUpdateButton').innerHTML = '';
				var editButtonEl = EditLocation.createEditUpdateButton(editButtonText);
			}
		},
		
		respondToLocationEditUpdateButtonClick : function() {
			thisEvent = $('locationEditUpdateButton').firstDescendant().getAttribute('value');
			//alert(thisEvent);			
			if (thisEvent == editButtonText) {
				// pressed 'edit'
				var editBoxEl = document.createElement('input');
				editBoxEl.setAttribute('type', 'text');
				editBoxEl.setAttribute('id', 'locationEditLocationTextBox');
				editBoxEl.setAttribute('value', $('locationEditLocation').innerHTML);
				$('locationEditLocation').innerHTML = '';
				$('locationEditLocation').appendChild(editBoxEl);
				
				$('locationEditUpdateButton').innerHTML = '';
				var updateButtonEl = EditLocation.createEditUpdateButton(updateButtonText);
				var cancelButtonEl = EditLocation.createCancelButton();
				
				$('locationEditLocationTextBox').focus();
				$('locationEditLocationTextBox').select();
				if (self.ConversionCount)
					return ConversionCount();				
			} else {
				// pressed 'update'
				if (redirectUrl) {
					//var cleanedText = EditLocation.cleanTextForUrl($('locationEditLocationTextBox').value);
					//if ($('locationBarFmn'))
						window.location = '/change-location?location='+escape($('locationEditLocationTextBox').value)+'&redirectUrl='+escape(redirectUrl)+'&cont='+escape(controller);
					//else
						//window.location = '/confirm-location/l/'+escape($('locationEditLocationTextBox').value)+'.html?fpage='+escape(redirectUrl)+'&loc='+escape($('locationEditLocationTextBox').value);
				}
			}
		},
		
		respondToLocationCancelButtonClick : function() {
			$('locationEditLocation').innerHTML = originalTitleHtml;
			EditLocation.bootStrapEditLocation();
		},
		
		setUrl : function(url) {
			redirectUrl = url;
		},
		
		setController : function(c) {
			controller = c;
		},
		
		isSafariOrChrome : function() {
			return (BrowserDetect.browser == 'Chrome' || BrowserDetect.browser == 'Safari');
		},
		
		createEditUpdateButton : function(name) {
			var buttonEl = document.createElement('input');
			buttonEl.setAttribute('type', 'image');
			buttonEl.setAttribute('id', 'locationEditUpdateButtonId');
			if (name == editButtonText)
				buttonEl.setAttribute('src', '/images/map/editbutton.gif');
			else if (name == updateButtonText)
				buttonEl.setAttribute('src', '/images/map/savebutton.gif');
			buttonEl.setAttribute('value', name);
			
			if (EditLocation.isSafariOrChrome())
				buttonEl.setAttribute('onclick', 'EditLocation.respondToLocationEditUpdateButtonClick()');

			$('locationEditUpdateButton').appendChild(buttonEl);
			
			if (!EditLocation.isSafariOrChrome())
				$('locationEditUpdateButtonId').observe('click', EditLocation.respondToLocationEditUpdateButtonClick);
			
			return buttonEl;
		},
				
		createCancelButton : function() {
			var cancelButtonEl = document.createElement('input');
			cancelButtonEl.setAttribute('type', 'image');
			cancelButtonEl.setAttribute('id', 'locationEditCancelButtonId');
			cancelButtonEl.setAttribute('src', '/images/map/cancelbutton.gif');
			cancelButtonEl.setAttribute('value', cancelButtonText);
			
			if (EditLocation.isSafariOrChrome())
				cancelButtonEl.setAttribute('onclick', 'EditLocation.respondToLocationCancelButtonClick()');

			$('locationEditUpdateButton').appendChild(document.createTextNode(' or '));
			$('locationEditUpdateButton').appendChild(cancelButtonEl);
			
			if (!EditLocation.isSafariOrChrome())
				$('locationEditCancelButtonId').observe('click', EditLocation.respondToLocationCancelButtonClick);
		}									
		
	};
}();

//Event.observe(window, 'load', EditLocation.bootStrapEditLocation);

var TabbedPropertySearchPanel = function() {
	return {
		bootstrap : function(event) {
			if ($('homepagepropertytabs')) {
				var tabs = new tabset('homepagepropertytabs');
				tabs.autoActivate($('tab_forsale'));
			}
			if ($('propertysearchselect')) {
				$('propertysearchselect').innerHTML = '<div class="propertysearchoptions"><input type="radio" name="searchType" value="sale" checked="checked" id="propertysearchselectsale" /><label class="propertysearchselectsale">For Sale</label> <br /><input type="radio" name="searchType" value="rent" id="propertysearchselectrent" /><label class="propertysearchselectsale">For Rent</label></div>';
				$('propertysearchselectsale').observe('change', TabbedPropertySearchPanel.changeForm);
				$('propertysearchselectrent').observe('change', TabbedPropertySearchPanel.changeForm);
				TabbedPropertySearchPanel.changeForm();				
			}
		},
		
		clearAll: function() {
			$('tab_forsale').removeClassName('selected');
			$('tab_forsale').addClassName('unselected');
		},
		
		respondToForSaleClick: function(event) {
			TabbedPropertySearchPanel.clearAll();
		},
		
		respondToSoldClick: function(event) {
			TabbedPropertySearchPanel.clearAll();
			$('tab_sold').addClassName('selected');
		},			
		
		changeForm : function() {
			if ($('propertysearchselectsale').checked) {
				$('propertysearchsaleform').show();
				$('propertysearchrentform').hide();
			} else {
				$('propertysearchsaleform').hide();
				$('propertysearchrentform').show();
			}
		}
	}
}();

var TabbedFindHomesPanel = function() {
	return {
		bootstrap : function(event) {
			if ($('findhomespanel')) {
				var tabs = new tabset('findhomespanel');
				tabs.autoActivate($('tab_findforsale'));
			}
			
		},
		
		clearAll: function() {
			$('tab_findforsale').removeClassName('selected');
			$('tab_findforsale').addClassName('unselected');
		},
		
		respondToFindForSaleClick: function(event) {
			TabbedFindHomesPanel.clearAll();
		},
		
		respondToFindForRentClick: function(event) {
			TabbedFindHomesPanel.clearAll();
			$('tab_findtorent').addClassName('selected');
		}			
	}
}();

var TabbedSaveBillsPanel = function() {
	return {
		bootstrap : function(event) {
			if ($('savebillspanel')) {
				var tabs = new tabset('savebillspanel');
				tabs.autoActivate($('tab_savegaselec'));
			}
			
		},
		
		clearAll: function() {
			$('tab_savegaselec').removeClassName('selected');
			$('tab_savegaselec').addClassName('unselected');
		},
		
		respondToSaveGasElecClick: function(event) {
			TabbedSaveBillsPanel.clearAll();
		},
		
		respondToSaveHomePhoneClick: function(event) {
			TabbedSaveBillsPanel.clearAll();
			$('tab_savehomephone').addClassName('selected');
		}	
	}
}();

var TabbedPriceTrendsPanel = function() {
	return {
		bootstrap : function(event) {
			if ($('pricetrendsgraph')) {
				var tabs = new tabset('pricetrendsgraph');
				tabs.autoActivate($('tab_pricetrends'));
			}
			
		},
		
		clearAll: function() {
			$('tab_pricetrends').removeClassName('selected');
			$('tab_pricetrends').addClassName('unselected');
		},
		
		respondToPriceTrendsClick: function(event) {
			TabbedPriceTrendsPanel.clearAll();
		},
		
		respondToLatestStatsClick: function(event) {
			TabbedPriceTrendsPanel.clearAll();
			$('tab_lateststats').addClassName('selected');
		}			
	}
}();


var Navigation = function() {

	return {
		bootStrap : function() {
			if(typeof Tip == 'function') { 
				var hooksIds = ['navigation-home-hook', 'navigation-home-hook-on', 'navigation-fmn-hook', 'navigation-fmn-hook-on', 'navigation-property-hook', 'navigation-property-hook-off', 'navigation-smarter-hook', 'navigation-local-hook', 'navigation-news-hook'];
				var linksIds = ['navigation-home-links', 'navigation-home-links', 'navigation-fmn-links', 'navigation-fmn-links', 'navigation-property-links', 'navigation-property-links', 'navigation-smarter-links', 'navigation-local-links', 'navigation-news-links'];
				var tips = ['topMiddle', 'topMiddle', 'topMiddle', 'topMiddle', 'topMiddle', 'topMiddle', 'topMiddle', 'topMiddle', 'topMiddle'];
				var targets = ['bottomMiddle', 'bottomMiddle', 'bottomMiddle', 'bottomMiddle', 'bottomMiddle', 'bottomMiddle', 'bottomMiddle', 'bottomMiddle', 'bottomMiddle'];
	
				for(var i=0; i<=hooksIds.length; i++) {
					if ($(hooksIds[i]) != null) {
						new Tip(hooksIds[i], $(linksIds[i]), {
							className: 'ums',
							border: 1,
							radius: 3,
							borderColor: '#000',
							target: $(hooksIds[i]),
							hook: { tip: tips[i], target: targets[i] },
							hideOn: false,
							hideAfter: 2,
							hideOthers: true,
							    stem: {
							      position: 'topMiddle',
							      height: 5,
							      width: 0
								}
						});
					}
				}
			}
		}
	}
}();

Event.observe(window, 'load', Navigation.bootStrap);


var Utility = function() {
	
	return {
		
		includeScript : function(scriptFilename) {
			// TODO: Make this use Prototype
		    var htmlDoc = document.getElementsByTagName('head').item(0);
		    var js = document.createElement('script');
		    js.setAttribute('language', 'javascript');
		    js.setAttribute('type', 'text/javascript');
		    js.setAttribute('src', scriptFilename);
		    htmlDoc.appendChild(js);
		    return false;
		},
		
		selectValue : function(el, val) {
			for(i = 0; i < el.length; i++) {
				if (el[i].value == val) {
					el.selectedIndex = i;
				}
			}
		},
		
		clearSelectBox : function(el) {
			while (el.options.length > 0) el.options[0] = null;
		},
		
		addOption : function(selectBox, text, value) {
			var option = document.createElement('option');
			option.text = text;
			option.value = value;
			selectBox.options.add(option);
		},
		
		addCommas : function(nStr) {
			nStr += '';
			x = nStr.split('.');
			x1 = x[0];
			x2 = x.length > 1 ? '.' + x[1] : '';
			var rgx = /(\d+)(\d{3})/;
			while (rgx.test(x1)) {
				x1 = x1.replace(rgx, '$1' + ',' + '$2');
			}
			return x1 + x2;
		}
	}

}();


// stereotabs.js v1.0, Mon Jul 23 2007
//
// Copyright (c) 2007 Stereo :: Interactive & Design (http://blog.stereodevelopment.com)
// Author: Scott Meves 
//
// Inspired by:
//  accordion.js by Kevin P Miller | http://www.stickmanlabs.com
// 
// tabs.js freely distributable under the terms of an MIT-style license.

// fixed by UMS

//if (typeof Effect == 'undefined')
//	throw("tabs.js requires including script.aculo.us' effects.js library!");
	
var tabset = Class.create();

tabset.prototype = {
  tabs:           [], 
  panels:         [],
  showPanel:     null,
  currentPanel:  null,
  
  initialize: function(container, options) {
    this.options = Object.extend({
      classNames: {
        tab:        'tab',
        panel:      'panel',
        tabActive:  'selected',
		tabInactive:'unselected'
      },
      ids: {
        tab:        'tab_',
        panel:      'panel_'
      },
      onEvent:      'click',
      effects:      false // note: cannot use effects without Scriptaculous
    }, options || {} );
    
    container = $(container);
    
    this.tabs = container.select('.'+this.options.classNames.tab);
    this.tabs.each(function(tab) {
      Event.observe(tab, this.options.onEvent, this.activate.bind(this, tab), false);
    }.bind(this));
    
    this.panels = container.select('.'+this.options.classNames.panel);
    this.panels.invoke('hide');
  },
  
  activate: function(tab) {
    var tabName = tab.id.replace(this.options.ids.tab,'');
    this.currentPanel = this.options.ids.panel+tabName;
    if (this.showPanel == this.currentPanel) {
      return false;
    }
    
    if (this.showPanel) {
      if (this.options.effects) {
        new Effect.Fade(this.showPanel, {queue: 'front'});
      } else {
        $(this.showPanel).hide();
      }
    }
    
    if (this.options.effects) {
      new Effect.Appear(this.currentPanel, {queue: 'end'});
    } else {
      $(this.currentPanel).show();
    }

    this.tabs.invoke('removeClassName', this.options.classNames.tabActive);
	this.tabs.invoke('addClassName', this.options.classNames.tabInactive);
	tab.removeClassName(this.options.classNames.tabInactive);
    tab.addClassName(this.options.classNames.tabActive);
    this.showPanel = this.currentPanel;
  },
  
  getHash: function() {
    var hash = window.location.hash;
    return hash.substring(1); // remove #
  },
  
  autoActivate: function(tab) {
    var canDoAuto = false;
    var hash = this.getHash();
    if (hash) {
      var autoTab = $(this.options.ids.tab+hash);
      if (autoTab) {
        this.activate(autoTab);
        canDoAuto = true;
      }
    }
    if (!canDoAuto && tab) {
      this.activate(tab);
    }
  }
}

//Event.observe(window, 'load', HomePageTabs.bootstrap, false);

var BrowserDetect = {
	init: function () {
		this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
		this.version = this.searchVersion(navigator.userAgent)
			|| this.searchVersion(navigator.appVersion)
			|| "an unknown version";
		this.OS = this.searchString(this.dataOS) || "an unknown OS";
	},
	searchString: function (data) {
		for (var i=0;i<data.length;i++)	{
			var dataString = data[i].string;
			var dataProp = data[i].prop;
			this.versionSearchString = data[i].versionSearch || data[i].identity;
			if (dataString) {
				if (dataString.indexOf(data[i].subString) != -1)
					return data[i].identity;
			}
			else if (dataProp)
				return data[i].identity;
		}
	},
	searchVersion: function (dataString) {
		var index = dataString.indexOf(this.versionSearchString);
		if (index == -1) return;
		return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
	},
	dataBrowser: [
		{
			string: navigator.userAgent,
			subString: "Chrome",
			identity: "Chrome"
		},
		{ 	string: navigator.userAgent,
			subString: "OmniWeb",
			versionSearch: "OmniWeb/",
			identity: "OmniWeb"
		},
		{
			string: navigator.vendor,
			subString: "Apple",
			identity: "Safari"
		},
		{
			prop: window.opera,
			identity: "Opera"
		},
		{
			string: navigator.vendor,
			subString: "iCab",
			identity: "iCab"
		},
		{
			string: navigator.vendor,
			subString: "KDE",
			identity: "Konqueror"
		},
		{
			string: navigator.userAgent,
			subString: "Firefox",
			identity: "Firefox"
		},
		{
			string: navigator.vendor,
			subString: "Camino",
			identity: "Camino"
		},
		{		// for newer Netscapes (6+)
			string: navigator.userAgent,
			subString: "Netscape",
			identity: "Netscape"
		},
		{
			string: navigator.userAgent,
			subString: "MSIE",
			identity: "Explorer",
			versionSearch: "MSIE"
		},
		{
			string: navigator.userAgent,
			subString: "Gecko",
			identity: "Mozilla",
			versionSearch: "rv"
		},
		{ 		// for older Netscapes (4-)
			string: navigator.userAgent,
			subString: "Mozilla",
			identity: "Netscape",
			versionSearch: "Mozilla"
		}
	],
	dataOS : [
		{
			string: navigator.platform,
			subString: "Win",
			identity: "Windows"
		},
		{
			string: navigator.platform,
			subString: "Mac",
			identity: "Mac"
		},
		{
			string: navigator.platform,
			subString: "Linux",
			identity: "Linux"
		}
	]

};
BrowserDetect.init();

function AdvertPeeler()
{
	this.small_path = '/swf/peel/small.swf';
	this.big_path = '/swf/peel/large.swf';
	this.small_width = '100';
	this.small_height = '100';
	this.big_width = '650';
	this.big_height = '650';
}

function sizeup987()
{
	document.getElementById('jcornerBig').style.top = '0px';
	document.getElementById('jcornerSmall').style.top = '-1000px';
}

function sizedown987()
{
	document.getElementById("jcornerSmall").style.top = "0px";
	document.getElementById("jcornerBig").style.top = "-1000px";
}
		
AdvertPeeler.prototype.display = function()
{
	this.ad_url = escape(this.ad_url);
	this.big_image = escape(this.big_image);
	this.small_image = escape(this.small_image);
	this.small_params = 'ico=' + this.small_image;
	this.big_params = 'big=' + this.big_image + '&ad_url=' + this.ad_url;	

	document.write('<div id="jcornerSmall" style="position:absolute;width:'+ this.small_width +'px;height:'+ this.small_height +'px;z-index:9999999;right:0px;top:0px;">');
	document.write('<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"');
	document.write(' codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,19,0"');
	document.write(' id="jcornerSmallObject" width="'+this.small_width+'" height="'+this.small_height+'">');
	document.write(' <param name="allowScriptAccess" value="always"/> ');
	document.write(' <param name="movie" value="'+ this.small_path +'?'+ this.small_params +'"/>');
	document.write(' <param name="wmode" value="transparent" />');
	document.write(' <param name="quality" value="high" /> ');
	document.write(' <param name="FlashVars" value="'+this.small_params+'"/>');
	document.write('<embed src="'+ this.small_path + '?' + this.small_params +'" name="jcornerSmallObject" wmode="transparent" quality="high" width="'+ this.small_width +'" height="'+ this.small_height +'" flashvars="'+ this.small_params +'" allowscriptaccess="always" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer"></embed>');
	document.write('</object></div>');
	document.write('</script>');
	document.write('<div id="jcornerBig" style="position:absolute;width:'+ this.big_width +'px;height:'+ this.big_height +'px;z-index:9999999;right:0px;top:0px;">');
	document.write('<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"');
	document.write(' codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,19,0"');
	document.write(' id="jcornerBigObject" width="'+ this.big_width +'" height="'+ this.big_height +'">');
	document.write(' <param name="allowScriptAccess" value="always"/> ');
	document.write(' <param name="movie" value="'+ this.big_path +'?'+ this.big_params +'"/>');
	document.write(' <param name="wmode" value="transparent"/>');
	document.write(' <param name="quality" value="high" /> ');
	document.write(' <param name="FlashVars" value="'+ this.big_params +'"/>');
	document.write('<embed src="'+ this.big_path + '?' + this.big_params +'" id="jcornerBigEmbed" name="jcornerBigObject" wmode="transparent" quality="high" width="'+ this.big_width +'" height="'+ this.big_height +'" flashvars="'+ this.big_params +'" swliveconnect="true" allowscriptaccess="always" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer"></embed>');
	document.write('</object></div>');

	setTimeout('document.getElementById("jcornerBig").style.top = "-1000px";',1000);
}