GoHome = new Object();

GoHome.Opera = (navigator.userAgent.indexOf('Opera') != -1);
GoHome.IE = (navigator.userAgent.indexOf('MSIE') != -1);
if (GoHome.Opera && GoHome.IE) GoHome.IE = false;

GoHome.clearDivContent = function(elem) {
	$(elem).innerHTML = '';
	$(elem).contentLoaded = '';
}

GoHome.replaceDivContentAjax = function(elem, ajaxurl, alwaysload) {
	if (!alwaysload && ($(elem).contentLoaded == ajaxurl)) {
		return;
	}
	new Ajax.Updater(elem, ajaxurl, {
		method:'get',
		onComplete: function () {
			$(elem).contentLoaded = ajaxurl;
		}
	});
}

GoHome.photoScrollBox = function (sbclass, photodiv, photos, npp, img_w, img_h, margin, onclick, next, prev) {
	this.target = photodiv;
	this.width = photodiv.getWidth();
	this.pages = 0;
	this.next = next;
	this.prev = prev;
	this.currentpage = 0;
 	this.initialize(sbclass, photos, npp, img_w, img_h, margin, onclick);
}

GoHome.photoScrollBox.prototype.left = function () {
	if (this.currentpage < this.pages) {
		new Effect.Move(this.target, { x: this.width*-1, y: 0, mode: 'relative', duration:0.4, transition: Effect.Transitions.linear });
		this.currentpage++;
		if (this.currentpage == this.pages) {
			for (var i=0; i < this.next.length; i++) {
				this.next[i].addClassName('disabled');
			}
		}
		if (this.currentpage == 2) {
			for (var i=0; i < this.prev.length; i++) {
				this.prev[i].removeClassName('disabled');
			}
		}
	}
}

GoHome.photoScrollBox.prototype.right = function () {
	if (this.currentpage > 1) {
		new Effect.Move(this.target, { x: this.width, y: 0, mode: 'relative', duration:0.4, transition: Effect.Transitions.linear });
		this.currentpage--;
		if (this.currentpage == 1) {
			for (var i=0; i < this.prev.length; i++) {
				this.prev[i].addClassName('disabled');
			}
		}
		if (this.currentpage == (this.pages - 1)) {
			for (var i=0; i < this.next.length; i++) {
				this.next[i].removeClassName('disabled');
			}
		}
	}
}

GoHome.photoScrollBox.prototype.initialize = function (sbclass, photos, npp, img_w, img_h, margin, onclick) {
	var style = '';
	var html = [];
	for (var i=0; i < photos.length; i++) {
		if (i%npp == 0) {
			html.push('<div class="'+sbclass+'_page">');
			this.pages++;
		}
		var height = parseInt(photos[i].thumbheight);
		var width = parseInt(photos[i].thumbwidth);
		if (height*4/3 > width) {
			width = Math.floor(width/(height/img_h));
			if (width>img_w) width=img_w;
			height = img_h;
			style = ' style="margin-left: '+(margin+Math.ceil((img_w-width)/2))+'px;"';
		} else {
			height = Math.floor(height/(width/img_w));
			if (height>img_h) height=img_h;
			width = img_w;
			style = ' style="margin-top: '+(margin+Math.ceil((img_h-height)/2))+'px;"';
		}
		html.push('<div class="'+sbclass+'_thumb"><'+'img src="' + photos[i].photourl + '" width=' + width + ' height=' + height + style + ' onclick="'+onclick+'"><\/div>');
		if (((i+1)%npp == 0) || ((i+1) == photos.length)) {
			html.push('<div class="clearfloat"><!-- spacer --><\/div><\/div>');
		}
	}
	this.target.setStyle({width: this.width*this.pages+'px'});
	this.target.innerHTML = html.join('');

	if (this.pages > 1) {
		this.currentpage = 1;
		for (var i=0; i < this.prev.length; i++) {
			var self=this;
			Event.observe(this.prev[i], 'click', function() { self.right(); });
		}
		for (var i=0; i < this.next.length; i++) {
			Event.observe(this.next[i], 'click', function() { self.left(); });
			if(this.pages > 1) {
				this.next[i].removeClassName('disabled');
			}
		}
	}
}

/* setCheckedValue
 * set the radio button with the given value as being checked
 * do nothing if there are no radio buttons
 * if the given value does not exist, all the radio buttons are reset to unchecked
 *
 */
GoHome.setCheckedValue = function(radioObj, newValue) {
	if(!radioObj) return;
	var radioLength = radioObj.length;
	if(radioLength == undefined) {
		radioObj.checked = (radioObj.value == newValue.toString());
		return;
	}
	for(var i = 0; i < radioLength; i++) {
		radioObj[i].checked = false;
		if(radioObj[i].value == newValue.toString()) {
			radioObj[i].checked = true;
		}
	}
}

/* toggleCheckBox
 * set the radio button with the given value as being checked
 * do nothing if there are no radio buttons
 * if the given value does not exist, all the radio buttons are reset to unchecked
 *
 */
GoHome.toggleCheckBox = function(obj) {
	obj.checked = obj.checked ? false : true;
}

/* getWindowSize
 * Usage:
 * var dim = GoHome.GetWindowSize();
 * dim[0] or dim.width is the window width
 * dim[1] or dim.height is the window height
 *
 */
GoHome.getWindowSize = function(w) {
	var array = [];
	if (w) {
		array.width = array[0] = w.innerWidth || (w.document.documentElement.clientWidth || w.document.body.clientWidth);
	}
	else {
		/* if its the main window remove the scrollbar by not using innerwidth */
		w = window;
		array.width = array[0] = (w.document.documentElement.clientWidth || w.document.body.clientWidth);
	}
	array.height = array[1] = w.innerHeight || (w.document.documentElement.clientHeight || w.document.body.clientHeight);
	return array;
}

/* Cookie
 * Usage:
 * var mycookie = new GoHome.Cookie(document, name, hours, path, domain, secure);
 * document = document
 * name = name of the cookie variable to be saved on the client
 * hours = how long before the cookie expires in hours
 * path = what path in the url should the cookie be accessible to ("/" = the entire site)
 */
GoHome.Cookie = function(document, name, hours, path, domain, secure)
{
	this.$document = document;
	this.$name = name;
	if (hours)
		this.$expiration = new Date((new Date()).getTime() + hours*3600000);
	else this.$expiration = null;
	if (path) this.$path = path; else this.$path = null;
	if (domain) this.$domain = domain; else this.$domain = null;
	if (secure) this.$secure = true; else this.$secure = false;
}

GoHome.Cookie.prototype.store = function()
{
	var cookieval = "";
	for(var prop in this) {
		if ((prop.charAt(0) == '$') || ((typeof this[prop]) == 'function'))
			continue;
		if (cookieval != "") cookieval += '&';
		cookieval += prop + ':' + escape(this[prop]);
	}

	var cookie = this.$name + '=' + cookieval;
	if (this.$expiration)
		cookie += '; expires=' + this.$expiration.toGMTString();
	if (this.$path) cookie += '; path=' + this.$path;
	if (this.$domain) cookie += '; domain=' + this.$domain;
	if (this.$secure) cookie += '; secure';

	this.$document.cookie = cookie;
}

GoHome.Cookie.prototype.load = function()
{
	var allcookies = this.$document.cookie;
	if (allcookies == "") return false;

	var start = allcookies.indexOf(this.$name + '=');
	if (start == -1) return false;
	start += this.$name.length + 1;
	var end = allcookies.indexOf(';', start);
	if (end == -1) end = allcookies.length;
	var cookieval = allcookies.substring(start, end);

	var a = cookieval.split('&');
	for(var i=0; i < a.length; i++)
		a[i] = a[i].split(':');

	for(var i = 0; i < a.length; i++) {
		this[a[i][0]] = unescape(a[i][1]);
	}

	return true;
}

GoHome.Cookie.prototype.remove = function()
{
	var cookie;
	cookie = this.$name + '=';
	if (this.$path) cookie += '; path=' + this.$path;
	if (this.$domain) cookie += '; domain=' + this.$domain;
	cookie += '; expires=Fri, 02-Jan-1970 00:00:00 GMT';

	this.$document.cookie = cookie;
}

GoHome.MoveDiv = function(div2mv,x,y) {
	if (div2mv) {
		div2mv.style.left = x+'px';
		div2mv.style.top = y+'px';
	}
}

GoHome.ShowDiv = function(div2show,x,y) {
	if (div2show) {
		div2show.style.visibility = "visible";
	}
}

GoHome.HideDiv = function(div2hide,x,y) {
	if (div2hide) {
		div2hide.style.visibility = "hidden";
	}
}

GoHome.PrintParts = function(arrElementNames)
{
	var objWindow=window.open("about:blank", "print", "left=0, top=0, width=600, height=640, toolbar=no, scrollbars=yes");
	var strHtml="<html>";
	strHtml += "<head>";
	strHtml += "<link rel='stylesheet' type='text\/css' href='\/dat\/_style.css'>";
	strHtml += "<link rel='stylesheet' type='text\/css' href='\/common\/_style_tags.css'>";
	strHtml += "<link rel='stylesheet' type='text\/css' href='\/common\/_style_pw.css'>";
	strHtml += "<!--[if lt IE 7]><link rel='stylesheet' type='text\/css' href='\/common\/_pngfiles.css'><![endif]-->";
	strHtml += "<\/head>";
	strHtml += "<body>";
	for (var i=0; i<arrElementNames.length; i++) {
		var element=document.getElementById(arrElementNames[i]);
		strHtml += element.innerHTML;
	}
	strHtml += "<\/body>";
	strHtml += "<\/html>";
	objWindow.document.write(strHtml);
	objWindow.document.close();
	objWindow.print();
	objWindow.close();
}

GoHome.MapWindow = function(divname, mapdivname, dirdivname, lat, lng, mapaddress) {
	this.name = divname;
	this.mapname = mapdivname;
	this.dirname = dirdivname;
	this.dirinputboxname = this.name+'_inputbox';
	this.address = mapaddress;
	this.fromaddress = null;
	this.fromaddrinput = this.name+'_fromaddr';
	this.elem = null;
	this.mapelem = null;
	this.direlem = null;
	this.marker = null;
	this.lat = lat;
	this.lng = lng;
	this.latlng = null;
	this.vp = [];
	this.vpoffset = null;

	this.directionsService = new google.maps.DirectionsService();
	this.directionsDisplay = new google.maps.DirectionsRenderer();

	Event.observe(window, 'load', this.BuildDivs.bind(this));
}

GoHome.MapWindow.prototype.BuildDivs = function() {
	var objBody = $$('body')[0];
	objBody.appendChild(
		Builder.node('div', {id: this.name, className: 'showHomeMap'}, [
			Builder.node('div', {className: 'showHomeMap_address'}, ['Address: ', this.address]),
			Builder.node('div', {id: this.name+'_close', className: 'showHomeMap_close'},
				Builder.node('img', { style: 'border: 0px; cursor: pointer', src: '/common/in_images/lightbox_close2.gif' })
			),
			Builder.node('div', {id: this.dirinputboxname, className: 'showHomeMap_dirinput'}, [
				Builder.node('form', {id: this.name+'_form', onsubmit: 'return false;'}, [
					Builder.node('div', {className: 'header'}, 'Get Directions'),
					Builder.node('div', {className: 'inner_container'}, [
						Builder.node('div', {className: 'input'}, [
							Builder.node('img', {width: '16px', height: '16px', style: 'padding-right: 3px; border: 0px; cursor: pointer', src: '/common/in_images/mapit_a.png' }),
							Builder.node('input', {id: this.fromaddrinput, name: 'fromaddress', type: 'text'} )
						]),
						Builder.node('div', {className: 'submit'}, [
							Builder.node('img', {id: this.name+'_getdirections', width: '99px', height: '20px', style: 'border: 0px; cursor: pointer', src: '/common/in_images/button_getdirections.gif' })
						]),
					]),
				]),
			]),
			Builder.node('div', {id: this.dirname, className: 'showHomeMap_dirs'}),
			Builder.node('div', {id: this.mapname})
		])
	);
	$(this.name+'_close').observe('click', (function(event) { event.stop(); this.Close(); }).bind(this));
	$(this.name+'_getdirections').observe('click', (function(event) {
		event.stop();
		this.ProcessFrom();
	}).bind(this));
	$(this.name+'_form').observe('submit', (function(event) {
		event.stop();
		this.ProcessFrom();
	}).bind(this));
/*
	new Draggable(this.name);
	$(this.dirname).observe('mousedown', (function(event) { event.stop(); }).bind(this));
	$(this.dirinputboxname).observe('mousedown', (function(event) { event.stop(); }).bind(this));
*/
}

GoHome.MapWindow.prototype.ProcessFrom = function () {
	this.fromaddress = $(this.fromaddrinput).value;
	this.LoadDirections('en_US');
}

GoHome.MapWindow.prototype.Close = function () {
	GoHome.HideDiv(this.elem);
}

GoHome.MapWindow.prototype.MapIt = function (lat, lng, address) {
	if (lat != undefined) {
		this.lat = lat;
	}
	if (lng != undefined) {
		this.lng = lng;
	}
	if (address != undefined) {
		this.address = address;
	}
	if (!this.elem) {
		this.elem = $(this.name);
	}
	this.vpoffset = document.viewport.getScrollOffsets();
	this.vp = GoHome.getWindowSize();
	var myOffsetHeight = (this.vp.height-this.elem.getHeight())/3;
	var myOffsetWidth = (this.vp.width-this.elem.getWidth())/3;
	myOffsetHeight = myOffsetHeight>0?myOffsetHeight:0;
	myOffsetWidth = myOffsetWidth>0?myOffsetWidth:0;
	GoHome.MoveDiv(this.elem, this.vpoffset.left + myOffsetWidth, this.vpoffset.top + myOffsetHeight)
	GoHome.ShowDiv(this.elem);
	if (!this.mapelem) {
		this.latlng = new google.maps.LatLng(this.lat, this.lng);
		this.mapelem = new google.maps.Map(document.getElementById(this.mapname), {
			zoom: 16,
			center: this.latlng,
			mapTypeId: google.maps.MapTypeId.ROADMAP,
          	mapTypeControl: true,
          	mapTypeControlOptions: { style: google.maps.MapTypeControlStyle.DROPDOWN_MENU },
          	navigationControl: true,
          	navigationControlOptions: {
                style: google.maps.NavigationControlStyle.DEFAULT,
                position: google.maps.ControlPosition.LEFT
          	},
          	scrollwheel: false
		});
		this.marker = new google.maps.Marker({ position: this.latlng, map: this.mapelem, title: 'MLS# ' + ln });
		this.directionsDisplay.setMap(this.mapelem);
		this.directionsDisplay.setPanel(document.getElementById(this.dirname));
	}

	if (this.fromaddress) {
		this.LoadDirections('en_US');
	}
	else {
		this.mapelem.setCenter(this.latlng, 16);
	}
	return false;
}

GoHome.MapWindow.prototype.SetFromAddress = function(fromaddress) {
	this.fromaddress = fromaddress;
}

// Calculate Route & queue up async display of results
GoHome.MapWindow.prototype.LoadDirections = function(locale) {
	var request = {
		origin: this.fromaddress,
		destination: this.address,
		unitSystem: google.maps.DirectionsUnitSystem.IMPERIAL,
		travelMode: google.maps.DirectionsTravelMode.DRIVING
	};
	var mapwin = this;

	this.directionsService.route(request, function(response, status) {
		if (status == google.maps.DirectionsStatus.OK) {
			mapwin.directionsDisplay.setDirections(response);
		} else if (status == google.maps.DirectionsStatus.INVALID_REQUEST) {
			alert('A directions request could not be successfully parsed.');
		} else if (status == google.maps.DirectionsStatus.NOT_FOUND) {
			alert('Unable to determine the latitude/longitude of one of the locations.');
		} else if (status == google.maps.DirectionsStatus.OVER_QUERY_LIMIT) {
			alert('Please try the request again in a few minutes.');
		} else if (status == google.maps.DirectionsStatus.REQUEST_DENIED) {
			alert('Server unable to perform directions requests at this time.  Sorry for the inconvenience.');
		} else if (status == google.maps.DirectionsStatus.UNKNOWN_ERROR) {
			alert('A directions request was not able to be perfomred due to a server error.  Please try again later.  Sorry for the inconvenience.');
		} else if (status == google.maps.DirectionsStatus.ZERO_RESULTS) {
			alert('No route could be found between the two points.');
		}
	});
}

function LoadDirections(objectname) {
	showHomeMapObj.SetFromAddress($(objectname).value);
	showHomeMapObj.LoadDirections('en_US');
}


