﻿var map = null;
var pushpin = null;

var defaultMapLat = -28.265;
var defaultMapLng = 25.093;
var defaultMapZoom = 5;
var defaultMapView = null;
var defaultGridProps = '';

//set page event handlers for onload and unload
if (window.attachEvent) {
    window.attachEvent("onunload", Page_Unload); 
} else {
    window.addEventListener("unload", Page_Unload, false);
}

//Clean up all objects
function Page_Unload() {
    DisposeMap();
}

function handleApiReady() {
    DisposeMap();
    var latlng = new google.maps.LatLng(defaultMapLat, defaultMapLng);
    var myOptions = {
        zoom: defaultMapZoom,
        center: latlng,
        mapTypeControl: false,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
    var mapViewArgs = document.getElementById('ctl00_ContentPlaceHolder1_pvtDefaultMapArgs');
    if (mapViewArgs != null && mapViewArgs.value != '') {
        defaultMapView = mapViewArgs.value;

    }
    SetBounds();
    google.maps.event.addListener(map, 'bounds_changed', function(event) { mapPanEnd(); });
}

function DisposeMap() {
    if(map != null) {
        map = null;
    }
}

function SetBounds() {
    if (map != null && defaultMapView != null) {
        var myargs = defaultMapView.split(",");
        var latlng = new google.maps.LatLng(myargs[0], myargs[1]);
        map.setCenter(latlng);
        map.setZoom(parseFloat(myargs[2]));
        defaultGridProps = myargs[3] + "|" + myargs[4] + "|" + myargs[5];
        LoadProperties(false);
    }
}

function ClearPinOnMap() {
    if (pushpin != null) pushpin.setVisible(false);
}

function ShowPinOnMap(e,lat,lng) {
    if (map != null) {
        ClearPinOnMap();
        var latlng = new google.maps.LatLng(lat, lng);
        pushpin = new google.maps.Marker({ position: latlng, map: map });
    }
    return false;
}

function LoadProperties(mapMoved) {
    if (map != null) {
        var ss = document.getElementById('SearchStatus');
        // get the zoom level
        var zoom = map.getZoom();
        if (zoom < 7) {
            ss.innerHTML = 'Please Zoom In further to reduce the search area.<br>&nbsp;';
            var up = document.getElementById('ctl00_ContentPlaceHolder1_UpdatePanel1');
            if (up != null) up.style.display='none';
            return;
        } else {
            ss.innerHTML = '<img src="/Images/indicator_small.gif" height="12px" />&nbsp;Searching for properties in the selected area...<br>&nbsp;';
        }

        var result_arg = GetSearchParameters(mapMoved);
        
        // perform a callback to the server to load property for this location
        __doPostBack('ctl00_ContentPlaceHolder1_UpdatePanel1',result_arg)
    }
}

function GetSearchParameters(mapMoved) {
    if (map != null) {
        var bounds = map.getBounds();
        if (bounds == null) return;
        var southWest = bounds.getSouthWest();
        var northEast = bounds.getNorthEast();
        var result_arg = northEast.lat() + "|" + southWest.lng() + "|";
        result_arg += southWest.lat() + "|" + northEast.lng();

        // add the center and zoom
        var latlng = map.getCenter();
        result_arg += "|" + latlng.lat() + "|" + latlng.lng() + "|" + map.getZoom();                
                      
        // get the specified sort
        var so = document.getElementById('cboSortOrder');
        var sort = ""; if (so != null) sort = so.value;
        
        // get the specified results per page
        var rpp = document.getElementById('cboResultsPerPage');
        var pagesize = ""; if (rpp != null) pagesize = rpp.value;
        
        // get the current page
        var cpage = document.getElementById('hidCurrentPage');
        var curpg = ""; if (cpage != null) curpg = cpage.value;
        if (mapMoved) curpg = "";
        
        // add the default sort, pagesize and page number on reload
        if (defaultGridProps != '') {
            result_arg += "|"+defaultGridProps;
            defaultGridProps = '';
        } else {
            // add the sort and pagesize and page number
            result_arg += "|" + sort + "|" + pagesize + "|" + curpg;
        }
        
        return result_arg;
    }
    return "";
}

var timelastsearchrequested;
function mapPanEnd(){
    //re-run search for new view
    checkUserMapMovingFinished();
}

//function mapShowPos(e) {
//    if (map != null && e != null) {
//        var x = e.mapX;
//        var y = e.mapY;
//        pixel = new VEPixel(x, y);
//        var LL = map.PixelToLatLong(pixel);
//        window.status = "Mouse LatLong: " + LL;
//    }
//}

function checkUserMapMovingFinished(timecalled){
    if(timecalled==null){
        //get current time
        timecalled = new Date().getTime();
        //update member to store time
        timelastsearchrequested=timecalled;
        //call this method again with timecalled, 1 secs later
        setTimeout("checkUserMapMovingFinished(" + timecalled + ")",1000);
    }
    else{
        //build search if another move has not happened
        if(timecalled==timelastsearchrequested) LoadProperties(true);
    }
}

function DisplayProperties(cnt,sort,pagesize,currpg) {
    var ss = document.getElementById('SearchStatus');
    if (cnt > 400) {
        ss.innerHTML = 'More than 400 properties have been located.<br/>Please Zoom In to reduce the search area.';
    } else if (cnt < 1) {
        ss.innerHTML = 'TPN rentbay does not have any properties available in the specified area.<br/>Try Zoom Out or Pan the map to view properties in the surrounding area.';
    } else {
    ss.innerHTML = 'TPN rentbay has ' + cnt + ' properties to rent in the specified area.<br/>A <a href=#MapSearchResults style=\'color:red\'>list of the properties</a> in the visible area can be seen below the map.';
    }
    var so = document.getElementById('cboSortOrder');
    if (so != null) so.value = sort;
    var rpp = document.getElementById('cboResultsPerPage');
    if (rpp != null) rpp.value = pagesize;
    var cpage = document.getElementById('hidCurrentPage');
    if (cpage != null) cpage.value = currpg;
    
    var up = document.getElementById('ctl00_ContentPlaceHolder1_UpdatePanel1');
    if (up != null) up.style.display='';   
}

function ChangeToPage(pg) {
    var cpage = document.getElementById('hidCurrentPage');
    if (cpage != null) cpage.value = pg;
    LoadProperties(false);
}

function SetMapPos(CP_lat, CP_lng, zoom) {
    if (map != null) {
        var latlng = new google.maps.LatLng(CP_lat, CP_lng);
        map.setCenter(latlng);
        map.setZoom(zoom);    
    } else {
        alert('Please wait for the map to finish loading...');
    }
}


