var map = null, geocoder = null, tabView = null, offX, offY, displayMode;

function showHideNeighborhoods()
{
	if (YAHOO.util.Dom.get("searchNeighborhoodLink").innerHTML == "Search By Neighborhoods")
	{
		YAHOO.util.Dom.setStyle("neighborhoodContainer", "display", "block");
		YAHOO.util.Dom.setStyle("neighborhoodSelected", "display", "none");
		YAHOO.util.Dom.get("searchNeighborhoodLink").innerHTML = "Hide Neighborhoods";
	}
	else
	{
		YAHOO.util.Dom.setStyle("neighborhoodContainer", "display", "none");
		YAHOO.util.Dom.setStyle("neighborhoodSelected", "display", "block");
		YAHOO.util.Dom.get("searchNeighborhoodLink").innerHTML = "Search By Neighborhoods";
	}
}
function loadGeneralMap()
{
	displayMode = "M";
	map = new GMap2(YAHOO.util.Dom.get("generalMap"));
	map.addControl(new GSmallMapControl());
	geocoder = new GClientGeocoder();
	var markers = new Array();
if(listings)
	for(var i = 0; i < listings.length; i++)
	{
		var adrStr = listings[i].streetNumber + " " + listings[i].streetName + ", " + listings[i].city + ", " + listings[i].state;
    	if (listings[i].zip != null)
        	adrStr += " " + listings[i].zip;
    	
    	if (listings[i].latitude != null && listings[i].longitude != null)
    	{
    		var point = new GLatLng(listings[i].latitude, listings[i].longitude);
    		map.setCenter(point, 13);
    	
    	    // Create YGL marker icon
    		var YGLIcon = new GIcon(G_DEFAULT_ICON);
    	    //YGLIcon.image = "http://maps.google.com/intl/en_us/mapfiles/ms/micons/blue-dot.png";
    		YGLIcon.image = "http://localhost/ygl/images/house_pin.png";
    		YGLIcon.shadow = "";
    		YGLIcon.iconSize = new GSize(28, 26);

    	    // Set up  GMarkerOptions object
    		markerOptions = { icon:YGLIcon };

    		var marker = new GMarker(point, markerOptions);
    		marker.listingId = listings[i].id;
    			
    		map.addOverlay(marker);
        	GEvent.addListener(marker, "click", function() {
        		  openMapInfo(this);
        		  });
    	}
	}
}
function openMapInfo(marker)
{
	var html = "<table>";
	html += "<tr>";
		html += "<td colspan='4' style='font-weight:bold; padding-bottom:10px;'>" + YAHOO.util.Dom.get(marker.listingId + "_ADDRESS").innerHTML + "</td>";
	html += "</tr>";
	html += "<tr>";
		html += "<td colspan='4' style='text-align:center; padding-bottom:10px;'><img src='" + YAHOO.util.Dom.get(marker.listingId + "_PHOTO").src + "' style='width:200px;' /></td>";
	html += "</tr>";
	html += "<tr>";
		html += "<td>Rent:</td>";
		html += "<td style='padding-left:15px;padding-right:15px;'>" + YAHOO.util.Dom.get(marker.listingId + "_RENT").innerHTML + "</td>";
		html += "<td>Available:</td>";
		html += "<td style='padding-left:15px;padding-right:15px;'>" + YAHOO.util.Dom.get(marker.listingId + "_AVAIL").innerHTML + "</td>";
	html += "</tr>";
	html += "<tr>";
		html += "<td>Bed:</td>";
		html += "<td style='padding-left:15px;padding-right:15px;'>" + YAHOO.util.Dom.get(marker.listingId + "_BED").innerHTML + "</td>";
		html += "<td>Bath:</td>";
		html += "<td style='padding-left:15px;padding-right:15px;'>" + YAHOO.util.Dom.get(marker.listingId + "_BATH").innerHTML + "</td>";
	html += "</tr>";
	html += "<tr>";
		html += "<td colspan='4'>" + YAHOO.util.Dom.get(marker.listingId + "_UTIL").innerHTML + "</td>";
	html += "</tr>";
	html += "<tr>";
		html += "<td colspan='4' style='text-align:right;'><a href='javascript:void(0);' style='font-weight:bold;' onclick='viewApartmentDetails(\"" + marker.listingId + "\", \"Details\");'>Click Here For Details</a></td>";
	html += "</tr>";
	html += "</table>";
	
	marker.openInfoWindowHtml(html);
}
function activateListing(listingId)
{
	window.location = "apartments.php?listing=" + listingId;
}
function positionGeneralMap()
{
	if (displayMode == "M")
		positionDetailsDiv();
}
function positionDetailsDiv()
{
	var xy = findPos(YAHOO.util.Dom.get("apartments-left"));
	if (YAHOO.util.Dom.get("bottomPager"))
		var stop = findPos(YAHOO.util.Dom.get("bottomPager"))[1];
	else
		var stop = 500;
	var newX = xy[0] + offX;
	if( typeof( window.pageYOffset ) == 'number' ) {
		var newY = window.pageYOffset;
	} else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
		var newY = document.body.scrollTop;
	} else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
		var newY = document.documentElement.scrollTop;
	} else 
		var newY = document.body.scrollTop;
	newY = (newY > xy[1]) ? (newY + offY) : (xy[1] + offY);

	YAHOO.util.Dom.setStyle("apartments-right", "left", newX + "px");
	if ((newY + 500) < stop)
	{
		YAHOO.util.Dom.setStyle("apartments-right", "top", newY + "px");
	}
	setTimeout("positionDetails();", 500);
}
function changePage(diff)
{
	YAHOO.util.Dom.get("pageIndex").value = parseInt(YAHOO.util.Dom.get("pageIndex").value) + diff;
	YAHOO.util.Dom.get("simpleSearchForm").submit();
}
function viewApartmentDetails(id, type)
{
	YAHOO.util.Dom.setStyle("generalMap", "display", "none");
	YAHOO.util.Dom.setStyle("apartmentDetails", "display", "block");
	displayMode = "D";
	positionDetailsDiv();

	if (tabView != null)
	{
		tabView = null;
		YAHOO.util.Dom.get("apartmentDetails").innerHTML = "";
	}
	if (typeof( defaultAgentId ) == 'undefined' )
		defaultAgentId = "";
	
	tabView = new YAHOO.widget.TabView();
	
    tabView.addTab( new YAHOO.widget.Tab({
        label: 'Apartment Info',
        content: '<img src=\'' + imagePath + 'loading.gif\'></img> Loading...',
        dataSrc: 'services.php?loadListingDetails=Y&id=' + id, 
        cacheData: true, 
        active: true
    }));

    tabView.addTab( new YAHOO.widget.Tab({
        label: 'Photos',
        content: '<img src=\'' + imagePath + 'loading.gif\'></img> Loading...',
        dataSrc: 'services.php?loadListingPhotos=Y&id=' + id, 
        cacheData: true
    }));

    tabView.addTab( new YAHOO.widget.Tab({
        label: 'Map',
        content: '<div id=\'listingMap\' style=\'width:100%;height:500px;\'><img src=\'' + imagePath + 'loading.gif\'></img> Loading...</div>'
    }));
    
    tabView.addTab( new YAHOO.widget.Tab({
        label: 'Inquiry',
        content: '<img src=\'' + imagePath + 'loading.gif\'></img> Loading...',
        dataSrc: 'services.php?loadInquiryForm=Y&id=' + id + '&agentId=' + defaultAgentId, 
        cacheData: true
    }));
    
    tabView.addTab( new YAHOO.widget.Tab({
        label: 'Appointment',
        content: '<img src=\'' + imagePath + 'loading.gif\'></img> Loading...',
        dataSrc: 'services.php?loadAppointmentForm=Y&id=' + id + '&agentId=' + defaultAgentId, 
        cacheData: true
    }));
    
    var mapTab = tabView.getTab(2);
    mapTab.addListener('click', function() { clickMap(id); } );
    tabView.appendTo('apartmentDetails');
    
    if (type == "Details")
    	tabView.selectTab(0);
    else if (type == "Photos")
    	tabView.selectTab(1);
    else if (type == "Map")
    {
    	tabView.selectTab(2);
    	clickMap(id);
    }
    else if (type == "Inquiry")
    	tabView.selectTab(3);
    else if (type == "Appointment")
    	tabView.selectTab(4);
}
function clickMap(id) {
	if (YAHOO.util.Dom.get("listingMap").innerHTML.indexOf("Loading") != -1)
		YAHOO.util.Connect.asyncRequest("POST", "services.php", loadMap_Callback, "getListingAddress=Y&id=" + id);
} 
loadMap_Success = function(arg)
{
	
	var map = new GMap2(YAHOO.util.Dom.get("listingMap"));
	map.addControl(new GSmallMapControl());
	
	geocoder.getLatLng(
	    arg.responseText,
	    function(point) {
	      if (point) {
	        map.setCenter(point, 15);
	        // Create YGL marker icon
    		var YGLIcon = new GIcon(G_DEFAULT_ICON);
    	    //YGLIcon.image = "http://maps.google.com/intl/en_us/mapfiles/ms/micons/blue-dot.png";
    		YGLIcon.image = imagePath+"house_pin.png";
    		YGLIcon.shadow = "";
    		YGLIcon.iconSize = new GSize(28, 26);

    	    // Set up  GMarkerOptions object
    		markerOptions = { icon:YGLIcon };
	        var marker = new GMarker(point, markerOptions);
	        map.addOverlay(marker);
	        //marker.openInfoWindowHtml(address);
	      }
	      else
	    	  alert("Cannot locate apartment on map.");
	    }
	  );
}
loadMap_Fail = function(arg)
{
	YAHOO.util.Dom.get("apartmentDetails").innerHTML = "<span class='error'>Loading apartment map failed.</span>";
}
loadMap_Callback = 
{
	success : loadMap_Success,
	failure: loadMap_Fail
};
function setInquiryStatus(msg)
{
	YAHOO.util.Dom.get("listingInquiryStatus").innerHTML = msg;
}
function sendInquiry()
{
	var name = YAHOO.util.Dom.get("listingInquiryName").value;
	var phone = YAHOO.util.Dom.get("listingInquiryPhone").value;
	var email = YAHOO.util.Dom.get("listingInquiryEmail").value;
	var inquiry = YAHOO.util.Dom.get("listingInquiry").value;
	var agentId = YAHOO.util.Dom.get("agentInquiryId").value;
	var id = YAHOO.util.Dom.get("listingInquiryId").value;
	
	if (name == "")
	{
		setInquiryStatus("<span class='error'>* Please enter your name.</span>");
		return;
	}
	if (email == "")
	{
		setInquiryStatus("<span class='error'>* Please enter your email address.</span>");
		return;
	}
	if (inquiry == "")
	{
		setInquiryStatus("<span class='error'>* Please enter your questions.</span>");
		return;
	}
	
	var qstring = "id=" + id + "&name=" + name + "&phone=" + phone + "&email=" + email + "&inquiry=" + inquiry + "&agentId=" + agentId;
	setInquiryStatus("<img src='" + imagePath + "loading.gif'/> Sending...");
	YAHOO.util.Connect.asyncRequest("POST", "services.php", sendInquiry_Callback, "sendInquiry=Y&" + qstring);
}
sendInquiry_Success = function(arg)
{
	if (arg.responseText.trim() == "Y")
		setInquiryStatus("<span class='success'>Thank you. Your inquiry has been sent.</span>");
	else
		sendInquiry_Fail(arg);
}
sendInquiry_Fail = function(arg)
{
	setInquiryStatus("<span class='error'>Sending inquiry failed.</span>");
}
sendInquiry_Callback = 
{
	success : sendInquiry_Success,
	failure: sendInquiry_Fail
};
function setAppointmentStatus(msg)
{
	YAHOO.util.Dom.get("listingAppointmentStatus").innerHTML = msg;
}
function scheduleAppointment()
{
	if (YAHOO.util.Dom.get("listingAppointmentName").value == "")
	{
		setAppointmentStatus("<span class='error'>* Please enter your name.</span>");
		return;
	}
	if (YAHOO.util.Dom.get("listingAppointmentPhone").value == "")
	{
		setAppointmentStatus("<span class='error'>* Please enter your phone number.</span>");
		return;
	}
	if (YAHOO.util.Dom.get("listingAppointmentEmail").value == "")
	{
		setAppointmentStatus("<span class='error'>* Please enter your email address.</span>");
		return;
	}
	
	var qstring = YAHOO.util.Connect.setForm("listingAppaointmentForm");
	setAppointmentStatus("<img src='" + imagePath + "loading.gif'/> Sending...");
	YAHOO.util.Connect.asyncRequest("POST", "services.php", scheduleAppointment_Callback, "scheduleAppointment=Y&" + qstring);
}
scheduleAppointment_Success = function(arg)
{
	alert(arg.responseText);
	if (arg.responseText.trim() == "Y")
		setAppointmentStatus("<span class='success'>Thank you. Your inquiry has been sent.</span>");
	else
		scheduleAppointment_Fail(arg);
}
scheduleAppointment_Fail = function(arg)
{
	setAppointmentStatus("<span class='error'>Sending inquiry failed."+"?"+arg.responseText+"</span>");
}
scheduleAppointment_Callback = 
{
	success : scheduleAppointment_Success,
	failure: scheduleAppointment_Fail
};
function findPos(obj) 
{
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		do {
			curleft += obj.offsetLeft;
			curtop += obj.offsetTop;
		} while (obj = obj.offsetParent);
	}
	return [curleft,curtop];
}
String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
}