// 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 = "Price";
var SortDir = "asc";
var SortImg = "arrowup";
var NewResults = false;
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.RentalSearch(0,0,0,0,"list",false,ApplyBounds));
    }
    catch(err)
    { 
        //alert(err.message);
    }
    if( map )
    {
        /*map.AttachEvent("onendzoom",CheckZoom);
        map.AttachEvent("onresize",UpdateSearchResults);
        map.AttachEvent("onendcontinuouspan",UpdateSearchResults);
        map.AttachEvent("onobliquechange", UpdateSearchResults);*/
        map.AttachEvent("onchangeview",UpdateSearchResults);
    } 
}
//
// resize map object
//
function ResizeMap()
{
    var oldHeight = PageHeight;
    var oldWidth = PageWidth;
    SetupLoadingMessage();
    UpdatePageDimensions();
    if( !(oldHeight == PageHeight && oldWidth == PageWidth) )
    {
        // get height of other elements
        var _tabs = document.getElementById("tabs").clientHeight;
        var _results = document.getElementById("infoRow").clientHeight;
        // 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;
        }
        document.getElementById("tabs").style.width = mapwidth + 2;
    }
}

//
// fix icon size depending on zoom level
//
function CheckZoom()
{       
    var pinID;
    // alter image according to zoomLevel
    for( var c=0; c < fullResults.length; c++ )
    {
        pinID = fullResults[c].ListingID+"_"+mapID;
        if( document.getElementById(pinID))
        {
            if( document.getElementById(pinID).src != setIcon() )
            {
                document.getElementById(pinID).src = setIcon();
            }
        }
    }

    UpdateSearchResults();
}

// update results
function UpdateSearchResults()
{
    var oldNWLat = nwLat, oldNWLng = nwLng, oldSELat = seLat, oldSELng = seLng;
    UpdateMapBounds();
    
    if( oldNWLat != nwLat || oldNWLng != nwLng || oldSELat != seLat || oldSELng != seLng )
    {
        // show loading message
        ShowLoadingMessage("Updating...");
        if( document.getElementById("ctl00_cphMain_chkDelisted") )
        {
            EliteProp.MapService.RentalSearch(seLat, seLng, nwLat, nwLng, view, document.getElementById("ctl00_cphMain_chkDelisted").checked, UpdateMap);
        }
        else
        {
            EliteProp.MapService.RentalSearch(seLat, seLng, nwLat, nwLng, view, false, UpdateMap);
        }
    }
}

// sort results by the given column
function SortResults(sortCol)
{
    // if clicked option is already sorted, reverse sort
    // if NewResults == true, then array is new search results so sort normally
    if( sortCol == SortOrder && !NewResults )
    {
        fullResults.reverse();
        if( SortDir == "asc" )
        {
          SortDir = "desc";
          SortImg = "arrowdown";
        }
        else
        {
          SortDir = "asc";
          SortImg = "arrowup";
        }
    }
    else
    {   
        NewResults = false;
        // update SortOrder
        SortOrder = sortCol;
        SortDir = "asc";
        SortImg = "arrowup";
        
        if( sortCol == "Address" )
        {
            fullResults.sort(SortByAddress);
        }
        else if( sortCol == "City")
        {
            fullResults.sort(SortByCity);
        }
        else if( sortCol == "Beds")
        {
            fullResults.sort(SortByBeds);
        }
        else if( sortCol == "Baths")
        {
            fullResults.sort(SortByBaths);
        }
        else if( sortCol == "Deposit")
        {
            fullResults.sort(SortByDeposit);
        }
        else if( sortCol == "Available")
        {
            fullResults.sort(SortByAvailable);
        }
        else
        {
            // default sorting is by price
            fullResults.sort(SortByRent);
        }
    }

    //SetCookie("sort",SortOrder + "," + SortDir,7);
    updatePages();
}

//
// display loading message
//
function ShowLoadingMessage(message)
{
    document.getElementById("Message").style.display = "none";
    document.getElementById("loading").style.display = "block";
    document.getElementById("loadingMessage").innerHTML = message;
}

//
// display results message
//
function ShowResultsMessage(results)
{
    document.getElementById("loading").style.display = "none";
    document.getElementById("Message").style.display = "block";
    if( results.length == 0 )
    {
        document.getElementById("Message").innerHTML = "No Properties Found";
    }
    else
    {
        if( view == "map" )
        {
            if( results.length == 1 )
            {
                document.getElementById("Message").innerHTML = results.length + " Property Shown";
            }
            else
            {
                document.getElementById("Message").innerHTML = results.length + " Properties Shown";
            }
        }
        else
        {
            if( results.length == 1 )
            {
                document.getElementById("Message").innerHTML = results.length + " Property Found";
            }
            else
            {
                document.getElementById("Message").innerHTML = results.length + " Properties Found";
            }
        }
    }
}

//
// update map points
//
function UpdateMap(results)
{
    if( !areArraysEqual(fullResults, results) )
    {
        // remove any old properties
        if( fullResults.length > 0 )
        {
            RemoveOldProperties(results);
        }
        // add any new properties to map
        if( results.length > 0 )
        {
            AddNewProperties(results);
        }
        
        // update fullResults object
        fullResults = results;
        NewResults = true;
        SortResults(SortOrder);
    }
    // update pages
    updatePages();
    ShowResultsMessage(fullResults);
}

//
// remove points no longer on map
//
function RemoveOldProperties(results)
{
    var ItemsToDelete = new Array();
    var found = false;

    for( var i=0; i < fullResults.length; i++)
    {
        found = false;
        for( var c=0; c< results.length && !found; c++)
        {
            if( fullResults[i].ListingID == results[c].ListingID )
            {
                found = true;
            }
        }
        
        if( !found )
        {
            ItemsToDelete.push(fullResults[i]);
        }
    }
    
    for( var r=0; r<ItemsToDelete.length; r++)
    {
        // remove from map
        try
        {
          map.DeletePushpin(ItemsToDelete[r].ListingID);
        }
        catch(err)
        {
            //alert(err.message);
        }
        var done = false;
        for( var x=0; x<fullResults.length && !done; x++)
        {
            if( fullResults[x].ListingID == ItemsToDelete[r].ListingID )
            {
                done = true;
                // remove item from array
                fullResults.splice(x,1);
                // offset x because of deletion
                x = x - 1;
            }
        }
    }
}

//
// add new points to map
//
function AddNewProperties(results)
{
    var ItemsToAdd = new Array();
    var found = false;
    
    
    for( var i=0; i < results.length; i++)
    {
        found = false;
        for( var c=0; c < fullResults.length && !found; c++)
        {
            if( results[i].ListingID == fullResults[c].ListingID )
            {
                found = true;
            }
        }
        
        if( !found )
        {
            ItemsToAdd.push(results[i]);
        }
    }
    
    if( ItemsToAdd.length > 0 )
    {
        fullResults.concat(ItemsToAdd);
        PlotPoints(ItemsToAdd);
    }
}

//
// perform search
//
function LoadResults()
{
    NewResults = true;
    pageIndex = 0;
    ShowLoadingMessage("Loading...");
    document.getElementById("Pages").innerHTML = "";
    document.getElementById("resultsDiv").style.display = "none";
    document.getElementById("Message").style.display = "none";
    if( view == "map" && map )
    {
        map.Clear();
        // set map bounds
        UpdateMapBounds();
    }

    if(document.getElementById("ctl00_cphMain_chkDelisted"))
    {
        EliteProp.MapService.RentalCount(document.getElementById("ctl00_cphMain_chkDelisted").checked,SetTotalCount);
        EliteProp.MapService.RentalSearch(seLat, seLng, nwLat, nwLng, view,document.getElementById("ctl00_cphMain_chkDelisted").checked, onSearchComplete);
    }
    else
    {
        EliteProp.MapService.RentalCount(false,SetTotalCount);
        EliteProp.MapService.RentalSearch(seLat, seLng, nwLat, nwLng, view,false, onSearchComplete);
    }
}

// read the specified cookie
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;
}

// 
// Update the map bounds variables
//
function UpdateMapBounds()
{
    if( view == "map" )
    {
        var nw;
	    var se;
	    var mapWidth = document.getElementById("map").clientWidth;
	    var mapHeight = document.getElementById("map").clientHeight;
    	
	    var p1 = new VEPixel(0,0);
	    var p2 = new VEPixel(0,0);

	    if(map.vemapcontrol.GetMapStyle() == VEMapStyle.Birdseye)
	    {
		    var scene = map.vemapcontrol.GetObliqueScene();
		    var zoom = map.vemapcontrol.GetZoomLevel();
		    if(zoom == 1)
		    {
			    p1.x = 20;
			    p1.y = 100;
			    p2.x = (scene.GetWidth()/2)-20;
			    p2.y = (scene.GetHeight()/2)-100;
		    }
		    else
		    {
			    p1.x = 40;
			    p1.y = 200;
			    p2.x = scene.GetWidth()-40;
			    p2.y = scene.GetHeight()-200;
		    }

		    nw = scene.PixelToLatLong(p1,zoom);
		    se = scene.PixelToLatLong(p2,zoom);
	    }
	    else
	    {
		    p2.x = mapWidth;
		    p2.y = mapHeight;
		    nw = map.vemapcontrol.PixelToLatLong(p1,map.vemapcontrol.GetZoomLevel());
		    se = map.vemapcontrol.PixelToLatLong(p2,map.vemapcontrol.GetZoomLevel());
	    }
	    
	    if( nw.latitude > se.latitude )
	    {
            nwLat = nw.latitude;
            seLat = se.latitude;
        }
        else
        {
            nwLat = se.latitude;
            seLat = nw.latitude;
        }
        
        if( nw.longitude > se.longitude )
        {
            nwLng = se.longitude;
            seLng = nw.longitude;
        }
        else
        {
            nwLng = nw.longitude;
            seLng = se.longitude;
        }
    }
}

//
// update pages on page switch
//
function onResultsPerPageChange()
{
    pageIndex = 0;
    resultsPerPage = document.getElementById(ddResultsPerPage).options[document.getElementById(ddResultsPerPage).selectedIndex].value;
    //SetCookie("resultsPerPage", resultsPerPage, 7);
    if( fullResults != null)
    {
        updatePages();
    }
}

//
// update results pages
//
function updatePages()
{
    var pagesHtml = "";
    totalPages = Math.ceil(fullResults.length / resultsPerPage);
    if( pageIndex >= totalPages)
    {
        pageIndex = totalPages - 1;
    }
    if( pageIndex < 0 )
    {
        pageIndex = 0;
    }
    
    if( totalPages > 1 )
    {
        if( pageIndex != 0 )
        {
            pagesHtml += "<a href=\"javascript:prevPage()\" id=\"prevPage\">&lt;</a>&nbsp;";
        }
        else
        {
            pagesHtml += "&lt;&nbsp;";
        }
        for( var c=0; c < totalPages; c++)
        {
            if( c != pageIndex )
            {
                pagesHtml += "<a id=\"page" + (c+1) +"\" href=\"javascript:changePage(" + (c+1) + ")\">" + (c+1) + "</a>&nbsp;"
            }
            else
            {
                pagesHtml += (c+1) + "&nbsp";
            }
        }
        
        if( pageIndex < totalPages-1)
        {
            pagesHtml += "<a href=\"javascript:nextPage()\" id=\"nextPage\">&gt;</a>";
        }
        else
        {
            pagesHtml += "&gt;";
        }
    }

    document.getElementById("Pages").innerHTML = pagesHtml;

    var start = pageIndex * resultsPerPage;
    var end = start + resultsPerPage;
    var results = fullResults.slice(start, end);
    
    GetResultsTable(results);
}

//
// change search results page
//
function changePage(page)
{
    // pages are zero based in code, one based in user view
    // offset input by -1
    pageIndex = page - 1;
    updatePages();
}

//
// show the previous results page
//
function prevPage()
{
    if( pageIndex > 0 )
    {
        pageIndex--;
        updatePages();
    }
}

//
// show the next results page
//
function nextPage()
{
    if( pageIndex < totalPages - 1 )
    {
        pageIndex++;
        updatePages();
    }
}

function SetTotalCount(count)
{
    totalCount = count;
}

// load search results to map/list
function onSearchComplete(results)
{
    fullResults = results;
    // sort results properly
    SortResults(SortOrder);
    // display results in list view
    updatePages();
    if( view == "map" )
    {
        // plot points on map
        PlotPoints(results);
    }
    // display property count
    ShowResultsMessage(fullResults);
}

// 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\">";
        // thumbnail -> LISTVIEW ONLY
        if( view == "list" )
        {
            tableHtml += "<td class=\"thumbHdr\"><span>Thumbnail</span></td>";
        }
        // address -> ALL
        tableHtml += "<td class=\"addressHdr\"><span><a href=\"javascript:SortResults('Address')\">Address";
        if( SortOrder == "Address" )
        {
          tableHtml += "&nbsp;<img src=\"Images/" + SortImg + ".gif\" class=\"sortimg\" alt=\"\" />";
        }
        tableHtml += "</a></span></td>";
        // city -> ALL
        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>";
        // beds/baths -> S-F & condo
        tableHtml += "<td class=\"bedsHdr\"><span><a href=\"javascript:SortResults('Beds')\">Beds";
        if( SortOrder == "Beds" )
        {
          tableHtml += "&nbsp;<img src=\"Images/" + SortImg + ".gif\" class=\"sortimg\" alt=\"\" />";
        }
        tableHtml += "</a></span></td>";
        tableHtml += "<td class=\"bathsHdr\"><span><a href=\"javascript:SortResults('Baths')\">Baths";
        if( SortOrder == "Baths" )
        {
          tableHtml += "&nbsp;<img src=\"Images/" + SortImg + ".gif\" class=\"sortimg\" alt=\"\" />";
        }
        tableHtml += "</a></span></td>";
        // rent -> ALL
        tableHtml += "<td class=\"rentHdr\"><span><a href=\"javascript:SortResults('Rent')\">Rent";
        if( SortOrder == "Rent" )
        {
          tableHtml += "&nbsp;<img src=\"Images/" + SortImg + ".gif\" class=\"sortimg\" alt=\"\" />";
        }
        tableHtml += "</a></span></td>";
        // deposit -> ALL
        tableHtml += "<td class=\"depositHdr\"><span><a href=\"javascript:SortResults('Deposit')\">Deposit";
        if( SortOrder == "Deposit" )
        {
          tableHtml += "&nbsp;<img src=\"Images/" + SortImg + ".gif\" class=\"sortimg\" alt=\"\" />";
        }
        tableHtml += "</a></span></td>";
        // available -> ALL
        tableHtml += "<td class=\"availableHdr\"><span><a href=\"javascript:SortResults('Available')\">Available";
        if( SortOrder == "Available" )
        {
          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].ListingID + "\",\"" 
                          + results[c].Latitude + "\",\"" 
                          + results[c].Longitude + "\", \"" 
                          + "" + "\", \"" 
                          + escape(GetHTML(results[c])) 
                          + "\",\"VE_Pushpin_Popup_Title\",\"VE_Pushpin_Popup_Body\");'";
            }
            else
            {
                tableHtml += "onmouseout='this.className=\"" + className + "\";' onmouseover='this.className=\"hoverrow\";'";
            }
            tableHtml += ">";            
            
            // thumbnail FOR LISTVIEW ONLY
            if( view == "list" )
            {
                tableHtml += "<td class=\"ThumbCol\"><a href=\"RentalDetails.aspx?id=" + results[c].ListingID + "\"><img class=\"thumbnail\" src=\""+ results[c].ImageUrl +"\" alt=\"" + results[c].Address + "\"></a></td>";
            }
            // property details
            tableHtml += "<td class=\"addressCol\"><span class=\"address\"><a href=\"RentalDetails.aspx?id=" + results[c].ListingID + "\">" + results[c].Address + "</a></span></td>";
            tableHtml += "<td class=\"cityCol\">" + results[c].CityName + "</td>";
            tableHtml += "<td class=\"bedsCol\">" + results[c].Beds + "</td>";
            tableHtml += "<td class=\"bathsCol\">" + results[c].Baths;
            tableHtml += "</td>";
            tableHtml += "<td class=\"rentCol\">" + results[c].Rent + "</td>";
            tableHtml += "<td class=\"depositCol\">" + results[c].SecurityDeposit + "</td>";
            tableHtml += "<td class=\"availableCol\">" + results[c].DateAvailable + "</td>";
            tableHtml += "</tr>";
        }
        
        // close table
        tableHtml += "</tbody></table>";        
        // set HTML and display
        resultsDiv.innerHTML = tableHtml;
        resultsDiv.style.display = "block";
    }
    else
    {
        resultsDiv.style.display = "none";
    }
}

//
// plot search results on map
//
function PlotPoints(results)
{
    // set appropriate icon
    var icon = setIcon();
    
    for ( var pinID = 0; pinID < results.length; pinID++ )
    {
        if( !document.getElementById(results[pinID].ListingID) )
        {
            try
            {
                var pin = new VEPushpin(
                    results[pinID].ListingID,
                    new VELatLong(results[pinID].Latitude,results[pinID].Longitude),
                    icon,
                    null,
                    GetHTML(results[pinID]));
                
                  map.AddPushpin(pin);
                  document.getElementById(results[pinID].Id+"_"+map.GUID).onmousedown = null;
                  document.getElementById(results[pinID].Id).href="RentalDetails.aspx?id=" + results[pinID].ListingId;
                  document.getElementById(results[pinID].Id).onclick = null;
            }
            catch(err)
            {
                //alert(err.message);
            }
        }
    }
}

//
// set map icon to appropriate image
//
function setIcon()
{
    var icon = 'Images/house';
    
    /*
    // if birdseye view, use large image
    if( map.GetMapStyle() != VEMapStyle.Birdseye )
    {
        // check zoom level, set appropriate icon size
        if( map.GetZoomLevel() < 12 && map.GetZoomLevel() >= 6 )
        {
            icon += '_sm';
        }
        else if( map.GetZoomLevel() < 6 )
        {
            icon += '_xs';
        }
    }
    */
    
    icon += '.gif';
    
    return icon;
}

//
// SORT FUNCTIONS
//
function SortByAddress(a,b)
{
    if( a.Address < b.Address ) return -1;
    if( a.Address > b.Address ) 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 SortByBeds(a,b)
{
    if( a.Bedrooms < b.Bedrooms ) return -1;
    if( a.Bedrooms > b.Bedrooms ) return 1;
    return 0;
}

function SortByBaths(a,b)
{
    if( a.NumberOfFullBaths < b.NumberOfFullBaths ) return -1;
    if( a.NumberOfFullBaths > b.NumberOfFullBaths ) return 1;
    if( a.NumberOfHalfBaths < b.NumberOfHalfBaths ) return -1;
    if( a.NumberOfHalfBaths > b.NumberOfHalfBaths ) return 1;
    return 0;
}
function SortByAvailable(a,b)
{
    if( a.DateAvailable < b.DateAvailable ) return -1;
    if( a.DateAvailable > b.DateAvailable ) return 1;
    return 0;
}
function SortByDeposit(a,b)
{
    if( ((a.SecurityDeposit.toString().replace("$","")).replace(/\,/g,"")/1) < ((b.SecurityDeposit.toString().replace("$","")).replace(/\,/g,"")/1) ) return -1;
    if( ((a.SecurityDeposit.toString().replace("$","")).replace(/\,/g,"")/1) > ((b.SecurityDeposit.toString().replace("$","")).replace(/\,/g,"")/1) ) return 1;
    return 0;
}
function SortByRent(a,b)
{
    if( ((a.Rent.toString().replace("$","")).replace(/\,/g,"")/1) < ((b.Rent.toString().replace("$","")).replace(/\,/g,"")/1) ) return -1;
    if( ((a.Rent.toString().replace("$","")).replace(/\,/g,"")/1) > ((b.Rent.toString().replace("$","")).replace(/\,/g,"")/1) ) 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);
}

var currentID = null;

//
// OVERRIDDEN HIDE FUNCTION
//
VEPushpin.Hide=function(a)
{
  map.DetachEvent("onclick",onMouseClick);
  currentID = null;
  var popup = document.getElementById("RentalPopup");
  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)
{
    map.AttachEvent("onclick",onMouseClick);
    currentID = m;
    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("RentalPopup");
    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);
    
    // special case if in bird's eye mode
    if( map.GetMapStyle() == VEMapStyle.Birdseye )
    {
        // 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;
        }
        
        // 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
        {
        
            /*
            if( zoom < 12 && zoom >= 6 )
            {
                popupHolder.style.top = pixelPos.y + 155 + 60 + "px";
                popupHolder.style.left = pixelPos.x + 177 + 5 + "px";
            }
            else if( zoom < 6 )
            {
                popupHolder.style.top = pixelPos.y + 155 + 55 + "px";
                popupHolder.style.left = pixelPos.x + 177 + "px";
            }
            else
            {
            */
                popupHolder.style.top = pixelPos.y + 155 + 65 + "px";
                popupHolder.style.left = pixelPos.x + 177 + 17 + "px";
            //}
            HideBeaks();
            beak_top_left.style.display = "block";
            break;
        }
        case 2: // top right
        {
        /*
            if( zoom < 12 && zoom >= 6 )
            {
                popupHolder.style.top = pixelPos.y + 155 + 60 + "px";
                popupHolder.style.left = pixelPos.x + 177 - 5 - popupHolder.clientWidth + "px";
            }
            else if( zoom < 6 )
            {
                popupHolder.style.top = pixelPos.y + 155 + 55 + "px";
                popupHolder.style.left = pixelPos.x + 177 - 5 - popupHolder.clientWidth + "px";
            }
            else
            {
            */
                popupHolder.style.top = pixelPos.y + 155 + 65 + "px";
                popupHolder.style.left = pixelPos.x + 177 - 5 - popupHolder.clientWidth + "px";
            //}
            HideBeaks();
            beak_top_right.style.display = "block";
            break;
        }
        case 3: // bottom left
        {
        /*
            if( zoom < 12 && zoom >= 6 )
            {
                popupHolder.style.top = pixelPos.y + 155 + 12 -  popupHolder.clientHeight + "px";
                popupHolder.style.left = pixelPos.x + 177 + 5 + "px";
            }
            else if (zoom < 6 )
            {
                popupHolder.style.top = pixelPos.y + 155 + 12 - popupHolder.clientHeight + "px";
                popupHolder.style.left = pixelPos.x + 177 + "px";
            }
            else
            {
            */
                popupHolder.style.top = pixelPos.y + 155 + 12 -  popupHolder.clientHeight + "px";
                popupHolder.style.left = pixelPos.x + 177 + 17 + "px";
            //}
            HideBeaks();
            beak_bot_left.style.display = "block";
            break;
        }
        case 4: // bottom right
        {
        /*
            if( zoom < 12 && zoom >= 6 )
            {
                popupHolder.style.top = pixelPos.y + 155 + 12 - popupHolder.clientHeight + "px";
                popupHolder.style.left = pixelPos.x + 177 - 5 - popupHolder.clientWidth + "px";
            }
            else if( zoom < 6 )
            {
                popupHolder.style.top = pixelPos.y + 155 + 12 - popupHolder.clientHeight + "px";
                popupHolder.style.left = pixelPos.x + 177 - 5 - popupHolder.clientWidth + "px";
            }
            else
            {
            */
                popupHolder.style.top = pixelPos.y + 155 + 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";
}

// change to listview
function ShowList()
{
    if( view != "list" )
    {
        view = "list";
        //SetCookie("view", view, 7);
    }
    document.getElementById("map").style.display = "none";
    document.getElementById("ctl00_cphMain_hypHelp").style.display = "none";
    if( document.getElementById("ctl00_cphMain_litAddNew") )
    {
        document.getElementById("ctl00_cphMain_litAddNew").style.display = "none";
    }
    document.getElementById("MapViewTab").className = "";
    document.getElementById("ListViewTab").className = "selected";
    // add border to tab element for list view
    document.getElementById("tabs").style.borderBottom = "solid 1px #000000";
    document.getElementById("resultsDiv").style.display = "none";
    //updatePages();
    LoadResults();
} 

// change to mapview
function ShowMap()
{
    if( view != "map" )
    {
        view = "map";
        //SetCookie("view", view, 7);
    }
    document.getElementById("map").style.display = "block";
    document.getElementById("ctl00_cphMain_hypHelp").style.display = "inline";
    if( document.getElementById("ctl00_cphMain_litAddNew") )
    {
        document.getElementById("ctl00_cphMain_litAddNew").style.display = "inline";
    }
    document.getElementById("MapViewTab").className = "selected";
    document.getElementById("ListViewTab").className = "";
    if( !map )
    {
        LoadMap();
    }
    // remove border on tab element
    document.getElementById("tabs").style.borderBottom = "none";
    document.getElementById("resultsDiv").style.display = "none";
    //updatePages();
    LoadResults();
}

//
// get requested query string variable
//
function Query(variable)
{
  var query = window.location.search.substring(1);
  var vars = query.split("&");
  for (var i=0;i<vars.length;i++) {
    var pair = vars[i].split("=");
    if (pair[0] == variable) {
      return pair[1];
    }
  } 
  return false
}

// capture key press
function keyPress(e)
{
    var key = e ? e.which : window.event.keyCode;
          
    if( key == 13)
    {
      LoadResults();
      return false;
    }
    else
    {
        return true;
    }
}

// reads view cookie and sets search mode
function SetView()
{
    if( ReadCookie("view") != null )
    {
        view = ReadCookie("view");
    }
    else
    {
        view = "map";
    }
    // load last view mode
    if( view == "list" )
    {
        ShowList();
    }
    else
    {
        LoadMap();
    }
}

// set onresize
function SetOnResize()
{
    // set onresize function
    if( typeof window.onresize != 'function')
    {
        window.onresize = ResizeMap;
    }
    else
    {
        window.onresize = function(){ ResizeMap(); };
    }
}

function GetHTML(rental)
{
    var html = "<table cellspacing=\"2\" cellpadding=\"0\" border=\"0\" class=\"rentalpopuptable\"><tr><td valign=\"top\" colspan=\"2\" class=\"address\">";
    var rentalAddy = rental.Address + ", " + rental.CityName;
    // check for overflowing row
    if( rentalAddy.length > 33 )
    {
        // shorten
        rentalAddy = rentalAddy.substr(0,30) + "...";
        
    }
    html += rentalAddy;
    html += "</td></tr><tr><td class=\"thumbnailholder\" valign=\"top\">";
    html += "<img class=\"popupThumb\" src=\"" + rental.ImageUrl + "\" alt=\"\" /></td><td valign=\"top\" style=\"text-align: right;\">";
    html += "<table border=\"0\" cellpadding=\"1\" cellspacing=\"0\" class=\"rentalpopupdetails\">";
    html += "<tr><td valign=\"top\" style=\"font-weight: bold;\">Rent:</td><td valign=\"top\" class=\"right\">" + rental.Rent +"</td></tr>";
    html += "<tr><td valign=\"top\" style=\"font-weight: bold;\">Deposit:</td><td valign=\"top\" class=\"right\">" + rental.SecurityDeposit +"</td></tr>";
    html += "<tr><td valign=\"top\" style=\"font-weight: bold;\">Beds:</td><td valign=\"top\" class=\"right\">" + rental.Beds + "</td></tr>";
    html += "<tr><td valign=\"top\" style=\"font-weight: bold;\">Baths:</td><td valign=\"top\" class=\"right\">" + rental.Baths;
    html += "</td></tr>";
    html += "<tr><td valign=\"top\" style=\"font-weight: bold;\">Available:</td><td valign=\"top\" class=\"right\">" + rental.DateAvailable + "</td></tr>";
    html += "</table>";    
    html += "</td></tr></table>";
 
     return html;
}

function ApplyBounds(rentals)
{
    var locs = new Array;
    for( var i=0; i < rentals.length; i++ )
    {
        var loc = new VELatLong(rentals[i].Latitude, rentals[i].Longitude);
        locs.push(loc);
    }
    
    totalCount = rentals.length;
    
    map.SetMapView(locs);
    onSearchComplete(rentals);
}

// function to capture mouse clicks
function onMouseClick(mapEvent)
{
    document.location.href = "RentalDetails.aspx?id=" + currentID;
}