var toCalendar, toDialog;
function init() 
{  
	offX = 435;
	offY = 5;
	var height = YAHOO.util.Dom.getClientHeight();
	height = height-295;
	//YAHOO.util.Dom.setStyle("apartments-right", "height", height + "px");
	//YAHOO.util.Dom.setStyle("apartments-left", "height", height + "px");
	height = height-3;
//	YAHOO.util.Dom.setStyle("generalMap", "height", height + "px");

	loadGeneralMap();
	positionDetails();
	
	fromCalendar = new YAHOO.widget.Calendar("fromContainer", {
        iframe:false,          // Turn iframe off, since container has iframe support.
        hide_blank_weeks:true  // Enable, to demonstrate how we handle changing height, using changeContent
    });
    fromDialog = new YAHOO.widget.Dialog("fromSelectorContainer", {
        context:["moveFromIcon", "tl", "bl"],
        width:"14em",  // Sam Skin dialog needs to have a width defined (7*2em + 2*1em = 16em).
        draggable:false,
        close:true
    });
    fromCalendar.render();
    fromDialog.render();
    fromDialog.hide();
    fromCalendar.selectEvent.subscribe(fromOkHandler, fromCalendar, true);
	fromCalendar.renderEvent.subscribe(function() {
        // Tell Dialog it's contents have changed, Currently used by container for IE6/Safari2 to sync underlay size
        dialog.fireEvent("changeContent");
    });
	YAHOO.util.Event.on("moveFromIcon", "click", function() {
		if (YAHOO.util.Dom.get("moveFrom").value != "")
		{
			var selDateVal = YAHOO.util.Dom.get("moveFrom").value;
			if (fromCalendar.select(selDateVal) != "Invalid Date" && !isNaN(fromCalendar.select(selDateVal)))
			{
				var selectedDates = fromCalendar.getSelectedDates(); 
		        if (selectedDates.length > 0) { 
		            var firstDate = selectedDates[0]; 
		            fromCalendar.cfg.setProperty("pagedate", (firstDate.getMonth()+1) + "/" + firstDate.getFullYear()); 
		            fromCalendar.render();
		        }
		    	//YAHOO.util.Dom.get("moveFrom").style.color="black";
	        }
			else
			{
				YAHOO.util.Dom.get("moveFrom").style.color="#d5d0d0";
				YAHOO.util.Dom.get("moveFrom").value = "From";
			}
		        
			toCalendar.render();
		}
		fromDialog.show();
		if (YAHOO.env.ua.opera && document.documentElement) {
			// Opera needs to force a repaint
			document.documentElement.className += "";
		} 
	});
	
	toCalendar = new YAHOO.widget.Calendar("toContainer", {
        iframe:false,          // Turn iframe off, since container has iframe support.
        hide_blank_weeks:true  // Enable, to demonstrate how we handle changing height, using changeContent
    });
    toDialog = new YAHOO.widget.Dialog("toSelectorContainer", {
        context:["moveToIcon", "tl", "bl"],
        width:"14em",  // Sam Skin dialog needs to have a width defined (7*2em + 2*1em = 16em).
        draggable:false,
        close:true
    });
    toCalendar.render();
    toDialog.render();
    toDialog.hide();
    toCalendar.selectEvent.subscribe(toOkHandler, toCalendar, true);
	toCalendar.renderEvent.subscribe(function() {
        // Tell Dialog it's contents have changed, Currently used by container for IE6/Safari2 to sync underlay size
        dialog.fireEvent("changeContent");
    });
	YAHOO.util.Event.on("moveToIcon", "click", function() {
		if (YAHOO.util.Dom.get("moveTo").value != "")
		{
			var selDateVal = YAHOO.util.Dom.get("moveTo").value;
			if (toCalendar.select(selDateVal) != "Invalid Date" && !isNaN(toCalendar.select(selDateVal)))
			{
				var selectedDates = toCalendar.getSelectedDates(); 
		        if (selectedDates.length > 0) { 
		            var firstDate = selectedDates[0]; 
		            toCalendar.cfg.setProperty("pagedate", (firstDate.getMonth()+1) + "/" + firstDate.getFullYear()); 
		            toCalendar.render();
		        	
		        }
		        
		        //YAHOO.util.Dom.get("moveTo").style.color="black";
	        }
			else
			{ 
				YAHOO.util.Dom.get("moveTo").style.color="#d5d0d0";
				YAHOO.util.Dom.get("moveTo").value = "To";
			}
			toCalendar.render();
		}
		toDialog.show();
		if (YAHOO.env.ua.opera && document.documentElement) {
			// Opera needs to force a repaint
			document.documentElement.className += "";
		} 
	});
	
	if (selListingId != "")
	{
		viewApartmentDetails(selListingId, selType);
	}
	unfocusSearchFields(YAHOO.util.Dom.get("searchRentFrom"));
	unfocusSearchFields(YAHOO.util.Dom.get("searchRentTo"));
	unfocusSearchFields(YAHOO.util.Dom.get("moveFrom"));
	unfocusSearchFields(YAHOO.util.Dom.get("moveTo"));
}
function fromOkHandler(type,args,obj) {
    var selected = args[0];
	var selDate = this.toDate(selected[0]);

    // Pretty Date Output, using Calendar's Locale values: Friday, 8 February 2008
    var dStr = selDate.getDate();
    var mStr = selDate.getMonth() + 1;
    var yStr = selDate.getFullYear();
   
    YAHOO.util.Dom.get("moveFrom").value = mStr + "/" + dStr + "/" + yStr;
    if(YAHOO.util.Dom.get("moveFrom").value!="From")
        YAHOO.util.Dom.get("moveFrom").style.color="black";
    fromDialog.hide();
}
function toOkHandler(type,args,obj) {
    var selected = args[0];
	var selDate = this.toDate(selected[0]);

    // Pretty Date Output, using Calendar's Locale values: Friday, 8 February 2008
    var dStr = selDate.getDate();
    var mStr = selDate.getMonth() + 1;
    var yStr = selDate.getFullYear();
	
    YAHOO.util.Dom.get("moveTo").value = mStr + "/" + dStr + "/" + yStr;
    if(YAHOO.util.Dom.get("moveTo").value!="To")
    YAHOO.util.Dom.get("moveTo").style.color="black";
    toDialog.hide();
}
function positionDetails()
{
	positionGeneralMap();
}
function sortResults(sort)
{
	YAHOO.util.Dom.get("searchSort").value = sort;
	YAHOO.util.Dom.get("simpleSearchForm").submit();
}

//------------copied from common js-----------------
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();

	var center = null;
	for(var i = 0; i < listings.length; i++)
	{
    	if (listings[i].latitude != null && listings[i].longitude != null)
    	{
    		var point = new GLatLng(listings[i].latitude, listings[i].longitude);
    		if (center == null)
    			center = point;
    		// Create YGL marker icon
    		var YGLIcon = new GIcon(G_DEFAULT_ICON);
    		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);
    		marker.listingId = listings[i].rentalPropertyId;
    			
    		map.addOverlay(marker);
        	GEvent.addListener(marker, "click", function() {
        		  openMapInfo(this);
        	});
    	}
	}
	
	map.setCenter(center, 13);
}
function openMapInfo(marker)
{
	var html = "<table style='margin:0px;'>";
	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 style=\"display:none;\">";
		html += "<td colspan='4' style='text-align:center; padding-bottom:10px;'><img src='" + YAHOO.util.Dom.get(marker.listingId + "_PHOTO").src + "' style='width:120px;' /></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=\"http://integration.yougotlistings.com/metrorealtycorpDetails.php?id="+marker.listingId+ "\" style='font-weight:bold;'   >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 sentThank 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)
{
	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.</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,"");
};

function focusSearchFields(node)
{
	//var ele = document.getElementById(id);
	var ele = node;
	var value = node.value;
	var id = node.id;
	ele.isFocused = true;
	if (value=="From"||value=="To")
	{ 
		ele.value = "";
		ele.style.color="black";
		
	}
	else if (!value)
	{  
		if (id.indexOf("From")!=-1)
		ele.value = "From";
		else if (id.indexOf("To")!=-1)
		ele.value ="To";
		ele.style.color="black";
	}
}
function unfocusSearchFields(node)
{ 
	var ele = node;
	var value = node.value;
	var id = node.id;
	
	ele.isFocused = false;
	
	if (!ele.value)
	{
		if (id.indexOf("From")!=-1)
		{
			ele.value = "From";
			
		}
	    else if (id.indexOf("To")!=-1)
			ele.value ="To";
		
		ele.style.color="#d5d0d0";
	}
	else if (ele.value != "From" && ele.value != "To")
		ele.style.color = "black";
}
