var icon = '';
var fav = '';
var mapData = {};
var zoomLevel = 12;

WindowObjectReference = null;
function openPopup(url, name, width, height){
	if(WindowObjectReference == null || WindowObjectReference == "" || WindowObjectReference.closed) {
		WindowObjectReference = window.open(url, name, "location=no,resizable=no,scrollbars=yes,status=no,dialog=no,width="+width+",height="+height);
	} else {
    	WindowObjectReference.focus();
	}
}

window.addEvents({
	'domready':function(){
		if($('retsbondui_gMap')){
			icon = new GIcon();
			icon.image = '/retsbondui/images/icon.png';
			icon.iconSize = new GSize(22,36);
			icon.iconAnchor = new GPoint(5, 34);
			
			fav = new GIcon();
			fav.image = '/retsbondui/images/fav.png';
			fav.iconSize = new GSize(22,36);
			fav.iconAnchor = new GPoint(5, 34);
			
			mapData = JSON.decode($('retsbondui_gMap').get('html'));
	
			var searchCriteria = readCookie('RETSbondUI_Search_Criteria');
			if(searchCriteria != null && searchCriteria != ''){
				var searchArray = searchCriteria.split('%2C');
				searchArray.each(function(string){
					var searchValues = string.split('%3D');
					mapData[searchValues[0]] = searchValues[1];
				});
			}
			
			GLoad('retsbondui_gMap',mapData);
		}
	
		if($('retsbondui_listingMap')){
			icon = new GIcon();
			icon.image = '/retsbondui/images/icon.png';
			icon.iconSize = new GSize(22,36);
			icon.iconAnchor = new GPoint(5, 34);
			
			fav = new GIcon();
			fav.image = '/retsbondui/images/fav.png';
			fav.iconSize = new GSize(22,36);
			fav.iconAnchor = new GPoint(5, 34);

			mapData = JSON.decode($('retsbondui_listingMap').get('html'));
			
			showMap('retsbondui_listingMap');
		}
			
		$$('.retsbondui_listing').addEvents({
			'click':function(){
				window.location = this.getElement('.detailLink').get('href');
			}
		});
			
		$$('.listingThumb').each(function(el){
			el.addEvents({
				'click':function(){
					var img = el.getElement('img').get('src');
					var src = img.replace('tmb','big');
					$('mainImage').set('src',src.replace('/lr','/hr'));
				}
			});
		});
		
		$$('.retsbondui_search').each(function(el){
			el.addEvent('click',function(e){
				e = new Event(e).stop();
				var criteria = {};
				criteria['retsbondui_search'] = 'true';
				if(el.get('rel') != ''){
					var criteria_strings = el.get('rel').split(',');
					criteria_strings.each(function(val){
						var key_val = val.split('=');
						criteria[key_val[0]] = key_val[1];
					});
				}
				var updateCriteria = new Request({
					method: 'post',
					url: '/retsbondui/core.php',
					data: criteria,
					onComplete: function(){
						window.location = el.get('href');
					}
				}).send();
			});
		});
		
		if($('retsbondui_prev_pages')){
			$('retsbondui_prev_pages').addEvent('click',function(e){
				e = new Event(e).stop();
				if($('retsbondui_page_links').getStyle('margin-left') != null){
					var margin = parseInt($('retsbondui_page_links').getStyle('margin-left'));
				}else{
					var margin = 0;
				}
				
				if(margin + 200 > 0){
					$('retsbondui_page_links').tween('margin-left',0);
				}else{
					$('retsbondui_page_links').tween('margin-left',margin + 200);
				}
			});
			
			$('retsbondui_next_pages').addEvent('click',function(e){
				e = new Event(e).stop();
				var limits = $('retsbondui_page_links').get('rel').split(',');
				if(limits[1] > 10){
					var maxMargin = (-20 * limits[1]) + 200;	
				}else{
					var maxMargin = 0;	
				}
				
				if($('retsbondui_page_links').getStyle('margin-left') != null){
					var margin = parseInt($('retsbondui_page_links').getStyle('margin-left'));
				}else{
					var margin = 0;
				}
				
				if(margin - 200 < maxMargin){
					$('retsbondui_page_links').tween('margin-left',maxMargin);
				}else{
					$('retsbondui_page_links').tween('margin-left',margin - 200);
				}
			});
		}
		
		favLinks();
	},
	'unload':function(){
		if($('retsbondui_gMap') || $('retsbondui_listingMap')){
			GUnload();
		}
	}
});

var favLinks = function(){
	$$('.favLink').each(function(el){
		el.addEvent('click',function(e){
			e = new Event(e).stop();
			addFav(el);
		});
	});
	
	$$('.removeFav').each(function(el){
		el.addEvent('click',function(e){
			e = new Event(e).stop();
			removeFav(el);
		});
	});	
}

var addFav = function(el){
	var Favs = readCookie('RETSbondUI_Favorite_Listings');
	var mlsNum = el.get('rel');
	if(Favs == null || Favs.indexOf(mlsNum) == -1){
		eraseCookie('RETSbondUI_Favorite_Listings');
		if(Favs != '' && Favs != null){
			createCookie('RETSbondUI_Favorite_Listings',Favs + ',' + mlsNum);	
		}else{
			createCookie('RETSbondUI_Favorite_Listings',mlsNum);
		}
		
		el.set('class','removeFav');
		el.set('html','Remove From Favorites');
		el.removeEvents('click');
		
		el.addEvent('click',function(e){
			e = new Event(e).stop();
			removeFav(el);
		});
		
		if($('favCount')){
			$('favCount').set('html',parseInt($('favCount').get('html')) + 1);
		}
	}	
}

var removeFav = function(el){	
	var Favs = readCookie('RETSbondUI_Favorite_Listings');
	var mlsNum = el.get('rel');
	var found = false;
	
	if(Favs.indexOf(mlsNum + ',') != -1){
		Favs = Favs.replace(mlsNum + ',','');
		found = true;
	}else if(Favs.indexOf(',' + mlsNum) != -1){
		Favs = Favs.replace(',' + mlsNum,'');
		found = true;
	}else if(Favs.indexOf(mlsNum) != -1){
		Favs = Favs.replace(mlsNum,'');
		found = true;
	}
	
	if(found == true){
		eraseCookie('RETSbondUI_Favorite_Listings');
		createCookie('RETSbondUI_Favorite_Listings',Favs);
		
		el.set('class','favLink');
		el.set('html','Add To Favorites');
		el.removeEvents('click');
		
		el.addEvent('click',function(e){
			e = new Event(e).stop();
			addFav(el);
		});
		if($('favCount')){
			if(parseInt($('favCount').get('html')) > 0){
				$('favCount').set('html',parseInt($('favCount').get('html')) - 1);
			}
		}
	}
}

var showMap = function(id){
	if(GBrowserIsCompatible()){
		var zoom = mapData.Zoom;
		var el = $(id);
		var lat = mapData.Lat;
		var lng = mapData.Lng;
		var mlsNum = $$('.mlsNum').get('html');
		
		var map = new GMap2(el);
		map.setCenter(new GLatLng(lat,lng),zoom);
		map.enableDoubleClickZoom();
		map.addControl(new GLargeMapControl());
		map.addControl(new GMapTypeControl());		
		G_DEFAULT_MAP_TYPES.each(function(TYPE){
			map.addMapType(TYPE);							  
		});
		var mapMarkers = new GMarkerManager(map);
		
		var favoriteListings = readCookie('RETSbondUI_Favorite_Listings');
		if(favoriteListings != '' && favoriteListings != null){
			if(favoriteListings.indexOf(mlsNum) != -1){
				var markerIcon = fav;
			}else{
				var markerIcon = icon;
			}
		}else{
			var markerIcon = icon;
		}
		
		var marker = new GMarker(new GLatLng(lat,lng),markerIcon);
		mapMarkers.addMarker(marker,zoomLevel);
	}
}

var GLoad = function(mapID,mapData){
	if(GBrowserIsCompatible()){
		var zoom = mapData.Zoom;
		var mls = [];
		
		var map = new GMap2($(mapID));
		map.setCenter(new GLatLng(mapData.Lat,mapData.Lng),zoom);
		map.enableDoubleClickZoom();
		map.addControl(new GLargeMapControl());
		map.addControl(new GMapTypeControl());		
		G_DEFAULT_MAP_TYPES.each(function(TYPE){
			map.addMapType(TYPE);							  
		});
		var mapMarkers = new GMarkerManager(map);
				
		var updateListings = function(){
			
			var lat1 = map.getBounds().getSouthWest().lat();
			var lng1 = map.getBounds().getSouthWest().lng();
			var lat2 = map.getBounds().getNorthEast().lat();
			var lng2 = map.getBounds().getNorthEast().lng();
			
			if(map.getZoom() >= (zoomLevel)){	
				var myRequest = new Request.JSON({
					'method': 'post',
					'url': '/retsbondui/listings.php',
					'data': {
						'data':JSON.encode({
							'type':'map',
							'lat1':lat1,
							'lat2':lat2,
							'lng1':lng1,
							'lng2':lng2,
							'mlsArray':mls,
							'mapData':mapData
						})
					},
					onComplete:function(listings){
						$('averagePropertyPrice').set('html',listings.Avg_Price);
						var newListings = listings.Markers;
						if(newListings.length > 0){
							markers = [];
							newListings.each(function(val){
								var favoriteListings = readCookie('RETSbondUI_Favorite_Listings');
								if(favoriteListings != null && favoriteListings != '' && favoriteListings.indexOf(val.MLSNum) != -1){
									var markerIcon = fav;
								}else{
									var markerIcon = icon;
								}
								var marker = new GMarker(new GLatLng(val.Latitude,val.Longitude),markerIcon);
								mls.extend([val.MLSNum]);
								mapMarkers.addMarker(marker,(zoomLevel));
								GEvent.addListener(marker, "click", function(){
									var myRequest = new Request({
										'method': 'post',
										'url': '/retsbondui/listings.php',
										'data': {
											'data':JSON.encode({
												'type':'detail',
												'mlsNum':val.MLSNum
											})
										},
										onComplete: function(content){
											window.addEvent('keyup', function(event){
												if (event.key == 'esc') 
													closeOverlay();
											});
											
											var overlay = new Element('div', {
												'class': 'retsbondui_overlay',
												'id': 'retsbondui_overlayID',
												'events': {
													'click': function(){
														closeOverlay();
													}
												}
											}).set('opacity', 0).inject(document.body, 'top').tween('opacity', .5);
											
											var detailBox = new Element('div', {
												'class': 'retsbondui_detailBox',
												'id': 'retsbondui_detailBoxID',
												'html': content
											}).set('opacity', 0).inject(document.body, 'top').tween('opacity', 1);
											
											favLinks();
											
											$$('.closeOverlay').each(function(el){
												el.removeEvents('click');
												el.addEvent('click', function(e){
													e = new Event(e).stop();
													closeOverlay();
												});
											});
											
											var closeOverlay = function(){
												window.removeEvents('keyup');
												var fx = new Fx.Morph(detailBox).start({
													'opacity': 0
												}).chain(function(){
													detailBox.destroy();
												});
												var overlayFx = new Fx.Morph(overlay).start({
													'opacity': 0
												}).chain(function(){
													overlay.destroy();
												});
											}


											//IE6 overlay
											var overlayPos = function overlayPos(){
												var overlayBG = document.getElementById('retsbondui_overlayID');
												var overlay = document.getElementById("retsbondui_detailBoxID");
												
												//Grabs the INNER WINDOW DIMENSIONS for various browsers.
												if (typeof(window.innerWidth && window.innerHeight) == 'number') {
													//Non-IE, FF
													winWidth = window.innerWidth;
													winHeight = window.innerHeight;
													var DoNotCalculate = 1;
												} else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
													//IE 6 Standars Compliant Mode
													winWidth = document.documentElement.clientWidth - 2;
													winHeight = document.documentElement.clientHeight;
												} else if (document.body && (document.body.clientWidth || document.body.clientHeight)) {
													winWidth = document.body.clientWidth;
													winHeight = document.body.clientHeight;
												} else {
													//No window support.
													winWidth = 0;
													winHeight = 0;
												}
												
												/*scrollY is the ENTIRE DOCUMENT HEIGHT*/
												var scrollY = 0;
												if (typeof(window.pageYOffset) == 'number') {
													scrollY = window.pageYOffset;
												} else if (document.documentElement && document.documentElement.scrollTop) {
													scrollY = document.documentElement.scrollTop;
												} else if (document.body && document.body.scrollTop) {
													scrollY = document.body.scrollTop;
												}
												
												if(winWidth != 0 && winHeight != 0){
													if(DoNotCalculate == 1){
														var vertPos = (winHeight + scrollY) - 800;
														overlay.style.top = 35 + 'px';
													} else {
														var vertPos = (winHeight + scrollY) - 800;
														overlay.style.top = vertPos + 'px';
													}
												
													var htmlDocHeight = document.body.scrollHeight;
													overlayBG.style.height = htmlDocHeight;
													
													if(document.getElementById("retsbondui_overlayID") != "" && document.getElementById("retsbondui_overlayID") != null){
														onresize = overlayPos;
														onscroll = overlayPos;
													}
												}
											}
											overlayPos();


											/*
											//IE6 overlay
											function overlayPos(){
												var overlayBG = document.getElementById('retsbondui_overlayID');
												var overlay = document.getElementById("retsbondui_detailBoxID");
												
												if (typeof(window.innerWidth && window.innerHeight) == 'number') {
													winWidth = window.innerWidth - 18;
													winHeight = window.innerHeight;
												} else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
													winWidth = document.documentElement.clientWidth - 2;
													winHeight = document.documentElement.clientHeight;
												} else if {
													winWidth = document.body.clientWidth;
													winHeight = document.body.clientHeight;
												}
												
												var scrollY = 0;
												if (typeof(window.pageYOffset) == 'number') {
													scrollY = window.pageYOffset;
												} else if (document.documentElement && document.documentElement.scrollTop) {
													scrollY = document.documentElement.scrollTop;
												} else {
													scrollY = document.body.scrollTop;
												}
												
												var vertPos = (winHeight + scrollY) - 800;
												overlay.style.top = vertPos + 'px';
												
												var htmlDocHeight = document.body.scrollHeight;
												overlayBG.style.height = htmlDocHeight;
											}
											onresize = overlayPos;
											onscroll = overlayPos;
										*/
										}
									}).send();
								});
							});
						}
						
						$$('img[id^=mtgt_unnamed_]').each(function(el){
							if(!el.hasClass('gMapDontAnimate')){
								el.addClass('gMapAnimate');
							}
						});
												
						$$('.gMapAnimate').each(function(el){
							el.set('opacity',0);
							
							var rand = Math.floor(Math.random() * 1000);							
							var fx = new Fx.Morph(el,{
								'duration': rand,
								'transition': Fx.Transitions.Sine.easeOut
							});
							
							(function(){ fx.start({ 
								'opacity': 1
							}); }).delay(rand);
							
							el.removeClass('gMapAnimate');
							el.addClass('gMapDontAnimate');
						});
					}
				}).send();
			}
		}
		
		updateListings();
		GEvent.addListener(map,"zoomend",function(){ updateListings(); });
		GEvent.addListener(map,"dragend",function(){ updateListings(); });
	}
}
		
function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}