// setup dropdown variables for convenience
var prefix = "ctl00_cphMain_";
var ddResultsPerPage = prefix + "ddResultsPerPage";
var map = null;
var pageIndex = 0;
var totalPages = 0;
var totalCount = 0;
var resultsPerPage = 100;
var fullResults = new Array();
var SortOrder = "CondominiumName";
var SortDir = "asc";
var SortImg = "arrowup";
var First = true;
var mapID;
var view = "map";

// map bounds
var nwLat = 0, nwLng = 0, seLat = 0, seLng  = 0;
// page dimensions
var PageHeight = 0;
var PageWidth = 0;

// call load function
if( typeof window.onload != 'function')
{
  window.onload = Load;
}
else
{
  window.onload = function(){ Load(); };
}

SetOnResize();

function UpdatePageDimensions()
{
    PageHeight = document.documentElement.clientHeight;
    PageWidth = document.documentElement.clientWidth;
}
//
// load function
//
function Load()
{
    ResizeMap();
    //SetView();
    LoadMap();
    SetupLoadingMessage()
    UpdatePageDimensions();
}
// set up for loading message
function SetupLoadingMessage()
{
    var _loading = document.getElementById("loading");
    var _map = document.getElementById("map");
    var topOffset = 359;
    var leftOffset = 179 + ((PageWidth - 179)/2)-100;
    _loading.style.top = topOffset + "px";
    _loading.style.left = leftOffset + "px";
}
//
// Load Map
//
function LoadMap()
{   
    try
    {
        var defaultLocation = new VELatLong(43.05584433592095,-88.08013916015625);
        var defaultZoom = 9;
        var defaultStyle = 'r';
        
        map = new VEMap('map');
        map.LoadMap(defaultLocation,defaultZoom,defaultStyle,false,VEMapMode.Mode2D,false,EliteProp.MapService.ClientSearch(ApplyBounds));
    }
    catch(err)
    { 
        //alert(err.message);
    }
    if( map )
    {
        map.HideDashboard();
    }
}
//
// resize map object
//
function ResizeMap()
{
    var oldHeight = PageHeight;
    var oldWidth = PageWidth;
    SetupLoadingMessage();
    UpdatePageDimensions();
    if( !(oldHeight == PageHeight && oldWidth == PageWidth) )
    {
        // get full height / width
        var mapheight = 380;
        // left panel = 177px
        var mapwidth = document.documentElement.clientWidth - 177 - 14;

        if( view == "map" && map )
        {
            map.Resize(mapwidth, mapheight);
        }
        else
        {
            document.getElementById("map").style.height = mapheight;
            document.getElementById("map").style.width = mapwidth;
        }
    }
}

// sort results by the given column
function SortResults(sortCol)
{
    // if clicked option is already sorted, reverse sort
    if( sortCol == SortOrder && !First )
    {
        fullResults.reverse();
        if( SortDir == "asc" )
        {
          SortDir = "desc";
          SortImg = "arrowdown";
        }
        else
        {
          SortDir = "asc";
          SortImg = "arrowup";
        }
    }
    else
    {   
        First = false;
        // update SortOrder
        SortOrder = sortCol;
        SortDir = "asc";
        SortImg = "arrowup";
        
        if( sortCol == "City")
        {
            fullResults.sort(SortByCity);
        }
        else if( sortCol == "State")
        {
            fullResults.sort(SortByState);
        }
        else
        {
            // default sorting is by CondominiumName
            fullResults.sort(SortByCondominiumName);
        }
    }

    GetResultsTable(fullResults);
}

//
// display loading message
//
function ShowLoadingMessage(message)
{
    //document.getElementById("Message").style.display = "none";
    document.getElementById("loading").style.display = "block";
    document.getElementById("loadingMessage").innerHTML = message;
}

function SetTotalCount(count)
{
    totalCount = count;
}

// load search results to map/list
function onSearchComplete(results)
{
    fullResults = results;
    // sort results properly
    SortResults(SortOrder);
    //GetResultsTable(fullResults);
    if( view == "map" )
    {
        // plot points on map
        PlotPoints(results);
    }
    document.getElementById("loading").style.display = "none";
}

// get search results list table
function GetResultsTable(results)
{
    var count = results.length;
    var resultsDiv = document.getElementById("resultsDiv");

    if( count > 0 )
    {
        // table/header open tags
        var tableHtml = "<table cellpadding=\"0\" cellspacing=\"0\" border=\"0\" id=\"resultsTable\"><tr class=\"detailHeader\">";

        tableHtml += "<td class=\"condominiumNameHdr\"><span><a href=\"javascript:SortResults('CondominiumName')\">Condominium Name";
        if( SortOrder == "CondominiumName" )
        {
          tableHtml += "&nbsp;<img src=\"Images/" + SortImg + ".gif\" class=\"sortimg\" alt=\"\" />";
        }
        tableHtml += "</a></span></td>";

        tableHtml += "<td class=\"cityHdr\"><span><a href=\"javascript:SortResults('City')\">City";
        if( SortOrder == "City" )
        {
          tableHtml += "&nbsp;<img src=\"Images/" + SortImg + ".gif\" class=\"sortimg\" alt=\"\" />";
        }
        tableHtml += "</a></span></td>";

        tableHtml += "<td class=\"stateHdr\"><span><a href=\"javascript:SortResults('State')\">State";
        if( SortOrder == "State" )
        {
          tableHtml += "&nbsp;<img src=\"Images/" + SortImg + ".gif\" class=\"sortimg\" alt=\"\" />";
        }
        tableHtml += "</a></span></td>";
        // close header row
        tableHtml += "</tr><tbody class=\"resultsTBody\">";

        // bind search results
        for( var c=0; c<count && c<resultsPerPage;c++)
        {
            var className = "resultsRow";
            if( (c % 2) == 0 )
            {
                className = "resultsRow";
                tableHtml += "<tr class=\"resultsRow\" ";
            }
            else
            {
                className = "altDetailRow";
                tableHtml += "<tr class=\"altDetailRow\" ";
            }
            
            // add mouseover/mouseout/mousedown functionality if in mapview
            if( view == "map" )
            {
                tableHtml += "onmouseout='VEPushpin.Hide(); this.className=\"" + className + "\";' onmousedown='VEPushpin.Hide(true);' ";
                tableHtml += "onmouseover='this.className=\"hoverrow\"; VEPushpin.Show(\"" 
                          + mapID + "\",\"" 
                          + results[c].ClientID + "\",\"" 
                          + results[c].Latitude + "\",\"" 
                          + results[c].Longitude + "\", \"" 
                          + "" + "\", \"" 
                          + escape(GetHTML(results[c].CondominiumName)) 
                          + "\",\"VE_Pushpin_Popup_Title\",\"VE_Pushpin_Popup_Body\");'";
            }
            else
            {
                tableHtml += "onmouseout='this.className=\"" + className + "\";' onmouseover='this.className=\"hoverrow\";'";
            }
            tableHtml += ">";            
            
            // property details
            tableHtml += "<td class=\"condominiumNameCol\"><span class=\"address\">" + results[c].CondominiumName + "</span></td>";
            tableHtml += "<td class=\"cityCol\">" + results[c].City + "</td>";
            tableHtml += "<td class=\"stateCol\">" + results[c].State + "</td>";
            tableHtml += "</tr>";
        }
        
        // close table
        tableHtml += "</tbody></table>";        
        // set HTML and display
        resultsDiv.innerHTML = tableHtml;
        resultsDiv.style.display = "block";
    }
    else
    {
        resultsDiv.style.display = "none";
    }
}

function GetHTML(condominiumName)
{
    var html = "<table cellspacing=\"2\" cellpadding=\"0\" class=\"clientpopuptable\" border=\"0\"><tr><td valign=\"top\" class=\"address\">";
    
    html += condominiumName;
    html += "</td></tr></table>";
 
     return html;
}

//
// plot search results on map
//
function PlotPoints(results)
{
    var icon = 'Images/house.gif';
    
    for ( var pinID = 0; pinID < results.length; pinID++ )
    {
        if( !document.getElementById(results[pinID].ListingID) )
        {
            try
            {
                var pin = new VEPushpin(
                    results[pinID].ClientID,
                    new VELatLong(results[pinID].Latitude,results[pinID].Longitude),
                    icon,
                    null,
                    GetHTML(results[pinID].CondominiumName));
                
                  map.AddPushpin(pin);
            }
            catch(err)
            {
                //alert(err.message);
            }
        }
    }
}

//
// SORT FUNCTIONS
//
function SortByCondominiumName(a,b)
{
    if( a.CondominiumName < b.CondominiumName ) return -1;
    if( a.CondominiumName > b.CondominiumName ) return 1;
    return 0;
}

function SortByCity(a,b)
{
    if( a.City < b.City ) return -1;
    if( a.City > b.City ) return 1;
    return 0;
}

function SortByState(a,b)
{
    if( a.State < b.State ) return -1;
    if( a.State > b.State ) return 1;
    return 0;
}

//
// open map help window
//
function MapHelp() 
{
    window.open('Map_Help.htm','Help','width=420,height=600,resizable=yes,scrollbars=yes');
}

//
// check if two arrays are equal
//
function areArraysEqual(array1, array2) {
   var temp = new Array();
   if ( (!array1[0]) || (!array2[0]) ) { // If either is not an array
      return false;
   }
   if (array1.length != array2.length) {
      return false;
   }
   // Put all the elements from array1 into a "tagged" array
   for (var i=0; i<array1.length; i++) {
      key = (typeof array1[i]) + "~" + array1[i];
   // Use "typeof" so a number 1 isn't equal to a string "1".
      if (temp[key]) { temp[key]++; } else { temp[key] = 1; }
   // temp[key] = # of occurrences of the value (so an element could appear multiple times)
   }
   // Go through array2 - if same tag missing in "tagged" array, not equal
   for (var i=0; i<array2.length; i++) {
      key = (typeof array2[i]) + "~" + array2[i];
      if (temp[key]) {
         if (temp[key] == 0) { return false; } else { temp[key]--; }
      // Subtract to keep track of # of appearances in array2
      } else { // Key didn't appear in array1, arrays are not equal.
         return false;
      }
   }
   // If we get to this point, then every generated key in array1 showed up the exact same
   // number of times in array2, so the arrays are equal.
   return true;
}

//
// OVERRIDDEN GETCONTENT FUNCTION
//
VEPushpin.prototype.GetContent= function()
{
    var pinId=this.ID+"_"+this.m_vemap.GUID;
    mapID = this.m_vemap.GUID;
    var content="<img class='"+this.IconStyle+"' src='"+this.Iconurl+"' id='"+pinId+"' ";

    var isTitleValid=this.Title!=null&&this.Title!="undefined"&&this.Title.length>0;

    var isDetailsValid=this.Details!=null&&this.Details!="undefined"&&this.Details.length>0;

    if(isTitleValid||isDetailsValid)
    {
        content+=" onmouseout='VEPushpin.Hide();' onmouseover='VEPushpin.Show(\""
          +this.m_vemap.GUID
          +"\",\""
          +this.ID
          +"\","
          +this.LatLong.Latitude
          +","+this.LatLong.Longitude;

        if(isTitleValid)content+=", \""+escape(this.Title)+"\"";
	      else content+=",\"\"";

        if(isDetailsValid)content+=", \""+escape(this.Details)+"\"";
        else content+=",\"\"";
      
        content+=",\""+this.TitleStyle+"\"";
        content+=",\""+this.DetailsStyle+"\"";
        content+=");' ";

    }

    content+=" />";
    return content;
}

// OVERRIDDEN DISPOSE FUNCTION
VEPushpin.prototype.Dispose=function()
{
    this.DetailsStyle=null;
    this.TitleStyle=null;
    this.IconStyle=null;
    this.Details=null;
    this.Iconurl=null;
    this.Title=null;
    this.LatLong=null;
    this.ID=null;
    this.m_vemapcontrol=null;
    this.m_vemap=null
    purge(this);
}

//
// OVERRIDDEN HIDE FUNCTION
//
VEPushpin.Hide=function(a)
{
  var popup = document.getElementById("ClientPopup");
  var popupHolder = document.getElementById("PopupHolder");
  popup.innerHTML = "";
  popupHolder.style.display = "none";
}

//
// OVERRIDDEN SHOW FUNCTION
// l = mapID, m = popupID, k = lat, h = long, d = title, c = details, g = title style, f = details style
//
VEPushpin.Show=function(l,m,k,h,d,c,g,f)
{
    var center = map.GetCenter();
    var q = 1;
    // determine what quadrant point is in
    // 1: top/left; 2: top/right; 3: bottom/left; 4: bottom/right;
    if( k > center.Latitude && h <= center.Longitude)
      q = 1;
    else if( k > center.Latitude && h > center.Longitude)
      q = 2
    else if( k <= center.Latitude && h <= center.Longitude )
      q = 3;
    else if( k <= center.Latitude && h > center.Longitude)
      q = 4;
      
    var popup = document.getElementById("ClientPopup");
    var popupHolder = document.getElementById("PopupHolder");
    var beak = document.getElementById("Beak");
    var beak_top_left = document.getElementById("beak_top_left");
    var beak_bot_left = document.getElementById("beak_bot_left");
    var beak_top_right = document.getElementById("beak_top_right");
    var beak_bot_right = document.getElementById("beak_bot_right");
    var position = new VELatLong(k,h);
    var pixelPos = map.LatLongToPixel(position);
    
    // adjust popup if it isn't on map
    var maxX = document.getElementById("map").clientWidth + 8;
    if( pixelPos.y < 7 )
    {
        pixelPos.y = 7;
    }
    else if( pixelPos.y > 390 )
    {
        pixelPos.y = 390;
    }
    if( pixelPos.x < 2 )
    {
        pixelPos.x = 2;
    }
    if( pixelPos.x > maxX )
    {
        pixelPos.x = maxX;
    }
    
    // special case if in bird's eye mode
    if( map.GetMapStyle() == VEMapStyle.Birdseye )
    {
        // set q for bird's eye
        var center = map.LatLongToPixel(map.GetCenter());
        if( pixelPos.y <= center.y && pixelPos.x <= center.x )
          q = 1;
        else if( pixelPos.y <= center.y && pixelPos.x > center.x )
          q = 2;
        else if( pixelPos.y > center.y && pixelPos.x <= center.x )
          q = 3;
        else if( pixelPos.y > center.y && pixelPos.x > center.x )
          q = 4;
    }
   
    popup.innerHTML = unescape(c);
    popupHolder.style.display = "block";
    var zoom = map.GetZoomLevel();
    switch(q)
    {
        case 1: // top left
        {
            popupHolder.style.top = pixelPos.y + 210 + 65 + "px";
            popupHolder.style.left = pixelPos.x + 177 + 25 + "px";

            HideBeaks();
            beak_top_left.style.display = "block";
            break;
        }
        case 2: // top right
        {
            popupHolder.style.top = pixelPos.y + 210 + 65 + "px";
            popupHolder.style.left = pixelPos.x + 177 - 5 - popupHolder.clientWidth + "px";
            
            HideBeaks();
            beak_top_right.style.display = "block";
            break;
        }
        case 3: // bottom left
        {
            popupHolder.style.top = pixelPos.y + 210 + 12 -  popupHolder.clientHeight + "px";
            popupHolder.style.left = pixelPos.x + 177 + 17 + "px";
            
            HideBeaks();
            beak_bot_left.style.display = "block";
            break;
        }
        case 4: // bottom right
        {
            popupHolder.style.top = pixelPos.y + 210 + 12 - popupHolder.clientHeight + "px";
            popupHolder.style.left = pixelPos.x + 177 - 5 - popupHolder.clientWidth + "px";
            
            HideBeaks();
            beak_bot_right.style.display = "block";
            break;
        }
    }
};
// Hide all popup beaks
function HideBeaks()
{
    document.getElementById("beak_top_left").style.display = "none";
    document.getElementById("beak_bot_left").style.display = "none";
    document.getElementById("beak_top_right").style.display = "none";
    document.getElementById("beak_bot_right").style.display = "none";
}

// set onresize
function SetOnResize()
{
    // set onresize function
    if( typeof window.onresize != 'function')
    {
        window.onresize = ResizeMap;
    }
    else
    {
        window.onresize = function(){ ResizeMap(); };
    }
}

function ApplyBounds(clients)
{
    var locs = new Array;
    for( var i=0; i < clients.length; i++ )
    {
        var loc = new VELatLong(clients[i].Latitude, clients[i].Longitude);
        locs.push(loc);
    }
    
    totalCount = clients.length;
    
    map.SetMapView(locs);
    onSearchComplete(clients);
}