// County, City, Listing
var levels = new Array(8, 10, 12);
var lasturl;
var mycount;
var currentLegend = 'price';

var parentSite="" + window.location;
parentSite = parentSite.substring(0, parentSite.lastIndexOf("/"));

var latminp = 0;
var latmaxp = 0;
var lonminp = 0;
var lonmaxp = 0;
var zoomp = 0;

var imageBase = "http://prudential.mlskit.com/prudentialasheville/images/houseIcons/";

var icon1, icon2, icon3, icon4, icon5, icon6, icon7, icon8, icon9;
var stat_icon1, stat_icon2, stat_icon3, stat_icon4, stat_icon5, stat_icon6, stat_icon7, stat_icon8, stat_icon9;
var point_nw = imageBase + "point_nw.gif"
var point_ne = imageBase + "point_ne.gif"
var point_sw = imageBase + "point_sw.gif"
var point_se = imageBase + "point_se.gif"
var testicon;
var map;
var popup;
var zoom;
var zoomp;

function getListings(init, force) {

	// We don't need to change anything if the zoom is less than 10
	zoom = map.getZoom();
    if(zoom < 9) {
        return;
    }

	// Show the loading table
	document.getElementById('loadingTable').style.visibility = 'visible';

    // First, load up the filters
	var type = document.searchForm.s_resType.value;
    var beds = document.searchForm.s_bedrooms.value;
    var baths = document.searchForm.s_bathrooms.value;
	var halfbaths = document.searchForm.s_halfbathrooms.value;
	var priceLow = document.searchForm.s_list_priceLow.value;
	var priceHigh = document.searchForm.s_list_priceHigh.value;
	
	var acresLow = document.searchForm.s_acres_low.value;
	var acresHigh = document.searchForm.s_acres_high.value;
	
	var finsqftLow = document.searchForm.s_fin_sqft_low.value;
	var finsqftHigh = document.searchForm.s_fin_sqft_high.value;
	
	var unfinsqftLow = document.searchForm.s_unfin_sqft_low.value;
	var unfinsqftHigh = document.searchForm.s_unfin_sqft_high.value;

	// Get selected cities
	var count = document.searchForm.s_city_count.value;
	var mycities = "";
	for(var i = 0; i < count; i++) {
		if(document.searchForm['s_city_' + i].checked) {
			mycities += document.searchForm['s_city_' + i].value + "~";
		}
	}
	
	// Get selected counties
	var count = document.searchForm.s_county_count.value;
	var mycounties = "";
	for(var i = 0; i < count; i++) {
		if(document.searchForm['s_county_' + i].checked) {
			mycounties += document.searchForm['s_county_' + i].value + "~";
		}
	}
	
    // Calculate lat and lon
    var bounds = map.getBounds();
    var southWest = bounds.getSouthWest();
    var northEast = bounds.getNorthEast();
    
    var latmin = southWest.lat();
    var latmax = northEast.lat();
    var lonmin = southWest.lng();
    var lonmax = northEast.lng();

	if(init) {
		latminp = 0;
		latmaxp = 0;
		lonminp = 0;
		lonmaxp = 0;
		zoomp = -1;
	}
	
	if(zoom != zoomp) {
		// Always remove popup  when zooming
		removePopup();
	}

	// Counties shown at zoom 9
	if(zoom != 9) {
		counties.clearMap();
	}
	else {
		if(zoomp == 9) {
			counties.cleanupMap(latmin,latmax,lonmin,lonmax);
		}
	}
	
	// Cities shown at 10 and 11
	if(zoom != 10 && zoom != 11) {
		cities.clearMap();
	}
	else {
		if(zoomp == 10 || zoomp == 11) {
			cities.cleanupMap(latmin,latmax,lonmin,lonmax);
		}
	}
	
	// Subdivisions and listings shown at 12+
	if(zoom < 11) {
		subdivisions.clearMap();
		listings.clearMap();
	}
	else {
		if(zoomp >= 11 || force) {
			subdivisions.cleanupMap(latmin,latmax,lonmin,lonmax);
			if((mycount > 500 && zoom != zoomp) || force) {
				listings.clearMap();	
				lonminp = 0;
				lonmaxp = 0;
				lanminp = 0;
				lanmaxp = 0;
			}
			else {
				listings.cleanupMap(latmin,latmax,lonmin,lonmax);
			}
		}
	}
	
	// put the url together
    var url = "index.php?fuseaction=mapsearch.mapLookup&noheader=true&s_resType=" + myescape(type) + "&bedrooms=" + myescape(beds) + "&bathrooms=" + myescape(baths) + "&halfbathrooms=" + myescape(halfbaths) + "&list_priceLow=" + myescape(priceLow) + "&list_priceHigh=" + myescape(priceHigh) + "&s_acres_low=" + myescape(acresLow) + "&s_acres_high=" + myescape(acresHigh) +"&s_fin_sqft_low=" + myescape(finsqftLow)+"&s_fin_sqft_high=" + myescape(finsqftHigh)+"&s_unfin_sqft_low=" + myescape(unfinsqftLow)+"&s_unfin_sqft_high=" + myescape(unfinsqftHigh) + "&s_cities=" + myescape(mycities) + "&s_counties=" + myescape(mycounties) +  "&latmin=" + latmin + "&latmax=" + latmax + "&lonmin=" + lonmin + "&lonmax=" + lonmax + "&zoom=" + zoom + "&latminp=" + latminp + "&latmaxp=" + latmaxp + "&lonminp=" + lonminp + "&lonmaxp=" + lonmaxp + "&zoomp=" + zoomp + "&count=" + (500-listings.getCurrentCount()) + "&force=" + force;
	//getDiv("debug").innerHTML = url;
	lasturl = "index.php?fuseaction=mapsearch.mapLookup&noheader=true&bedrooms=" + myescape(beds) + "&bathrooms=" + myescape(baths) + "&halfbathrooms=" + myescape(halfbaths) + "&list_priceLow=" + myescape(priceLow) + "&list_priceHigh=" + myescape(priceHigh) + "&latmin=" + latmin + "&latmax=" + latmax + "&lonmin=" + lonmin + "&lonmax=" + lonmax + "&zoom=" + zoom;
	
	if(listings.getCurrentCount() < 500) {	
		// load the url
		ajaxPage(url, 'getResults');
	}
	else {
		document.getElementById('loadingTable').style.visibility = 'hidden';
	}

	latminp = latmin;
	latmaxp = latmax;
	lonminp = lonmin;
	lonmaxp = lonmax;
	zoomp = zoom;
}

function getResults(data){
	var detailedListings = "";

	// Hide the loading table
	document.getElementById('loadingTable').style.visibility = 'hidden';

	// See if we have a count
	mycount = getValue("<listing_count>", "</listing_count>",data);
	
	// See if we need to relocate
	var relocate = getValue("<relocate>", "</relocate>",data)
	if(relocate.length > 0 && mycount > 0) {
		ignore = true;
		var lat = getValue("<lat>", "</lat>",relocate);
		var lon = getValue("<lon>", "</lon>",relocate);
		//getDiv("debug").innerHTML = relocate;
		map.setCenter(new GLatLng(lat,lon), 11); 
		//map.panTo(new GLatLng(lat,lon));
	}
	
	
	
	mycurrent = getValue("<listing_current>", "</listing_current>",data);
	if(mycount.length > 0) {
		// Populate the appropriate div
		setCount(mycurrent, mycount);
	}
	
	
	// Parse out the individual listings
	if(data.indexOf("</listings>") > -1) {
		// Parse the listing data
		listings.parseListings(data);
		frames['listingData'].showData(listings.getListingThumbnails());
	}
	
	// Parse out the subdivisions
	if(data.indexOf("</subdivisions>") > -1) {
		subdivisions.parseStatistics(data, "<subdivisions>","</subdivisions>", "<subdivision>");
	}

	// Parse out groups of listings
	if(data.indexOf("</groups>") > -1) {
		// Data is determined by zoom level
		if(zoom == 9) {
			counties.parseStatistics(data, "<groups>","</groups>","<group>");
		}
		else {
			cities.parseStatistics(data, "<groups>","</groups>","<group>");
		}
	}
}

function removePopup() {
	if(popup != null) {
		map.getPane(G_MAP_MARKER_PANE).removeChild(popup);
		popup = null;
	}
}

function mapListing(mls) {	
	listings.mapListing(mls);
}

function zoomIn(lat, lon) {
	// Find the current zoom level
	if(map.getZoom() <= levels[0]) {
		current = 0;
	}
	else if(map.getZoom() <= levels[1]) {
		current = 1;
	}
	else {
		current = 2;
	}
	
	map.setCenter(new GLatLng(lat,lon), levels[current]+1);
}


function start() {
	map = new GMap2(document.getElementById("map"));
	map.addControl(new GScaleControl());
	map.addControl(new GLargeMapControl());
	map.addControl(new GMapTypeControl());
	
	// Get the hash
	if(window.location.hash.length > 0) {
		// Parse out the parts
		var parts = window.location.hash.split(":");
		if(parts.length == 3) {
			parts[0] = parts[0].substring(1, parts[0].length);
			map.setCenter(new GLatLng(Number(parts[1]), Number(parts[2])), Number(parts[0])); 
		}
		else {
			map.setCenter(new GLatLng(35.5778676667,-82.5416563333), 9); 
		}
	}
	else {
		map.setCenter(new GLatLng(35.5778676667,-82.5416563333), 9); 
	}
	
	

	for(var i = 1; i <= 9; i++) {
		var icon = new GIcon();
		icon.image = imageBase + i + ".gif";
		icon.iconSize = new GSize(12, 10);
		icon.iconAnchor = new GPoint(6, 20);
		icon.infoWindowAnchor = new GPoint(5, 1);
		
		eval('icon' + i + ' = icon;');
		
		icon = new GIcon();
		icon.image = imageBase + i + "_stat.gif";
		icon.iconSize = new GSize(13, 13);
		icon.iconAnchor = new GPoint(13, 13);
		icon.infoWindowAnchor = new GPoint(5, 1);
		
		eval('stat_icon' + i + ' = icon;');
	}

	GEvent.addListener(map, "move", function() {moveEvent();});
	
	// Setup our collections
	listings = new MapCollection();
	subdivisions = new MapCollection();
	cities = new MapCollection();
	counties = new MapCollection();
	
	listings.setListingData(listingthumbnail_res, listingthumbnail_res_preview);
	listings.setMapData(map, icon1, icon2, icon3, icon4, icon5, icon6, icon7, icon8, icon9);
	subdivisions.setMapData(map, icon1, icon2, icon3, icon4, icon5, icon6, icon7, icon8, icon9);
	cities.setMapData(map, icon1, icon2, icon3, icon4, icon5, icon6, icon7, icon8, icon9);
	counties.setMapData(map, icon1, icon2, icon3, icon4, icon5, icon6, icon7, icon8, icon9);
	
	getListings(true, false);
}

var timerID = null;
function moveEvent() {
	if(timerID != null || timerID != 0) {
		clearTimeout(timerID);
	}
	
	var zoom = map.getZoom();
	var center = map.getCenter();

	// Set the hash
	window.location.hash = zoom + ":" + center.lat() + ":" + center.lng();

	timerID = setTimeout('getListings(false, false)',500);
}

function createMarker(map, point, text) {
	var icon = new GIcon();
	icon.image = "http://labs.google.com/ridefinder/images/mm_20_red.png";
	icon.shadow = "http://labs.google.com/ridefinder/images/mm_20_shadow.png";
	icon.iconSize = new GSize(12, 20);
	icon.shadowSize = new GSize(22, 20);
	icon.iconAnchor = new GPoint(6, 20);
	icon.infoWindowAnchor = new GPoint(5, 1);

	var marker = new GMarker(point, icon);
	map.addOverlay(marker);
	GEvent.addListener(marker, "click", function() {
		marker.openInfoWindowHtml(text);
	});
}

function myCreateMarker3(map, lattitude, longitude, myicon) {
    var marker2 = new GMarker(new GLatLng(lattitude,longitude), myicon);
    map.addOverlay(marker2);
}

function setCount(current, count) {
	mycount = count;

	if(count < 500) {
		getDiv("countDiv").innerHTML = "Displaying 1-" + count + " of " + count + " listings.";
	}
	else {
		// Calculate some menus
		var menu = "";
		var totalPages = Math.ceil(count / 500.0);
		
		for(var i = 0; i < totalPages; i++) {
			var temp1 = i * 500 + 1;
			var temp2 = temp1 + 499;
			if(temp2 > count) {
				temp2 = count;
			}
			
			if(current == i) {
				menu += temp1 + '-' + temp2 + ' &nbsp;';
			}
			else {
				menu += '<div style="color: blue; text-decoration: underline; cursor: pointer; display: inline;" onclick="changePage(' + i + ');">' + temp1 + '-' + temp2 + '</div> &nbsp;';
			}
		}
		
		// Lets see what we are displaying
		var start = current * 500 + 1;
		var finish = (start+499);
		if(finish > count) {
			finish = count;
		}

		getDiv("countDiv").innerHTML = "Displaying " + start + "-" + finish + " of " + count + " listings.<br>" + menu;
	}
}

function changePage(page) {
	document.getElementById('loadingTable').style.visibility = 'visible';
	removePopup();
	listings.clearMap();
	ajaxPage(lasturl + "&page=" + page, 'getResults');
}


function doneMapping(element) {
	element.style.backgroundColor = "FAFAFA";
}

function filterSearch() {
	// Redo the page of listings with the filter on
	getListings(true, true);
}

function changeLegend() {
	var legend = "";
	for(var i = 0; i < document.legendForm.legendGroup.length; i++) {
		if(document.legendForm.legendGroup[i].checked) {
			legend = document.legendForm.legendGroup[i].value;
		}
	}
	
	if(legend != currentLegend) {
	
		if(legend == "price") {
			getDiv("sqftDiv").style.display = 'none';
			getDiv("acresDiv").style.display = 'none';
			getDiv("$sqftDiv").style.display = 'none';
			getDiv("$acreDiv").style.display = 'none';
			getDiv("priceDiv").style.display = '';
		}
		else if(legend == "sqft") {
			getDiv("priceDiv").style.display = 'none';
			getDiv("acresDiv").style.display = 'none';
			getDiv("$sqftDiv").style.display = 'none';
			getDiv("$acreDiv").style.display = 'none';
			getDiv("sqftDiv").style.display = '';
		}
		else if(legend == "$PerSqft") {
			getDiv("priceDiv").style.display = 'none';
			getDiv("acresDiv").style.display = 'none';
			getDiv("sqftDiv").style.display = 'none';
			getDiv("$acreDiv").style.display = 'none';
			getDiv("$sqftDiv").style.display = '';
		}
		else if(legend == "$PerAcre") {
			getDiv("priceDiv").style.display = 'none';
			getDiv("acresDiv").style.display = 'none';
			getDiv("sqftDiv").style.display = 'none';
			getDiv("$sqftDiv").style.display = 'none';
			getDiv("$acreDiv").style.display = '';
		}
		else {
			getDiv("priceDiv").style.display = 'none';
			getDiv("sqftDiv").style.display = 'none';
			getDiv("$sqftDiv").style.display = 'none';
			getDiv("$acreDiv").style.display = 'none';
			getDiv("acresDiv").style.display = '';
		}

		listings.changeLegend(legend);	
		currentLegend = legend;
	}
}

function jumpTo(lat, lon, level) {
	removePopup();
	map.setCenter(new GLatLng(lat,lon), level); 
}

function showQuickLookup() {
	frames['listingData'].showQuickLookup();
	getDiv("listingDiv").style.display = '';
	getDiv("countDiv").style.display = '';
	frames['listingData'].scrollTo(0,0);
	map.checkResize();
}

function showListings() {
	frames['listingData'].hideQuickLookup();
	getDiv("listingDiv").style.display = '';
	getDiv("countDiv").style.display = '';
	map.checkResize();
}

function hideListings() {
	frames['listingData'].showQuickLookup();
	getDiv("countDiv").style.display = 'none';
	getDiv("listingDiv").style.display = 'none';
	map.checkResize();
}