﻿//Javascript file for Listings.aspx

//Impliment a Standard Grid
//Only want to Refresh the data on the map if the bounds move out of this standard Grid.
//Logic on server side is synced with this.

//Our client side map object
var mymap = null;
//our client side custom ERO object
var customERO;

var control;
var mapRestrictionZoomLevel = 9
//When the map has fully load this function is called prior to calling the server method for the same event
function ListingsMap_OnLoadMap(o, e) {
    //get a client side reference to the VE Map control generated.
    mymap = $find(cMapControlID).get_VEMap()
    if (mymap) {
        // load our stylesheet
        //setup the intial bounds object
        IsNewBounds(mymap);
        //wire up custom ERO
        //The elements within an update panel have to be called by ID
        //The ERO has four modes triggered by postion relative to centre XY supplied
        //The popupdelay is important to prevent accidental triggers of the ERO
        customERO = $create(TrackMyERO.CustomERO, {
            "triggerelementID": cEROKeyID,
            "contentelementID": cEROPanelID,
            "closeelement": $get(cCustomEROCloseID),
            "map": mymap,
            "CentreX": 350,
            "CentreY": 300,
            "PopupDelay": 300,
            "Enabled": true
        }, null, null, $get(cCustomEROID));
        zS = $find(cZoomSliderID);
        zS.set_value(mymap.GetZoomLevel());
        mymap.AttachEvent("onmousewheel", trap);
        //mymap.AttachEvent("onmousemove", mousemovehandler);
    }
}

//Whenever the map pans or zoom or changes this is called, if we don't need to refresh the data we can cancel the server call
function ListingsMap_OnChangeView(o, e) {
    if (mymap) {
        if (e._mapEvent.zoomLevel < mapRestrictionZoomLevel) {
            //Zoom the map back in to the restricted area
            //SetZoomLevel(mapRestrictionZoomLevel);
            recCount = $get(cRecordCount)
            recCount.innerText = "Zoom level too high, zoom in closer to start search."
            e.set_cancel(true);
        }
        if (IsNewBounds(mymap)) {
            //clear the current data.
            mymap.Clear();
            //notify the customERO that the data will be changing
            if (customERO) customERO.NotifyDataChange();
        } else {
            //cancel call to the server
            e.set_cancel(true);
        }
    }
    zS = $find(cZoomSliderID)
    zS.set_value(mymap.GetZoomLevel());

    //AddMyControl(mymap);
}

//spare layer to show our highlight dot
var mylayer;
//boolean to know if we have to remove a shape
var shapeadded = false;

//This function is called from the list template "ResultListing.ascx" to provide visual feedback on the map
function ListItem_OnMouseOver(lat, lon) {
    if (mymap) {
        if (!mylayer) {
            mylayer = new VEShapeLayer();
            mymap.AddShapeLayer(mylayer);
            shapeadded = true;
        }
        var s = new VEShape(VEShapeType.Pushpin, new VELatLong(parseFloat(lat), parseFloat(lon)));
        s.SetCustomIcon("<div class='PinHighlight'></div>");
        mylayer.AddShape(s);
    }
}

//Removes the shape if it was added
function ListItem_OnMouseOut() {
    if (shapeadded) {
        mylayer.DeleteAllShapes();
    }
}

//This function is called from the list template "ResultListing.ascx" to launch the modal popup for the item
function ListItem_OnClick(id) {
    //launch the modal popup
    var modelpopup = $find("ItemDisplayModalPopup");
    if (modelpopup) {
        modelpopup.show();
        //Trigger the updatepanel to get content from server by setting the Key in field
        $get(cItemPopupKeyID).value = id;
        $get(cItemPopupKeyID).onchange();
    }
}

//When the user presses enter in the map search box trigger a map Find()
function MapFindBox_OnKeyDown(o, e) {
    if (e.keyCode == 13) {
        SearchbyText(o.value);
    }
}

function SetZoomLevel(zoomLevel) {
    if (mymap) mymap.SetZoomLevel(zoomLevel);
}

//When the user clicks the map search go button trigger a map Find()
function MapFindGo_OnClick(o, e) {
    SearchbyText(o.value);
}

function MoreResults(layer,resultsArray, places, hasMore, veErrorMessage) 
         {
            if(hasMore)
            {
               var r = "<a href='#' onclick='javascript:FindLoc(parseInt(document.getElementById('txtNumResults').value));'>" +
                       "Click for More Results</a>";
               document.getElementById('results').innerHTML = r;
            }
            else
            {
               index=0;
               number=Number(document.getElementById('txtNumResults').value); 
               document.getElementById('results').innerHTML = "";
               document.getElementById('results').innerHTML = "No More Results Available";
            }
         }
//If the map has been created search for the location provided
function SearchbyText(_searchtxt)
{
    if (mymap) {
        try {
            mymap.Find(null, _searchtxt);
        }  catch (e) {
            alert(e.message)
        }
    }
}

//We only want to get new data for the map if it has moved from our standad grid bounds
//Store the current value
var CurrentBounds;

//Has the stardard grid bounds changed? Identical to server side code.
function IsNewBounds(_map) {
    if (_map.GetMapStyle() == VEMapStyle.Birdseye) {
        //Birdeye hides its actual value, best to request every change:       
        var be = _map.GetBirdseyeScene();
        var rect = be.GetBoundingRectangle();
        CurrentBounds = new Array();
        CurrentBounds.push(rect.TopLeftLatLong);
        CurrentBounds.push(rect.BottomRightLatLong);
    } else {
        var view = _map.GetMapView();
        //Bounds must be NW, SE. Reorder if not
        if (view.TopLeftLatLong.Latitude < view.BottomRightLatLong.Latitude) {
            var temp = view.TopLeftLatLong.Latitude;
            view.TopLeftLatLong.Latitude = view.BottomRightLatLong.Latitude;
            view.BottomRightLatLong.Latitude = temp;
        }
        if (view.TopLeftLatLong.Longitude > view.BottomRightLatLong.Longitude) {
            var temp = view.TopLeftLatLong.Longitude;
            view.TopLeftLatLong.Longitude = view.BottomRightLatLong.Longitude;
            view.BottomRightLatLong.Longitude = temp;
        }

        //Round bounds to a standard grid. Improves server side caching performance and reduces web service calls.
        var zoom = _map.GetZoomLevel();
        var latrounding = (90 / (Math.pow(2, (zoom - 2))));
        var lonrounding = (180 / (Math.pow(2, (zoom - 1))));

        var lat1 = view.TopLeftLatLong.Latitude;
        var lat2 = view.BottomRightLatLong.Latitude;
        var lon1 = view.TopLeftLatLong.Longitude;
        var lon2 = view.BottomRightLatLong.Longitude;

        var TLat = (Math.floor(lat1 / latrounding) + 1) * latrounding;
        var BLat = (Math.floor(lat2 / latrounding)) * latrounding;
        var LLon = (Math.floor(lon1 / lonrounding)) * lonrounding;
        var RLon = (Math.floor(lon2 / lonrounding) + 1) * lonrounding;

        if (CurrentBounds
            && CurrentBounds[0].Latitude == TLat
            && CurrentBounds[0].Longitude == LLon
            && CurrentBounds[1].Latitude == BLat
            && CurrentBounds[1].Longitude == RLon)
        { return false };
        //else save new bounds:
        CurrentBounds = new Array();
        CurrentBounds.push(new VELatLong(TLat, LLon));
        CurrentBounds.push(new VELatLong(BLat, RLon));
    }
    return true;
}

function AddMyControl(_map) {
    if (control == null) {
        control = document.createElement("div");
        control.id = "myControl";
        control.style.top = "100px";
        control.style.left = "100px";
        control.style.border = "2px solid black";
        control.style.background = "White";
        control.innerHTML = "my control";
        _map.AddControl(control);
        //addShim(control);
    }
}
function addShim(el) {
    var shim = document.createElement("iframe");
    shim.id = "myShim";
    shim.frameBorder = "0";
    shim.style.position = "absolute";
    shim.style.zIndex = "1";
    shim.style.top = el.offsetTop;
    shim.style.left = el.offsetLeft;
    shim.width = el.offsetWidth;
    shim.height = el.offsetHeight;
    el.shimElement = shim;
    el.parentNode.insertBefore(shim, el);
}

trap = function() { return true; }

// onmousemove handler
function mousemovehandler(e) {
    var loc = mymap.PixelToLatLong(new VEPixel(e.mapX, e.mapY));
    document.getElementById("MouseLat").innerHTML = loc.Latitude.toFixed(4);
    document.getElementById("MouseLng").innerHTML = loc.Longitude.toFixed(4);
}

function OnClientSelectedIndexChanged(sender, eventArgs) {
    var item = eventArgs.get_item();
    cThisPlace = $get(cSelectPlaceID);
    cThisPlace.value = item.get_value();
}

function updateLabels(from, fromVal, to, toVal) {
    from.innerHTML = fromVal;
    to.innerHTML = toVal;
}

function zoomEnd(sender, args) {
    var thisZoomLevel = sender.get_value();
    SetZoomLevel(thisZoomLevel)
}

function checkValues() {
    if (mymap.GetZoomLevel() < 8) {
        return false;
    }
    if ($get(cbCondo).checked || $get(cbFarm).checked || $get(cbLand).checked || $get(cbMobile).checked || $get(cbMulti).checked || $get(cbSFR).checked) {
        return true;
    }
    alert('Please check at least one property type.');
    return false;
}

function sliderEnd(sender, args) {
    var fromCtrl;
    var fromVal = "No Min";
    var toCtrl;
    var toVal = "No Max";
    if (sender.get_id() == sliderPrice) {
        fromCtrl = $get(lblPriceFrom);
        if (sender.get_selectionStart() > 0) {
            fromVal = '$' + CommaFormatted(sender.get_selectionStart());
        }
        toCtrl = $get(lblPriceTo);
        if (sender.get_selectionEnd() < 1000000) {
            toVal = '$' + CommaFormatted(sender.get_selectionEnd());
        }
    }
    if (sender.get_id() == sliderBeds) {
        fromCtrl = $get(lblBedsFrom);
        if (sender.get_selectionStart() > 0) {
            fromVal = sender.get_selectionStart();
        }
        toCtrl = $get(lblBedsTo);
        if (sender.get_selectionEnd() < 6) {
            toVal = sender.get_selectionEnd();
        }
    }
    if (sender.get_id() == sliderBaths) {
        fromCtrl = $get(lblBathsFrom);
        if (sender.get_selectionStart() > 0) {
            fromVal = sender.get_selectionStart();
        }
        toCtrl = $get(lblBathsTo);
        if (sender.get_selectionEnd() < 6) {
            toVal = sender.get_selectionEnd();
        }
    }
    if (sender.get_id() == sliderSqFt) {
        fromCtrl = $get(lblSqFtFrom);
        if (sender.get_selectionStart() > 0) {
            fromVal = sender.get_selectionStart();
        }
        toCtrl = $get(lblSqFtTo);
        if (sender.get_selectionEnd() < 10000) {
            toVal = sender.get_selectionEnd();
        }
    }
    if (sender.get_id() == sliderLotSize) {
        fromCtrl = $get(lblLotSizeFrom);
        toCtrl = $get(lblLotSizeTo);
        thisVal = sender.get_value()
        switch (thisVal) {
            case 0:
                fromVal = "Any";
                toVal = " size";
                break;
            case 1:
                fromVal = "Up";
                toVal = " to 1/2 acre";
                break;
            case 2:
                fromVal = "Up";
                toVal = " to 1 acre";
                break;
            case 3:
                fromVal = "Up";
                toVal = " to 3 acres";
                break;
            case 4:
                fromVal = "Up";
                toVal = " to 5 acres";
                break;
            case 5:
                fromVal = "5";
                toVal = " to 10 acres";
                break;
            case 6:
                fromVal = "10";
                toVal = " to 100 acres";
                break;
            case 7:
                fromVal = "100";
                toVal = "+ acres";
                break;
        }
    }
    updateLabels(fromCtrl, fromVal, toCtrl, toVal)
}

function CommaFormatted(amount) {
    var delimiter = ","; // replace comma if desired
    //var a = amount.split('.', 2)
    //var d = a[1];
    var i = parseInt(amount);
    if (isNaN(i)) { return ''; }
    var minus = '';
    if (i < 0) { minus = '-'; }
    i = Math.abs(i);
    var n = new String(i);
    var a = [];
    while (n.length > 3) {
        var nn = n.substr(n.length - 3);
        a.unshift(nn);
        n = n.substr(0, n.length - 3);
    }
    if (n.length > 0) { a.unshift(n); }
    n = a.join(delimiter);
    amount = n;
    amount = minus + amount;
    return amount;
}

function checkPropTypes(sender) {
    var thisID = sender.id
    if (thisID == cbLand && $get(cbLand).checked) {
        $get(cbSFR).checked = false;
        $get(cbCondo).checked = false;
        $get(cbMobile).checked = false;
        $get(cbMulti).checked = false;
        $get(cbFarm).checked = false;
        return false;
    }
    if (thisID == cbMulti && $get(cbMulti).checked) {
        $get(cbSFR).checked = false;
        $get(cbCondo).checked = false;
        $get(cbMobile).checked = false;
        $get(cbLand).checked = false;
        $get(cbFarm).checked = false;
        return false;
    }
    if (thisID == cbSFR || thisID == cbCondo || thisID == cbMobile || thisID == cbFarm) {
        $get(cbLand).checked = false;
        $get(cbMulti).checked = false;
    }
}
