var map;
var listings;
var selections, selectedIndex;
var bubble =false;
var loading =false;
var markers = new Array();
var hideAnimLeft, expandAnim;
var sheet;
var isHidden = false;
var first_come_in=true;
var current_listing;
var initCall=true;
var reloading =false;
var mgr;
var  latStart = null, latEnd = null, longStart = null, longEnd = null;
var maxZoom =14;
var initCall = true;
function init() {
	
	resizeMap(); // calculate the map size based on client screen resolution.
	googleMapsInit(); // initialize the google map.
}
function findMarker(lat, lng) {
	for ( var i = 0; i < markers.length; i++) {
		var pt = markers[i].getLatLng();
		if (lat == pt.lat() && lng == pt.lng())
			return markers[i];
	}
	return null;
}
function resizeMap() {
	var height = YAHOO.util.Dom.getClientHeight();
	height = height -170;
	YAHOO.util.Dom.setStyle("map_search_results", "height", height + "px");
	var width = 906;
	YAHOO.util.Dom.setStyle("map_search_results", "width", width + "px");
}
function bubbleShowLoading() {
	
	YAHOO.util.Dom.get("map_status1").style.display = "block";
	
	YAHOO.util.Dom.get("map_status1").innerHTML = "<img src=\"" + YGL_URL
			+ "images/loading.gif\" /> Loading...";
}
function bubbleHideLoading() {

	YAHOO.util.Dom.get("map_status1").style.display = "none";
}

function googleMapsInit() {
	if (GBrowserIsCompatible()) {
		map = new GMap2(document.getElementById("map_search_results"));

		
	      G_PHYSICAL_MAP.getMinimumResolution = function () { return maxZoom };
        G_NORMAL_MAP.getMinimumResolution = function () { return maxZoom };
        G_SATELLITE_MAP.getMinimumResolution = function () { return maxZoom };
        G_HYBRID_MAP.getMinimumResolution = function () { return maxZoom}; 
		// initCall=true;
	
		GEvent.addListener(map, "load", loadListings); // the event gets called when the map is loaded, so we start load listings.
		GEvent.addListener(map, "dragend", loadListings);  // when user drag the map, we need to reload the listings.
		GEvent.addListener(map, "zoomend", reloadListings); 
		//GEvent.addListener(map, "moveend", loadListings);
		 GEvent.addListener(map,"infowindowclose", function() {
		       bubble = false;
		      }); 
		 GEvent.addListener(map,"infowindowopen", function() {
		       bubble =true;
		      }); 
		var centerLocation=null ;
		
		if(latitude&&longitude&&first_come_in) 
		{
			centerLocation = new GLatLng(latitude, longitude);	
		}
		else
			centerLocation = new GLatLng(42.35036169021923, -71.10445976257324);
		map.setCenter(centerLocation, defaultZoom);
		map.setUIToDefault();
		//alert(map.getZoom());
		mgr = new MarkerManager(map);
		var infoWin = map.getInfoWindow();
		infoWin.enableMaximize();
		GEvent.addListener(infoWin, "maximizeend", expandSingle);

	} else
		map = null;

}
function reloadListings() {
	
	clearSearch();
	latStart = null, latEnd = null, longStart = null, longEnd = null;
	var bound = map.getBounds();
	var sw = bound.getSouthWest();
	var ne = bound.getNorthEast();
		var qstring ="";
		qstring += "&min_rent=" + YAHOO.util.Dom.get("min_rent").value
				+ "&max_rent=" + YAHOO.util.Dom.get("max_rent").value;
		qstring += "&move_in="
			+ YAHOO.util.Dom.get("move_in").options[YAHOO.util.Dom
					.get("move_in").selectedIndex].value;
		qstring += "&beds_from="
				+ YAHOO.util.Dom.get("beds_from").options[YAHOO.util.Dom.get("beds_from").selectedIndex].value;
		qstring += "&beds_to="
			+ YAHOO.util.Dom.get("beds_to").options[YAHOO.util.Dom.get("beds_to").selectedIndex].value;
		qstring += "&photo=" + ((YAHOO.util.Dom.get("photos").checked) ? "Y" : "");
		qstring += "&latitude_start=" +  sw.lat() + "&latitude_end=" + ne.lat()
		+ "&longitude_start=" + sw.lng() + "&longitude_end=" + ne.lng();	//alert("reload"+qstring);
		showLoading();  // show loading message
		YAHOO.util.Connect.asyncRequest("POST", "listings",	loadListings_Callback, qstring);
		return false; // stops the search from submitting.
	
	}
function loadListings() {
//alert("load");
	if(initCall)
	{
		initCall = false; 
		
	return;
	}
	var bound = map.getBounds();
	var sw = bound.getSouthWest();
	var ne = bound.getNorthEast();
	
	var isReload = false;
	if (latStart == null || sw.lat() < latStart)
	{
		latStart = sw.lat();
		isReload = true;
	}
	if (latEnd == null || ne.lat() > latEnd)
	{
		latEnd = ne.lat();
		isReload = true;
	}
	if (longStart == null || sw.lng() < longStart)
	{
		longStart = sw.lng();
		isReload = true;
	}
	if (longEnd == null || ne.lng() > longEnd)
	{
		longEnd = ne.lng();
		isReload = true;
	}
	//alert("reload?"+isReload);

if (isReload)
{
	//alert("reload");
	//clearSearch();
	//var mapBound = map.getBounds();  // get the map coordinates, so we know which listings to get.
	//var sw = mapBound.getSouthWest();
	//var ne = mapBound.getNorthEast();
	// Construct the query string based on the map and the search criteria.
//	var qstring = "latitude_start=" + sw.lat() + "&latitude_end=" + ne.lat()
		//	+ "&longitude_start=" + sw.lng() + "&longitude_end=" + ne.lng();
	var qstring ="";
	qstring += "&min_rent=" + YAHOO.util.Dom.get("min_rent").value
			+ "&max_rent=" + YAHOO.util.Dom.get("max_rent").value;
	qstring += "&move_in="
		+ YAHOO.util.Dom.get("move_in").options[YAHOO.util.Dom
				.get("move_in").selectedIndex].value;
	qstring += "&beds_from="
			+ YAHOO.util.Dom.get("beds_from").options[YAHOO.util.Dom.get("beds_from").selectedIndex].value;
	qstring += "&beds_to="
		+ YAHOO.util.Dom.get("beds_to").options[YAHOO.util.Dom.get("beds_to").selectedIndex].value;
	qstring += "&photo=" + ((YAHOO.util.Dom.get("photos").checked) ? "Y" : "");
	qstring += "&latitude_start=" + latStart + "&latitude_end=" + latEnd
	+ "&longitude_start=" + longStart + "&longitude_end=" + longEnd;
	if(!bubble&&!loading)
	{
		showLoading();  // show loading message
		loading = true;
	//	alert(qstring);
		loading =true;
		YAHOO.util.Connect.asyncRequest("POST", "listings",
				loadListings_Callback, qstring);
		return false; // stops the search from submitting.
	}
	else if(bubble&&!loading)
	{
		bubbleShowLoading();
		loading = true;
		YAHOO.util.Connect.asyncRequest("POST", "listings",
				loadListings_Callback, qstring);
		//alert("bubble loading");
		return false; // stops the search from submitting.
		}
return false;}
	return false; 
}
loadListings_Callback = {
		success : function(arg) {
			//hideLoading(); // hide the loading message
			listings = eval("(" + arg.responseText + ")"); // unserialize the json object.
			if (listings != null && listings.length > 0)
			{
				setTextResults(); 
			}
		},
		failure : function(arg) {
			showError("Loading listings failed.");
		}
};	
function setTextResults() {
	 hideLoading(); // hide the loading message
	if (listings.length > 0) {
		//var newMarkers = new Array();
		for ( var i = 0; i < listings.length; i++) {
			var listing = listings[i];
			// Add the marker to map
			if (listing.latitude != null && listing.longitude != null) {
				//var mk = findMarker(listing);
				var mk = findMarker(listing.latitude, listing.longitude);
				if (mk != null)
					mk.show();
			
				
				else {
					var YGLIcon = new GIcon(G_DEFAULT_ICON);
		    		YGLIcon.image = site_url+"images/house_pin.png";
		    		YGLIcon.shadow = "";
		    		YGLIcon.iconSize = new GSize(28, 26);
		    		markerOptions = { icon:YGLIcon };
		    		var point = new GLatLng(listing.latitude, listing.longitude);
		    		var marker = new GMarker(point, markerOptions);
					GEvent.addListener(marker, "click", openListings);
					map.addOverlay(marker);
					markers[markers.length] = marker;
					//markers[listing.buildingId] = marker;
					//newMarkers.push(marker);
				}
			}
		}
		// mgr.addMarkers(newMarkers,map.getZoom());
		// mgr.refresh();
		
	}
	if(bubble)
	{
		
		bubble= false;
		}
	bubbleHideLoading();
	hideLoading(); // hide the loading message
	loading =false;
}
function openListings(point, expandListingId) {
	
	// Find the apartments at this location.
	selections = new Array(); // contains the listings at this particular location.
	selectedIndex = 0;  // Contains the index of the selected listing.

	// Loop through the listings to find out which ones are at this location.
	for ( var i = 0; i < listings.length; i++) {
		if (parseFloat(listings[i].latitude) == point.lat()	&& parseFloat(listings[i].longitude) == point.lng())
		{
			selections[selections.length] = listings[i];
			if (expandListingId == listings[i].id) // if an id is passed in, then we select the given listing.
					selectedIndex = selections.length - 1; 
		}
	}
	
	// construct the html
	var html = "";
	if (selections.length > 1)
		html += "<div class=\"counter\">" + selections.length
				+ " apartments found at this location!</div>"
	html += "<div id=\"map_listing_overview\" "
			+ ((selections.length > 2) ? "style=\"height:300px; overflow:auto;\""
					: "") + ">";
	for ( var j = 0; j < selections.length; j++) {
		var listing = selections[j];
		var isOdd = (j % 2 == 1);
		html += "<div " + ((isOdd) ? "class=\"odd\"" : "") + ">";
		html += "<div class=\"address\">"
				+ listing.streetName
				+ ", "
				+ ((listing.neighborhood != null && listing.neighborhood != "") ? " ("
						+ listing.neighborhood + ")"
						: "") + "</div>";
	
		html += "<div class=\"city\">" + listing.city + ", " + listing.state
		+ " " + listing.zip
		+ " &nbsp; &nbsp; <a href=\"javascript:maximizeWindow(" + j
		+ ");\">More Info >></a></div>";
		html += "<div class=\"details\">"
		
				+ "<div class=\"price\">For Rent: $"
				+ addCommas(listing.price)
				+ "</div>"
				+ "<div class=\"listing_id\">Apartment ID: "
				+ listing.id
				+ "</div>"
				+ "<div class=\"beds\">"
				+ ((listing.beds == 0) ? "Studio" : listing.beds + " bedroom")
				+ " / "
			
				+ listing.baths
				+ " bathroom</div>"
				+ "<div class=\"available\">Available: "
				+ ((listing.availableDate != null) ? listing.availableDate
						: "All-Times") + "</div>" + "</div>";
	
		if (listing.photos.length > 0)
			html += "<div class=\"photo\"><img src=\"" + listing.photos[0]
					+ "\" /></div>";
		html += "<div class=\"clear\"></div>";
		html += "</div>";
	}
	html += "</div>";

	// Find marker
	//var marker = findMarker(selections[0]);
	var marker = findMarker(point.lat(), point.lng());
	//bubble =true;
	
	var infoWindow = marker.openInfoWindow(
			html,
			{
				maxTitle : "<span id=\"map_listing_details_title\">Listing Details</span>",
				maxContent : "<div id=\"map_listing_details_content\"><img src=\""
						+ YGL_URL
						+ "images/loading.gif\"/> Loading...</div>",
					
			});

	
	if (expandListingId != undefined && expandListingId != null)  // if an id is passed in
	{
		// attach the event to maximize the info window after it is opened.
		GEvent.addListener(marker, "infowindowopen", function() {
			bubble =true;
			maximizeWindow(selectedIndex);	
			
		});
	}
	else  // if not id passed in, then remove any previous attached events.
		GEvent.clearListeners(marker, "infowindowopen");
}
function clearSearch() {
	//alert("clear");
	for ( var i = 0; i < markers.length; i++) {
	//	markers[i].closeInfoWindow();
		markers[i].hide();
	}
	selections = new Array();
	selectedIndex = 0;
}
function showLoading() {
var tempWindow =	map.getInfoWindow();
if(!tempWindow.isHidden())
//	if(bubble)
{//map.getInfoWindow().maximize();
	}
else{ 
	YAHOO.util.Dom.get("map_status").innerHTML = "<img src=\"" + YGL_URL + "images/loading.gif\" /> Loading...";
	YAHOO.util.Dom.get("map_status").style.display = "block";
}
}
//This function gets called after the info window finishes maximizing.
function expandSingle() 
{
	id = selections[selectedIndex].id;
	// retrieve listing details
	YAHOO.util.Connect.asyncRequest("POST", "listing", expandSingle_Callback, "id=" + id);
}
expandSingle_Callback = {
	success : function(arg) {
		var listing = eval("(" + arg.responseText + ")");
		if (listing != null) {
			// format the results.
			YAHOO.util.Dom.get("map_listing_details_title").innerHTML = listing.streetName
					+ ", "
					+ ((listing.neighborhood != null) ? listing.neighborhood
							: listing.city);
			var html = "";
			if (selections.length > 1) {
				html += "<div class=\"paging\">";
				if (selectedIndex > 0)
					html += "<a href=\"javascript:void(0)\" onclick=\"prevSingle()\"><< Prev</a> &nbsp; ";
				html += "Showing ";
				if ((selectedIndex + 1) == 1)
					html += (selectedIndex + 1) + "st";
				else if ((selectedIndex + 1) == 2)
					html += (selectedIndex + 1) + "nd";
				else if ((selectedIndex + 1) == 3)
					html += (selectedIndex + 1) + "rd";
				else
					html += (selectedIndex + 1) + "th";
				html += " of " + selections.length
						+ " listings at this location.";
				if (selectedIndex < (selections.length - 1))
					html += " &nbsp; <a href=\"javascript:void(0);\" onclick=\"nextSingle()\">Next >></a>";
				html += "</div>";
			}

			html += "<div class=\"details\">" 
					
					+ "<div class=\"address\">"
					+ listing.streetName
					+ ", "
					+ ((listing.neighborhood != null && listing.neighborhood != "") ? listing.neighborhood
							: "")
					+ "</div>"
					+ "<div class=\"city\">"
					+ listing.city
					+ ", "
					+ listing.state
					+ " "
					+ listing.zip
					+ "</div>"
					+ "<div class=\"price\">For Rent: $"
					+ addCommas(listing.price)
					+ "</div>"
					+ "<div class=\"beds\">"
					+ ((listing.beds == 0) ? "Studio" : listing.beds
							+ " bedroom") + " / " + listing.baths
					+ " bathroom</div>"
					+ "<div class=\"listing_id\">Apartment ID: " + listing.id
					+ "</div>" 
					+ "<div class=\"detail-contact-info\">For more information, please email us: <br \>" 
					+ "<a href= \"mailto:Showings@HodaraRealEstate.com\">Showings@HodaraRealEstate.com</a>"	
					+ "<br \>or call (617) 787-3002"
					+ "</div>" 
					+ "</div>";
			current_listing=listing.id;
			if (listing.photos.length > 0) 
			{
				
				html += "<div class=\"listing_static_img\">"
					+"<img src=\""
					+ listing.photos[0] + "\" alt=\"apt img\" />"
					+"</div>"; 
			}
			else
			{
				html += "<div class=\"listing_static_img\"></div>";
			}
			html += "<div class\"clear\"></div>";
			html += "<div class=\"yui-skin-sam\"><div id=\"listing_tabs\"></div></div>";
			
			YAHOO.util.Dom.get("map_listing_details_content").innerHTML = html;
			
			var tabView = new YAHOO.widget.TabView();

			var detailsTab = "";
			detailsTab += "<div class=\"overview\">";
			detailsTab += "<div><span class=\"heading\">Available:</span> "
					+ listing.availableDate + "</div>";
			detailsTab += "<div><span class=\"heading\">Fee:</span> "
					+ getFeeDisplay(listing.fee) + "</div>";
			detailsTab += "<div><span class=\"heading\">Pet:</span> "
					+ listing.pet + "</div>";
			detailsTab += "<div><span class=\"heading\">Rent Includes:</span> "
					+ getRentalIncludes(listing) + "</div>";
			detailsTab += "</div>";

			if (listing.features.length > 0) {
				var features = listing.features.join(", ");
				detailsTab += "<div class=\"heading\">Apartment Features</div>";
				detailsTab += "<div class=\"description\">" + features
						+ "</div>";
			}
			if (listing.poi.length > 0) {
				var poi = listing.poi.join(", ");
				detailsTab += "<div class=\"heading\">Point of Interests</div>";
				detailsTab += "<div class=\"description\">" + poi + "</div>";
			}
			tabView.addTab(new YAHOO.widget.Tab( {
				label : 'Apartment Details',
				content : detailsTab,
				active : true
			}));
			
			var photosTab = "<div id=\"photos_area\">";
			if (listing.photos.length > 0) {
				for (i = 0; i < listing.photos.length; i++) {
					photosTab += "<div class=\"photo\"><img src=\""
							+ listing.photos[i] + "\" /></div>";
				}
			} else {
				photosTab += "<div class=\"photo\"><img src=\"images/nophoto.gif\" /></div>";
			}
			photosTab += "</div>";
			tabView.addTab(new YAHOO.widget.Tab( {
				label : 'Photos (' + listing.photos.length + ")",
				content : photosTab
			}));
			tabView.addListener("activeIndexChange", function(e) {
				if (e.newValue == 1) {
					YAHOO.util.Dom.setStyle("photos_area", "display", "block");
				} else {
					YAHOO.util.Dom.setStyle("photos_area", "display", "none");
				}
			});
			var ContactTab = "";
			 ContactTab += "<div class=\"YGLContactUs\">";
			 ContactTab += "<form method=\"post\" >";		
			 ContactTab += "<h3>Send Inquery</h3>";
			 ContactTab += "<div id=\"email-status\" name=\"email-status\"></div>";
			 ContactTab += "<div class=\"contactform\">";		 
			 ContactTab += "<div class=\"contactheader\">Name " +  "<span class=\"requiredfield\">*</span>"  + "</div>";
			 ContactTab += "<div class=\"contactfield name\"><input id=\"contact_name\" name=\"" + "contact_name" + "\" maxlength=\"100\" value=\"\" /></div>";
			 ContactTab += "<div class=\"contactheader\">Email " +  "<span class=\"requiredfield\">*</span>" + "</div>";
			 ContactTab += "<div class=\"contactfield email\"><input id=\"contact_email\" name=\"" + "contact_email" + "\" maxlength=\"100\" value=\"\" /></div>";
			 ContactTab += "<div class=\"contactheader\">Phone " +  "</div>";
			 ContactTab += "<div class=\"contactfield phone\"><input id=\"contact_phone\" name=\"" +"contact_phone" + "\" maxlength=\"20\" value=\"\" /></div>";
			 ContactTab += "<div class=\"contactheader\">Subject " +  "<span class=\"requiredfield\">*</span>"  + "</div>";
			 ContactTab += "<div class=\"contactfield subject\"><input id=\"contact_subject\" name=\"contact_subject" + ""+ "\" maxlength=\"100\" value=\"\" /></div>";
			 ContactTab += "<div class=\"contactheader message\">Your message " +  "<span class=\"requiredfield\">*</span>"  + "</div>";
			 ContactTab += "<div class=\"contactfield message\"><textarea id=\"contact_msg\" name=\"contact_msg\" value=\"\"></textarea></div>";
			 ContactTab += "<div class=\"contactsubmit\"><input type=\"button\" name=\"" + "contact_submit" + "\" value=\"Submit\" onclick=\"parseAndSend(current_listing);\"/></div>";
			 ContactTab += "</div>";
			 ContactTab += "</form>";
			 ContactTab += "</div>";
			tabView.addTab(new YAHOO.widget.Tab( {
				label : 'Inquiry',
				content : ContactTab
			}));
			tabView.appendTo('listing_tabs');

			// First set the photos hidden so there is no so much white space.
			YAHOO.util.Dom.setStyle("photos_area", "display", "none"); 
		} else {
			YAHOO.util.Dom.get("map_listing_details_content").innerHTML = "<span class=\"error\">Loading listing details failed.</span>";
		}
	},
	failure : function(arg) {
		YAHOO.util.Dom.get("map_listing_details_content").innerHTML = "<span class=\"error\">Loading listing details failed.</span>";
	}
};
function hideLoading() {

	YAHOO.util.Dom.get("map_status").innerHTML = "";
	YAHOO.util.Dom.get("map_status").style.display= "none";
}
function showError(err) 
{
	YAHOO.util.Dom.get("map_status").innerHTML = "<span class=\"error\" style=\"margin-top:3px;\">" + err + "</span>";
}
/*function findMarker(listing) {
	if (markers[listing.buildingId] != null)
		return markers[listing.buildingId];
	else
		return null;
}*/
function maximizeWindow(ind) {
	
	selectedIndex = ind;
	// expand the map first
	var infowin = map.getInfoWindow();
	infowin.maximize();
}
function prevSingle() {
	selectedIndex -= 1;
	YAHOO.util.Dom.get("map_listing_details_title").innerHTML = "Listing Details";
	YAHOO.util.Dom.get("map_listing_details_content").innerHTML = "<img src=\""
			+ YGL_URL + "images/loading.gif\"/> Loading...";
	expandSingle();
}
function nextSingle() {
	selectedIndex += 1;
	YAHOO.util.Dom.get("map_listing_details_title").innerHTML = "Listing Details";
	YAHOO.util.Dom.get("map_listing_details_content").innerHTML = "<img src=\""
			+ YGL_URL + "images/loading.gif\"/> Loading...";
	expandSingle();
}

function parseAndSend (listingID)
{
	var qstring = "contact_name=" + YAHOO.util.Dom.get("contact_name").value
	+ "&contact_email=" + YAHOO.util.Dom.get("contact_email").value;

	qstring += "&contact_phone="
		+ YAHOO.util.Dom.get("contact_phone").value;
	qstring += "&contact_email="
		+ YAHOO.util.Dom.get("contact_email").value;
	qstring += "&contact_subject="
		+ YAHOO.util.Dom.get("contact_subject").value;
	qstring += "&contact_msg=" + YAHOO.util.Dom.get("contact_msg").value;	
	qstring += "&listingID=" + listingID;	
	YAHOO.util.Connect.asyncRequest("POST", "email-service",
	parseAndSend_Callback, qstring);
}
parseAndSend_Callback = {
	success : function(arg) {
		if(arg)
		{
			showEmailStatus(arg.responseText);
			if(arg.responseText.indexOf("Thank you")>0)
			{
				YAHOO.util.Dom.get("contact_name").value ="";
				YAHOO.util.Dom.get("contact_email").value ="";
				YAHOO.util.Dom.get("contact_phone").value ="";
				YAHOO.util.Dom.get("contact_subject").value ="";
				YAHOO.util.Dom.get("contact_msg").value ="";
			}
		}
	},
	failure : function(arg) {
		showEmailStatus("send email failed. ");
	}
};
function showEmailStatus(status) {
	YAHOO.util.Dom.get("email-status").innerHTML = "<span style=\"margin-bottom:5px\">" + status + "</span>";
}

YAHOO.util.Event.on(window, "load", init);
YAHOO.util.Event.on(window, "onunload", function() {
	GUnload();
});