﻿function findPosX(obj) {
    var curleft = 0;
    if (obj.offsetParent) {
        while (1) {
            curleft += obj.offsetLeft;
            if (!obj.offsetParent) {
                break;
            }
            obj = obj.offsetParent;
        }
    } else if (obj.x) {
        curleft += obj.x;
    }
    return curleft;
}
function findPosY(obj) {
    var curtop = 0;
    if (obj.offsetParent) {
        while (1) {
            curtop += obj.offsetTop;
            if (!obj.offsetParent) {
                break;
            }
            obj = obj.offsetParent;
        }
    } else if (obj.y) {
        curtop += obj.y;
    }
    return curtop;
}
function setDropdownValue(obj, val) {
    if (obj) {
        for (i = 0; i < obj.length; i++) {
            if (obj.options[i].value == val)
                return obj.selectedIndex = i;
        }
    }
}
function getObj(name) {
    if (document.getElementById) {
        this.obj = $get(name);
        this.style = $get(name).style;
    }
    else if (document.all) {
        this.obj = document.all[name];
        this.style = document.all[name].style;
    }
    else if (document.layers) {
        this.obj = document.layers[name];
        this.style = document.layers[name];
    }
}
var DHTML = (document.getElementById || document.all || document.layers);
function toggle(div, flag) {
    
    if (!DHTML) return;
    var x = new getObj(div);
    x.style.display = (flag) ? 'none' : 'block'
    x.style.visibility = (flag) ? 'hidden' : 'visible';
}
/* Manage cookies */
function createCookie(name, value, days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        var expires = "; expires=" + date.toGMTString();
    }
    else var expires = "";
    document.cookie = name + "=" + value + expires + "; path=/";
}

function readCookie(name) {
   
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
    }
    return null;
}
function eraseCookie(name) {
    createCookie(name, "", -1);
}
function SaveRecentSearches(JsonSearchStr, maxCount, REC_SEARCHES, REC_SEARCHES_COUNTER) {
  var counter;
    if (readCookie(REC_SEARCHES_COUNTER)) {
        counter = parseInt(readCookie(REC_SEARCHES_COUNTER));
        counter = counter < maxCount ? counter : maxCount-1;
        for (var i = counter + 1; i > 1; i--) {
            var PrevCookieVal = readCookie(REC_SEARCHES + (i-1));
            createCookie(REC_SEARCHES + i, PrevCookieVal, 10);
        }
        counter++;
    }
    else counter = 1;
    
    if (REC_SEARCHES=="PortalRS_")
    {
    $get('ctl00_Login_RecActivity_RSCount').innerHTML = counter;
    }
    else
    {
    $get('ctl00_Login_RecActivity_RLCount').innerHTML = counter;
    }
    
    
    createCookie(REC_SEARCHES + "1", JsonSearchStr,10);
    createCookie(REC_SEARCHES_COUNTER, counter, 10);
}
/* Manage cookies ends*/

function showPageCover() {
    var widCover = Math.max(document.documentElement.scrollWidth, document.body.scrollWidth) + "px";
    var htCover = Math.max(document.documentElement.scrollHeight, document.body.scrollHeight) + "px";
    $get('pageCover').style.width = widCover;
    $get('pageCover').style.height = htCover;
    $get('pageCover').style.display = 'block';
    $get('pageCover').style.visibility = 'visible';
}
function hideDropDowns() {
    if (document.all) {
        var arrDD = document.documentElement.getElementsByTagName('select');
        for (i = 0; i < arrDD.length; i++) {
            arrDD[i].style.display = "none";
        }
    }
}
function showDropDowns() {
    if (document.all) {
        var arrDD = document.getElementsByTagName('select');
        for (i = 0; i < arrDD.length; i++) {
            arrDD[i].style.display = "block";
            //arrDD[i].style.visibility = "visible";
        }
    }
}
function GetWindowHeight() {
    var height = 0;
    if (typeof (window.innerHeight) == 'number') {
        height = window.innerHeight;
    } else if (document.documentElement && document.documentElement.clientHeight) {
        height = document.documentElement.clientHeight;
    } else if (document.body && document.body.clientHeight) {
        height = document.body.clientHeight;
    }
    if (!height || height < 100) {
        height = 100;
    }
    return height;
}

function GetWindowWidth() {
    var width = 0;
    if (typeof (window.innerWidth) == 'number') {
        width = window.innerWidth;
    } else if (document.documentElement && document.documentElement.clientWidth) {
        width = document.documentElement.clientWidth;
    } else if (document.body && document.body.clientWidth) {
        width = document.body.clientWidth;
    } if (!width || width < 100) {
        width = 100;
    }
    return width;
}
// This populates the price combo box 
function PopulatePriceDropDown(priceOption, priceDropDown) {
    var priceOptionText = "";
    var priceOptionValue = "";
    var item = "";
    priceDropDown.innerHTML = "";
    var items = priceOption.split("~");
    for (i = 0; i < items.length; i++) {
        item = items[i].split("|");
        priceOptionText = item[1];
        priceOptionValue = item[0];

        if (priceOptionText != "") {
            optionItem1 = new Option(priceOptionText, priceOptionValue, false, false);
            priceDropDown.options[priceDropDown.length] = optionItem1;
        }
    }
}
function setFnaDivPosition() {
    fnaAnchorObj = $get('FnaAnchor');
    fnaSearchDivObj = $get('FnaSearchDiv');

    fnaSearchDivObj.style.position = 'absolute';
    fnaSearchDivObj.style.top = findPosY(fnaAnchorObj) + 'px';
    fnaSearchDivObj.style.left = 30 + 'px'; //findPosX(fnaAnchorObj) - 300 + 'px';
}
function Reset()
{
     $get(prefix + "MinPriceDropDown").value=0;
     $get(prefix + "MaxPriceDropDown").value=999999999999;
     $get(prefix+"BedsDropDown").value =0;
     $get(prefix+"BathsDropDown").value =0;
      
     $get(prefix+"SortingDropDown").value=1;
        $get("SingleFamily").checked =false;
        $get("TownHouse").checked  =false;
        $get("MultiFamily").checked  =false;
        $get("Commercial").checked  =false;
        $get("Lots").checked  =false;
        $get("Other").checked =false;
     $get(prefix+"garage").value ='';
     $get(prefix+"style").value =511; 
     $get(prefix+"LotFromDropdown").value =''; 
     $get(prefix+"LotToDropdown").value ='';
        
     $get(prefix+"WithPhotos").checked =false;
     $get(prefix+"OpenHouses").checked =false;
     $get(prefix+"Foreclosured").checked =false;
     $get(prefix+"waterView").checked =false;
     $get(prefix+"waterFront").checked =false;
     $get(prefix+"waterAccess").checked =false;
     $get(prefix+"RentalListings").checked =false;
     $get(prefix+"SwimmingPool").checked =false;
     
     $get(prefix+"ChkUnderContract").checked =false;
     
}
function SearchParameters() {
    this.OriginalSearchString = $get(prefix + "SearchTextBox").value;
    this.MinPrice = $get(prefix + "MinPriceDropDown").value;
    this.MaxPrice = $get(prefix + "MaxPriceDropDown").value;
    this.BedRooms = $get(prefix+"BedsDropDown").value != "0" ? $get(prefix+"BedsDropDown").value : null;
    this.Bathrooms = $get(prefix+"BathsDropDown").value != "0" ? $get(prefix+"BathsDropDown").value : null;
    
    this.SortOrder = $get(prefix+"SortingDropDown").value;
    this.PropertyMasterTypeID = CalculateMultiSelectionValue();
    this.Garage = $get(prefix+"garage").value != "" ? $get(prefix+"garage").value : null;
    this.Style = $get(prefix+"style").value != "" ? $get(prefix+"style").value : null;
    this.LotSizeFrom = $get(prefix+"LotFromDropdown").value != "" ? $get(prefix+"LotFromDropdown").value : null;
    this.LotSizeTo = $get(prefix+"LotToDropdown").value != "" ? $get(prefix+"LotToDropdown").value : null;
    
    this.WithPhotos = $get(prefix+"WithPhotos").checked == true ? 1 : null;
    this.OpenHouses = $get(prefix+"OpenHouses").checked == true ? 1 : null;
    this.IsForeClosure = $get(prefix+"Foreclosured").checked == true ? 1 : null;
    this.WaterView = $get(prefix+"waterView").checked == true ? 1 : null;
    this.WaterFront = $get(prefix+"waterFront").checked == true ? 1 : null;
    this.WaterAccess = $get(prefix+"waterAccess").checked == true ? 1 : null;
    this.IsRental = $get(prefix+"RentalListings").checked == true ? 1 : null;
    this.Pool = $get(prefix+"SwimmingPool").checked == true ? 1 : null;
    
    this.UnderContract = $get(prefix+"ChkUnderContract").checked == true ? 1 : null;
    
}
function MapSearchParameters(p_CenterLat,p_CenterLong,p_ZoomLvel,p_LatLeft,p_LongTop,p_LatRight,p_LongBottom) {
    this.CenterLat=p_CenterLat!= "" ? p_CenterLat : null;
    this.CenterLong=p_CenterLong!= "" ? p_CenterLong : null;
    this.CurrentZoomLevel=p_ZoomLvel!= "" ? p_ZoomLvel : null;
    this.BoundingLatLeft=p_LatLeft!= "" ? p_LatLeft : null;
    this.BoundingLonTop=p_LongTop!= "" ? p_LongTop : null;
    this.BoundingLatRight=p_LatRight!= "" ? p_LatRight : null;
    this.BoundingLonBottom=p_LongBottom!= "" ? p_LongBottom : null;
}
function SearchResults(obj) {
    this.MapDetalis = obj[0]!= "" ? obj[0] : null;
    this.ListingSummary = obj[1]!= "" ? obj[1] : null;
    this.ListingCount = obj[2]!= "" ? obj[2] : null;
    this.Layer = obj[3]!= "" ? obj[3] : null;
    this.ToggleFirstMlsNo= obj[4]!= ""  ? obj[4] : null;
    this.ToggleFirstMlsID= obj[5]!= ""  ? obj[5] : null;
    this.ResultType= obj[6] != "" ? obj[6] : null;
    if(typeof(obj[7]) != "undefined")
        this.ExceedLimit= obj[7] ;
    else
        this.ExceedLimit='';
    this.ShowResult = function() {
        eval(this.MapDetalis);
        $get(prefix + "ListingHeaderField").value = this.ListingSummary;
        //START: map/summary div handler
        if (this.ListingCount > 0) {
            var mapHt = GetWindowHeight() > 528 ? 528 : GetWindowHeight();
            var mapWt = GetWindowWidth() - $get('SummaryResultDiv').clientWidth - 100 > 200 ? GetWindowWidth() - $get('SummaryResultDiv').clientWidth - 100 : 200;
            $get('myMap').style.width = GetWindowWidth() - $get('SummaryResultDiv').clientWidth - 100;
            map.Resize(mapWt + 'px', mapHt + 'px');
            $get('SummaryResultDiv').style.display = "block";
            $get('ListingCountDiv').style.display = "block";
        }
        else {
            var mapWt = GetWindowWidth() - 100 > 200 ? GetWindowWidth() - 100 : 200;
            var mapHt = GetWindowHeight() > 528 ? 528 : GetWindowHeight();
            $get('myMap').style.width = (window.screen.width) * 87 / 100 + "px";
            map.Resize(mapWt + 'px', mapHt + 'px');
            $get('SummaryResultDiv').style.display = "none";
            $get('ListingCountDiv').style.display = "none";
        }
        //END: map/summary div handler
        $get(prefix + 'SaveSearchAncr').style.display = "block";
        $get('SearchTitleDiv').style.display = "none";
        // to handle the layer types
        switch (this.ResultType) {
            case "StateSearch":
                // show the appropriate layer
                var searchText = $get(prefix + 'SearchTextBox');
                $get(prefix + 'firstTimeMsgDiv').style.display = 'block';
                $get(prefix + 'countMsg').innerHTML = "<br /><br /><br />Please narrow down your search to an address, city, zip code or Mls.";
                searchText.value = "";
                GetSummary("");
                onUpdated();
                break;
            case "Layer":
                $get(prefix + 'firstTimeMsgDiv').style.display = 'block';
                $get(prefix + 'countMsg').innerHTML = this.Layer + " ";
                if (this.ListingCount!='City') {
                $get(prefix + 'SaveSearchAncr').style.visibility = 'hidden';
                $get(prefix + 'divbtnSaveSearch').style.display = 'none';}
                else{
                $get(prefix + 'SaveSearchAncr').style.visibility = 'visible';
                $get(prefix + 'divbtnSaveSearch').style.display = 'block';}
                onUpdated();
                break;
            default:
                $get(prefix + 'firstTimeMsgDiv').style.display = 'none';
                if (this.ListingCount <= 1) {
                    $get("listingCountText").innerHTML = "Listing";
                }
                else if (this.ListingCount > 1) {
                    $get("listingCountText").innerHTML = "Listings";
                }
                $get("listingCount").innerHTML = this.ListingCount + " ";
                GetSummary(parseInt(this.ListingCount));
                toggleBodyDiv(this.ToggleFirstMlsNo, this.ToggleFirstMlsID, 1, 1);
                onUpdated();
                // show no layer
                break;
        }
        attachMapEvents();
    };
}
function validate() {
    var searchText = $get(prefix + 'SearchTextBox');
    var ErrorMessage = $get(prefix + 'ErrorMessage');
            if (searchText.value.trim() == "" || searchText.value == "Enter a ZIP, city or MLS number") {

                ErrorMessage.innerHTML = "<b>Please enter a location or MLS number to proceed. Thank you.</b>";
                return false;
            }
            else if(searchText.value=='Use Mapped Area')
                ExecuteSingleMapSearch();
            else
            {
                var minPrice = $get(prefix + 'MinPriceDropDown');
                var minPriceValue = minPrice[minPrice.selectedIndex].value;
                var maxPrice = $get(prefix + 'MaxPriceDropDown');
                var maxPriceValue = maxPrice[maxPrice.selectedIndex].value;
                if (minPriceValue * 1 > maxPriceValue * 1) {
                    ErrorMessage.innerHTML = "<br/>Minimum value of Price cannot be greater than maximum value";
                    return false;
                }
            ErrorMessage.value = "";
            return true;
            }
        }
function CalculateMultiSelectionValue() {
    var totalValue = 0;
           if ($get("SingleFamily").checked == true)
                totalValue = totalValue | parseInt($get("SingleFamily").name);
           if ($get("TownHouse").checked == true)
                totalValue = totalValue | parseInt($get("TownHouse").name);
           if ($get("MultiFamily").checked == true)
                totalValue = totalValue | parseInt($get("MultiFamily").name);
           if ($get("Commercial").checked == true)
                totalValue = totalValue | parseInt($get("Commercial").name);
           if ($get("Lots").checked == true)
                totalValue = totalValue | parseInt($get("Lots").name);
           if ($get("Other").checked == true)
                totalValue = totalValue | parseInt($get("Other").name);
             
           if (totalValue==0)totalValue=63;
    return totalValue;
}
function assignPropertyType(propertyType) {
    // since top 3 are by default checked, need to uncheck if not selected...
    $get("SingleFamily").checked = (parseInt($get("SingleFamily").name) & parseInt(propertyType)) > 0 ? true : false;
    $get("TownHouse").checked = (parseInt($get("TownHouse").name) & parseInt(propertyType)) > 0 ? true : false;
    $get("MultiFamily").checked = (parseInt($get("MultiFamily").name) & parseInt(propertyType)) > 0 ? true : false;
    if ((parseInt($get("Commercial").name) & parseInt(propertyType)) > 0) $get("Commercial").checked = true;
    if ((parseInt($get("Lots").name) & parseInt(propertyType)) > 0) $get("Lots").checked = true;
    if ((parseInt($get("Other").name) & parseInt(propertyType)) > 0) $get("Other").checked = true;
}
function onUpdating() {
    toggle('mapCover', 0);
    var updateProgressDiv = $get('updateProgressDiv');
    updateProgressDiv.style.display = 'block';
}

function onUpdated() {
    var updateProgressDiv = $get('updateProgressDiv');
    updateProgressDiv.style.display = 'none';
    toggle('mapCover', 1);
}

function setPositionElement(value,elementId)
{
    var scrollY=0;    
    if(window.pageYOffset)
    {
        scrollY=window.pageYOffset;
    }
    if(document.all)
    {
        scrollY= document.documentElement.scrollTop;
    }
    var adjustedY=scrollY+value+'px';    
    $get(elementId).style.top = adjustedY;
}
function hideAncrButtons() {
    fnaAnchorObj = $get('FnaAnchor');
    fnaSearchDivObj = $get('FnaSearchDiv');

    fnaSearchDivObj.style.position = 'absolute';
    fnaSearchDivObj.style.top = findPosY(fnaAnchorObj) + 'px';
    $get('FnaAnchor').style.visibility = 'hidden';
    $get(prefix + 'SearchBtn').style.visibility = 'hidden';
    $get(prefix + 'SaveSearchAncr').style.visibility = 'hidden';
    $get(prefix + 'divbtnSearch').style.display = 'none';
    $get(prefix + 'divbtnSaveSearch').style.display = 'none';
}
function showAncrButtons() {
    $get('FnaAnchor').style.visibility = 'visible';
    $get(prefix + 'SearchBtn').style.visibility = 'visible';
    $get(prefix + 'SaveSearchAncr').style.visibility = 'visible';
    $get(prefix + 'divbtnSearch').style.display = 'block';
    $get(prefix + 'divbtnSaveSearch').style.display = 'block';
}

function check(checkboxid) {
    if ($get(checkboxid).checked)
        $get(checkboxid).checked = ""
    else
        $get(checkboxid).checked = "checked";
}
function ZoomLinkClick() {
    var latlng = map.GetCenter();
    lat = latlng.Latitude;
    lon = latlng.Longitude;
    ExecuteRecursiveMapSearch(lat, lon);
}
function ZoomOutLinkClick() {
    map.SetZoomLevel(map.GetZoomLevel() - 2);
    try
    {
        ExecuteSingleMapSearch();
    }
    catch(e) 
    {
    }
}
function EditLinkClick() {
    toggleSlide('FnaSearchDiv'); hideAncrButtons();
    $get(prefix + 'SearchTextBox').focus();
    return false;
}
function ResetLinkClick() {
    Reset();
    toggleSlide('FnaSearchDiv'); hideAncrButtons();
    $get(prefix + 'SearchTextBox').focus();
    return false;
}
//function ShowListingSummary() {
//    $get('ListingCountDiv').style.display = "block";
//    $get('SummaryResultDiv').style.display = "block";
//    mapHeight = GetWindowHeight() > 528 ? 528 : GetWindowHeight();
//    mapWidth = GetWindowWidth() - $get('SummaryResultDiv').clientWidth - 100 > 200 ? GetWindowWidth() - $get('SummaryResultDiv').clientWidth - 100 : 200;
//    if (map != null)
//        map.Resize(mapWidth + 'px', mapHeight + 'px');
//}

function UpdateSavedSearch(ssID) {
    var searchname = $get(prefix + "SearchNameTxt").value;
    var mapParamjson=$get(prefix + 'MapSearch').value;
    if(searchname != '')
    {
        if(mapParamjson!="")
        Real_Estate_Search.UpdateSearchBtn_Click(ssID,JSON.stringify(new SearchParameters()),mapParamjson, searchname,'MapSearch', UpdateSearch_CallBack);
        else
        Real_Estate_Search.UpdateSearchBtn_Click(ssID,JSON.stringify(new SearchParameters()),mapParamjson, searchname,'QuickSearch', UpdateSearch_CallBack);
    }
    else
        $get(prefix + 'ssMsgLbl').innerHTML = "Please give a name to this search";
        return false;
}

function UpdateSearch_CallBack(result) {
    if (result.value == 0) {
        OpenLoginDiv("You must be logged in to save this search.");
    }
    else if (result.value == 1) {
    hideSsTitleDiv();
    $get(prefix + 'ErrorMessage').innerHTML = "Search updated successfully";
    }
}
var updateSsID = '';
var searchName = '';
function saveThisSearch() {    
    if (updateSsID != '' && searchName == $get(prefix + "SearchNameTxt").value) {
        UpdateSavedSearch(updateSsID);
        return;
    }
    var searchname = $get(prefix + "SearchNameTxt").value;
    var mapParamjson=$get(prefix + 'MapSearch').value;
    if(searchname != '')
    {
        if (mapParamjson != "")       
          Real_Estate_Search.SaveSearchBtn_Click(JSON.stringify(new SearchParameters()),mapParamjson, searchname,'MapSearch', SaveSearch_CallBack);
        else
         Real_Estate_Search.SaveSearchBtn_Click(JSON.stringify(new SearchParameters()),mapParamjson, searchname,'QuickSearch', SaveSearch_CallBack);
    }
    else
        $get(prefix + 'ssMsgLbl').innerHTML = "Please give a name to this search";
    return false;
}
function SaveSearch_CallBack(result) {    
    if (result.value == 0) {
        OpenLoginDiv("You must be logged in to save this search.","saveSearch");
    }
    else if (result.value== null)
    {
        hideSsTitleDiv();
        $get(prefix + 'ErrorMessage').innerHTML = "Search saved successfully";
    }
    else
    {
        $get(prefix + 'ssMsgLbl').innerHTML = "You have an existing search with the same name. Please rename this search. If you want to save it with the same name, it will overwrite the existing search."
        updateSsID = result.value;
        searchName = $get(prefix + "SearchNameTxt").value;
    }
    
 }
 function hideSsTitleDiv() {
     updateSsID = '';
     searchName = '';
     $get(prefix + 'ssMsgLbl').innerHTML = '';
     $get('SearchTitleDiv').style.display = "none";
     toggle('pageCover', 1);
     showDropDowns();
 }
