/*

Script to get rental listings
*/

//Initialize global variables
var map = null; //Map object
var noOFRecordsToDisplay = 30; //Number of listings to be displayed
var urlForInfoWindow = "http://rentagents.net/contact.htm"; //URL that should be shown in the info window of marker

//Longitude and Latitude of Manhattan. Default location to be shown if Client location not found
var defaultLat = 40.783435;
var defualtLng = -73.966249;

//Define icon data
var iconData = {
  "bd1": { width: 22, height: 22 },
  "bd2": { width: 22, height: 22 },
  "bd3": { width: 22, height: 22 },
  "bd4": { width: 22, height: 22 },
  "blue": { width: 22, height: 22 },
  "bd-shadow": { width: 22, height: 22 }
};

//Function to set the initial state of Map. Find the user location and display it on the Center of Map
function initialize() {

	map = new GMap2(document.getElementById("map_canvas"));//Create Map object

	//If able to get Client location
	if (google.loader.ClientLocation) {
		map.setCenter(new GLatLng(google.loader.ClientLocation.latitude, google.loader.ClientLocation.longitude), 14);
	}
	else {
		map.setCenter(new GLatLng(defaultLat,defualtLng), 14);//Show default location
	}

	map.setUIToDefault();


	/*var detail = "<h3>User Location based on IP</h3>Country: " + google.loader.ClientLocation.address.country +
				 "<br> State: " + google.loader.ClientLocation.address.region +
				 "<br> City: " + google.loader.ClientLocation.address.city;

	document.getElementById("ipdetail").innerHTML =  detail;
	*/

	GEvent.addListener(map, 'dragend', innerMapChanged);//Listen to dragevent of map. Call function when user ends the 'drag'
	innerMapChanged();
}//initialize

//Function to reload map periodically. Not in use.
var thread = null;
function mapChanged(){
	try{ window.clearTimeout(thread); }catch(ex){}
	thread = window.setTimeout(innerMapChanged, 5000);
}

//Function to fetch properties on rent
function innerMapChanged(){
	//Find map boundaries
	var bounds = map.getBounds();
	var min = bounds.getSouthWest();
	var max = bounds.getNorthEast();

	//Build the API to fetch the properties
	var url = "http://www.rentrent.org/RENT/Ads.aspx?xmin="+min.lng()+"&ymin="+min.lat()+"&xmax="+max.lng()+"&ymax="+max.lat()+"&bd=&ba=&pets=-1&type=2&callback=gotListings&maxRecords=2000";

	//Call API
	var element = document.createElement('script');
	element.src = url;
	document.body.appendChild(element);
}//mapChanged

//Function called to retrieve listings from the API return object
function gotListings(json){
	map.clearOverlays();

	if (json.Status!='Success') {
		alert(json.Message);
		return;
	}

	// Create marker icon
	var blueIcon = new GIcon(G_DEFAULT_ICON);
	blueIcon.image = "http://gmaps-samples.googlecode.com/svn/trunk/markers/blue/blank.png";
	// Set up our GMarkerOptions object

	var data = json.Data;
	var icount = 0;
	var centerLat=0;
	var centerLng=0;

	var place = new Array();
	place[0] = "blue";
	place[1] = "bd-shadow";

	for (var ids in data) {
		var ad = data[ids];
		var latlng = new GLatLng(ad.Y, ad.X);
		centerLat = centerLat + parseFloat(ad.Y);
		centerLng = centerLng + parseFloat(ad.X);

		if(ad.AdBedroom == "1") {
			place[0] = "bd1";
			place[1] = "bd-shadow";
		}

		if(ad.AdBedroom == "2") {
			place[0] = "bd2";
			place[1] = "bd-shadow";
		}

		if(ad.AdBedroom == "3") {
			place[0] = "bd3";
			place[1] = "bd-shadow";
		}

		if(ad.AdBedroom == "4") {
			place[0] = "bd4";
			place[1] = "bd-shadow";
		}

		var icon = getIcon(place);
		var markerOptions = { icon:icon };

		var marker = new GMarker(latlng, markerOptions);
		map.addOverlay(marker);

		setupMarker(marker, ad);
		icount++;

		//Display limited records and set the center of map
		if (icount == noOFRecordsToDisplay)
		{
			centerLat = centerLat / noOFRecordsToDisplay;
			centerLng = centerLng / noOFRecordsToDisplay;
			 map.setCenter(new GLatLng(centerLat,centerLng), 14);
			return;
		}
	}//for ids
}//gotListings

//Function to setup the markers
function setupMarker(marker, ad){
		
		var tab1HTML = "<Div id='info' style='width: 300px; height: 150px'><b>Property description : </b>" + ad.AdHeader + 
				"<br> <br><b>Price : </b>$" + ad.AdPrice + 
				"<br> <br><a href='#' onClick='map.getInfoWindow().selectTab(2)'><b>Contact us</b></a>" + 
				"</Div>";
		
		var imageHTML = getImageHTML(ad);
		
		if(imageHTML == "") {
			imageHTML = "No images";
		}
		
		var tab2HTML = "<Div id='info' style='width: 300px; height: 150px; overflow:auto''>" + imageHTML + "</Div>";
		var tab3HTML = "<Div id='info' style='width: 300px; height: 150px; overflow:auto'>" + 
				"<p>Your contact info here.</p>" + 
                                "<form method='POST' action='mailer.php'>" + 
   				"<p><strong>Your name:</strong>   <input type='text' name='name' size='30'></p>" +
   				"<p><strong>Your email:</strong>   <input type='text' name='email' size='30'></p>" + 
   				"<p><strong>Message:</strong>   <textarea rows='9' name='message' cols='30'></textarea></p>" +
   				"<input type='submit' value='Submit' name='submit'>" + 
				"</form></Div>";
		
		var tab1 = new GInfoWindowTab("Description", tab1HTML);
		var tab2 = new GInfoWindowTab("Images", tab2HTML);
		var tab3 = new GInfoWindowTab("Contact us", tab3HTML);
		
		var infoTabs = [tab1,tab2,tab3];
		
		GEvent.addListener(marker, "mouseover", function() {
			marker.openInfoWindowTabsHtml(infoTabs);
		});

}//setupMarker

//Function to create custom icon
function getIcon(images) {
	var icon = null;
	if (images) {

	  icon = new GIcon();
	  icon.image = "/images/"
	      + images[0] + ".png";
	  var size = iconData[images[0]];
	  icon.iconSize = new GSize(size.width, size.height);
	  icon.iconAnchor = new GPoint(size.width >> 1, size.height >> 1);
	  icon.shadow = "/images/"
	      + images[1] + ".png";
	  size = iconData[images[1]];
	  icon.shadowSize = new GSize(size.width, size.height);

	  icon.infoWindowAnchor = new GPoint(9, 2);
	}
	return icon;
}

function getImageHTML(rec){var desc = "";
	var arr = rec.AdImages.split(",");
	var imgId = gGuid("I");
	var imgCount = 1;
	var firstImg = "";
	for (var i=0; i<arr.length; i++){if (arr[i]=="") continue;
	desc += "<a href='#' id='L"+imgId+"' onMouseOver='gChangeImage(\""+arr[i]+"\", \""+imgId+"\")'>Image"+ imgCount+"</a>&nbsp;";
	if (imgCount==1){var img = "";
	if (arr[i].indexOf("http:")<0){img = "http://images.craigslist.org/"+arr[i];
	}else{img = arr[i];
	}
	firstImg = "<img id='"+imgId+"' src='"+img+"' />";
	}
	imgCount++;
	}
	desc += firstImg;
	if (desc!="") desc = "<br/>"+desc;
	return desc;
}

function gChangeImage(img,imgId){
	if (img.indexOf("http:")<0){img = "http://images.craigslist.org/"+img;
	}
	document.getElementById(imgId).src = img;
}

function gGuid(seed){
	function S4(){return (((1+Math.random())*0x10000)|0).toString(16).substring(1);
	}
	var d = new Date();
	return seed+(S4()+S4()+""+S4())+d.getTime();
}
