YAHOO.namespace("ps.Popup.nearby");
(function () {
    var Dom  = YAHOO.util.Dom,
    	Ev   = YAHOO.util.Event,
    	Conn = YAHOO.util.Connect,
    	Pop	 = YAHOO.ps.Popup,
    	Near = YAHOO.ps.Popup.nearby;
    
    var lat,
    	lng,
    	forSale,
    	listId;
    
	var config = { enableSold: false };
	
	var setConfig = function (keys) {
		for(var i in keys) {
			if (YAHOO.lang.hasOwnProperty(keys, i)) {
				config[i] = keys[i];
			}
		}
	};
	
	var tabChange = function () {
		var postValues = 'lat=' + lat + '&lng=' + lng;
		var listings   = '';
		// Sold is active
		if (Dom.hasClass('contentActive','yui-hidden')) {	
			listings = Dom.getElementsByClassName('listing', 'div', 'nearbySoldNavResults');
			if (listings.length == 0) {
				Conn.asyncRequest('POST', '/server/realestate/nearby-sold', callbackNearbySold, postValues); 
			}
			Dom.addClass('boxActiveTitle','hide');
			Dom.removeClass('boxSoldTitle','hide');
		} else { // Otherwise only active is present
			listings = Dom.getElementsByClassName('listing', 'div', 'nearbyActiveNavResults');
			if (listings.length == 0) {
				if (forSale == 'Y') {
					Conn.asyncRequest('POST', '/server/realestate/nearby-active', callbackNearbyActive, postValues); 
				} else {
					Conn.asyncRequest('POST', '/server/realestate/nearby-rent', callbackNearbyActive, postValues);  
				}
			}
			Dom.addClass('boxSoldTitle','hide');
			Dom.removeClass('boxActiveTitle','hide');
		}
	};
    
	var setPoint = function (newLat, newLng, newForSale, newId) {
		lat 	= newLat;
		lng 	= newLng;
		forSale = newForSale;
		listId	= newId;
    };

	var 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;
	};
	
	var show = function () {
		// Get title for rental if listings are not for sale
		var tabTitle = 'Active Listings';
		var tabClass = 'tabSingle'
		if (forSale != 'Y') {
			tabTitle = 'Rental Listings';
		}
		if (config['enableSold'] == true && forSale == 'Y') {
			tabClass = 'tabActive';
		}
		
		// Build HTML
		var html = '<div id="selectedTitle">HOMES CLOSE TO THIS LISTING:</div>';
		html += '<div id="selectedListing" class="loading"></div><div id="nearbyListings" class="yui-navset boxTab">';
		html += '<div id="boxActiveTitle" class="hide"></div><div id="boxSoldTitle" class="hide"></div>';
		html += '<ul id="tabNearby" class="yui-nav"><li id="' + tabClass + '"><a href="#tab1">' + tabTitle + '</a></li>';
		if (config['enableSold'] == true && forSale == 'Y') {
			html += '<li id="tabSold"><a href="#tab2">Recently Sold</a></li>';
		}
		html += '</ul><div id="contentNearby" class="yui-content"><div id="contentActive" class="yui-hidden"> ';
		html += '<div id="nearbyActiveNavResults" class="loading"></div></div>';
		if (config['enableSold'] == true && forSale == 'Y') {
			html += '<div id="contentSold" class="yui-hidden"><div id="nearbySoldNavResults" class="loading"></div></div>';
		}
		html += '</div></div>';
		
    	Pop.setContent(html);
    	Pop.setBodyClass('nearby');
		Pop.setHeader('');
    	Pop.setFooter('');
    	Pop.showFullscreen();
    	// Initial tabs
    	initTabs();
    	// Set content height
    	var top  = document.getElementById('selectedTitle').offsetHeight + 
    			   document.getElementById('selectedListing').offsetHeight + 
				   document.getElementById('tabNearby').offsetHeight + 3;
    	var cont = document.getElementById('dynBody').offsetHeight;
    	document.getElementById('contentNearby').style.height = (cont - top) + 'px';
    };
    
	var getActiveDisplay = function(listing) {
		var htmlListing = '';
		
		if (listing['url_mapview'] != '' && !YAHOO.lang.isUndefined(listing['url_mapview'])) {		   
			htmlListing += '<div class="image"><img src="' + listing['url_mapview'] + '" /><br />';
		} else {
			htmlListing += '<div class="image"><img src="/resources/images/nolisting-map.jpg" /><br />';
		}
		htmlListing += '<span class="distance">';	
		if (!YAHOO.lang.isUndefined(listing['distance']) && listing['listing_key'] != listId) {
			htmlListing += listing['distance'] + ' Miles Away';
		} else {
			htmlListing += '&nbsp;';
		}
		htmlListing += '</span></div>';
		
		htmlListing += '<div class="detailGrp">';
		
		htmlListing += '<div class="status"><span class="';
		htmlListing += (listing['list_status'] == 'ACTIVE') ? 'green' : 'red';
		htmlListing += '">' + listing['list_status'] + '</span></div>';
		
		htmlListing += '<div class="title">' + listing['street_address'] + '<br />' + listing['city'];
		htmlListing += ', ' + listing['state'] + ' ' + listing['zip'] + '</div>';
		htmlListing += '<div class="info">Subdivision: ' + listing['subdivision'] + '</div>';

		htmlListing += '</div>';

		htmlListing += '<div class="detailInfo">';
		htmlListing += '<div class="price">$' + addCommas(listing['list_price']) + '</div>';
		htmlListing += '<div class="info">Listed: ' + listing['dis_list_date'] + '</div>';

		if (listing['beds'] > 0 || listing['baths'] > 0) {
			htmlListing += '<div class="info">';
			if (listing['beds'] > 0) {
				htmlListing += listing['beds'] + ' Bed';
			}
			if (listing['baths'] > 0) {
				if (listing['beds'] > 0) {
					htmlListing += ' | ';
				}
				var bathTotal = (parseInt(listing['baths_full']) + (listing['baths_half']/2));
				bathTotal += ' Bath';
				htmlListing += bathTotal.replace('.5', ' 1/2');
			}
			htmlListing += '</div>';
		}

		if (listing['type_listing'] == 'lot') {
			htmlListing += '<div class="info">Lot Size: ' + (listing['area_lot_size']/43560).toFixed(2) + ' Acre(s)</div>';
		}
		htmlListing += '</div>';
		
		// Build link if needed
		var link = ' style="cursor:default;"';
		if (listing['listing_key'] != listId) {
			link = ' onclick="location.href = \'/realestate/listing/key/' + listing['listing_key'] + '\';"';
		}
		// Encapsulate html in give tag
		htmlListing = '<div id="keyList' + listing['listing_key'] + '" class="listing"' + link + '>' + htmlListing + '</div>';			
		
		
		return htmlListing;
	};
	
	var getSoldDisplay = function(listing) {
		var htmlListing = '';
		
		if (listing['url_mapview'] != '' && !YAHOO.lang.isUndefined(listing['url_mapview'])) {		   
			htmlListing += '<div class="image"><img src="' + listing['url_mapview'] + '" /><br />';
		} else {
			htmlListing += '<div class="image"><img src="/resources/images/nolisting-map.jpg" /><br />';
		}
		htmlListing += '<span class="distance">';	
		if (!YAHOO.lang.isUndefined(listing['distance'])) {
			htmlListing += listing['distance'] + ' Miles Away';
		} else {
			htmlListing += '&nbsp;';
		}
		htmlListing += '</span></div>';
		
		htmlListing += '<div class="detailGrp">';
		
		htmlListing += '<div class="title">' + listing['street_address'] + '<br />' + listing['city'];
		htmlListing += ', ' + listing['state'] + ' ' + listing['zip'] + '</div>';

		htmlListing += '</div>';

		htmlListing += '<div class="detailInfo">';
		htmlListing += '<div class="price">$' + addCommas(listing['close_price']) + '</div>';
		htmlListing += '<div class="info">Sold Date: ' + YAHOO.ps.Date.getDate(listing['close_date']) + '</div>';

		if (listing['beds'] > 0 || listing['baths'] > 0) {
			htmlListing += '<div class="info">';
			if (listing['beds'] > 0) {
				htmlListing += listing['beds'] + ' Bed';
			}
			if (listing['baths'] > 0) {
				if (listing['beds'] > 0) {
					htmlListing += ' | ';
				}
				var bathTotal = (parseInt(listing['baths_full']) + (listing['baths_half']/2));
				bathTotal += ' Bath';
				htmlListing += bathTotal.replace('.5', ' 1/2');
			}
			htmlListing += '</div>';
		}

		if (listing['type_listing'] == 'lot') {
			htmlListing += '<div class="info">Lot Size: ' + (listing['area_lot_size']/43560).toFixed(2) + ' Acre(s)</div>';
		}
		htmlListing += '</div>';

		htmlListing += '<div class="detailBroker">';
		htmlListing += '<div class="broker">Listing Broker: ' + listing['pri_office_name'] + '</div>';
		htmlListing += '<div class="broker">Selling Broker: ' + listing['sale_office_name'] + '</div>';
		htmlListing += '</div>';
		
		
		htmlListing = '<div id="keyList' + listing['listing_key'] + '" class="listing" style="cursor:default;">' + htmlListing + '</div>';			
		
		return htmlListing;
	};
	
	var setTitle = function (dis,cnt,active) {
		var html = '<h3>' + cnt + ' Listings / ' + dis + ' Mile Radius</h3>';
		if (active == true) { 
			Dom.get('boxActiveTitle').innerHTML = html;
		} else {
			Dom.get('boxSoldTitle').innerHTML = html;
		}
	};

	var successNearbyActive = function (o) {
		// Run response Ajax response through common eval
		var response = YAHOO.ps.Ajax.eval(o);
		// If not false response was evaluated
		if (response !== false) {  
            if (response['success'] > 0) { 
            	var html = '';
            	var curr = '';
            	var cnt  = response['listings'].length;
				for(var i=0; i<cnt; i++) {
					if (response['listings'][i]['listing_key'] != listId) {
						html += getActiveDisplay(response['listings'][i]);
					} else {
						curr = getActiveDisplay(response['listings'][i]);
					}
				}
				// Remove loading background
				Dom.removeClass('nearbyActiveNavResults', 'loading');
				Dom.removeClass('selectedListing', 'loading');
				
				// Add current listing and nearby matches
				Dom.get('selectedListing').innerHTML 		= curr;
				Dom.get('nearbyActiveNavResults').innerHTML = html;
				// Set the title
				setTitle(response['listings'][(cnt-1)]['distance'],(cnt-1),true);
            }                 
        }               
    };

	var successNearbySold = function (o) {
		// Run response Ajax response through common eval
		var response = YAHOO.ps.Ajax.eval(o);
		// If not false response was evaluated
		if (response !== false) {                             
            if (response['success'] > 0) { 
            	var html = '';
            	var cnt  = response['listings'].length;
				for(var i=0; i<cnt; i++) {
					if (response['listings'][i]['listing_key'] != listId) {
						html += getSoldDisplay(response['listings'][i]);
					}
				}
				// Remove loading background
				Dom.removeClass('nearbySoldNavResults', 'loading');

				Dom.get('nearbySoldNavResults').innerHTML = html;
				// Set the title
				setTitle(response['listings'][(cnt-1)]['distance'],cnt,false);
            }                 
        }               
    };
    
    var failureNearby = function (o) {
    };    
    
	var callbackNearbyActive = {
		success:successNearbyActive,
		failure:failureNearby,
		timeout:15000
	};
    
	var callbackNearbySold = {
		success:successNearbySold,
		failure:failureNearby,
		timeout:15000
	};
    
	var setLink = function () {
    	if (Dom.inDocument('nearbyLink')) {
	    	Ev.addListener('nearbyLink', 'click', function () {
	    		show();	
			});
    	}
	};
	
    var initTabs = function() {
        // Create tab and set default view
    	var tab = new YAHOO.widget.TabView("nearbyListings");
        tab.addListener("activeTabChange", tabChange);
    	tab.selectTab(0);
    };
    
    // Public functions
    Near.setPoint  = setPoint;
    Near.setLink   = setLink;
    Near.setConfig = setConfig;
})();