﻿var _map = null;
var _points = [];
var _shapes = [];
var _bingMeUp = [];
var _eugeneSpringfield;
var _currentMode = 1;
var _houseLayer = null;
var _constraintLayer = null;
var _selectBox = null;
var _modeOneText = "Click the Globe to Draw a Box on the Map!";
var _modeTwoText = "Click and Drag around the Area you wish to Search.";
var _modeThreeText = "To remove the Box on the Map, Click the Red X to the Left.";
var StartLatLon;
var EndLatLon;

var _displayQiv = true;

function formSubmit(newPage, message) {
    
    if (message == null || message == '')
        message = "Searching...";

    $('#CurrentPage').val(newPage);
    $('.searchResultsResults').attr('innerHTML', '<span style="color: #0000ff">' + message + '</span>');
    populateMap();
    $('#hbPropertySearch').trigger('click');
}
function populateMap() {
    clearMap();
    _eugeneSpringfield = new VELatLong(44.05222, -123.08556);

    $.post("/Search/GetPropertyLocationsForSearch",
        {
            CityName: $("#CityName").val(),
            AreaId: $("#AreaId").val(),
            FromPrice: $("#FromPrice").val(),
            ToPrice: $("#ToPrice").val(),
            FromBedrooms: $("#FromBedrooms").val(),
            FromBathrooms: $("#FromBathrooms").val(),
            FromSqft: $("#FromSqFt").val(),
            ToSqft: $("#ToSqFt").val(),
            PropertyType: $("#PropertyType").val(),
            CurrentPage: $("#CurrentPage").val(),
            StartLat: $("#StartLat").val(),
            StartLon: $("#StartLon").val(),
            EndLat: $("#EndLat").val(),
            EndLon: $("#EndLon").val()
        }, function(mappables) {

            $.each(mappables, function(i, mappable) {
                addPropertyToMap(mappable, '/Content/Images/home.png');
            });

            if (_points.length > 1)
                _map.SetMapView(_points);
            else {
                _map.SetCenter(_eugeneSpringfield);
                _map.SetZoomLevel(11);
            }

            $('#liPropertySearch').attr('value','Update');

        }, "json"
      );
}
function saveSearch() {
    $('#saveSearchMessage').attr('innerHTML', 'Saving Search...');
    $('#saveSearchMessage:hidden').show();

    $.post("/Search/SaveSearch",
        {
            CityName: $("#CityName").val(),
            AreaId: $("#AreaId").val(),
            FromPrice: $("#FromPrice").val(),
            ToPrice: $("#ToPrice").val(),
            FromBedrooms: $("#FromBedrooms").val(),
            FromBathrooms: $("#FromBathrooms").val(),
            FromSqft: $("#FromSqFt").val(),
            ToSqft: $("#ToSqFt").val(),
            PropertyType: $("#PropertyType").val(),
            CurrentPage: $("#CurrentPage").val(),
            StartLat: $("#StartLat").val(),
            StartLon: $("#StartLon").val(),
            EndLat: $("#EndLat").val(),
            EndLon: $("#EndLon").val(),
            SearchTitle: $("#SaveSearchTitle").val(),
            SendEmails: $("#SaveSearchEmails").attr('checked')
        }, function(result) {

            if (result.SubmitSuccessful) {
                $('#saveSearchMessage').css('color', '#00f');
                $('#btnSaveSearchCancel').attr('value', 'Close');
                $('#saveSearchMessage').attr('innerHTML', 'Search Successfully Saved!');
                setTimeout('closeSaveSearchWindow();', 3000);
            }
            else {
                $('#saveSearchMessage').css('color', '#f00');
                $('#saveSearchMessage').attr('innerHTML', result.ErrorMessage);
                $('#btnSaveSearchCancel').attr('value', 'Cancel');
            }

        }, "json"
     );
}
function populateBuyersMap() {
    clearMap();
    _eugeneSpringfield = new VELatLong(44.05222, -123.08556);

    $.post("/BuyersFolder/GetBuyersPropertiesForMap",
        {}, function(mappables) {
            $.each(mappables, function(i, mappable) {
                addPropertyToMap(mappable, '/Content/Images/home.png');
            });

            if (_points.length > 1)
                _map.SetMapView(_points);
            else {
                _map.SetCenter(_eugeneSpringfield);
                _map.SetZoomLevel(11);
            }
        }, "json"
        );
}
function clearMap() {
    _houseLayer.DeleteAllShapes();
    _points = [];
    _shapes = [];
    _bingMeUp = [];
}
function addPropertyToMap(mappable, iconUrl) {

    var latlon = new VELatLong(mappable.Latitude, mappable.Longitude, 0, null);

    var shape = new VEShape(VEShapeType.Pushpin, latlon);
    shape.SetCustomIcon(iconUrl);

    shape.SetTitle('MLS Listing #: ' + mappable.ListingId);

    if (mappable.IsResidential)
        shape.SetDescription(getResidentialDescriptionFromMappable(mappable));
    else
        shape.SetDescription(getBarelandDescriptionFromMappable(mappable));

    _houseLayer.AddShape(shape);
    _points.push(latlon);
    _shapes.push(shape);
    _bingMeUp.push(mappable.ListingId);
}
function getIndexFromListingId(listingId) {
    var result = null;
    $(_bingMeUp).each(function(i) {
        if (this == listingId)
            result = i;
    });
    
    return result;
}
function showPager() {
    setTimeout(actualShowPager, 250);
}
function actualShowPager() {
    $('#srPager').show('explode');
}
function popDescription(listingId) {
    var index = getIndexFromListingId(listingId);
    if (index != null)
    {
        _map.SetCenterAndZoom(_points[index], 16);
        _map.ShowInfoBox(_shapes[index], _points[index], new VEPixel(10,0));
    }
}
function getBarelandDescriptionFromMappable(mappable) {
    var desc = '<div style="width: 330px; height: auto;">';
    desc += '<div style="font-weight: bold; margin-bottom: 5px;">Price: ' + mappable.Price + '</div>';
    desc += '<div><img src="' + mappable.FirstImageUrl + '" style="width: 70px; height: 57px; float: left;" />';
    desc += '<div style="float: right; width: 250px">';
    desc += mappable.Acres + ' Acres<br />';
    desc += 'Zoned: ' + mappable.Zoning + '<br />';
    desc += 'Road Surface: ' + mappable.RoadSurface + '</div></div><div style="clear: both;"></div>';
    desc += '<div style="margin-top: 5px; margin-bottom: 5px;">' + mappable.Address + '</div>';
    desc += '<div style="text-align: left; margin-top: 5px;">';
    desc += '<img src="/Content/Images/view2.png" class="imgButton sib2" title="View Full Property Details" onclick="showPropertyDetails(\'' + mappable.ListingId + '\');" />';
    desc += '<img src="/Content/Images/user_message.png" class="imgButton sib2" title="Contact a Broker about this Property" onclick="openContactWindow(\'' + mappable.ListingId + '\', \'\');" />';

    if (mappable.IsUserLoggedIn)
        desc += '<img src="/Content/Images/folder_into.png" class="imgButton sib2" title="Add this Property to Your Buyer\'s Folder" onclick="addToBuyersFolder(\'' + mappable.ListingId + '\', \'\');" />';
    
    desc += '</div>';
    desc += '</div>';

    return desc;
}
function getResidentialDescriptionFromMappable(mappable)
{
    var desc = '<div style="width: 330px; height: auto;">';
    desc += '<div style="font-weight: bold; margin-bottom: 5px;">Price: ' + mappable.Price + '</div>';
    desc += '<div><img src="' + mappable.FirstImageUrl + '" style="width: 70px; height: 57px; float: left;" />';
    desc += '<div style="float: right; width: 250px">';
    desc += mappable.Bedrooms + ' Beds / ' + mappable.Bathrooms + ' Baths<br />';
    desc += mappable.Sqft + ' SqFt.<br />';
    desc += 'Built in: ' + mappable.YearBuilt + '</div></div><div style="clear: both;"></div>';
    desc += '<div style="margin-top: 5px; margin-bottom: 5px;">' + mappable.Address + '</div>';
    desc += '<div style="text-align: left; margin-top: 5px;">';
    desc += '<img src="/Content/Images/view2.png" class="imgButton sib2" title="View Full Property Details" onclick="showPropertyDetails(\'' + mappable.ListingId + '\');" />';
    desc += '<img src="/Content/Images/user_message.png" class="imgButton sib2" title="Contact a Broker about this Property" onclick="openContactWindow(\'' + mappable.ListingId + '\', \'\');" />';
        
    if (mappable.IsUserLoggedIn)
        desc += '<img src="/Content/Images/folder_into.png" class="imgButton sib2" title="Add this Property to Your Buyer\'s Folder" onclick="addToBuyersFolder(\'' + mappable.ListingId + '\', \'\');" />';
    
    desc += '</div>';
    desc += '</div>';
    
    return desc;
}
function showQiv(listingId) {
    if (_displayQiv) {
        var listingId = '#qiv_' + listingId;
        $(listingId).show();
    }
}
function hideQiv(listingId) {
    $('#qiv_' + listingId).hide();
}
function setValuesAndSearch(city, areaId, fromPrice, toPrice, bedrooms, bathrooms, fromsqft, tosqft, propertyType,
        upperLeftX, upperLeftY, lowerRightX, lowerRightY) {
    $("#CityName option").each(function() {
        if ($(this).val() == city)
            this.selected = true;
    });
    $("#AreaId option").each(function() {
        if ($(this).val() == areaId)
            this.selected = true;
    });
    $("#FromPrice option").each(function() {
        if ($(this).val() == fromPrice)
            this.selected = true;
    });
    $("#ToPrice option").each(function() {
        if ($(this).val() == toPrice)
            this.selected = true;
    });
    $("#FromBedrooms option").each(function() {
        if ($(this).val() == bedrooms)
            this.selected = true;
    });
    $("#FromBathrooms option").each(function() {
        if ($(this).val() == bathrooms)
            this.selected = true;
    });
    $("#FromSqFt option").each(function() {
        if ($(this).val() == fromsqft)
            this.selected = true;
    });
    $("#ToSqFt option").each(function() {
        if ($(this).val() == tosqft)
            this.selected = true;
    });
    $("#PropertyType option").each(function() {
    if ($(this).val() == propertyType)
            this.selected = true;
    });
    if (upperLeftX != 0 && upperLeftX != null) {
        $("#StartLat").val(upperLeftX);
        $("#StartLon").val(upperLeftY);
        $("#EndLat").val(lowerRightX);
        $("#EndLon").val(lowerRightY);

        StartLatLon = new VELatLong(upperLeftX, upperLeftY);
        EndLatLon = new VELatLong(lowerRightX, lowerRightY);
        hideAddMapConstraint();
        setAreaModePresent();
        drawBox();
    }
    formSubmit('0');
}
function citySelected() {
    document.getElementById('AreaId').options[0].selected = "selected";
    removeAreaConstraint();
}
function areaSelected() {
    document.getElementById('CityName').options[0].selected = "selected";
    removeAreaConstraint();
}
function startAreaConstraint() {
    _currentMode = 2;
    $("#mapConstraintText").attr('innerHTML', _modeTwoText);
    hideAddMapConstraint(true);
    resetMapConstraintValues();
}
function showAddMapConstraint() {
    $("#mapConstraintAdd").show();
    $("#mapConstraintRemove").hide();
}
function hideAddMapConstraint() {
    $("#mapConstraintAdd").hide();
    $("#mapConstraintRemove").show();
}
function removeAreaConstraint() {
    _currentMode = 1;
    if (_selectBox != null)
        _constraintLayer.DeleteShape(_selectBox);
    _selectBox = null;
    $("#mapConstraintText").attr('innerHTML', _modeOneText);
    showAddMapConstraint();
    resetMapConstraintValues();
}
function resetMapConstraintValues() {
    $("#StartLat").val(0);
    $("#StartLon").val(0);
    $("#EndLat").val(0);
    $("#EndLon").val(0);
}
function MouseDownHandler(e) {
    if (_currentMode != 2) {
        return false;
    } else {
        // enable selecting mode
        _currentMode = 3;

        // set the start points 
        startX = e.mapX;
        startY = e.mapY;

        StartLatLon = _map.PixelToLatLong(new VEPixel(startX, startY));

        $("#StartLat").val(StartLatLon.Latitude.toFixed(4));
        $("#StartLon").val(StartLatLon.Longitude.toFixed(4));

        // disable the VE mouse events 
        return true;
    }
}
function MouseMoveHandler(e) {
    //When moving the mouse, if in "drawing" mode, draw, otherwise do nothing.
    if (_currentMode != 3) {
        return false;
    } else {
        // clear select box
        if (_selectBox != null) { _constraintLayer.DeleteShape(_selectBox) };

        // set the latest endpoints (opposite side of the selection box) 
        currentX = e.mapX;
        currentY = e.mapY;

        EndLatLon = _map.PixelToLatLong(new VEPixel(currentX, currentY));

        $("#EndLat").val(EndLatLon.Latitude.toFixed(4));
        $("#EndLon").val(EndLatLon.Longitude.toFixed(4));

        drawBox();
    }
}
function drawBox() {
    // create new selection box (VEShape) from start and end (corners) coordinates
    _selectBox = new VEShape(
                VEShapeType.Polygon,
                [
                StartLatLon,
                new VELatLong(StartLatLon.Latitude, EndLatLon.Longitude),
                EndLatLon,
                new VELatLong(EndLatLon.Latitude, StartLatLon.Longitude)
                ]);

    _selectBox.HideIcon();
    _selectBox.SetLineWidth(2);
    _selectBox.SetLineColor(new VEColor(35, 93, 174, 1.0));
    _selectBox.SetFillColor(new VEColor(116, 167, 212, .4));
    _selectBox.Primitives[0].symbol.stroke_dashstyle = "Solid";

    _constraintLayer.AddShape(_selectBox);
}
function MouseUpHandler(e) {
    // On mouse up, if in selecting mode cancel selecting mode
    if (_currentMode == 3) {
        // Set the Mode to 3 (Area Present)
        setAreaModePresent();
        clearNeighborhoodArea();
        formSubmit(0, null);
    }
}
function clearNeighborhoodArea() {
    document.getElementById('AreaId').options[0].selected = "selected";
    document.getElementById('CityName').options[0].selected = "selected";
}
function setAreaModePresent() {
    _currentMode = 4;
    $("#mapConstraintText").attr('innerHTML', _modeThreeText);
    $("#mapConstraintRemove").attr('title', 'Remove Geographical Constraint.');
}
function refreshNewListings(date) {
    $("#newListingsMessage").attr("innerHTML", "Updating...");

    $.post("/Listings/GetNewListingsForDate", {
        Date: date
    }, function(result) {
        $("#newListingsUpdateContainer").attr("innerHTML", result);
        setTimeout('setDatePicker();', 200);
    }, "html"
    );
} 