var Popup = {
	open : function(options) {
		this.options = {
			url : '#',
			width : 600,
			height : 500,
			name : "_blank",
			location : "no",
			menubar : "no",
			toolbar : "no",
			status : "yes",
			scrollbars : "yes",
			resizable : "yes",
			left : "",
			top : "",
			normal : false
		}
		Object.extend(this.options, options || {});

		if (this.options.normal) {
			this.options.menubar = "yes";
			this.options.status = "yes";
			this.options.toolbar = "yes";
			this.options.location = "yes";
		}

		this.options.width = this.options.width < screen.availWidth
				? this.options.width
				: screen.availWidth;
		this.options.height = this.options.height < screen.availHeight
				? this.options.height
				: screen.availHeight;
		var openoptions = 'width=' + this.options.width + ',height='
				+ this.options.height + ',location=' + this.options.location
				+ ',menubar=' + this.options.menubar + ',toolbar='
				+ this.options.toolbar + ',scrollbars='
				+ this.options.scrollbars + ',resizable='
				+ this.options.resizable + ',status=' + this.options.status
		if (this.options.top != "")
			openoptions += ",top=" + this.options.top;
		if (this.options.left != "")
			openoptions += ",left=" + this.options.left;
		window.open(this.options.url, this.options.name, openoptions);
		return false;
	}
};

var cmcd = {
	capCellId : 'captioncell',
	capImageId : 'captioncellimage',
	capTextId : 'captioncelltext',
	capHoverCls : '.caphoversel',
	capDescriptionSel : '.captiondescription',
	listHoverCls : '.list .property_price',
	listSummaryCls : '.propsummary',
	listSummaryIds : 'propsummary_',
	listParentId : 'property_records',
	thumbHoverSel : 'div.thumbs a.medialink img',
	thumbHoverPri : 'img.primary_property_image',
	thumbHoverCnt : 0,
	thumbAnchorSel : 'a.medialink',
	obj : null,
	initialize : function() {
		try {
			Event.observe(window, 'load', cmcd.onLoad);
		} catch (e) {
			// Handle Error
		}
	},
	onLoad : function() {
		cmcd.bindHoverCells();
		cmcd.bindListHovers();
		cmcd.bindThumbHovers();
		//cmcd.bindThumbAnchor();
	},
	getCaptionImage : function() {
		var i = $(cmcd.capImageId);
		if (!Object.isElement(i)) {
			i = new Element('img', {
				'id' : cmcd.capImageId
			});
			$(cmcd.capCellId).insert(i);
		}
		return i;
	},
	getCaptionText : function() {
		return $(cmcd.capTextId);
	},
	bindHoverCells : function() {
		$$(cmcd.capHoverCls).each(function(item) {
			item.observe('mouseover', function(event) {
				var elm = Event.element(event);
				var img = cmcd.getCaptionImage();
				var spn = cmcd.getCaptionText();
				var src = (elm.readAttribute('abbr') != null) ? elm
						.readAttribute('abbr') : elm.readAttribute('rel');
				var txt = elm.down(cmcd.capDescriptionSel).innerHTML;
				img.writeAttribute('src', src);
				spn.update(txt);
				img.show();
			});
			item.observe('mouseout', function(event) {
				var img = cmcd.getCaptionImage();
				// img.hide();
				});
		});
	},
	bindListHovers : function() {
		$$(cmcd.listHoverCls).each(function(item) {
			item.observe('mouseover', function(event) {
				var elm = Event.element(event);
				var eid = elm.identify();
				var hid = eid.replace(/property_price_/g, "");
				var div = $(cmcd.listSummaryIds + hid);
				var pos = elm.positionedOffset();

				var dht = parseInt(div.getStyle('height').replace(/px/g, ""));

				div.setStyle({
					left : (pos.left + 0) + 'px',
					top : (pos.top - (dht + 10)) + 'px'
				});
				$(cmcd.listParentId).insert(div);
				cmcd.obj = div;
				div.show();
			});
			item.observe('mouseout', function(event) {
				try {
					var elm = Event.element(event);
					var eid = elm.identify();
					var hid = eid.replace(/property_/g, "");
					var nid = cmcd.listSummaryIds + hid;
					$(nid).hide();
				} catch (e) {
					$$(cmcd.listSummaryCls).each(function(item) {
						item.hide();
					});
				} finally {
					// Handle error
				}
			});
		});
	},
	bindThumbAnchor : function() {
		$$(cmcd.thumbAnchorSel).each(function(item) {
			item.observe('click', function(event) {
				try {
					Event.stop(event);
					return Popup.open({
						url : item.readAttribute('href'),
						width : 960,
						height : 1024
					});
				} catch (e) {

				}
			});
		});
	},
	bindThumbHovers : function() {
		$$(cmcd.thumbHoverSel).each(function(item) {
			item.observe('mouseover', function(event) {
				try {
					var elm = Event.element(event);
					var prt = elm.up('table');
					var prm = prt.select(cmcd.thumbHoverPri).first();
					prm.writeAttribute('src', elm.readAttribute('src'));
					cmcd.thumbHoverCnt++;
				} catch (e) {
					// Handle error
				}
			});
			item.observe('mouseout', function(event) {
				try {
					var elm = Event.element(event);
					var prt = elm.up('table');
					var prm = prt.select(cmcd.thumbHoverPri).first();
					cmcd.thumbHoverCnt--;
					setTimeout("cmcd.swapRestore()", 1250);
					// prm.writeAttribute('src', prm.readAttribute('lowsrc'));
				} catch (e) {
					// Handle error
				}
			});
		});
	},
	swapRestore : function() {
		if (cmcd.thumbHoverCnt == 0) {
			$$(cmcd.thumbHoverPri).each(function(item) {
				item.writeAttribute('src', item.readAttribute('lowsrc'));
			});
		}
	}
};

var mapper = {
	mapclass : ".map_canvas",
	propblock : ".propertylisting",
	mapProperties : function() {
		$$(mapper.propblock).each(function(prop) {
			mapper.mapProperty(prop);
		});
	},
	mapProperty : function(propdiv) {
		var img = propdiv.down('.primary_property_image', 0);
		var canvas = propdiv.down('.map_canvas', 0);
		var pcanvas = propdiv.down('.pano_canvas', 0);
		var scanvas = propdiv.down('.property-map-canvas', 0);
		var gplain = propdiv.down('#mediabuttons a.gplain', 0);
		var gstreet = propdiv.down('#mediabuttons a.gstreet', 0);
		var geocoder = new GClientGeocoder();
		
		var address = null;
		if(img  && img != "undefined") {
			address = img.readAttribute('alt');
		} else {
			address = scanvas.readAttribute('title');
		}
		
		geocoder.getLatLng(address, function(point) {
			if (point) {
				var map = new GMap2(canvas);
				var marker = new GMarker(point);

				if(gplain && gplain != "undefined") {
					// Hide the map after it has completed loading
					var mapLoadHandle = GEvent.addListener(map, 'load', function() {
						mapper.toggleMap(canvas);
						GEvent.removeListener(mapLoadHandle);
					});
				}

				map.setCenter(point, 13);
				map.addControl(new GMapTypeControl());
				map.addControl(new GLargeMapControl3D());

				// Enable the additional map types within
				// the map type collection
				map.enableRotation();
				map.addOverlay(marker);
				marker.openInfoWindowHtml(address);
				
				if(gplain && gplain != "undefined") {
					gplain.observe('click', function(event) {
						// mapper.toggleMap(canvas);
						//mapper.toggleMap(canvas);
						//Event.stop(event);
					});
					gplain.setStyle({
						display : 'inline-block'
					});
					mapper.panoProperty(point, pcanvas, gstreet);
				}
			}
		});
	},
	panoProperty : function(latlng, canvas, button) {
		var pano = new GStreetviewPanorama(canvas);
		var panoClient = new GStreetviewClient();

		// Hiding the canvas before the panorama loads causes the flash object to be sized incorrectly
		// This event hides the canvas after the panorama is initialized, and removes
		// the listner to prevent it from firing when the canvas visibility is toggled
		var initHandle = GEvent.addListener(pano, 'initialized', function() {
			mapper.toggleMap(canvas);
			GEvent.removeListener(initHandle);
		});

		panoClient.getNearestPanoramaLatLng(latlng, function(point) {
			if (point) {
				pano.setLocationAndPOV(point);
				GEvent.addListener(panoClient, "error", function(errorCode) {
					if (errorCode == 603) {
						alert("Error: Flash doesn't appear to be supported by your browser");
						return;
					}
				});
				button.observe('click', function(event) {
					mapper.toggleMap(canvas);
					Event.stop(event);
				});
				button.setStyle({
					display : 'inline-block'
				});
			}
		});
	},
	toggleMap : function(canvas) {
		canvas.toggle();
		var ndx = canvas.getStyle('zIndex');
		if(!canvas.visible()) {
			ndx = ndx * -1;
		} else {
			ndx = Math.abs(ndx) + 3;
		}
		canvas.setStyle({zIndex:ndx});
	},
	hideMap : function(canvas) {
		canvas.setStyle({
			opacity : 0,
			visibility : 'hidden'
		});
	},
	showMap : function(canvas) {
		canvas.setStyle({
			opacity : 100,
			visibility : 'visible'
		});
	}
};
cmcd.initialize();