﻿var isCCS, isIE6, isNN7;

var oNewsText            = null;
var iNewsTextWidth       = 0;
var iCurrentNewsTextLeft = 550;
var iNewsBannerWidth     = 550;

// Watch Dog
var hWatchDog            = null;
var bWatchDogStarted     = false;

// Zillow
var iCurrentSelectedZestCompRow = 0;
var sCurrentZpid                = '';

//****************************************************************************
// Method to determine the type of browser
function initDHTMLAPI()
{
  if (document.images)
  {
    isCCS = (document.body && document.body.style) ? true : false;
    isIE6 = (isCCS && document.all) ? true : false;
    isNN7 = (isIE6) ? false : true;
  }
}

//*****************************************************************************
// When the watchdog thread times out we need to reset everything
function WatchDog()
{
  hWatchDog = null;
  FinishAjaxCall();
}

//*****************************************************************************
// Provides the current state of the application
function IsWaitState()
{
  return bWatchDogStarted;
}

//*****************************************************************************
// Called to change the cursor on the form
function SetCursor(sCursor)
{
  try
  {
    if (document.getElementById('RunReport') != null)
      document.getElementById('RunReport').style.cursor = sCursor;
  }
  
  catch (e)
  {
  }
}

//*****************************************************************************
// Called when a ajax call is made
function StartAjaxCall()
{
  var bStart = false;
  
  try
  {
    if (bWatchDogStarted == false)
    {
      bWatchDogStarted = true;
      
      // Show the wait message
      document.getElementById('ProcessingMessageImage').innerHTML = '<img src="Images/LoadingNewRotateSmall.gif" alt="Loading Data" />';
      document.getElementById('ProcessingMessage').style.display = '';
      
      // Change everything to the wait cursor
      SetCursor('wait');
      
      // Start the watchdog thread for 15 seconds
      hWatchDog = setTimeout("WatchDog()", 15000);
      
      // Flag that we started
      bStart = true;
    }
  }
  
  catch (e)
  {
  }
  
  return bStart;
}

//*****************************************************************************
// Called when a ajax call is finished
function FinishAjaxCall()
{
  try
  {
    // Reset the watchdog flag
    bWatchDogStarted = false;
    
    // Stop the watchdog
    if (hWatchDog != null)
    {
      clearTimeout(hWatchDog);
      hWatchDog = null;
    }
    
    // Reset the cursor
    SetCursor('pointer');
    
    // Hide the wait message
    document.getElementById('ProcessingMessageImage').innerHTML = '';
    document.getElementById('ProcessingMessage').style.display  = 'none';
  }
  
  catch (e)
  {
  }
}

//****************************************************************************
// Called to get the zillow results
function ZillowSearchResults()
{
  try
  {
    var sAddress = document.getElementById('Address').value;
    var sZipcode = document.getElementById('Zipcode').value;
        
    if ((sAddress.length > 0) && (sZipcode.length > 0))
    {
      if (StartAjaxCall())
      {
        // Show the splash screen
        document.getElementById('ZillowSplash').style.display = '';
        document.getElementById('ZillowData').style.display   = 'none';
        document.getElementById('ZillowSplashMessage').innerHTML = 'Looking Up Zillow Records...';
      
        Homekeys.HomeValuations.ZillowInformation(sAddress, sZipcode, document.location.href, ZillowSearchResults_CallBack);
      }
    }
    else
      alert('Please enter an Address and Zipcode');
  }
  
  catch (e)
  {
  }
}

//*****************************************************************************
// Called to get zillow information
function ZillowSearchResults_CallBack(sResponse)
{
  sCurrentZpid = '';
  
  try
  {
    bNeedNewZestimate   = false;
    bNeedNewZestCompMap = true;
    
    if ((sResponse.value != null) && (sResponse.value.Rows.length > 0))
    {
      var oListing = sResponse.value.Rows[0];
      
      // Save the Zpid
      sCurrentZpid = oListing.Zpid;
      
      // Zestimate
      document.getElementById('Zestimate').innerHTML = '<span class="utxtnavzillowblue"><a href="' + oListing.HomeDetailLink + '" target="_blank">' + oListing.Zestimate + '</a></span>';
      document.getElementById('ZestimateValueRange').innerHTML  = oListing.ValuationRangeLow + '&nbsp;&nbsp;-&nbsp;&nbsp;' + oListing.ValuationRangeHigh;
      document.getElementById('ZestimateLastUpdated').innerHTML = oListing.ZestimateLastUpdated;
      
      // Charts
      document.getElementById('ZillowChart').src         = oListing.ChartUrl;
      document.getElementById('ZillowRegionChart').src   = oListing.RegionChartUrl;
      
      // Property details
      document.getElementById('ZillowAddress').innerHTML       = oListing.Address;
      document.getElementById('ZillowCityStateZip').innerHTML  = oListing.City + ', ' + oListing.State + ' ' + oListing.Zipcode;
      document.getElementById('ZillowPropertyType').innerHTML  = oListing.PropertyType;
      document.getElementById('ZillowYearBuilt').innerHTML     = oListing.YearBuilt;
      document.getElementById('ZillowLotSize').innerHTML       = oListing.LotSqFt;
      document.getElementById('ZillowBldgSize').innerHTML      = oListing.BldgSqFt;
      document.getElementById('ZillowBeds').innerHTML          = oListing.Beds;
      document.getElementById('ZillowBaths').innerHTML         = oListing.Baths;
      document.getElementById('ZillowLastSoldDate').innerHTML  = oListing.LastSoldDate;
      document.getElementById('ZillowLastSoldPrice').innerHTML = oListing.LastSoldDate;
      
      // Links
      document.getElementById('ZillowHomeDetailLink').href = oListing.HomeDetailLink;
      document.getElementById('ZillowChartDataLink').href  = oListing.ChartDataLink;
    }
    else
    {
      document.getElementById('Zestimate').innerHTML           = '';
      document.getElementById('ZestimateValueRange').innerHTML = '';
      document.getElementById('ZillowChart').src               = '';
      document.getElementById('ZillowRegionChart').src         = '';
      document.getElementById('ZillowAddress').innerHTML       = '';
      document.getElementById('ZillowCityStateZip').innerHTML  = '';
      document.getElementById('ZillowPropertyType').innerHTML  = '';
      document.getElementById('ZillowYearBuilt').innerHTML     = '';
      document.getElementById('ZillowLotSize').innerHTML       = '';
      document.getElementById('ZillowBldgSize').innerHTML      = '';
      document.getElementById('ZillowBeds').innerHTML          = '';
      document.getElementById('ZillowBaths').innerHTML         = '';
      document.getElementById('ZillowLastSoldDate').innerHTML  = '';
      document.getElementById('ZillowLastSoldPrice').innerHTML = '';
      document.getElementById('ZillowHomeDetailLink').href     = '';
      document.getElementById('ZillowChartDataLink').href      = '';
      
      document.getElementById('ZillowSplashMessage').innerHTML = 'No Zillow Records Found!';
    }
  }
  
  catch (e)
  {
    document.getElementById('ZillowSplashMessage').innerHTML = 'Error Occurred Retrieving Zillow Records!';
  }
  
  FinishAjaxCall();
  
  // Now get the comparables
  if (sCurrentZpid.length > 0)
  {
    ZillowComparables(sCurrentZpid);
  }
  else
  {
    if (sResponse.value.Rows.length > 0)
    {
      // Show the data screen
      document.getElementById('ZillowSplash').style.display = 'none';
      document.getElementById('ZillowData').style.display   = '';
      document.getElementById('ZillowSplashMessage').innerHTML = '';
    }
  }
}

//*****************************************************************************
// Called to show the zillow comparables
function ZillowComparables(sZpid)
{
  try
  {
    if (StartAjaxCall())
    {
      // Capture the comparables
      Homekeys.HomeValuations.ZillowComparables(sZpid, document.location.href, ZillowComparables_CallBack);
    }
  }
  
  catch (e)
  {
    FinishAjaxCall();
    
    document.getElementById('ZillowSplashMessage').innerHTML = 'Error Occurred Retrieving Zillow Records!';
  }
}

//*****************************************************************************
// Called to show the zillow comparables
function OnZillowComparablesClick(evt)
{
  try
  {
    var oCell = null;
    var oRow  = null;
    
    // Find the parent row
    if (isIE6)
    {
      oCell = evt.srcElement;
      if (oCell.tagName == 'SPAN')
        oCell = oCell.parentElement;
        
      oRow  = evt.srcElement;
      while ((oRow != null) && (oRow.tagName != 'TR'))
        oRow = oRow.parentElement;
    }
    else
    {
      oCell = evt.target;
      if (oCell.tagName == 'SPAN')
        oCell = oCell.parentNode;
        
      oRow  = evt.target;
      while ((oRow != null) && (oRow.tagName != 'TR'))
        oRow = oRow.parentNode;
    }
    
    if (oRow.rowIndex == 0)
    {
      // We clicked the header row
      
      if (StartAjaxCall())  
      {
        // Capture the sorting information
        var sSortBy   = oCell.getAttribute('SortBy');
        var sColIndex = oCell.getAttribute('ColIndex');
        
        // Capture the current sorting information
        var oTable = document.getElementById('ZillowComparables');
        var sCurrentSortOrder = oTable.getAttribute('SortOrder');
        var sCurrentSortCol   = oTable.getAttribute('SortCol');
        var sCurrentSortIndex = oTable.getAttribute('SortIndex');
        
        // Determine the new direction
        if (sSortBy == sCurrentSortCol)
        {
          if (sCurrentSortOrder == 'DESC')
            sCurrentSortOrder = 'ASC';
          else
            sCurrentSortOrder = 'DESC';
        }
        else
          sCurrentSortOrder = 'ASC';
          
        // UnLabel the sorted field
        var iSortIndex = parseInt(sCurrentSortIndex);
        oTable.rows[0].cells[iSortIndex].innerHTML = oTable.rows[0].cells[iSortIndex].getAttribute('Label');
        
        // Save the new sorting values
        oTable.setAttribute('SortOrder', sCurrentSortOrder);
        oTable.setAttribute('SortCol', sSortBy);
        oTable.setAttribute('SortIndex', sColIndex);
               
        // Sort the comparables
        Homekeys.HomeValuations.ZillowComparablesSort(sSortBy, sCurrentSortOrder, ZillowComparables_CallBack);
      }
      else
        FinishAjaxCall();
    }
    else
    {
      // Interact with the map
      ShowZestCompOnMap(oRow);
    }
  }
  
  catch (e)
  {
    FinishAjaxCall();
  }
}

//*****************************************************************************
// Called to get zillow comparables
function ZillowComparables_CallBack(sResponse)
{
  try
  {
    // Show the data screen
    document.getElementById('ZillowSplash').style.display = 'none';
    document.getElementById('ZillowData').style.display   = '';
    document.getElementById('ZillowSplashMessage').innerHTML = '';
    
    if ((sResponse.value != null) && (sResponse.value.Rows.length > 0))
    {
      // Load the comparables
      LoadZillowComparables(sResponse.value);
      
      // Map the comparables
      //OnMapZestComps();
    }
  }
  
  catch (e)
  {
    document.getElementById('ZillowSplash').style.display = '';
    document.getElementById('ZillowData').style.display   = 'none';
    document.getElementById('ZillowSplashMessage').innerHTML = 'Error Occurred Retrieving Zillow Records!';
  }
  
  FinishAjaxCall();
}

//*****************************************************************************
// Called to load the comparables
function LoadZillowComparables(pComparablesTable)
{
  try
  {
    // Capture the table to show the comps
    var oTable = document.getElementById('ZillowComparables');
    
    // Remove all the data rows
    var iLength = oTable.rows.length - 1;
    for (iRow = 0; iRow < iLength; ++iRow)
      oTable.deleteRow(1);
      
    // Set the sort marker
    var sArrow = '<span style="font-size: 8pt">&#9650;</span>';
    if (oTable.getAttribute('SortOrder') == 'ASC')
      sArrow = '<span style="font-size: 8pt">&#9660;</span>';
    
    // Label the sorted field
    var iSortIndex = parseInt(oTable.getAttribute('SortIndex'));
    oTable.rows[0].cells[iSortIndex].innerHTML = oTable.rows[0].cells[iSortIndex].getAttribute('Label') + sArrow;
    
    // Reset the selected comp row
    iCurrentSelectedZestCompRow = 0;
    
    // Add the new comps
    for (iRow = 0; iRow < pComparablesTable.Rows.length; ++iRow)
    {
      var oRow = oTable.insertRow(oTable.rows.length);
      
      if (isIE6 == true)
      {
        if ((iRow % 2) == 0)
          oRow.attributes['class'].value = 'resultrowzillow';
        else 
          oRow.attributes['class'].value = 'alternateresultrowzillow';
      }
      else
      {
        if ((iRow % 2) == 0)
          oRow.setAttribute('class', 'resultrowzillow');
        else 
          oRow.setAttribute('class', 'alternateresultrowzillow');
      }
      
      var oCell = oRow.insertCell(0);
      oCell.innerHTML = pComparablesTable.Rows[iRow].Latitude;
      oCell.style.display = 'none';
      
      var oCell = oRow.insertCell(1);
      oCell.innerHTML = pComparablesTable.Rows[iRow].Longitude;
      oCell.style.display = 'none';
      
      var oCell = oRow.insertCell(2);
      oCell.innerHTML = pComparablesTable.Rows[iRow].Compscore;
      
      var oCell = oRow.insertCell(3);
      oCell.innerHTML = pComparablesTable.Rows[iRow].Address;
      
      var oCell = oRow.insertCell(4);
      oCell.innerHTML = pComparablesTable.Rows[iRow].City;
      
      var oCell = oRow.insertCell(5);
      oCell.innerHTML = pComparablesTable.Rows[iRow].Zipcode;
      
      var oCell = oRow.insertCell(6);
      oCell.innerHTML = pComparablesTable.Rows[iRow].YearBuilt;
      
      var oCell = oRow.insertCell(7);
      oCell.innerHTML = pComparablesTable.Rows[iRow].LotSqFt;
      
      var oCell = oRow.insertCell(8);
      oCell.innerHTML = pComparablesTable.Rows[iRow].BldgSqFt;
      
      var oCell = oRow.insertCell(9);
      oCell.innerHTML = pComparablesTable.Rows[iRow].Baths;
      
      var oCell = oRow.insertCell(10);
      oCell.innerHTML = pComparablesTable.Rows[iRow].Beds;
      
      var oCell = oRow.insertCell(11);
      oCell.innerHTML = pComparablesTable.Rows[iRow].LastSoldPrice;
      
      var oCell = oRow.insertCell(12);
      oCell.innerHTML = '<span class="utxtnavzillowgrid"><a href="' + pComparablesTable.Rows[iRow].HomeDetailLink + '" target="_blank">' + pComparablesTable.Rows[iRow].Zestimate.toString() + '</a></span>';
    }
  }
  
  catch (e)
  {
  }
}

//*****************************************************************************
// Called to show a different duration
function OnHistoricalChart(sDuration)
{
  try
  {
    // Call the server for new chart
    if (StartAjaxCall())
      Homekeys.HomeValuations.HistoricalChart(sCurrentZpid, sDuration, document.location.href, OnHistoricalChart_CallBack);
  }
  
  catch (e)
  {
    FinishAjaxCall();
  }
}

//*****************************************************************************
// Called to show the new chart
function OnHistoricalChart_CallBack(sResponse)
{
  try
  {
    if ((sResponse.value != null) && (sResponse.value.length > 0))
    {
      document.getElementById('ZillowChart1year').style.fontWeight   = '';
      document.getElementById('ZillowChart5years').style.fontWeight  = '';
      document.getElementById('ZillowChart10years').style.fontWeight = '';
      
      var sParts = sResponse.value.split('~');
      document.getElementById('ZillowChart').src = sParts[1];
      document.getElementById('ZillowChart' + sParts[0]).style.fontWeight = 'bold';
    }
  }
  
  catch (e)
  {
  }
  
  FinishAjaxCall();
}

//*****************************************************************************
// Called to show a different duration
function OnHistoricalRegionChart(sDuration)
{
  try
  {
    // Call the server for new chart
    if (StartAjaxCall())
      Homekeys.HomeValuations.HistoricalRegionChart(sCurrentZpid, sDuration, document.location.href, OnHistoricalRegionChart_CallBack);
  }
  
  catch (e)
  {
    FinishAjaxCall();
  }
}

//*****************************************************************************
// Called to show the new chart
function OnHistoricalRegionChart_CallBack(sResponse)
{
  try
  {
    if ((sResponse.value != null) && (sResponse.value.length > 0))
    {
      document.getElementById('ZillowRegionChart1year').style.fontWeight   = '';
      document.getElementById('ZillowRegionChart5years').style.fontWeight  = '';
      document.getElementById('ZillowRegionChart10years').style.fontWeight = '';
      
      var sParts = sResponse.value.split('~');
      document.getElementById('ZillowRegionChart').src = sParts[1];
      document.getElementById('ZillowRegionChart' + sParts[0]).style.fontWeight = 'bold';
    }
  }
  
  catch (e)
  {
  }
  
  FinishAjaxCall();
}

//*****************************************************************************
// Called to animate the search header
function SearchMouseOverZillow(oCell)
{
  oCell.attributes['class'].value = 'text10boldzillowwhite';
}

//*****************************************************************************
// Called to animate the search header
function SearchMouseOutZillow(oCell)
{
  oCell.attributes['class'].value = 'text10boldzillowdarkblue';
}

//*****************************************************************************
// Called when a key stroke is press in the specified text box
function ValidateKeyPress(evt, oTextBox, sType, iLength)
{
  var sCode = (isIE6 == true) ? evt.keyCode : evt.charCode;
  
  // Get the key that was pressed
  var sChar = String.fromCharCode(sCode);
  
  if ((typeof(sType) == 'undefined') || (sType == 'Numeric'))
  {
    // If this is not a number do not allow it
    if (isNaN(parseInt(sChar)) == true)
      if (isIE6 == true) evt.returnValue = false; else { if (sCode != '0') evt.preventDefault(); }
  }
  else if (sType == 'Currency')
  {
    // If this is not a number and not a '.'
    if ((isNaN(parseInt(sChar)) == true) && (sChar != '.'))
      if (isIE6 == true) evt.returnValue = false; else { if (sCode != '0') evt.preventDefault(); }
  }
  else if (sType == 'Date')
  {
    // If this is not a number and not a '/'
    if ((isNaN(parseInt(sChar)) == true) && (sChar != '/'))
      if (isIE6 == true) evt.returnValue = false; else { if (sCode != '0') evt.preventDefault(); }
  }
  else if (sType == 'Phone')
  {
    // If this is not a number and not a '( ) or space'
    if ((isNaN(parseInt(sChar)) == true) && (sChar != '(') && (sChar != ')') && (sChar != ' ') && (sChar != '-'))
      if (isIE6 == true) evt.returnValue = false; else { if (sCode != '0') evt.preventDefault(); }
  }
  else if (sType == 'CurrencyNeg')
  {
    // If this is not a number and not a '.'
    if ((isNaN(parseInt(sChar)) == true) && (sChar != '.') && (sChar != '-'))
      if (isIE6 == true) evt.returnValue = false; else { if (sCode != '0') evt.preventDefault(); }
  }
  else if (sType == 'SingleDecimal')
  {
    var RxPattern = /^\d+\.{0,1}(\d{1})?$/;
    if (oTextBox.value.length > 0)
    {
      // Create Regular expression object
      var oRegEx = new RegExp(RxPattern);
      oRegEx.Global = true

      // Test input field with regular expression
      var result = oRegEx.exec(oTextBox.value + sChar);
      if (result == null)
        if (isIE6 == true) evt.returnValue = false; else { if (sCode != '0') evt.preventDefault(); }
    }
  }
 
  if (typeof(iLength) != 'undefined')
  {
    if (document.selection.type == 'None')
      if (oTextBox.value.length >= iLength)
        if (isIE6 == true) evt.returnValue = false; else { if (sCode != '0') evt.preventDefault(); }
  }
}