﻿function setView(view)
{
    _view = view;
    renderListings();
}

function renderListings()
{
    var r = "";
    if (_listings.length > 0)
    {
        if (_view == 2)
        {
            r += "<table border='0' cellpadding='0' cellspacing='0'>";
        }
        for (var i = 0; i < Math.min(_listings.length, _maxPageResults); i++)
        {
            if (_view == 1)
            {
                r += getListingHtml(_listings[i], i+1);
            }
            else if (_view == 2)
            {       
                if (i % 2 == 0)
                {
                    r += "<tr>";
                }         
                r += "<td valign='top' class='listingItemCell'>" + getGalleryHtml(_listings[i], i+1) + "</td>";
                if (i % 2 == 1)
                {
                    r += "</tr>";
                }         
            }
            else
            {
                r += getFineHomesHtml(_listings[i], i+1);
            }           
        }
        
        if (_view == 2)
        {
            //debugger;
            if (_listings.length % 2 == 1)
            {
                r += "<td></td></tr>";
            }
            r += "</table>";
        }
    }
    $get('divListings').innerHTML = r;
}

function sortListings(sort)
{
    if (_sort == sort)
    {
        if (_sortDirection == "ASC")
            _sortDirection = "DESC";
        else
            _sortDirection = "ASC";
    }
    else
    {
        _sortDirection = "ASC";
    }
    
    _sort = sort;
    _calcPaging = true;
    _pageNumber = 1;
    searchListings();
}

function viewPage(page)
{
    _pageNumber = page;
    searchListings();
}

function filterSearch()
{
    _calcPaging = true;
    _pageNumber = 1;
    searchListings();
}

function searchListings(results)
{
    if (results == null)
    {
        _bounds = null;
        _markers = new Array();
        
        window.scroll(0,0); 
        
        var h = $get('divProperties').clientHeight;
        var w = $get('divProperties').clientWidth;
        var loading = $get('divLoading');
        loading.style.height = h + 'px';
        loading.style.width = w + 'px';
        loading.style.display = '';        
                       
        $find(ControlIDs.extPopSearch).hidePopup();
        
        var minPrice = 0;
        var maxPrice = 0;
        try { minPrice = parseFloat($get(ControlIDs.txtMinPrice).value); } catch(e){}
        try { maxPrice = parseFloat($get(ControlIDs.txtMaxPrice).value); } catch(e){}
        
        var pTypes = new Array();
        for(var i = 0; i < _ptypeCheckboxes.length; i++)
        {  
            var chk = $get(_ptypeCheckboxes[i]);
            if (chk.checked)
                Array.add(pTypes, parseInt(chk.value));
        }        
        
        if (_hasMap)
            objMap.clearOverlays();
        
        
        if (_pages != null && _pageNumber <= _pages.length)
        {
            _systemIndex = _pages[_pageNumber - 1].SystemListingsStartIndex;
            _mlsIndex = _pages[_pageNumber - 1].MlsListingsStartIndex;
            
            document.cookie = "rindex=" + _pageNumber + "|" + _systemIndex + "|" + _mlsIndex + "; path=/"; 

        }
        
        var office = document.getElementById(ControlIDs.cmbOffice);
        
        if (office != null)
        {
            _officeId = parseInt(office.value);
        }
        
        //alert( _systemIndex + " " + _mlsIndex);
        _searchCount++;
        SA.Core.SearchProperties2($get(ControlIDs.txtXml2).value, minPrice, maxPrice, pTypes, parseInt($get(ControlIDs.cmbBedrooms).value), parseInt($get(ControlIDs.cmbBathrooms).value), parseInt($get(ControlIDs.cmbSquareFootage).value), _officeId, _sort, _sortDirection, _pageSize, _systemIndex, _mlsIndex, _calcPaging, _systemListingsFirst, ControlIDs.AnonUserKey, ControlIDs.InDesignMode, searchListings, searchError);
    }
    else
    {
        if ((results == null || results.Listings.length == 0) && results.MlsTimeout)
        {
            $get('divResults').style.display = 'none';
            $get('divViewLinks').style.display = 'none';
            $get('divNoResults').style.display = 'none'; 
            $get('divTimeout').style.display = ''; 
            
            if (_hasMap && _mapVisible == 1)
            {
                adjustMapVisibility();
            }                     
        }
        else if ((results == null || results.Listings.length == 0) )
        {
            $get('divResults').style.display = 'none';
            $get('divViewLinks').style.display = 'none';
            $get('divTimeout').style.display = 'none';
            $get('divNoResults').style.display = '';          
            
            if (_hasMap && _mapVisible == 1)
            {
                adjustMapVisibility();
            } 
        }
        else
        {
            $get('divResults').style.display = '';
            $get('divViewLinks').style.display = '';
            $get('divNoResults').style.display = 'none';    
            $get('divTimeout').style.display = 'none';            
            
            _total = results.TotalResults;
            _maxResults = results.MaxAllowedResults;
            var effTotal = (_maxResults > 0) ? Math.min(_maxResults, _total) : _total;
            var counts = $get('divCounts');
            
            if (_maxResults > 0 && Math.min(_pageNumber * _pageSize, _total) > _maxResults)
                _maxPageResults = _maxResults % _pageSize;

            counts.innerHTML = "<b>" + (((_pageNumber - 1) * _pageSize) + 1) + " - " + Math.min(_pageNumber * _pageSize, effTotal) + "</b> of <b>" + _total + "</b> listings";
                                        
            if (_calcPaging)
            {                    
                _calcPaging = false;
                _pages = results.Pages;                    
            }                       
            
            updatePaging();

            _listings = results.Listings;
            displayMapListings();            
            
            renderListings();

            $get('lblMlsDates').innerHTML = results.MlsSystemDates + " Search Count : " + _searchCount;
            if (results.MlsMessages != null)
            {
                var m = "";
                for(var i = 0; i < results.MlsMessages.length; i++)
                {
                    var msg = results.MlsMessages[i];
                    m += "<table><tr><td valign='top'><img alt='" + msg.MlsName + "' src='" + msg.MlsImageUrl + "'/></td><td valign='top'>" + msg.Message + "</td></tr></table>";
                }
                
                $get('divMlsMessages').innerHTML = m;
            }
            
        }
        
        $get(ControlIDs.divSearchPopup).style.display = '';
        $get('divLoading').style.display = 'none';        
    }
}

function displayMapListings() {
    if (_hasMap && _listings != null)
        mapPoints(_listings);
}

function updatePaging() {
    var p = '';
    var pNext = '';
    var pPrev = '';

    if (_pages != null && _pages.length > 1) {
        var startPage = _pageNumber - 8;
        if (startPage < 1)
            startPage = 1;

        var allowedPages = _pages.length;
        if (_maxResults > 0 && _total > _maxResults) allowedPages = Math.ceil(_maxResults / _pageSize);
        var endPage = (startPage + 16 > allowedPages) ? allowedPages : startPage + 16;
        

        for (var i = startPage; i <= endPage; i++) {
            if (i == _pageNumber) {
                p += "<span style='font-weight: bold'>" + i + "</span> ";
            }
            else {
                p += "<a href=\"javascript:viewPage(" + i + ");\">" + i + "</a> ";
            }
        }

        var prevPage = (_pageNumber > 1) ? _pageNumber - 1 : 1;
        var nextPage = (_pageNumber < allowedPages) ? _pageNumber + 1 : allowedPages;

        pPrev = "<a href='javascript:viewPage(" + prevPage + ");'>&lt; Previous</a>&nbsp;&nbsp;";
        pNext = "&nbsp;&nbsp;<a href='javascript:viewPage(" + nextPage + ");'>Next &gt;</a>";
    }
    var paging = $get('pagingPages');
    var topPaging = $get('topPagingPages');

    var topPagingPrev = $get('topPagingPrev');
    var pagingPrev = $get('pagingPrev');

    var pagingNext = $get('pagingNext');
    var topPagingNext = $get('topPagingNext');

    paging.innerHTML = p;
    pagingPrev.innerHTML = pPrev;
    pagingNext.innerHTML = pNext;

    topPaging.innerHTML = p;
    topPagingPrev.innerHTML = pPrev;
    topPagingNext.innerHTML = pNext;
}

function getGalleryHtml(l, i)
{
    var s = "";
    s += "<div class='listingItemGallery' onmouseover=\"swapCssClass(this, 'listingItemGalleryHover', 'listingItemGallery');\" onmouseout=\"swapCssClass(this, 'listingItemGallery', 'listingItemGalleryHover');\"><a href='";
    s += l.DetailUrl;
    s += "'>";
    if (_hasMap)
    {
        s += "<div class='mapNumber' style='background-color: ";
        if (l.Latitude != 0)
        {
            s += "green";
        }
        else{
            s += "#d3d3d3";
        }
        s += ";'>" + i + "</div>";
    }
    s += "<img src='" + l.PrimaryImage + "' alt='' class='listingPhoto' style='width: 250px; height: 185px'/></a>";
    s += "<div style='padding-bottom: 2px; text-align: left'><a style='font-size: small; font-weight: bold' href='";
    s += l.DetailUrl;
    s += "'>" + l.StreetAddressPublic + "</a></div>";
    s += "<span style='color: #CC3300; font-size: medium; font-weight: bold'>" + l.PriceFormatted + "</span><br/>";
    if (l.Courtesy != null && l.Courtesy.length > 0)
    {
        s += "<div style='font-size: x-small; padding-top: 5px;'>Courtesy of " + l.Courtesy + "</div>";
    }
    s += "<div style='padding-top: 10px; font-size: x-small;'>";
    var hasLink = false;
    if (l.ShowingUrl.length != 0) {
        s += "<a href='" + l.ShowingUrl + "'>Request Showing</a>";
        hasLink = true;
    }
    if (l.SaveUrl.length != 0) {
        if (hasLink) { s += " | "; }
        s += "<a id='lnkSave" + l.ResultId + "' href=\"" + l.SaveUrl + "\">Save Property</a>";
        hasLink = true;
    }
    if (_hasMap && l.Latitude != 0) {
        if (hasLink) { s += " | "; }
        s += "<a href='javascript:showOnMap(_markers[" + (i-1) + "]);'>Show on Map</a>";
    }
    if (l.TourUrl != null && l.TourUrl.length > 0)
    {
        s += " | <a target='_blank' style='vertical-align: bottom' href='" + l.TourUrl + "'><img alt='Virtual Tour' src='/shared/i/vtour.gif'/></a>";
    }
    
    s += "</div><img src='" + l.MlsIconUrl + "' alt='' style='margin-top: 15px; display: block'/></div>";
    return s;
}

function getListingHtml(l, i)
{
    var s = "";
    s += "<div class='listingItem' onmouseover=\"swapCssClass(this, 'listingItemHover', 'listingItem');\" onmouseout=\"swapCssClass(this, 'listingItem', 'listingItemHover');\"><table style='width: 100%;'><tr><td valign='top' align='center'><a href='";
    s += l.DetailUrl;
    s += "'>";
    if (_hasMap)
    {
        s += "<div class='mapNumber' style='background-color: ";
        if (l.Latitude != 0)
        {
            s += "green";
        }
        else{
            s += "#d3d3d3";
        }
        s += ";'>" + i + "</div>";
    }
    s += "<img src='" + l.PrimaryImage + "' alt='' class='listingPhoto' style='width: 120px'/></a><img src='" + l.MlsIconUrl + "' alt='' style='margin-top: 15px; display: block'/></td><td valign='top' style='width: 95%'>";
    s += "<div style='padding-bottom: 2px'><a style='font-size: medium; font-weight: bold' href='";
    s += l.DetailUrl;
    s += "'>" + l.StreetAddressPublic + "</a></div>";
    s += "<span style='color: #CC3300; font-size: medium'>" + l.PriceFormatted + "</span><br/>";
    s += "<span style='font-size: x-small'>" + l.BedsBathsEtc + "</span>";
    if (l.Description != null && l.Description.length > 0)
    {
        s += "<div class='listingDescription' style='font-size: x-small;'>" + l.Description + "</div>";
    }
    if (l.Courtesy != null && l.Courtesy.length > 0)
    {
        s += "<div style='padding-top: 5px;'>Listing provided courtesy of " + l.Courtesy + "</div>";
    }
    s += "<div style='padding-top: 10px;'>";
    var hasLink = false;
    if (l.ShowingUrl.length != 0) {
        s += "<a href='" + l.ShowingUrl + "'>Request Showing</a>";
        hasLink = true;
    }
    if (l.SaveUrl.length != 0) {
        if (hasLink) { s += " | "; }
        s += "<a id='lnkSave" + l.ResultId + "' href=\"" + l.SaveUrl + "\">Save Property</a>";
        hasLink = true;
    }
    if (_hasMap && l.Latitude != 0) {
        if (hasLink) { s += " | "; }
        s += "<a href='javascript:showOnMap(_markers[" + (i-1) + "]);'>Show on Map</a>";
    }
    if (l.TourUrl != null && l.TourUrl.length > 0)
    {
        s += " | <a target='_blank' style='vertical-align: bottom' href='" + l.TourUrl + "'><img alt='Virtual Tour' src='/shared/i/vtour.gif'/></a>";
    }
    
    s += "</div></td></tr></table></div>";
    return s;
}

function getFineHomesHtml(l, i)
{
    var s = "";
    s += "<div class='listingItem' onmouseover=\"swapCssClass(this, 'listingItemHover', 'listingItem');\" onmouseout=\"swapCssClass(this, 'listingItem', 'listingItemHover');\"><table style='width: 100%;'><tr><td valign='top' align='center'><a href='";
    s += l.DetailUrl;
    s += "'>";
    if (_hasMap)
    {
        s += "<div class='mapNumber' style='background-color: ";
        if (l.Latitude != 0)
        {
            s += "green";
        }
        else{
            s += "#d3d3d3";
        }
        s += ";'>" + i + "</div>";
    }
    s += "<img src='" + l.PrimaryImage + "' alt='' class='listingPhoto' style='width: 190px'/></a></td><td valign='top' style='width: 95%'>";
    s += "<div style='padding-bottom: 5px'><a style='font-size: medium; font-weight: bold' href='";
    s += l.DetailUrl;
    s += "'>" + l.StreetAddressPublic + "</a></div>";        
    if (l.Description != null && l.Description.length > 0)
    {
        s += "<div class='listingDescription' style='font-size: small;'>" + l.Description + "</div>";
    }
    s += "<div style='color: #CC3300; font-size: medium; font-weight: bold;'>" + l.PriceFormatted + "</div>";

    s += "<div style='padding-top: 10px;'>";
    var hasLink = false;
    if (l.ShowingUrl.length != 0) {
        s += "<a href='" + l.ShowingUrl + "'>Request Showing</a>";
        hasLink = true;
    }
    if (l.SaveUrl.length != 0) {
        if (hasLink) {s += " | "; }
        s += "<a id='lnkSave" + l.ResultId + "' href=\"" + l.SaveUrl + "\">Save Property</a>";
        hasLink = true;
    }
    if (_hasMap && l.Latitude != 0) {
        if (hasLink) { s += " | "; }        
        s += "<a href='javascript:showOnMap(_markers[" + (i-1) + "]);'>Show on Map</a>";
    }
    
    s += "</div></td></tr></table></div>";
    return s;
}


function saveProperty(lnk, mlsSysId, uid) {
    _mlsSysId = mlsSysId;
    _uid = uid;
    _saveLinkControl = lnk;
    if (visitorIsLoggedIn()) {
        saveProperty2();
    }
    else {        
        requestWebsiteLogin(saveProperty2);
    }
}

function saveProperty2() {
    //window.location = _saveUrl;
    SA.Core.AddSavedListing(_mlsSysId, _uid, saveProperty3);
}
function saveProperty3(r) {
    if (r) {
        var lnk = $get(_saveLinkControl);
        lnk.innerHTML = "<span style='color:red'>Saved</span>";
        lnk.href = "#";
    }
    else {
        alert("Failed to save property. Please login again.");
    }
}


function saveSearch() {
    if (visitorIsLoggedIn()) {
        saveSearch2();
    }
    else {
        requestWebsiteLogin(saveSearch2);
    }
}

function saveSearch2() {
    window.location = ControlIDs.SaveSearchUrl + "?save=1";
}

function searchError(e)
{
    $get('divResults').style.display = 'none';
    $get('divViewLinks').style.display = 'none';
    $get('divNoResults').style.display = 'none'; 
    $get('divTimeout').style.display = ''; 
    
    if (_hasMap && _mapVisible == 1)
    {
        adjustMapVisibility();
    } 
    
    $get(ControlIDs.divSearchPopup).style.display = '';
    $get('divLoading').style.display = 'none'; 
                
    //alert(e.get_message());
} 
    
function getDecimal(s)
{
    var n = 0;
    try { n = parseFloat(s); if (isNaN(n)) n = 0; } catch (e) { n = 0; }
    return n;
}

function swapCssClass(e, showClass, hideClass)
{
    Sys.UI.DomElement.addCssClass(e, showClass);
    Sys.UI.DomElement.removeCssClass(e, hideClass);    
}

var _rpageStart = document.cookie.indexOf("rindex=");
if (_rpageStart != -1)
{    
    var _rpageEnd = document.cookie.indexOf(";", _rpageStart);
    if (_rpageEnd == -1) _rpageEnd = document.cookie.length;
    var p = document.cookie.substring(_rpageStart + 7, _rpageEnd);
    var vals = p.split("|");
    if (vals.length == 3)
    {
        _pageNumber = parseInt(vals[0]);
        _systemIndex = parseInt(vals[1]);
        _mlsIndex = parseInt(vals[2]);
        //alert(_pageNumber + " " + _systemIndex + " " + _mlsIndex);
    }
}