﻿var _searchObj = null;
// Logging EventID constants
/*
var EVENT_SEARCH = 1;
var EVENT_DETAILS = 2;
var EVENT_VTOUR = 3;
var EVENT_MAP = 4;
var EVENT_FAVORITE = 5;
*/

// function loadProperties()
function loadProperties()
{
    _message.style.visibility = 'visible';
    _pageContent.style.display = 'none';   

    var top = parseInt(_ddlTop.options[_ddlTop.selectedIndex].value);
    _pager.set_pageSize(top);
    _pagerBottom.set_pageSize(top); // NEW FOR PAGERBOTTOM
    
    var sortColumn = _gridView.get_sortColumn();
    var sortOrder = (_gridView.get_sortOrder() == AjaxDataControls.GridViewSortOrder.Descending) ? 'DESC' : 'ASC';
    var startIndex = (_pager.get_pageIndex() * _pager.get_pageSize() +1);
    var endIndex = startIndex + top - 1;
    
    // if wtProperty only (our listing)
    if (_listingType == 'wt')
    {
        getPropertyType();
        wsListing.GetAllWTListing( startIndex, endIndex, sortColumn, sortOrder, _pRes, _pMul, _pLnd, onLoadSuccess);
    }
    // main search (find a home)
    else if (_listingType == 'search')
    {
        getPropertyType();
        // Area Search
        if (_searchType == 1) 
        {
            wsListing.GetPropByArea(getddlValue(_ddlMinPrice),getddlValue(_ddlMaxPrice), getddlValue(_ddlBeds),getddlValue(_ddlBaths),getddlValue(_ddlMinSqft),getddlValue(_ddlMaxSqft), getAreas(), _pRes, _pMul, _pLnd, startIndex, endIndex, sortColumn, sortOrder, onLoadSuccess)
        }
        // Street/Zip Search
        else if (_searchType == 2)
        {
            wsListing.GetPropByStZip(getddlValue(_ddlMinPrice),getddlValue(_ddlMaxPrice), getddlValue(_ddlBeds),getddlValue(_ddlBaths),getddlValue(_ddlMinSqft),getddlValue(_ddlMaxSqft), getTxtValue(_tbStreetName), getTxtValue(_tbZipCode), _pRes, _pMul, _pLnd, startIndex, endIndex, sortColumn, sortOrder, onLoadSuccess)            
        }
        
    }
    else if (_listingType == 'agent')
    {
        var agentmls = getQueryString('agentmls');
        if (agentmls != '')
        {
            wsListing.GetListingByAgent(agentmls, startIndex, endIndex, sortColumn, sortOrder, onLoadSuccess);
        }
    }
}

// function onLoadSuccess(result)
// Called when properties are successfully pulled in from the database
function onLoadSuccess(result)
{
    _message.style.visibility = 'hidden'; 
    if (result != null) 
    {
        var total = result.Total;
        _pager.set_recordCount(total);
        _pagerBottom.set_recordCount(total);  // NEW FOR PAGERBOTTOM
        _gridView.set_dataSource(result.Rows);
        _gridView.dataBind();
        if(_listingType == 'search') { createHeader(); }
        setPageInfo(total);
        _header.style.display = 'block';
        
        // Log Search Results
        if(_listingType == 'search')
        {
            onInsertLog(_gridView.get_dataKeys(), EVENT_SEARCH);
        }  
    }
    else
    {
       _pager.set_recordCount(0);
       _pagerBottom.set_recordCount(0);  // NEW FOR PAGERBOTTOM
       setPageInfo(0);
       _gridView.set_dataSource(null);
       _gridView.dataBind();
       _header.style.display = 'none';
    }
    if(_listingType == 'search')
    {
        _listArea.style.display = 'block';
    }
    _pageContent.style.display = 'none';   
}

// function onShowDetails(uid)
// shows the details of the property with the given uid
function onShowDetails(uid)
{
    _detailsWrap.style.display = 'block';
    _mainRight.style.display = 'none';
    window.scrollTo(0,0);
    if (Sys.Services.AuthenticationService.get_isLoggedIn())
    { 
        wsListing.GetDetails(uid, true, onLoadDetailsSuccess);  
    }
    else
    {
        wsListing.GetDetails(uid, false, onLoadDetailsSuccess); 
    }
    // -- Used for full-screen show/hide
    //_mainLeft.className='hide';
    //_majRight.className='w100';
}

// function onShowDetails_ByMls(mlsnum)
// shows the details of the property with the given mlsnum
function onShowDetails_ByMls(mlsnum)
{
    _detailsWrap.style.display = 'block';
    _mainRight.style.display = 'none';
    window.scrollTo(0,0);
    if (Sys.Services.AuthenticationService.get_isLoggedIn())
    { 
        wsListing.GetDetailsByMls(mlsnum, true, onLoadDetailsSuccess);  
    }
    else
    {
        wsListing.GetDetailsByMls(mlsnum, false, onLoadDetailsSuccess); 
    }
}

// function onHideDetails()
// hides the details of the property being viewed
function onHideDetails()
{
    _detailsWrap.style.display = 'none';
    _mainRight.style.display = 'block';
    
    // Used for the back button functionality in ajax update panels - 2/26/08
    // Sys.Application.get_history().addHistoryPoint({pageClientState: -1}, top.document.title);
    
    // -- Used for full-screen show/hide
    //_mainLeft.className='showTbl mainLeft';
    //_majRight.className='majRight wtbox';
}

// function onFindHome()
function onFindHome()
{
    _listArea.style.display = 'none';
    _pageContent.style.display = 'block';
}

// function onLoadDetailsSuccess(result)
// Successfully loaded property details
function onLoadDetailsSuccess(result)
{
    _propDetails.innerHTML = result;
    _media = document.getElementById('divMedia');
    var tmpUID = document.getElementById('holduid');
    // Log Property Details
    onInsertLog(convertToArray(getText(tmpUID)), EVENT_DETAILS);
}

// function setPageInfo(total)
// Sets the text of "Showing: a-b of total"
function setPageInfo(total)
{
    if (total > 0)
    {
        var itemsL = (_pager.get_pageIndex() + 1) * _pager.get_pageSize();
        var itemsF = itemsL - _pager.get_pageSize() + 1;
        if (itemsL > total) {
            itemsL = total;
        }
        document.getElementById("pagerData").innerHTML = "Showing: " + itemsF + "-" + itemsL + " of " + total
    }
    else
    {
        document.getElementById("pagerData").innerHTML = "";
    }
}

// function createHeader()
// creates the header of the gridview
function createHeader()
{
    var tr = _gridView.get_headerRow().get_container();
    var table = document.getElementById("gvList_Header");
    table.deleteRow(0);    
    var row = table.insertRow(0);
    var len = tr.childNodes.length;
    for(var x=0;x<len;x++)
    {
        row.appendChild(tr.childNodes[0]);
    }
    tr = null;
}

// function pageChanged(sender, e)
// Used to change the pager information when a page is changed
// loads the new properties to be displayed
// set a history point to maintain back button functionality
function pageChanged(sender, e)
{
    _pager.set_pageIndex(e.get_newPageIndex());
    _pagerBottom.set_pageIndex(e.get_newPageIndex()); // NEW FOR PAGERBOTTOM
    loadProperties();
    window.scrollTo(0,0);
    Sys.Application.get_history().addHistoryPoint({pageClientState: e.get_newPageIndex() + 1}, top.document.title);
}

// function agentPageChanged(sender, e)
// Used to change the pager information when a page is changed on the agent details page
// load the new properties to be displayed
// set a history point to maintain back button functionality
function agentPageChanged(sender, e)
{
    _pager.set_pageIndex(e.get_newPageIndex());
    _pagerBottom.set_pageIndex(e.get_newPageIndex()); // NEW FOR PAGERBOTTOM
    loadProperties();
    Sys.Application.get_history().addHistoryPoint({pageClientState: e.get_newPageIndex() + 1}, top.document.title);
}

// function onSortcommand(sender, e)
function onSortCommand(sender, e)
{
    _gridView.set_sortColumn(e.get_sortColumn());
    _gridView.set_sortOrder(e.get_sortOrder());
    _pager.set_pageIndex(0);  
    _pagerBottom.set_pageIndex(0); // NEW FOR PAGERBOTTOM
    loadProperties();
}

// function setText(element, text)
// Helper method to set the text of element to text
function setText(element, text)
{
    if (typeof element.innerText != 'undefined' && text != null)
    {
        element.innerHTML = text;
    }
    else if (typeof element.textContent != 'undefined' && text != null) 
    {
        element.textContent = text;
    }
}

// function setPrice(element, price, hidePrice)
// Helper method used to set the price of element to price
// If hidePrice is true, the text of element will be set to "Call for Price"
function setPrice(element, price, hidePrice)
{
    if (typeof element.innerText != 'undefined' && price != null)
    {
        if (hidePrice == "1") {
            element.innerHTML = "Call for Price";
        } else {
            element.innerHTML = price;
        }
    }
    else if (typeof element.textContent != 'undefined' && price != null) 
    {
        if (hidePrice == "1") {
            element.textContent = "Calls for Price";
        } else {
            element.textContent = price;
        }
    }
}

// function getText(el)
// returns the text of el
function getText(el)
{
    if ('string' == typeof el.textContent) return el.textContent;
    if ('string' == typeof el.innerText) return el.innerText;
    return el.innerHTML.replace(/<[^>]*>/g,'');
}

// function setLogo(element, text)
// Helper method used to display the WT Logo if the property is a cuff
function setLogo(element, text)
{
    if (text != null)
    {
        text = text.substring(0, 8);
        //if ((text == 'WTFR00FW') || (text == 'WTRS00FW') || (text == 'WTRS01FW') || (text == 'WTPM00FW'))
        if (text == 'WTFR00FW' || text == 'WTRS00FW' || text == 'WTRS01FW' || text == 'WTPM00FW')
        {
            element.style.visibility = 'visible';
        }
    }
}

// function setListimg(element, text)
function setListImg(element, text)
{     
    if ((text != null) && (text != ''))
    {
        element.src = "image.wt?list=" + text;
    }
}

// function setImg(element, text)
function setImg(element, text)
{     
    if ((text != null) && (text != ''))
    {
        element.src = text;
    }
}

// function thumb_clicked(url)
function thumb_clicked(url){
    _media.innerHTML = "<img src=\"" + url + "\" class=\"dImg\" ></img>";
}

// function checkQuery()
// Checks the query string to determine what function to call to display the property
function checkQuery()
{
    // If there is a query string
    if (window.location.search != '')
    {
        if(getQueryString('uid') != '')
        {
            onShowDetails(getQueryString('uid'));
        }
        else if(getQueryString('mls') != '')
        {
            onShowDetails_ByMls(getQueryString('mls'));
        }
        else if(getQueryString('zip') != '' || getQueryString('stname') != '')
        {
            showStreet();
            var stnm = getQueryString('stname')
            stnm = stnm.replace(/%20/g," ");
            _tbStreetName.value = stnm;
            _tbZipCode.value = getQueryString('zip');
            var minP = parseInt(getQueryString('minprice'));
            var maxP = parseInt(getQueryString('maxprice'));
            if(minP != '')
            {
                for(var i=1;i<_ddlMinPrice.length-1;i++)
                {
                   if (parseInt(_ddlMinPrice[i].value) == minP) 
                   {
                        _ddlMinPrice.selectedIndex = i;
                        break;
                   }
                   else if(minP > parseInt(_ddlMinPrice[i].value) && minP < parseInt(_ddlMinPrice[i+1].value))
                   {
                         _ddlMinPrice.selectedIndex = i;
                         break;
                   }
                }
            }
            if(maxP != '')
            {
                for(var i=1;i<_ddlMaxPrice.length-1;i++)
                {
                   if (parseInt(_ddlMaxPrice[i].value) == maxP) 
                   {
                        _ddlMaxPrice.selectedIndex = i;
                        break;
                   }
                   else if(maxP > parseInt(_ddlMaxPrice[i].value) && maxP < parseInt(_ddlMaxPrice[i+1].value))
                   {
                         _ddlMaxPrice.selectedIndex = i;
                         break;
                   }
                }
            }
            loadProperties();
            Sys.Application.get_history().addHistoryPoint({pageClientState: 1}, top.document.title);
        }
    }
}

// function getQuertyString(name)
function getQueryString( name )
{
    name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
    var regexS = "[\\?&]"+name+"=([^&#]*)";
    var regex = new RegExp( regexS );
    var results = regex.exec( window.location.href );
    if( results == null )
        return "";
    else
        return results[1];
}

// function formatCurrency(num)
// Helper method to format num as currency
function formatCurrency(num) {
    num = num.toString().replace(/\$|\,/g,'');
    if(isNaN(num))
        num = "0";
    sign = (num == (num = Math.abs(num)));
    num = Math.floor(num*100+0.50000000001);
    num = Math.floor(num/100).toString();
    for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
        num = num.substring(0,num.length-(4*i+3))+ ','+ num.substring(num.length-(4*i+3));
    return (((sign)?'':'-') + '$' + num);
}


/***************************
 * Save Property Functions *
 ***************************/
 
// function onSaveProperty(uid)
// If the user is logged in, propety uid will be saved 
// With a successful save, onSavePropertySuccess will be called.
// If the user is not logged in, an alert will be popped up saying they must be logged in 
// to save searches.
function onSaveProperty(uid)
{
    if(Sys.Services.AuthenticationService.get_isLoggedIn())
    {
        wsUser.InsertSavedProp(uid, onSavePropertySuccess);
    }
    else
    {
        alert("Must be logged in to Save a Property.  Please register for an account.");
        var mywindow = window.open("../mywt/default.aspx", "mywindow", "location=1");
    }
}

// function onSavePropertySuccess(result)
// Called when a user successfully saves a property
// Will call insertFavorite(uid) to keep a log of the number of times the property has been saved
// as a favorite.
function onSavePropertySuccess(result)
{
    // Once a property has been saved, we need to log that the property has been saved to a users favorites.
    var qs = self.location.toString();
    if (qs.match("3A") == "3A") {
        var beg = qs.indexOf("3A");
        beg += 2;
        var end = qs.indexOf("%7D");
    } else {
        var beg = qs.indexOf("=") + 1;
        var end = beg + 7;
    }
    var uid = qs.substring(beg, end);
    insertFavorite(uid);
    
    alert("Save was Successful");
}


/************************
 * Save Search Funtions *
 ************************/
  
// function onSaveSearch()
// Will attempt to save a user search
function onSaveSearch()
{
    // Set chkbx to true or false depending on if the save search checkbox is checked or not
    var chkbx = document.getElementById("ctl00_contentLeft_saveSearchChkBx").checked;
    
    // If the checkbox is checked
    if (chkbx) {
        // Call web service to insert information into database
        wsUser.InsertUserSearch(getddlValue(_ddlMinPrice),getddlValue(_ddlMaxPrice), getddlValue(_ddlBeds),getddlValue(_ddlBaths),getddlValue(_ddlMinSqft),getddlValue(_ddlMaxSqft), getAreas(), getTxtValue(_tbStreetName), getTxtValue(_tbZipCode), _tbSearchName.value, _pager.get_recordCount());       
    }
}

// function saveSearchFromRight()
// Called when a user enters a search name and clicks the save button above the search results
// Verifies the user is logged in and then attempts to save the search
// If the search is successfully saved, an alert will popup informing the user
function saveSearchFromRight() {
    // verify user is logged in
    if(Sys.Services.AuthenticationService.get_isLoggedIn())
    {
        wsUser.InsertUserSearch(getddlValue(_ddlMinPrice),getddlValue(_ddlMaxPrice), getddlValue(_ddlBeds),getddlValue(_ddlBaths),getddlValue(_ddlMinSqft),getddlValue(_ddlMaxSqft), getAreas(), getTxtValue(_tbStreetName), getTxtValue(_tbZipCode), _tbSearchNameRight.value, _pager.get_recordCount());       
        alert(_tbSearchNameRight.value + " saved.");
        return false;
    }
}


/**************************************   
 * WT Listing (Our Listing) Functions *
 **************************************/
 
// function gvList_RowDataBound(sender, e)
function gvList_RowDataBound(sender, e)
{
    var row = e.get_row();

    if (row.get_isDataRowType())
    {
        var prop = row.get_dataItem();
        var tr = row.get_container();
        
        // add id to each row, to be called by popup behavior
        tr.id = "tr_" + _trCount;
        var uid = _gridView.get_dataKeys()[e.get_row().get_rowIndex()];
        
        // add onclick event to each row
        tr.onclick=function onRowClicked() { 
            onShowDetails(uid);
            
            // Set a history point for back button functionality in update panel
            var val = uid;
            Sys.Application.get_history().addHistoryPoint({pageClientState: val}, "Property Details");};

        _trCount++;       

        //tr.onclick=function onRowClicked() { onShowDetails(uid)};
        _trCount++;
        
        // add address data
        var spnAddress = row.findControl('spnAddress');
        setText(spnAddress, prop.Address);
        
        // If the image is a cuff, highlight the row.
        if (prop.UID < 10000) {
            spnAddress.style.marginLeft = '17px';
            var img = row.findControl("imgExcl");
            img.style.display = 'block';
            img.style.marginTop = '6px';
            document.getElementById(tr.id).style.backgroundColor = '#cdecff';
        }
        
        // add price 
        var spnPrice = row.findControl('spnPrice');
        setPrice(spnPrice, formatCurrency(prop.ListPrice), prop.HidePrice);
        
        // image and holder inside gv
        var pnImg = row.findControl('pnImg');
        var imgList = row.findControl('imgList');
        
        // if the property is a cuff and the image isnt stored in the database, get it from the 
        // ListingPicts folder and add it to the holder. 
        // Else add image from dbase to holder and create popup behavior for each row
        onCreateHover(tr, pnImg); 
        if ((prop.UID < 10000) && (prop.PictureCount > 0) && (prop.LowResPicURL == null)) {
            var uidForImg = prop.UID;
            setImg(imgList, "http://williamstrew.com/images/ListingPicts/" + uidForImg + "-1.jpg");
        }
        else if (prop.LowResPicURL != null ) 
            setImg(imgList, prop.LowResPicURL);
        
        // clear for memory leaks
        tr = null;
    }
}

// function onCreateHover(row, pn)
// Helper method to create the hovermenu for each row
function onCreateHover(row, pn)
{
    _hoverCount++;
    $create(AjaxControlToolkit.HoverMenuBehavior, {"OffsetY":-270,"OffsetX":30,"HoverCssClass":"popupHover","PopDelay":0,"PopupPosition":2,"dynamicServicePath":"/ourlistings/Default.aspx","id":"hme_" + _hoverCount,"popupElement":document.getElementById(pn.id)}, null, null, document.getElementById(row.id));
}

// function loadCounters()
function loadCounters()
{    
    var pArray = new Array();
    
    wsListing.GetWTListingCount(
        function(pTypes)
        {
            for(var i=0;i<pTypes.length;i++)
            {
                pArray[i] = pTypes[i];
            }
            document.getElementById("spnRes").innerHTML = "(" + pArray[0] + ")"
            document.getElementById("spnMul").innerHTML = "(" + pArray[1] + ")"
            document.getElementById("spnLnd").innerHTML = "(" + pArray[2] + ")"
        }
    );
}

// function clientEvent()
// events from client - reset page to 1
function clientEvent()
{
    _pager.set_pageIndex(0);
    _pagerBottom.set_pageIndex(0); // NEW FOR PAGERBOTTOM
    loadProperties();
}


/********************************
 * Listing Search (Find a Home) *
 ********************************/

// function gvBasicList_RowDataBound(sender, e)
function gvBasicList_RowDataBound(sender, e)
{
    var row = e.get_row();

    if (row.get_isDataRowType())
    {
        var prop = row.get_dataItem();
        var tr = row.get_container();
        
        // Find the controls 
        var spnListPrice = row.findControl('spnListPrice');
        var spnStreetNum = row.findControl('spnStreetNum');
        var spnStreetName = row.findControl('spnStreetName');
        var spnCity = row.findControl('spnCity');
        var spnZipCode = row.findControl('spnZipCode');
        var spnBeds = row.findControl('spnBeds');
        var spnBathsTotal = row.findControl('spnBathsTotal');
        var spnSqftTotal = row.findControl('spnSqftTotal');
        var spnSubdivision = row.findControl('spnSubdivision');
        var imgList = row.findControl('imgList');
        var wtLogo = row.findControl('wtLogo');
        
        // Set the image, price, and text for all of the controls
        if ((prop.UID < 10000) && (prop.PictureCount > 0)) {
            var uidForImg = prop.UID;
            setListImg(imgList, "http://williamstrew.com/images/ListingPicts/" + uidForImg + "-1.jpg");
        }
        else if (prop.LowResPicURL != null ) 
            setListImg(imgList, prop.LowResPicURL);
            
        setPrice(spnListPrice, formatCurrency(prop.ListPrice), prop.HidePrice);
        setText(spnStreetNum, prop.StreetNum);
        setText(spnStreetName, prop.StreetName);
        setText(spnCity, prop.City);
        setText(spnZipCode, prop.ZipCode);
        setText(spnBeds, prop.Beds);
        setText(spnBathsTotal, prop.BathsTotal);
        setText(spnSqftTotal, prop.SqFtTotal);
        setLogo(wtLogo, prop.OfficeList);
        setText(spnSubdivision, prop.Subdivision);
        
        // add id to each row, to be called by popup behavior
        tr.id = "tr_" + _trCount;
        
        var prevClass;
        tr.onmouseover = function onMouseOver() { 
            prevClass=this.className;
            this.className = 'popupHover';
        };
        tr.onmouseout = function onMouseOut() { 
            this.className = prevClass;
        };
        
        var uid = _gridView.get_dataKeys()[e.get_row().get_rowIndex()];
        
        // add onclick event to each row
        tr.onclick = function onRowClicked() { 
            onShowDetails(uid);
            var val = uid;
            Sys.Application.get_history().addHistoryPoint({pageClientState: val}, "Property Details");
        };
        
        _trCount++;       
        
        // clear for memory leaks
        tr = null;
    }
}

// function onSelectFW()
// When the FW checkbox is checked, select all FW areas
function onSelectFW()
{
    // iterate all rows in ListBox (assuming only one column per row)
    var count = _areaList.getElementsByTagName("td").length;
    for (var x=0;x<count;x++)
    {
        rowElem = _areaList.getElementsByTagName("td")[x];
        // removes any selected rows
        if (Sys.UI.DomElement.containsCssClass(rowElem, "AreaList-row-select"))
        {
            Sys.UI.DomElement.removeCssClass(rowElem, "AreaList-row-select");
        }
        // Get FW_Area value
        var fwArea = rowElem.getElementsByTagName("input")[0];
        // if row is fw_area, select it
        if (fwArea.value == "True")
        {
            Sys.UI.DomElement.addCssClass(rowElem, "AreaList-row-select");
        }
    }   
}

// function onDeselectFW()
// When the FW chekcbox is unchecked, unselect all FW areas
function onDeselectFW()
{
    var count = _areaList.getElementsByTagName("td").length;
    for (var x=0;x<count;x++)
    {
        rowElem = _areaList.getElementsByTagName("td")[x];
        // removes any selected rows
        if (Sys.UI.DomElement.containsCssClass(rowElem, "AreaList-row-select"))
        {
            Sys.UI.DomElement.removeCssClass(rowElem, "AreaList-row-select");
        }
    }
}

// function onCheckFW()
// When the checkbox is clicked, determine if it is checked or unchecked
// If checked, call onSelectFW(), if unchecked, call onDeselectFW()
function onCheckFW()
{
    if (_chkFW.checked)
    {
        onSelectFW();
    }
    else
    {
        onDeselectFW();
    }
}

// function getPropertyType()
function getPropertyType()
{
    _pRes = null;
    _pMul = null;
    _pLnd = null;
    if (document.getElementById("chkRes").checked){_pRes="RES";}
    if (document.getElementById("chkMul").checked){_pMul="MUL";}
    if (document.getElementById("chkLnd").checked){_pLnd="LND";}
}

// function getTxtValue(tb)
// get txtbox values from street name and zip - if area search return null
function getTxtValue(tb)
{
    if (_searchType == 1)
    {
        return null;
    }
    else 
    {
        if(tb.value == '')
        {
            return null;
        }
        else
        {
            return tb.value;
        }
        
    }
}

// function getAreas()
// Gets AreaCodes from user Selected Areas in AreaList box 
function getAreas()
{
    if(_searchType == 1)
    {
        var count = _areaList.getElementsByTagName("td").length;
        var areaVals = "";
        for (var x=0;x<count;x++)
        {
            rowElem = _areaList.getElementsByTagName("td")[x];
            // selected row
            if (Sys.UI.DomElement.containsCssClass(rowElem, "AreaList-row-select"))
            {
                if (areaVals.length > 0)
                    areaVals += ",";
                var area = rowElem.getElementsByTagName("input")[1].value;
                areaVals += area;
            }        
        }
        return areaVals;
    }
    else
    {
        return null;
    }
}

// function getddlValue(ddl)
// Helper method to get the value of the ddl
function getddlValue(ddl)
{
    var val = parseInt(ddl.options[ddl.selectedIndex].value);
    if (val < 0)
    {
        return null;
    }
    else
    {
        return val;
    }
}

// function showArea()
// If the user wants to do an area search, show the area gv
function showArea()
{
    $get("btnArea").className='radFill';
    $get("btnStreet").className='radNoFill';
    $get('pnStreet').style.display='none';
    $get('pnArea').style.display='block';
    _searchType = 1;
}

// function showStreet()
// If the user wants to do a street/zip search, show the street/zip textboxes
function showStreet()
{
    $get("btnStreet").className='radFill';
    $get("btnArea").className='radNoFill';
    $get('pnStreet').style.display='block';
    $get('pnArea').style.display='none';
    _searchType = 2;
}


/*************************
 * User Search Functions *
 *************************/
 
// function onClickSearch(sender, args)
// Called when the user clicks search
// If the user is logged in, will check to see if the user has selected to save the search
function onClickSearch(sender, args)
{   
    _pager.set_pageIndex(0);
    _pagerBottom.set_pageIndex(0);
    
    // If the user is logged in
    if(Sys.Services.AuthenticationService.get_isLoggedIn())
    {
        // Set chkbx to true or false depending on if the save search checkbox is checked or not
        var chkbx = document.getElementById("ctl00_contentLeft_saveSearchChkBx").checked;
        
        // If the user wants to save, make sure they name the search
        if ((chkbx) && ((_tbSearchName.value == "") || (_tbSearchName.value == null))) {
            alert("Please give your search a name.");
            document.getElementById("ctl00_contentLeft_saveSearchChkBx").checked = false;
        } else {
            onSaveSearch();
            window.scrollTo(0,0);
            onHideDetails();
            loadProperties();
    
            var val = 1;     
            Sys.Application.get_history().addHistoryPoint({pageClientState: val}, "Williams Trew: Search");
        }
    } else {
        window.scrollTo(0,0);
        onHideDetails();
        loadProperties();
    
        var val = 1;     
        Sys.Application.get_history().addHistoryPoint({pageClientState: val}, "Williams Trew: Search");
    }   
}

// function loadSavedSearch()
// If the user is loading a search from their myWT page
function loadSavedSearch() {
    
    // Load the search name
    var tbSearchName = document.getElementById("ctl00_contentLeft_tbSearchName");
    var tbSearchNameRight = document.getElementById("ctl00_contentRight_searchNameRightTB");
    var search_Name = document.getElementById("ctl00_contentLeft_Repeater1_ctl00_rptrSearchNameLbl").innerHTML;
    tbSearchName.value = search_Name;
    tbSearchNameRight.value = search_Name;
    
    var tbStreetName;
    var tbZipCode;
    
    // If it is a street/zip search
    if (document.getElementById("ctl00_contentLeft_Repeater1_ctl00_rptrZipLbl").innerHTML != "") {
        // Set the _searchType to 2 - the street/zip seach type
        _searchType = 2;
        
        // Set the street/zip panel visibility to true
        $get('pnStreet').visible = true;
        
        // Load the street name
        tbStreetName = document.getElementById("ctl00_contentLeft_tbStreetName");
        tbStreetName.value = document.getElementById("ctl00_contentLeft_Repeater1_ctl00_rptrStNameLbl").innerHTML;
        
        // Load the zip code
        tbZipCode = document.getElementById("ctl00_contentLeft_tbZip");
        tbZipCode.value = document.getElementById("ctl00_contentLeft_Repeater1_ctl00_rptrZipLbl").innerHTML;
    } 
    // Else it is an area search
    else { 
        _searchType = 1; 
        
        // Load the search areas
        var areaList = document.getElementById("ctl00_contentLeft_gvAreaList");
        var lists = document.getElementById("ctl00_contentLeft_Repeater1_ctl00_rptrAreasLbl").innerHTML;
        var aList = new Array();
        var index = 0;
        
        // Traverse through lists and add the areas to the lList array
        for (var i = 0; i < lists.length; i++) {
            if (((lists.charAt(i) == 'D') || (lists.charAt(i) == 'd')) && (lists.charAt(i + 1) == '>') && ((i + 2) < lists.length)) {
                if (lists.charAt(i + 2) != '<') {
                    var newArea = lists.substring(i + 2);
                    for (var j = 0; j < newArea.length; j++) { 
                        if (newArea.charAt(j) == '<') {
                            newArea = newArea.substring(0, j);
                            break;
                        }
                    }
                    i += 2;
                    aList[index] = newArea;
                    index++;
                }
            }
        }
        
        // Compare the area codes in aList to the ones in the table, 
        // if a match, then call Sys.UI.DomElement.containsCssClass(rowElem, "AreaList-row-select")
        var count = areaList.getElementsByTagName("td").length;
        for (var x = 0; x < count; x++) {
            rowElem = areaList.getElementsByTagName("td")[x];
            for (var y = 0; y < aList.length; y++) {
                // if it is Arlington with all of those area codes
                if (rowElem.getElementsByTagName("input")[1].value.substring(0,2) == "90") {
                    if (aList[y] == "90") {
                        rowElem.className = "AreaList-row-select";
                        break;
                    }
                }
                else if (rowElem.getElementsByTagName("input")[1].value == aList[y]) {
                    rowElem.className = "AreaList-row-select";
                    break;
                }
            }
        }
    }// End Else
    
    // Load the drop down list for minpPrice 
    var ddlMinPrice = document.getElementById("ctl00_contentLeft_ddlPriceMin");
    var minPrice = document.getElementById("ctl00_contentLeft_Repeater1_ctl00_rptrMinPriceLbl").innerHTML;
    if (minPrice != "" ) {
        if ((minPrice >= 5000) && (minPrice <= 750000)) {
            minPrice = minPrice / 1000;
            minPrice = "$" + minPrice + "K";
        }
        else if (minPrice >= 1000000) {
            minPrice = minPrice / 1000000;
            minPrice = "$" + minPrice + "M";
        }
        
        // Match the value of minPrice to the correct value in the ddl
        for (var i = 0; i < 20; i++) {
            if (minPrice == ddlMinPrice[i].text) {
                ddlMinPrice[i].selected = "true";
                break;
            }
        }
    }
    
    // Load the drop down list for maxPrice
    var ddlMaxPrice = document.getElementById("ctl00_contentLeft_ddlPriceMax");
    var maxPrice = document.getElementById("ctl00_contentLeft_Repeater1_ctl00_rptrMaxPriceLbl").innerHTML;
    if (maxPrice != "") {
        if ((maxPrice >= 5000) && (maxPrice <= 750000)) {
            maxPrice = maxPrice / 1000;
            maxPrice = "$" + maxPrice + "K";
        }
        else if (maxPrice >= 1000000) {
            maxPrice = maxPrice / 1000000;
            maxPrice = "$" + maxPrice + "M";
        }
        
        // Match the value of the maxPrice to the correct value in the ddl
        for (var i = 0; i < 20; i++) {
            if (maxPrice == ddlMaxPrice[i].text) {
                ddlMaxPrice[i].selected = "true";
                break;
            }
        }
    }
       
    // Load the drop down list for minSqft
    var ddlMinSqft = document.getElementById("ctl00_contentLeft_ddlSqftMin");
    var minSqft = document.getElementById("ctl00_contentLeft_Repeater1_ctl00_rptrMinSqftLbl").innerHTML;
    if (minSqft != "") {
        minSqft = minSqft / 1000;
        minSqft = minSqft + ",000";
        
        // Match the value of the minSqft to the correct value in the ddl
        for (var i = 0; i < 10; i++) {
            if (minSqft == ddlMinSqft[i].text) {
                ddlMinSqft[i].selected = "true";
                break;
            }
        }
    }
    
    // Load the drop down list for maxSqft
    var ddlMaxSqft = document.getElementById("ctl00_contentLeft_ddlSqftMax");
    var maxSqft = document.getElementById("ctl00_contentLeft_Repeater1_ctl00_rptrMaxSqftLbl").innerHTML;
    if (maxSqft != "") {
        maxSqft = maxSqft / 1000;
        maxSqft = maxSqft + ",000";
        
        // Match the value of the maxSqft to the correct value in the ddl
        for (var i = 0; i < 10; i++) {
            if (maxSqft == ddlMaxSqft[i].text) {
                ddlMaxSqft[i].selected = "true";
                break;
            }
        }
    }    
    
    // Load the number of beds into the ddl
    var ddlBeds = document.getElementById("ctl00_contentLeft_ddlBeds");
    var numBeds = document.getElementById("ctl00_contentLeft_Repeater1_ctl00_rptrBedsLbl").innerHTML;
    if (numBeds != "") {
        numBeds = numBeds + "+";
        
        // Match the value of numBeds to the correct value in the ddl
        for (var i = 0; i < 6; i++) {
            if (numBeds == ddlBeds[i].text) {
                ddlBeds[i].selected = "true";
                break;
            }
        }
    }
    
    // Load the numaber of baths into the ddl
    var ddlBaths = document.getElementById("ctl00_contentLeft_ddlBaths");
    var numBaths = document.getElementById("ctl00_contentLeft_Repeater1_ctl00_rptrBathsLbl").innerHTML;
    if (numBaths != "") {
        numBaths = numBaths + "+";
        
        // Match the value of numBaths to the correct value in the ddl
        for (var i = 0; i < 6; i++) {
            if (numBaths == ddlBaths[i].text) {
                ddlBaths[i].selected = "true";
                break;
            }
        }
    }
    
    // Call loadProperties() to load the properties onto the page.
    loadProperties();
    
    // Add client state to save history point for back button functionality
    var val = 1;     
    Sys.Application.get_history().addHistoryPoint({pageClientState: val}, "Williams Trew: Search");
}











          