// #region Event handlers
//-------------------------

function ValidGMapConnectivity(){        
    MM_preloadImages('images/nav/global/util_about_us_on.gif','images/nav/global/util_news_on.gif','images/nav/global/util_careers_on.gif','images/nav/global/util_investor_on.gif','images/nav/global/util_inlandgroup_on.gif','images/nav/top_on/nav_primary_home_buying.gif','images/nav/top_on/nav_primary_home_invest.gif','images/nav/top_on/nav_primary_home_leasing.gif','images/loading.gif');   
    try {
        if (GBrowserIsCompatible()) {
            globalGMapObject = new GMap2(document.getElementById("map"));
            globalGMapObject.addControl(new GSmallMapControl());
            globalGMapObject.addControl(new GMapTypeControl());
            globalGMapObject.addControl(new GScaleControl());
            return true;
        }   
        else {
            alert('Your browser is not compatible, try IE 7 or Firefox 2');
            return false;
        }    
    } 
    catch(err){
        alert("Unable to connect to Google maps");
        return false;
    }
}

// This runs when the control is first invoked document.onload
function Page_Load(){    
    if(ValidGMapConnectivity()){
        var inlandPropertyId = getcookie('InlandPropertyId');
        if(inlandPropertyId){
            InlandPropertyMap.WebServices.PropertyWS.GetPropertyById(inlandPropertyId,GetPropertyById_callBack);
        }
        else {
            //alert(document.cookie);
            var inlandSearchCriteria = getcookie('InlandSearchCriteria');
            //alert(inlandSelectedState);
            var inlandPropertyUsage = getcookie('InlandPropertyUsage');
            //alert(inlandPropertyUsage);
            if(inlandPropertyUsage==null || inlandPropertyUsage.trim().length==0)inlandPropertyUsage='ALL';
            var criteria = inlandSearchCriteria.split('@^');    
            document.getElementById('propertyName').value=criteria[0]?criteria[0]:'';       
            document.getElementById('street').value = criteria[1]?criteria[1]:'';
	        document.getElementById('city').value= criteria[2]?criteria[2]:'';
	        document.getElementById('state').value = criteria[3]?criteria[3]:'';
	        document.getElementById('zip').value = criteria[4]?criteria[4]:'';
            btnSearch_OnClick();	                         
        }
    }
}
    

// Used when clicking on a property link from propertylist
// Sets the map center and zoom
function PropertyName_OnClick(latitude, longitude, markerIndex){
    if(latitude==0 && longitude == 0){
        alert('There is no geocode for that property');
        return;
    }
    var zoom = 5;
    if(globalGMapObject.getZoom() < 5)zoom = globalGMapObject.getZoom(); 
    globalGMapObject.setCenter(new GLatLng(latitude, longitude), 17 - zoom);
    GEvent.trigger(markerCache[markerIndex],"click");
} 

// invoked on search button
function btnSearch_OnClick(){    
     var propertyName = (document.getElementById('propertyName').value).trim();
     if(propertyName.length>0 && propertyName.length<3){
        alert('Please provide at least 3 characters for property name search');
        return;
     }
	 var street = document.getElementById('street').value.trim();
	 var city = document.getElementById('city').value.trim();
	 var txtState = document.getElementById('state');
	 txtState.value = txtState.value.toUpperCase();
	 var state = txtState.value.trim();
	 var zip = document.getElementById('zip').value.trim();
	 if(zip.length>0){
	    if(!isValidZIP(zip)){
	        alert('Invalid Zip Code');
	        return;
	    }
	 }
	 var inlandPropertyUsage = getcookie('InlandPropertyUsage');
	 BePatient();
	 InlandPropertyMap.WebServices.PropertyWS.GetProperties(propertyName, street, city, state, zip, inlandPropertyUsage, DataBind);
}

// #region Web Service call back functions
//----------------------------------------

function DataBind(result, userContext, methodName){ 
    globalGMapObject.clearOverlays();
    var boundary = result.documentElement.getElementsByTagName("boundary")[0];  
    var s = parseFloat(boundary.getAttribute("minlat"));
    var w = parseFloat(boundary.getAttribute("minlng"));
    if(s==90 && w==180){
        globalGMapObject.clearOverlays();
        var propertyListPanel = document.getElementById("tdPropertyPanel");
        propertyListPanel.innerHTML="No properties found";    
    }
    else {
        var sw = new GLatLng(s,w);    
        var ne = new GLatLng(parseFloat(boundary.getAttribute("maxlat")),parseFloat(boundary.getAttribute("maxlng")));    
        var bounds = new GLatLngBounds(sw,ne);    
        var zoomLevel = globalGMapObject.getBoundsZoomLevel(bounds);
        if(zoomLevel>15){        
            zoomLevel=15;
        }
        globalGMapObject.setCenter(bounds.getCenter(), zoomLevel);
        RenderPropertiesAsGMarker(result);
        RenderPropertiesAsHTML(result,false);
    }
}

// Callback function for Firefox only
function GetPropertyById_callBack(result, userContext, methodName){
    globalGMapObject.clearOverlays(); 
    var marker = result.documentElement.getElementsByTagName("point")[0];    
    var point = new GLatLng(parseFloat(marker.getAttribute("lat")), parseFloat(marker.getAttribute("lng"))); 
    globalGMapObject.setCenter(point,15);
    RenderPropertiesAsGMarker(result);    
    RenderPropertiesAsHTML(result,false);    
}

// #region Rendering functions
// ----------------------------

// This function renders the xml data as HTML
// The rendering is through the stringbuilder class that performs better than string concatenation
// This is somehow cumbersome but this approach keeps the MVC pattern clean because the same Model (xml data)
// is used in 2 views, rendered as HTML in the property panel and rendered as markers in the GMap
function RenderPropertiesAsHTML(propertiesXml,createMarker){
    var propertyListPanel = document.getElementById("tdPropertyPanel");
    var points = propertiesXml.documentElement.getElementsByTagName("point"); 
    //alert(points.length + " points");
    var sb = new StringBuilder();
    sb.append("<div class='searchResults'>");
    for(var i = 0; i<points.length; i++){
        sb.append("<ul><li class='propName'><a href='#' onclick='");
        sb.append("PropertyName_OnClick(");
        sb.append(points[i].getAttribute("lat")+","+points[i].getAttribute("lng")+","+i+");return false;'");
//        if(createMarker==true){
//            sb.append("DisplayAddressMarker(");
//            sb.append(points[i].getAttribute("lat")+","+points[i].getAttribute("lng")+","+points[i].getAttribute("propertyid"));
//            sb.append(",this.propertyname,this.propertyaddress,this.propcitystzip,this.propertyurl,this.usagecode");
//        }
//        else{
//            sb.append("PropertyName_OnClick(");
//            sb.append(points[i].getAttribute("lat")+","+points[i].getAttribute("lng"));
//        }
//        sb.append(");return false;'");
//        if(createMarker==true){
//            sb.append(" propertyname='"+points[i].getAttribute("propertyname")+"'");
//            sb.append(" propertyaddress='"+points[i].getAttribute("propertyaddress")+"'");
//            sb.append(" propcitystzip='"+points[i].getAttribute("propcitystzip")+"'");
//            sb.append(" propertyurl='"+points[i].getAttribute("propertyurl")+"'");
//            sb.append(" usagecode='"+points[i].getAttribute("usagecode")+"'");
//        }
        sb.append(">");
        sb.append(points[i].getAttribute("propertyname"));
        sb.append("</a></li><li class='propAddress'>");
		sb.append(points[i].getAttribute("propertyaddress"));
		sb.append("</li><li class='propCityStZip'>");
		sb.append(points[i].getAttribute("propcitystzip"));
		sb.append("</li></ul>");
        //propertyListPanel.insertAdjacentHTML("BeforeEnd",sb.toString());
    }
    sb.append("</div>");
    propertyListPanel.innerHTML=sb.toString();
}

function RenderPropertiesAsGMarker(propertiesXml){
    globalGMapObject.clearOverlays();    
    // setting points
    var markers = propertiesXml.documentElement.getElementsByTagName("point"); 
    for(var i = 0; i<markers.length; i++) { 
        var point = new GLatLng(parseFloat(markers[i].getAttribute("lat")), parseFloat(markers[i].getAttribute("lng"))); 
        var propName = markers[i].getAttribute("propertyname");
        var propUrl = markers[i].getAttribute("propertyurl");
        var address =  markers[i].getAttribute("propertyaddress");
        var propcitystzip =  markers[i].getAttribute("propcitystzip");
        var usagecode = markers[i].getAttribute("usagecode");
        var theMarker = CreateAddressMarker(point,propName,address,propcitystzip,propUrl,usagecode);
        globalGMapObject.addOverlay(theMarker);
        markerCache[i]=theMarker;
    } 
}


// #region Google Map management functions
// ---------------------------------------

// Creates normal marker
// return type: GMarker
// parameters:
//      point - GLatLang point
//      propname - string, property name
//      propaddress - string, property address
//      propcitystzip - string, property city and zip code
//      propurl - string, property url
function CreateAddressMarker(point, propname,propaddress,propcitystzip,propurl,usagecode) {
    var html="<div class='SearchResults'><h5>"+propname+"</h5><p>"+propaddress+"<br/>"+propcitystzip+"<br/><a target='_blank' href=http://"+propurl+">More Info</a></p></div>";   
    // Create a "tiny" marker icon
    var icon = new GIcon();
    switch(usagecode){
        case 'RETAIL': icon.image = "images/icons/mm_20_3d_red2.png";
            break;
        case 'OFFICE': icon.image = "images/icons/mm_20_3d_blue.png";
            break;
        case 'INDUSTRIAL': icon.image = "images/icons/mm_20_3d_brown.png";
            break;
        case 'APARTMENT': icon.image = "images/icons/mm_20_3d_dkgreen.png";
            break;
        case 'MULTI_FAMILY': icon.image = "images/icons/mm_20_3d_ltgreen.png";
            break;
        case 'HOTEL': icon.image = "images/icons/mm_20_3d_orange1.png";
            break;
        default: icon.image = "images/icons/mm_20_3d_question.png";
            break;
    }
    icon.shadow = "images/icons/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 options = new Object();
    options.title=propname;
    options.icon = icon;
    var marker = new GMarker(point,options);
    // make the marker show the bubble with property url
    GEvent.addListener(marker, "click", function() {
        marker.openInfoWindowHtml(html);
    });
    return marker;
}

// #region Utility functions
// -------------------------

// this function shows the loading text and icon in the property panel
function BePatient(){
    var propertyListPanel = document.getElementById("tdPropertyPanel");
    propertyListPanel.innerHTML = "<div class='searchResultsLoading'><table><tr valign='center'><td><img src='Images/loading.gif'/></td><td>&nbsp;</td><td>Loading...</td></tr></table></div>";    
}

function ResetSearchControls(){
    document.getElementById("query").value="Enter a City/Zip Code";
}    

// Returns true if is a valid zipcode
function isValidZIP(field) {
    var valid = "0123456789-";
    var hyphencount = 0;
    if (field.length!=5 && field.length!=10) {
        // not zipcode
        return false;
    }
    for (var i=0; i < field.length; i++) {
        temp = "" + field.substring(i, i+1);
        if (temp == "-") hyphencount++;
        if (valid.indexOf(temp) == "-1") {
            // not zipcode, it must be some weird number
            return false;
        }
    if ((hyphencount > 1) || ((field.length==10) && ""+field.charAt(5)!="-")) {
        // bad zipcode, or address
        return false;
       }
    }
    // it must be a valid zipcode
    return true;
}

 // used to trap the return key when entering a zipcode
    function fnTrapKD(btnID, event){
		btn = findObj(btnID);
		if (document.all){
			if (event.keyCode == 13){
				event.returnValue=false;
				event.cancel = true;
				btn.click();
			}
		}
		else if (document.getElementById){
			if (event.which == 13){
				event.returnValue=false;
				event.cancel = true;
				btn.focus();
				btn.click();
			}
		}
		else if(document.layers){
			if(event.which == 13){
				event.returnValue=false;
				event.cancel = true;
				btn.focus();
				btn.click();
			}
		}
	}
	
	function findObj(n, d) { 
		var p,i,x;  
		if(!d) 
			d=document; 
		if((p=n.indexOf("?"))>0 && parent.frames.length) {
			d=parent.frames[n.substring(p+1)].document; 
			n=n.substring(0,p);
		}
		if(!(x=d[n])&&d.all) 
			x=d.all[n]; 
		for (i=0;!x&&i<d.forms.length;i++) 
			x=d.forms[i][n];
		for(i=0;!x&&d.layers&&i<d.layers.length;i++) 
			x=findObj(n,d.layers[i].document);
		if(!x && d.getElementById) 
			x=d.getElementById(n); 
		return x;
	}
	
function getcookie(cookiename) {
     var cookiestring=""+document.cookie;
     var index1=cookiestring.indexOf(cookiename);
     if (index1==-1 || cookiename=="") return ""; 
     var index2=cookiestring.indexOf(';',index1);
     if (index2==-1) index2=cookiestring.length; 
     return unescape(cookiestring.substring(index1+cookiename.length+1,index2));
}	

	
// #region StringBuilder functions
// --------------------------------
// Initializes a new instance of the StringBuilder class
// and appends the given value if supplied
function StringBuilder(value){
    this.strings = new Array("");
    this.append(value);
}
// Appends the given value to the end of this instance.
StringBuilder.prototype.append = function (value){
    if (value){
        this.strings.push(value);
    }
}
// Clears the string buffer
StringBuilder.prototype.clear = function (){
    this.strings.length = 1;
}
// Converts this instance to a String.
StringBuilder.prototype.toString = function (){
    return this.strings.join("");
}



// #region DEPRECATED
//-------------------------

// DEPRECATED August 2007
// Displays a mrker on the fly.
// used when the map is in national view and there are no markers available
// and the user clicks on a property in the panel
//function DisplayAddressMarker(lat,lng, propertyid,propname,propaddress,propcitystzip,propurl,usagecode) {
//    if(propname==null){
//        // this means the browser is not IE and we will need another WS call
//        InlandPropertyMap.WebServices.PropertyWS.GetPropertyById(propertyid,GetPropertyById_callBack);
//    }
//    else{ 
//        var point = new GLatLng(parseFloat(lat), parseFloat(lng)); 
//        globalGMapObject.addOverlay(CreateAddressMarker(point,propname,propaddress,propcitystzip,propurl,usagecode));
//        PropertyName_OnClick(lat,lng);
//    }
//}

// DEPRECATED July 2007
// Invokes web service GetPropertiesByBounds
// parameter:
//      querytype - string: ZIPCODE | NATIONALMARKER | CITY
// WS call back: GetPropertiesByBounds_callBack
//function Page_DataBind(queryType)
//{    
//    var bounds = globalGMapObject.getBounds(); 
//	var southWest = bounds.getSouthWest(); 
//	var northEast = bounds.getNorthEast(); 
//    //alert('sw lat=' + southWest.lat()+ ' sw lang=' + southWest.lng()+ ' ne lat='+ northEast.lat() + ' ne lang='+northEast.lng());
//    InlandPropertyMap.WebServices.PropertyWS.GetPropertiesByBounds(southWest.lat(),southWest.lng(),northEast.lat(),northEast.lng(),queryType,GetPropertiesByBounds_callBack);
//}

// DEPRECATED July 2007
//Used to set the map boundary to city or zipcode or national marker and refresh property list
//Parameters:
//  point - GLatLang, represents latitude and longitude of selection
//  isValidZip: boolean value indicating if is a zip-based query
//  zoomLevel:  optional parameter, used only by national marker query
//function CenterAndPointZoom(point,isValidZip,zoomLevel){
//    BePatient();  
//    var queryType;  
//    var zoom;
//    if(isValidZip){
//        queryType = 'ZIPCODE';
//        zoom = 13;
//    }
//    else{
//        if(zoomLevel){
//            queryType = 'NATIONALMARKER';
//            zoom = parseInt(zoomLevel);
//        }
//        else{
//            queryType = 'CITY';
//            zoom = 9;
//        }
//    }
//    //alert(queryType);
//    globalGMapObject.setCenter(point, zoom);	    
//	Page_DataBind(queryType);
//}

// This funcion is DEPRECATED as of July 2007 -- Region search not available
// Used to set the map boundary to the regions and refresh the data
// parameter:
///       dropDownList: the select dropdown that has the region options
//function CenterAndRegionZoom(dropDownList){
//    if(dropDownList.selectedIndex==0){
//        Page_Load();
//    }
//    else{
//        BePatient();
//        var strValue = dropDownList.options[dropDownList.selectedIndex].value;
//	    var valuesArr = strValue.split(',');
//	    globalGMapObject.setCenter(new GLatLng(valuesArr[0], valuesArr[1]), 17 - valuesArr[2]);	    
//	    Page_DataBind('REGION');
//	}
//}

// DEPRECATED as of July 2007 - no more city-zipcode boundary search
// invoked on submit button for City, Zipcode
//function OnSearchAddress(){
//    var query = document.getElementById('query').value;
//    if(query == 'Enter a City/Zip Code')
//    {
//	    document.getElementById('query').focus();
//	    return;
//    }
//    
//    geocoder.getLatLng(query,
//    function(point) {
//      if (!point) {
//        alert(query + " not found");
//      } 
//      else {        
//        // this alert is useful for getting lat and lng
//        //alert(point);   
//        CenterAndPointZoom(point,isValidZIP(query));
//      }
//    });
//}

// DEPRECATED as of July 2007 - no more national markers
// Displays the national markers stored in the global array cities
//function ShowNationalMarkers(){
//    for(var i in cities){
//        var point = new GLatLng(parseFloat(cities[i].lat), parseFloat(cities[i].lng)); 
//        globalGMapObject.addOverlay(CreateNationalMarker(point,cities[i].name,cities[i].zoomlevel));
//    }
//}


// DEPRECATED as of July 2007
// Creates small marker
// return type: GMarker
// parameters:
// point - GLatLang point
// tooltiptext - string, title for the marker onmouseover
// zoomLevel - int, zoom level
//function CreateNationalMarker(point, tooltipText, zoomLevel){
//    var icon = new GIcon();
//    icon.image = "images/icons/mm_20_3d_orange1.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 options = new Object();
//    options.title=tooltipText;
//    options.icon = icon;
//    var marker = new GMarker(point,options);
//    // the marker should pan to the location
//    GEvent.addListener(marker, "click", function() {
//        ResetSearchControls();
//        CenterAndPointZoom(point,false,zoomLevel);
//    });
//    return marker;
//}

// DEPRECATED July 2007
//function GetPropertiesByBounds_callBack(result, userContext, methodName){ //(result, eventArgs)   
//    RenderPropertiesAsGMarker(result);
//    RenderPropertiesAsHTML(result,false);
//    //ShowNationalMarkers();
//}


// DEPRECATED as of July 2007 - no more national markers
//function GetAllProperties_callBack(result, userContext, methodName){
//    globalGMapObject.clearOverlays();
//    var markers = result.documentElement.getElementsByTagName("marker"); 
//    // there will be markers only the first time
//    for(var i = 0; i<markers.length; i++) { 
//        var city = new Object();
//        var cityname = markers[i].getAttribute("city"); 
//        var cityzoom = markers[i].getAttribute("zoomLevel");
//        city.name = cityname;
//        city.zoomlevel = cityzoom;
//        city.lat=markers[i].getAttribute("lat");
//        city.lng=markers[i].getAttribute("lng");
//        cities[i]=city;
//    }    
//    ShowNationalMarkers();
//    RenderPropertiesAsHTML(result,true);
//}