function trim(str) {
    if (str != null) {
        var i;
        for (i=0; i<str.length; i++) {
            if (str.charAt(i)!=" ") {
                str=str.substring(i,str.length);
                break;
            }
        }
        for (i=str.length-1; i>=0; i--) {
            if (str.charAt(i)!=" ") {
                str=str.substring(0,i+1);
                break;
            }
        }

        if (str.charAt(0)==" "){
            return "";
        }else{
            return str;
        }
    }
}

function displayLargeImages(strimgname,strpropId){
    var path=new Array();
    path=strimgname.src.split("?");
    strsource=path[0]+"?x=208&y=158&mode=c";
    document.getElementById("largeImage").innerHTML='<img src="'+strsource+'" height="158" width="208" class="cursor" id="'+ strimgname.id +'" onclick="displayLarge(this,'+ strpropId +')" > <div class="rule" style="margin-bottom:4px;"></div><span class="note">Click the image to view the maximum size version.</span>';
}

function displayRecords(strvalue,straction,srturl,strpage){
    var url="?"+srturl+"&page="+strpage+"&count="+strvalue.value;
    document.frm.action=url;
    document.frm.submit();
}

function displayLarge(strVal,propID){
    var url="/details/largeimage/property_id/"+propID;
    document.frm.hdimage.value=strVal.id;
    document.frm.action=url;
    document.frm.submit();
}

function populateCountry(strObj,strVal,strFrm){
    var formname=strFrm.name;
    var region=strVal.value;
    var countyNum=strObj.CountryList.Country.length;
    var names= new Array();
    var j=0;
    var strSelect="";
    strSelect='<select id="country" name="country" onchange="disableOption('+formname+' , this);">';
    strSelect+='<option value="">All</option>';
    for(var i=0 ; i < countyNum ; i++){
        if(region==""){
            strSelect+='<option  value="'+ strObj.CountryList.Country[i].name +'" >'+ strObj.CountryList.Country[i].name +'</option>';

        }else{
            if(strObj.CountryList.Country[i]['@attributes'].region == region){
                strSelect+='<option value="'+ strObj.CountryList.Country[i].name +'" >'+ strObj.CountryList.Country[i].name +'</option>';
                j++;
            }
        }
    }
    strFrm.location.disabled=true;
    document.getElementById('Cout').innerHTML=strSelect;
}

function disableOption(srtfrm , strval){

    if(strval.value !=""){
        srtfrm.location.disabled=false;
    }else{
        srtfrm.location.value="";
        srtfrm.location.disabled=true;
        srtfrm.distance.value="";
        srtfrm.distance.disabled=true;
    }
}

function disableDistance(srtfrm , strval){
    var valu=trim(strval.value);
    if(valu.length > 0){
        srtfrm.distance.value="";
        srtfrm.distance.disabled=false;

    }else{
        srtfrm.distance.value="";
        srtfrm.distance.disabled=true;
    }
}

function getShow(){
    document.getElementById("showhide").style.display="block";
}

function getHide(){
    document.getElementById("showhide").style.display="none";
}

function checkDistance(frm){

    if(trim(frm.minsize.value) !="" && trim(frm.maxsize.value)==""){
        document.getElementById("errorMsg").innerHTML="<p>Please enter max size</p>";
        return false;
    }
    if(trim(frm.minsize.value) =="" && trim(frm.maxsize.value) !=""){
        document.getElementById("errorMsg").innerHTML="<p>Please enter min size</p>";
        return false;
    }
    if(trim(frm.minsize.value) > trim(frm.maxsize.value)){
        document.getElementById("errorMsg").innerHTML="Maxsize should be greater than minsize";
        return false;
    }
}



window.onload = function(){
    if(document.getElementById('locMap') || document.getElementById('searchMap')){
        loadGoogleApi();
    }
}

function loadGoogleApi(callback){
    var script = document.createElement("script");
    script.src = "http://www.google.com/jsapi?key="+document.googleKey+"&callback=loadGoogleMapsApi";
    script.type = "text/javascript";
    document.getElementsByTagName("head")[0].appendChild(script);
}

function loadGoogleMapsApi(){
    google.load('maps','2', {'callback':mapsApiLoaded});
}

function AjaxObj() {

    var self = this;
    var callback = null;

    this.getXmlHttp = function(){
        try { var xmlHttp = new XMLHttpRequest();}
        catch (e) { var xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");}
        return xmlHttp;
    }

    this.xmlHttp = this.getXmlHttp();

    this.doRequest = function(url, callback){
        this.callback = callback;
        this.xmlHttp.open('GET', url, true);
        this.xmlHttp.onreadystatechange = this.handleResponse;
        this.xmlHttp.send(null);
    }

    this.handleResponse = function(){
        if(4==self.xmlHttp.readyState){
            var response = eval('(' + self.xmlHttp.responseText + ')');
            if (typeof self.callback == 'function') { self.callback(response);}
        }
    }

}

function mapsApiLoaded(){
    if(google.maps.BrowserIsCompatible()){
        if(mapDiv=document.getElementById('locMap')){
            var map = new google.maps.Map2(mapDiv);
            var latLngArray = mapDiv.title.split(';');
            mapDiv.title = '';
            var latLng = new google.maps.LatLng(latLngArray[0], latLngArray[1]);
            map.setCenter(latLng, 12);
            map.addOverlay(new google.maps.Marker(latLng));
            map.addControl(new google.maps.SmallMapControl());
        }
        if(mapDiv=document.getElementById('searchMap')){

            var map = new google.maps.Map2(mapDiv);
            var boundsArray = mapDiv.title.split(';');
            mapDiv.title = '';
            var neLatLng = new google.maps.LatLng(boundsArray[1], boundsArray[0]);
            var swLatLng = new google.maps.LatLng(boundsArray[3], boundsArray[2]);
            var bounds = new google.maps.LatLngBounds(swLatLng, neLatLng);
            var zoom = map.getBoundsZoomLevel(bounds);
            if(zoom<2){ zoom=2; }
            map.setCenter(bounds.getCenter(),zoom);
            map.addControl(new google.maps.LargeMapControl());
            map.addControl(new google.maps.MenuMapTypeControl());
            map.addControl(new google.maps.OverviewMapControl());


            // gets the new points from the server
            GMap2.prototype.handleMove = function(){
            	if(this.oldZoom!=map.getZoom()){
            		this.clearOverlays();
            	}
                this.getPoints();
            }

            GMap2.prototype.handleMoveStart = function(){
                this.oldZoom = map.getZoom();
            }

            // sets the initial state and event handlers
            GMap2.prototype.initialiseMap = function(){
                var map = this;
                GEvent.addListener(this, 'moveend', function(){ map.handleMove(); });
                GEvent.addListener(this, 'movestart', function(){ map.handleMoveStart(); });
                map.handleMove();
            }


            // sends an AJAX request to get some points
            GMap2.prototype.getPoints = function(){
                if(response = this.getCachedResponse()){
                    return this.handlePointsResponse(response);
                }
                var map = this;
                mapBounds = this.getBounds();
                zoom = this.getZoom();
                map.req = new AjaxObj();
                qs = this.queryString;
                if(!qs){qs='?'; }
                qs += '&output=json';
                qs += '&submit_search=1';
                qs += '&map_bounds='+mapBounds;
                qs += '&zoom='+zoom;
                map.req.doRequest('/search/results/map'+qs,function(response){  map.handleJsonResponse(response); });
            }

            // decides if the map needs to fetch more data from the server
            GMap2.prototype.getCachedResponse = function(){
                if(this.storedResponses && this.storedResponses[this.getZoom()]){
                    for(var i=0; i<this.storedResponses[this.getZoom()].length; i++){
                        respBounds = new GLatLngBounds(
                            new GLatLng(
                                this.storedResponses[this.getZoom()][i].bounds[0][1],
                                this.storedResponses[this.getZoom()][i].bounds[0][0]
                            ),
                            new GLatLng(
                                this.storedResponses[this.getZoom()][i].bounds[1][1],
                                this.storedResponses[this.getZoom()][i].bounds[1][0]
                            )
                        );
                        if(respBounds.containsBounds(this.getBounds())){
                            return this.storedResponses[this.getZoom()][i];
                        }
                    }
                }
                return false;
            }

            GMap2.prototype.storeResponse = function(response){
                if(!this.storedResponses){
                    this.storedResponses = new Array();
                }

                if(!this.storedResponses[response.zoom]){
                    this.storedResponses[response.zoom] = new Array();
                }

                this.storedResponses[response.zoom].push(response);

            }

                
            // Handles the response from the server
            GMap2.prototype.handleJsonResponse = function(response){
                if(response.points){
                    this.storeResponse(response);
                }
                this.handlePointsResponse(response);
            }

            GMap2.prototype.clearRedundantPoints = function(){

                this.singleMarkerIds = new Array();

                // if zoom changes, clear everything
                if(map.oldZoom!=map.getZoom()){
                    this.markers = new Array();
                    return this.clearOverlays();
                }

                for(var i=0; i<this.markers.length; i++){
                    var m = this.markers[i];
                    if(m.propertycount==1){
                        this.singleMarkerIds.push(m.propertyid);
                    }
                    else{
                        this.removeOverlay(m);
                        this.markers.splice(i,1);
                        i--;
                    }
                }
            }

            Array.prototype.contains = function(value){
                for(var i=0;i<this.length; i++){
                    if(value==this[i]){ return true; }
                }
                return false;
            }

            // Handles the response from the server
            GMap2.prototype.handlePointsResponse = function(response){

                if(pointsData = response.points){

                    if(!this.markers){
                        this.markers= new Array();
                    }
                    this.clearRedundantPoints();
                    for(var i=0; i<pointsData.length; i++){
                        var icon=G_DEFAULT_ICON;
                        count = (pointsData[i].count);
                        if(count==1){
                            icon = custom_icon[1];
                        }
                        if(count>1 && count<10){
                            icon = custom_icon[pointsData[i]['count']];
                        }
                        if(count>=10 && count<20){
                            icon = custom_icon[10];
                        }
                        if(count>=20 && count<50){
                            icon = custom_icon[20];
                        }
                        if(count>=50 && count<100){
                            icon = custom_icon[50];
                        }
                        if(count>=100 && count<200){
                            icon = custom_icon[100];
                        }
                        if(count>=200 && count<500){
                            icon = custom_icon[200];
                        }
                        if(count>=500 && count<1000){
                            icon = custom_icon[500];
                        }
                        if(count>=1000 && count<2000){
                            icon = custom_icon[1000];
                        }
                        if(count>=2000){
                            icon = custom_icon[2000];
                        }
                        var marker = new GMarker(new GLatLng(pointsData[i].lat, pointsData[i].lng) ,{icon: icon});

                        marker.propertycount = count;
                        marker.propertyid=pointsData[i].id;

                        if(count!=1 || !this.singleMarkerIds.contains(marker.propertyid)){

                            this.addOverlay(marker);
                            this.markers.push(marker);

                            var map = this;
                            if(count==1){
                                GEvent.addListener(marker, "click", function() {
                                    map.getPointDetails(this);
                                });
                            }
                            else{
                                GEvent.addListener(marker, "click", function() {
                                    newZoom = (map.getZoom()<15)?(map.getZoom()+2):map.getZoom();
                                    map.setCenter(this.getLatLng(), newZoom);
                                });
                            }
                        }

                    }

                }


            }

            GMap2.prototype.getPointDetails = function(point){
                this.fetchPointDetails(point);
            }

            GMap2.prototype.fetchPointDetails = function(point){
                if(!this.pointsDetails){
                    this.pointsDetails = new Array();
                }
                if(this.pointsDetails[point.propertyid]){
                    return this.displayPointDetails(point, point.propertyid, this.pointsDetails[point.propertyid]);
                }
                map = this;
                map.req.doRequest('/property/display/'+point.propertyid + '?output=json',function(reponse){
                        map.displayPointDetails(point,reponse.id, reponse.details);
                        map.pointsDetails[reponse.id] = reponse.details;
                    });
            }

            GMap2.prototype.displayPointDetails = function(point,id, details){
                point.openInfoWindowHtml(details, {'maxWidth':'300'});
                point.infoWindowIsOpen=true;
                GEvent.addListener(point, "infowindowclose", function() {
                    this.infoWindowIsOpen=false;
                });
            }

            var custom_icon = [];
            var iconFolder = '/images/map/map-icons/';
            var iconPops = [1,2,3,4,5,6,7,8,9,10,20,50,100,200,500,1000,2000];
            var iconImages = ['1.png','2.png','3.png','4.png','5.png','6.png','7.png','8.png','9.png',
            '10+.png','20+.png','50+.png','100+.png','200+.png','500+.png',
            '1000+.png','2000+.png'];
            for(var i=0; i<iconPops.length; i++){

                custom_icon[iconPops[i]]=new GIcon(G_DEFAULT_ICON, iconFolder+iconImages[i]);

                if(iconPops[i]==1){
                    custom_icon[iconPops[i]].shadow =  iconFolder+'marker_shadow_1.png';
                    custom_icon[iconPops[i]].iconSize = new GSize(35,35);
                    custom_icon[iconPops[i]].iconAnchor = new GPoint(17,35);
                    custom_icon[iconPops[i]].shadowSize = new GSize(52,35);
                    custom_icon[iconPops[i]].imageMap = [16,1,22,2,26,5,30,11,30,16,29,20,27,23,
                    24,25,20,28,18,31,17,33,16,31,14,28,12,
                    27,8,24,5,21,4,16,4,11,7,6,11,2];
                }
                else {
                    custom_icon[iconPops[i]].shadow =  iconFolder+'marker_shadow.png';
                    custom_icon[iconPops[i]].iconSize = new GSize(54,56);
                    custom_icon[iconPops[i]].iconAnchor = new GPoint(27,39);
                    custom_icon[iconPops[i]].shadowSize = new GSize(54,56);
                    custom_icon[iconPops[i]].imageMap = [10,1,42,1,42,22,31,22,26,33,21,22,10,22];
                }

                custom_icon[iconPops[i]].transparent = iconFolder+'1_percent.png';

            }

            map.queryString = location.search;
            map.initialiseMap();

        }
    }
}
