
var gZoomLevel = 4;
var gMaxZoomLevel = 2;
var gMinZoomLevel = 7;
var _YahooAPI = 'apartmenthunters001';

var imagePath = '/upload/';

var map;
var zl;
var zlong;
var zlat;
var icon;

var results;

var isMember;

function gMapLoad(isMember){
	if (GBrowserIsCompatible()) {

		zl = document.getElementById('zlevel');
		zlong = document.getElementById('zlong');
		zlat = document.getElementById('zlat');
        
        mapDiv = document.getElementById("gMap");
        
		map = new GMap(mapDiv);
        map.setMapType(map.getMapTypes()[0]);
        
        map.addControl(new GSmallMapControl());
        map.addControl(new GMapTypeControl());
        map.addControl(new GScaleControl());
		
        map.centerAndZoom(new GPoint(-119.7462, 36.1700), 11);
		
		GEvent.addListener(map, "zoom", function() {
        	gCheckZoom(map);
			gGetCenter();
    	});		

		GEvent.addListener(map, 'moveend', function() {
			gGetCenter();
		});

        GEvent.addListener(map, 'click', function(overlay, point) {
            if (point) 
				map.recenterOrPanToLatLng(point);
        });		
		
		zl.value = map.getZoomLevel();
        
        //custom icons
        icon = new GIcon();
        icon.image = "http://labs.google.com/ridefinder/images/mm_20_green.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);     
        
        //results view
        results =  document.getElementById('gResults')          
		
	} else {
      alert('Sorry, the Google Maps is not compatible with this browser');
    }	
}


function gZoomTo(coordStr, level)
{
    if (coordStr == '') {
        return false;
    }
    if (!coordStr) {
		return false;
	}

	var coords = coordStr.split(',');
    if (!coords) {
        return false;
    }	
    
	var level = parseInt(level);
	var zoomLevel = level < gMaxZoomLevel ? gMaxZoomLevel : level;
	mapZoomLevel = map.getZoomLevel();
    
    var gPoint = new GPoint(coords[0], coords[1]);
	
	if (mapZoomLevel > zoomLevel) {
		map.centerAndZoom(gPoint, zoomLevel);
	} 
	
	map.recenterOrPanToLatLng(gPoint);
  
    return true;
}

function gCheckZoom(map)
{
	mapZoom = map.getZoomLevel();
	zl.value = mapZoom;
	
	if (mapZoom < gMaxZoomLevel)  { 
		map.zoomTo(gMaxZoomLevel); 
	}
}

function gGetCenter(){
	zlong.value = map.getCenterLatLng().x;
	zlat.value = map.getCenterLatLng().y;
}


/* AJAX */
var gXmlHttpReq;

// create an instance of XMLHTTPRequest Object, varies with browser type, try for IE first then Mozilla
function gCreateXmlHttpReq()
{
	// for IE
	try {
		gXmlHttpReq = new ActiveXObject("Msxml2.XMLHTTP");
	} catch(e) {
		try {
			gXmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
		} catch(oc) {
			gXmlHttpReq = null;
		}
	}
	// for Mozilla (FireFox) 
	if(!gXmlHttpReq && typeof XMLHttpRequest != "undefined") {
		gXmlHttpReq = new XMLHttpRequest();
	}
}

function gGetCitiesList(){
	var regSelect = document.getElementById("regSelect");
    var selectedReg = regSelect.options[regSelect.selectedIndex].value;

	gSwitchLoadWindow(true);
    gSwitchCriteriaForm(false);
    
    var requestUrl = '/search/map/xml.html?do=get_cities&region=' + encodeURIComponent(selectedReg);
	//alert('URL: ' + requestUrl);

	gCreateXmlHttpReq();
	if(gXmlHttpReq) {
		gXmlHttpReq.onreadystatechange = _AreaChangeHandler;
		gXmlHttpReq.open('GET', requestUrl,  true);
		gXmlHttpReq.send(null);		
	}	
}

function _AreaChangeHandler(){
	// state ==4 indicates receiving response data from server is completed
	if(gXmlHttpReq.readyState == 4) {
		// To make sure valid response is received from the server, 200 means response received is OK
		if(gXmlHttpReq.status == 200) {			
            gSwitchLoadWindow(false);
            gSwitchCriteriaForm(true);
          
			gPopulateCityList(gXmlHttpReq.responseXML.documentElement);
			gZoomToArea(gXmlHttpReq.responseXML.documentElement);
		} else {
			alert("problem retrieving data from the server, status code: "  + gXmlHttpReq.status);
		}
	}
}

function _ClearCityList(citySelect) {
	for (var count = citySelect.options.length-1; count >-1; count--) {
		citySelect.options[count] = null;
	}
}

function gPopulateCityList(cityNode)
{
   	var citySelect = document.getElementById('citySelect');
    _ClearCityList(citySelect);
	cityNodes = cityNode.getElementsByTagName('city');
    //empty option tag
	citySelect.options[0] = new Option( '', '',  false, false);
	var coordValue;
	var textValue; 
	var optionItem;
	// populate the dropdown list with data from the xml doc
	for (var count = 0; count < cityNodes.length; count++) {
   		textValue = _GetInnerText(cityNodes[count]);
		coordValue = cityNodes[count].getAttribute('point');
		optionItem = new Option( textValue, coordValue,  false, false);
		citySelect.options[citySelect.length] = optionItem;
	}
}

function gZoomToArea(areaNode){
	coordValue = areaNode.getAttribute('point');
	zoomValue = areaNode.getAttribute('zoom');    
	if(!zoomValue) {
		zoomValue = gZoomLevel;
	}
	gZoomTo(coordValue, zoomValue);
}

/* listings */
function gGetListings(page_nr)
{
	//street or area

	// coords
	var citySelect = document.getElementById("citySelect");
    var selectedCity = citySelect.options[citySelect.selectedIndex].value;
	if (!selectedCity) {
		zlong = document.getElementById("zlong").value;
		zlat = document.getElementById("zlat").value;
		selectedCity = zlong + ',' + zlat;
	}
	
	var propType = document.getElementById("propType").value;
	var minPrice = document.getElementById("minPrice").value;	
	var maxPrice = document.getElementById("maxPrice").value;			
	var minBeds = document.getElementById("minBeds").value;	
	var maxBeds = document.getElementById("maxBeds").value;		
	
   	gSwitchLoadWindow(true);

    var requestUrl = '/search/map/xml.html?do=get_listings' + 
					 '&coords=' + encodeURIComponent(selectedCity) + 
					 '&type=' + encodeURIComponent(propType) + 
					 '&min_price=' + encodeURIComponent(minPrice) + 
					 '&max_price=' + encodeURIComponent(maxPrice) + 
					 '&min_beds=' + encodeURIComponent(minBeds) + 
					 '&page_nr=' + encodeURIComponent(page_nr) + 
					 '&max_beds=' + encodeURIComponent(maxBeds); 
    if(isMember) {
        requestUrl = requestUrl + '&m=1';
	}
	
	//document.write(requestUrl);
	//document.getElementById('gResults').innerHTML= requestUrl;
  //return false;
				 
	//window.open(requestUrl);					 
  
	gCreateXmlHttpReq();
	if (gXmlHttpReq) {
		gXmlHttpReq.onreadystatechange = _CityChangeHandler;
		gXmlHttpReq.open("GET", requestUrl,  true);
		gXmlHttpReq.send(null);		
	}	
}

function _CityChangeHandler(){
	// state ==4 indicates receiving response data from server is completed
	if(gXmlHttpReq.readyState == 4) {
	   	gSwitchLoadWindow(false);
		// To make sure valid response is received from the server, 200 means response received is OK
		if(gXmlHttpReq.status == 200) {			
			gPopulateListings(gXmlHttpReq.responseXML.documentElement);
			gZoomToCity(gXmlHttpReq.responseXML.documentElement)
		} else {
			alert("problem retrieving data from the server, status code: "  + gXmlHttpReq.status);
		}
	}
}

function gPopulateListings(lData) {
	var lNodes = lData.getElementsByTagName('listing');
	var listing = new Array();
    var listingsHtml = '';
    // clear old pins
    map.clearOverlays();
    
    results.innerHTML = '<p>Loading results...</p>';
    
	for (var count = 0; count < lNodes.length; count++) {
		coords = lNodes[count].getAttribute('point').split(',');
		listing['lon'] = coords[0];
		listing['lat'] = coords[1];
		
		listing['id'] = lNodes[count].getAttribute('keyid');
		listing['icon'] = lNodes[count].getAttribute('icon');		
		listing['radius'] = _GetInnerText(lNodes[count].getElementsByTagName('radius').item(0));		
		listing['address'] = _GetInnerText(lNodes[count].getElementsByTagName('address').item(0));
		listing['price'] = _GetInnerText(lNodes[count].getElementsByTagName('price').item(0));
		listing['beds'] = _GetInnerText(lNodes[count].getElementsByTagName('beds').item(0));				
		listing['type'] = _GetInnerText(lNodes[count].getElementsByTagName('type').item(0));						
		listing['description'] = _GetInnerText(lNodes[count].getElementsByTagName('description').item(0));						
		
		listing['images'] = lNodes[count].getElementsByTagName('image');						

	  	var point = new GPoint(parseFloat(listing['lon']), parseFloat(listing['lat']));
	  	map.addOverlay( _CreateMarker(point, listing) );
        listingsHtml +=_CreateListing(listing);
	}
    
   var page_nr=lData.getElementsByTagName('page_nr');
   var page_count = _GetInnerText(lData.getElementsByTagName('listing_count').item(0));
   
   results.innerHTML = '<h3> Found ' + page_count + ' listings matching your criteria... </h3> <br /> ' + _GetInnerText(page_nr.item(0)) + ' <br /><br /><table class="mtable">'+listingsHtml+'</table> <br /> ' + _GetInnerText(page_nr.item(0)) + '';

   
   //var debug = document.getElementById('debug');
   //debug.value = listingsHtml;
    
}

function _CreateMarker(point, listing) {
    if(listing['icon'] == 2)	
        icon.image = "http://labs.google.com/ridefinder/images/mm_20_yellow.png";
	else	
		icon.image = "http://labs.google.com/ridefinder/images/mm_20_green.png";

    var marker = new GMarker(point, icon);

	var keyid = listing['id'];
	var html = '';
	var imageHtml = '';
	var imageCss = '';

	if(listing['images'].length > 0) {
        imageHtml = '<div class="pics">';
		for (var count = 0; count < listing['images'].length; count++) {
			var url = _GetInnerText(listing['images'][count]);			
            imageHtml += '<img src="'+imagePath+url+'" />';
		}
        imageHtml += '</div>';
        imageCss = ' style="width:170px"';
	}

    html = '<div class="lmarker">'+ imageHtml + 
'<div class="descr"'+imageCss+'>' + 
'<p>'+listing['address']+'</p>' + 
'<p><strong>$'+listing['price']+'/mo '+listing['beds']+' '+listing['type']+'</strong></p>' + 
'<p class="txt">'+listing['description']+'...</p>' + 
'<a href="#" onclick="window.open(\'/search/details/'+listing['id']+'.html\', \'lDetails\'); return false;">view details</a>' + 
'</div></div>';
  
    GEvent.addListener(marker, 'click', function() {
	    marker.openInfoWindowHtml(html);
    });
    

    return marker;
}

function _CreateListing(listing) {
    var keyid = listing['id'];
	var imageHtml = '';    
	if(listing['images'].length > 0) {
        var url = _GetInnerText(listing['images'][0]);			
        imageHtml = '<div class="pics"><img src="'+imagePath+url+'" /></div>';
	}

    return '<tr><td><div class="proxim">'+listing['radius']+' miles</div></td>' +
'<td>'+imageHtml+'</td>'+
'<td>'+listing['address']+'</td>'+
'<td><p><strong>'+listing['price']+'/mo '+listing['beds']+' '+listing['type']+'</strong></p>'+
'<p class="txt">'+listing['description']+'...</p>'+
'<a href="#" onclick="window.open(\'/search/details/'+listing['id']+'.html\', \'lDetails\'); return false;">view details</a></td></tr>';
    
}

function gZoomToCity(cityNode){
	coordValue = cityNode.getAttribute("point");
	gZoomTo(coordValue, 3);
}


/* yahoo API find address*/
function gFindAddress(){
	gSwitchLoadWindow(true);
	
	var street = document.getElementById('street').value;
    var city = document.getElementById('city').value;
    var state = document.getElementById('state').value;
    var zip = document.getElementById('zip').value;
	var requestUrl = '/search/map/xml.html?do=find_address' + 
                     '&street=' + encodeURIComponent(street) + 
                     '&city=' + encodeURIComponent(city) + 
                     '&state=' + encodeURIComponent(state) + 
                     '&zip=' + encodeURIComponent(zip);
	//var requestUrl = 'http://api.local.yahoo.com/MapsService/V1/geocode?appid='+ _YahooAPI +'&location=' + encodeURIComponent(csz);
	
	gCreateXmlHttpReq();
	if(gXmlHttpReq) {
		gXmlHttpReq.onreadystatechange = _FindAddressHandler;
		gXmlHttpReq.open("GET", requestUrl,  true);
		gXmlHttpReq.send(null);		
	}		
}

function _FindAddressHandler() {
	// state ==4 indicates receiving response data from server is completed
	if(gXmlHttpReq.readyState == 4) {
	   	gSwitchLoadWindow(false);
		// To make sure valid response is received from the server, 200 means response received is OK
		if(gXmlHttpReq.status == 200) {			
			_GetYahooResponse(gXmlHttpReq.responseXML.documentElement);
		} else {
			alert("problem retrieving data from the server, status code: "  + gXmlHttpReq.status);
		}
	}
}

function _GetYahooResponse(rData) {
	var yLong = _GetInnerText(rData.getElementsByTagName('Longitude').item(0));
	var yLat = _GetInnerText(rData.getElementsByTagName('Latitude').item(0));	
	gZoomTo(yLong + ',' + yLat, 2);
	
	//pretty address
	var yAddress = _GetInnerText(rData.getElementsByTagName('Address').item(0));
	var yCity = _GetInnerText(rData.getElementsByTagName('City').item(0));	
	var yState = _GetInnerText(rData.getElementsByTagName('State').item(0));
	var yZip = _GetInnerText(rData.getElementsByTagName('Zip').item(0));	
	
	// nice address line
	document.getElementById('street').value = yAddress;
	document.getElementById('city').value = yCity;
    //document.getElementById('state').value = yCity;
    document.getElementById('zip').value = yZip;    

	// show criteria form
	gSwitchCriteriaForm(true);
}
/* end yahoo address */

function _GetInnerText (node){
    return (node.textContent || node.innerText || node.text) ;
}

/* form switchers */
function gSwitchBox(box){
	var t1 = document.getElementById('t1');
	var t2 = document.getElementById('t2');
	var f1 = document.getElementById('sbByArea');
	var f2 = document.getElementById('sbByStreet');
	
	if(box == 1) {
		f1.style.display = 'block';
		f2.style.display = 'none';
		
		t1.style.background = '#f5f5f5';
		t1.style.border = '1px solid #D0D0D0';
		t1.style.borderBottom = '1px solid #f5f5f5';
				
		t2.style.background = '#fcfcfc';
		t2.style.border = '1px solid #D0D0D0';		
		
		gSwitchCriteriaForm(true);
	} else {
		f1.style.display = 'none';
		f2.style.display = 'block';
	
		t2.style.background = '#f5f5f5';
		t2.style.border = '1px solid #D0D0D0';
		t2.style.borderBottom = '1px solid #f5f5f5';
				
		t1.style.background = '#fcfcfc';
		t1.style.border = '1px solid #D0D0D0';	
		
		gSwitchCriteriaForm(false);
	}
}

function gSwitchCriteriaForm(state) {
	var sb = document.getElementById('sbCriteria');
	sb.style.display = state ? 'block' : 'none';	
}

function gSwitchLoadWindow(flag) {
	x = document.getElementById('pwait');
//    alert(x.style.visibility);
//	pwait.style.visibility = state ? 'visible' : 'hidden';	
    x.style.visibility = (flag) ? 'visible' : 'hidden';
}
