function SearchPageResults(pageNumber) {
    $get('ctl00_phContent_pageNumber').value = pageNumber;
    window.scrollTo(0,0);
    __doPostBack('ctl00_phContent_pageNumber','');
}

function SetupSearch()
{
    PositionProgressMeter();
//    if ($get('ctl00_phContent_isPageLinkSearch').value == 'true')
//    {
//        $get('ctl00_phContent_isPageLinkSearch').value = 'false';
//        $get("ctl00_phContent_pageNumber").value = "1";
//    }
} 

function PositionProgressMeter()
{    
    $get("progressMeter").style.marginTop = 400 + getScrollTop() + "px";
    $get("updateProgressBG").style.width = ((document.body.parentElement) ? document.body.parentElement.offsetWidth : document.body.offsetWidth) + "px";
}   

function getScrollTop()
{
    var ScrollTop = document.body.scrollTop;
    if (ScrollTop == 0)
    {
        if (window.pageYOffset)
            ScrollTop = window.pageYOffset;
        else
            ScrollTop = (document.body.parentElement) ? document.body.parentElement.scrollTop : 0;
    }
    return ScrollTop;
}

function ExpandDescription(propertyId)
{
    document.getElementById("result" + propertyId).style.display="none";
    document.getElementById("expandedResult" + propertyId).style.display="block";    
}

function CloseExpandedDescription(propertyId)
{
    document.getElementById("expandedResult" + propertyId).style.display="none";    
    document.getElementById("result" + propertyId).style.display="block";
}

function DoSearch(propertyId, section)
{
    PropertyData.GetPropertyData(propertyId, section, GetPropertySection);
}

function GetPropertySection(result)
{
    document.getElementById("expandedResult" + result.PropertyId).innerHTML = result.HTML;
}

function PopupProfile(url)
{
    profileWindow = window.open (url,"profile");
    profileWindow.focus();
} 

function CollapseSearchPanel()
{
    $find("collapsiblePanelExtender")._doClose();
}

function getCookie(cookieName)
{
    if (document.cookie.length>0)
    {
        cookieStart=document.cookie.indexOf(cookieName+"=");
        if (cookieStart!=-1)
        { 
            cookieStart=cookieStart+cookieName.length+1;
            cookieEnd=document.cookie.indexOf(";",cookieStart);
            if (cookieEnd==-1) 
                cookieEnd=document.cookie.length;
            return unescape(document.cookie.substring(cookieStart,cookieEnd));
        } 
    }
    return ""
}

function checkCookie()
{
    redirect=getCookie('redirect');
    if (redirect!=null && redirect!="")
    {
        document.cookie='redirect=';
        window.location=redirect;
    }
}

//the map object
var map = null;
var mapType;

//load map    
function Page_Load() {
    
    var mapArgs = new Zonder.VEMap.MapArgs("ctl00_phContent_zonderMapResults_VirtualEarthControl_ZonderMap", new VELatLong(39.5, -100), 3, VEMapStyle.Road, false, VEMapMode.Mode2D, VEDistanceUnit.Miles);
    map = new Zonder.VEMap.Map(Zonder.ClusterArticle.MapService, mapArgs);
    document.getElementById("updateProgressBG").style.visibility = "hidden";

}  

function beginRequestHandler(sender, args)
{
    
    if(checkIfMapUpdate(args,"amenityPanel"))
    {
        closeMapPopup();
        map._SaveMapParams();
        map._showWaiting();
    }
}

function KMLDone()
{
    window.location = siteurl+"/ExportKml.ashx";
}

function GetKML()
{
    map._setKML();
}

function closeMapPopup()
{
    if(window.ero)
    {
    window.ero.getAnimation().clear();
        if(window.ero.getElement)
        {
            
            if(map)
            {
                if(map._hide)
                {                   
                    map._hide();
                    window.ero.getElement().style.visibility = "hidden";                   
                }
            }
        }
    }
}

function unHideSpinner()
{
    document.getElementById("updateProgressBG").style.visibility = "visible";
}

function pageLoadedHandler(sender, args)
{
     if(checkIfMapUpdateReturn(sender,"amenityPanel"))
    {       
        map._resetupMap();
    }
}

function checkIfMapUpdateReturn(sender,lookfor)
{
    if(sender)
    {
        if(sender._postBackSettings)
        {
            if(sender._postBackSettings.panelID)
            {
                if(sender._postBackSettings.panelID.indexOf(lookfor) > 0 || sender._postBackSettings.panelID.indexOf('Slider') > 0)
                {
                    return true;
                }
            }
        }
    }
    return false;
}

function checkIfMapUpdate(args,panelContains)
{
    if(args)
    {   
        var postBackEle = args._postBackElement;
        if(postBackEle)
        {   
            
           if(postBackEle.id.indexOf("Slider") > 0 || postBackEle.id.indexOf("amenity") > 0)
           {          
               return true;
           }
            
        }
        
    }
    return false;
}

function doEmail(object,propId)
{
    map._map.HideInfoBox();
    __doPostBack("ctl00_phBanner_ShareForm1_ajaxHack","SHOWEMAILFORM_"+propId);
}




    function onClipFailed()
    {
    }
    
    function onClipSuccess()
    {
        Sys.WebForms.PageRequestManager.getInstance()._doPostBack(clipPanelId,'');
    }
    
    function addToFavoritesAjax(propId)
    {        
       PageMethods.AddToClipboardAJAX(propId,onClipSuccess,onClipFailed);      
    }

//Clean up all objects
function Page_Unload() {
Sys.WebForms.PageRequestManager.getInstance().remove_beginRequest(beginRequestHandler)
Sys.WebForms.PageRequestManager.getInstance().remove_pageLoaded(pageLoadedHandler)
    if (map!=null) {
        map.Dispose();
        map = null;
    }
}

//set page event handlers

if (typeof(Sys) !== "undefined") Sys.Application.notifyScriptLoaded();

function SendFindingMethod(thename)
{
   s.prop31 = thename;
}

function SendMapToPP()
{
    s.prop32 = 'map';
}

function SendSort(sortType)
{
    s.prop32 = sortType;
    s.t();
}

function SendPPCount(theName)
{
    s.prop33 = theName;
}

var Utility = {
    /// <summary>
    ///   static Utility class
    /// </summary>

    OnFailed: function(error) {
        /// <summary>
        ///     This is the failed callback function for all webservices.
        /// </summary>  
        /// <param name="error">The error object from the webservice</param>          
        
        var stackTrace = error.get_stackTrace();
        var message = error.get_message();
        var statusCode = error.get_statusCode();
        var exceptionType = error.get_exceptionType();
        var timedout = error.get_timedOut();
       
        // Display the error.    
        var RsltElem = 
            "Stack Trace: " +  stackTrace + "<br/>" +
            "Service Error: " + message + "<br/>" +
            "Status Code: " + statusCode + "<br/>" +
            "Exception Type: " + exceptionType + "<br/>" +
            "Timedout: " + timedout;
            
            alert(RsltElem);
    },
       
    decodeLine: function(encoded) {
        /// <summary>
        ///     Decode an encoded string into a list of VE lat/lng.
        /// </summary>  
        /// <param name="encoded">The encoded string</param>       
        /// <returns>Array of VELatLong</returns>
       
        var len = encoded.length;
        var index = 0;
        var array = [];
        var lat = 0;
        var lng = 0;
        try
        {
            while (index < len) {
                var b;
                var shift = 0;
                var result = 0;
                do {
                      b = encoded.charCodeAt(index++) - 63;
                      result |= (b & 0x1f) << shift;
                      shift += 5;
                } while (b >= 0x20);
                var dlat = ((result & 1) ? ~(result >> 1) : (result >> 1));
                lat += dlat;

                shift = 0;
                result = 0;
                do {
                      b = encoded.charCodeAt(index++) - 63;
                      result |= (b & 0x1f) << shift;
                      shift += 5;
                } while (b >= 0x20);
                var dlng = ((result & 1) ? ~(result >> 1) : (result >> 1));
                lng += dlng;

                array.push(new VELatLong((lat * 1e-5), (lng * 1e-5)));
            }
        } catch(ex) {
            //error in encoding.
        }
        return array;
    },  

    createEncodings: function(points) {
        /// <summary>
        ///     Create the encoded bounds.
        /// </summary>  
        /// <param name="points">Array of VELatLong</param>       
        /// <returns>The encoded string</returns>    
        var i = 0;
        var plat = 0;
        var plng = 0;
        var encoded_points = "";

        for(i = 0; i < points.length; ++i) {
            var point = points[i];
            var lat = point.Latitude;
            var lng = point.Longitude;

            var late5 = Math.floor(lat * 1e5);
            var lnge5 = Math.floor(lng * 1e5);

            dlat = late5 - plat;
            dlng = lnge5 - plng;

            plat = late5;
            plng = lnge5;

            encoded_points += this._encodeSignedNumber(dlat) + this._encodeSignedNumber(dlng);
        } 
        return encoded_points;
    },
    
    _encodeSignedNumber: function(num) {
        /// <summary>
        ///     Encode a signed number in the encode format.
        /// </summary>  
        /// <param name="num">signed number</param>       
        /// <returns>encoded string</returns>       
        var sgn_num = num << 1;

        if (num < 0) {
            sgn_num = ~(sgn_num);
        }

        return(this._encodeNumber(sgn_num));
    },

    _encodeNumber: function(num) {
        /// <summary>
        ///     Encode an unsigned number in the encode format.
        /// </summary>  
        /// <param name="num">unsigned number</param>       
        /// <returns>encoded string</returns>        
        var encodeString = "";

        while (num >= 0x20) {
            encodeString += (String.fromCharCode((0x20 | (num & 0x1f)) + 63));
            num >>= 5;
        }

        encodeString += (String.fromCharCode(num + 63));
        return encodeString;
    }      

}

if (typeof(Sys) !== "undefined") Sys.Application.notifyScriptLoaded();


Type.registerNamespace("Zonder.ClusteredPin")
Zonder.ClusteredPin.Pin=function(){
this._currentLoc = "";
this._propertyIds = null;

}

Zonder.ClusteredPin.Pin.prototype = {
   
    AddPin : function(pin)
    {
        this._currentLoc = pin;
        if(this._propertyIds == null)
        {
            this._propertyIds = pin.PropertyId;
        }
        else{
            this._propertyIds += ","+pin.PropertyId;
        }
    }
}

Zonder.ClusteredPin.Pin.registerClass('Zonder.ClusteredPin.Pin')
if(typeof(Sys)!=="undefined")Sys.Application.notifyScriptLoaded()


Type.registerNamespace("Zonder.VEMap");

Zonder.VEMap.Map = function(service, mapArgs) {
    /// <summary>
    ///   The VE Map.
    ///   Supports load on demand
    /// </summary>
    /// <param name="service">The webservice to call for the map data.</param>
    /// <param name="mapArgs">The map initalisation data.</param>
    Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(beginRequestHandler);
    Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded(pageLoadedHandler);
    this._service = service;
    this._mapArgs = mapArgs;
    
    this._boundsBuffer = .10;
    this._map = null;
    this._pinID = 0;
    this._zoomlevel = 0;
    this._layer = null;
    this._isFirstLoad = false;
    this._topLeftBox = null;
    this._bottomRightBox = null;
    
    //popup specific
    this._PopupPrefix = "POPUP";
    this._currentpin = null;
    this._currentindex = 0;   
    
    this.GetPinDataDelegate = null;
    this.PinHoverDelegate = null;
    this.PinStopHoverDelegate = null;
    
    this._init();
}

Zonder.VEMap.Map.prototype = {

     _DisableEroHide: function ()
        {
            this._hide = window.ero.hide;
            window.ero.hide = function(a)
            {
                return;
            }       
        },
        
        _CalculateBuffer: function()
        {
            var view = map._map.GetMapView();
            var topLeftLatLong = view.TopLeftLatLong;
            var bottomRightLatLong = view.BottomRightLatLong;
            map._boundsBuffer = (topLeftLatLong.Latitude-bottomRightLatLong.Latitude)*.65;
            topLeftLatLong.Latitude-bottomRightLatLong.Latitude
        },     
        
         _EnableEroHide: function()
        {
            window.ero.hide = this._hide;
        },
        
    _init: function() {
        /// <summary>
        ///   Initialises the Map.
        /// </summary>       
        
        //setup map
        if(!this._mapArgs.PropertyProfile)
        {
            this._showWaiting();
        }
         
        
        this._map = new VEMap(this._mapArgs.DivID); 
        if(this._mapArgs.PropertyProfile)
        {
             this._map.SetDashboardSize(VEDashboardSize.Tiny);   
        }
       
        this._map.LoadMap(this._mapArgs.Center,this._mapArgs.Zoomlevel,this._mapArgs.Style,this._mapArgs.Fixed,this._mapArgs.Mode,false);
        this._map.Hide3DNavigationControl();
        
        
        this._DisableEroHide();
        
        this._map.SetScaleBarDistanceUnit(this._mapArgs.Scale);
        
        this._layer = new VEShapeLayer();         
        this._map.AddShapeLayer(this._layer);
        if(!this._mapArgs.PropertyProfile)
        {
            //setup the function to get new data whenever the map changes
            this.GetPinDataDelegate = Function.createDelegate(this, this._GetPinData);
            this._map.AttachEvent("onchangeview", this.GetPinDataDelegate);
            this._map.AttachEvent("onstartpan", Function.createDelegate(this, function(e){closeMapPopup();}));
            this._map.AttachEvent("onstartzoom",Function.createDelegate(this, function(e){this._isFirstLoad = true;closeMapPopup();}));
            this._map.AttachEvent("onendzoom",Function.createDelegate(this, function(e){this._CalculateBuffer();}));
            
            //turn off the standard popup and attach our custom handler
            this.PinHoverDelegate = Function.createDelegate(this, this._PinActivate);
            this.PinStopHoverDelegate = Function.createDelegate(this,this._PinStopHover);
            this._map.AttachEvent("onmouseover", this.PinStopHoverDelegate);
            this._map.AttachEvent("onclick", this.PinHoverDelegate);
            document.getElementById("MSVE_navAction_container").cssClass = 'MSVE_Dashboard_V6 MSVE_OrthoView';

        }
        //Setup additional storage for shapes
        VEShape.prototype.Bounds = "";  

        if(this._mapArgs.PropertyProfile)
        {
            this._GetPinData();
        }
        else
        {
            //get the data for the default view
            this._GetDefaultPinData();
        }
    },
    _PinStopHover: function(e)
    {
        if (e.elementID)
        {
            return true;
        }
    },
    
    _resetWaitingDiv: function(){
    
    
                this._waitingDiv.inneHTML = null;
                this._waitingDiv.setAttribute('id', "loadingMap");
                this._waitingDiv.style.position = "absolute";
                this._waitingDiv.style.zIndex = 15003;
                this._waitingDiv.style.width = "100%";
                this._waitingDiv.style.height = "100%";
                this._waitingDiv.style.background = "White";
                this._waitingDiv.style.filter = "alpha(opacity=50)";
                this._waitingDiv.style.opacity = .5;
                this._waitingDiv.style.textAlign = "center";
                 
                if(this._waitingDiv.childNodes.length < 1)
                {
                    this._plsWt = null;
                    this._plsWt = document.createElement("div");
                    this._plsWt.setAttribute('id', "mapPlzWt");
                    this._plsWt.style.zIndex = 15003;
                    this._plsWt.innerHTML = "Please Wait - Loading Results";
                    this._plsWt.style.fontSize = "1.9em";
                    this._plsWt.style.marginTop = "20%";    
                    this._waitingDiv.appendChild(this._plsWt);
                    
                    this._spinner = null;
                    this._spinner = document.createElement('img');
                    this._spinner.setAttribute('id', "mapSpinner");
                    this._spinner.src = siteurl+"/images/Zonder-Spinner.gif";
                    this._spinner.style.width = "172px";
                    this._spinner.style.height = "120px";                          
                    this._waitingDiv.appendChild(this._spinner);
                    this._waitingDiv.appendChild(document.createElement("br"));             
                     
                }
                var theDiv = document.getElementById(this._mapArgs.DivID);
                if(theDiv)
                {
                    theDiv.appendChild(this._waitingDiv);   
                }
    },
    
    _createWaitingDiv: function(elem)
    {
             if(!document.getElementById("loadingMap"))
                {
                    this._waitingDiv = document.createElement('div');
                    this._waitingDiv.setAttribute('id', "loadingMap");
                    this._waitingDiv.style.position = "absolute";
                    this._waitingDiv.style.zIndex = 15003;
                    this._waitingDiv.style.width = "100%";
                    this._waitingDiv.style.height = "100%";
                    this._waitingDiv.style.background = "White";
                    this._waitingDiv.style.filter = "alpha(opacity=50)";
                    this._waitingDiv.style.opacity = .5;
                    this._waitingDiv.style.textAlign = "center";
                    
                    this._plsWt = document.createElement("div");
                    this._plsWt.setAttribute('id', "mapPlzWt");
                    this._plsWt.style.zIndex = 15003;
                    this._plsWt.innerHTML = "Please Wait - Loading Results";
                    this._plsWt.style.fontSize = "1.9em";
                    this._plsWt.style.marginTop = "20%";    
                    this._waitingDiv.appendChild(this._plsWt);
                    
                    this._spinner = document.createElement('img');
                    this._spinner.setAttribute('id', "mapSpinner");
                    this._spinner.style.width = "172px";
                    this._spinner.style.height = "120px";
                    this._spinner.src = siteurl+"/images/Zonder-Spinner.gif";                           
                    this._waitingDiv.appendChild(this._spinner);
                    this._waitingDiv.appendChild(document.createElement("br"));
               
                    var theDiv =document.getElementById(this._mapArgs.DivID);
                    if(theDiv)
                    {
                        theDiv.appendChild(this._waitingDiv);
                    }
                }
    },
    
    _showWaiting: function()
    {
            
            if(this._waitingDiv)
            {
                this._resetWaitingDiv();
            }
            else
            {
                this._createWaitingDiv();
      
            }
   },
    
    _endWaiting: function()
    {
        var elem = document.getElementById("loadingMap");
        if(elem)
        {
            elem.style.zIndex = -1000;
        }
        if(this._waitingDiv)
        {
            this._waitingDiv.style.zIndex = -1000;
        }
        
    },
    
    _createMapInfo: function(counter)
    {
    
    
        if(this._mapInfoDiv)
        {
            var removeDiv = document.getElementById(this._mapArgs.DivID);
            if(removeDiv)
            {
                try
                {
                removeDiv.removeChild(this._mapInfoDiv);
                }
                catch(Error)
                {
                }
            }
            this._mapInfoDiv = null;
        }
        this._mapInfoDiv = document.createElement('div');
        this._mapInfoDiv.setAttribute('id', "mapInformation");
        this._mapInfoDiv.style.zIndex = 11000;
        this._mapInfoDiv.style.backgroundColor = "#4A6A95";
        this._mapInfoDiv.style.position = "absolute";
        this._mapInfoDiv.style.fontSize = ".95em";
        this._mapInfoDiv.style.top = 0;
        this._mapInfoDiv.style.right = 0;
        this._mapInfoDiv.style.filter = "alpha(opacity=85)";
        this._mapInfoDiv.style.opacity = .85;
        
        numPins = document.createElement('span');
        numPins.innerHTML = "Showing "+counter+"/"+numProps+" Listings";
        numPins.style.margin = "5px 10px auto 10px;";
        numPins.style.color = "white";        
        numPins.style.fontWeight = "bolder";
        
        
        this._mapInfoDiv.appendChild(numPins);
        
        tempDiv = document.createElement('div');
        tempDiv.setAttribute('id','zoomInToSeeMore');
        tempDiv.style.margin = "0px 3px 3px 3px";
        tempDiv.style.backgroundColor = "white";
        tempDiv.style.textAlign = "center";
        tempDiv.style.filter = "alpha(opacity=50)";
        tempDiv.style.opacity = .95;
        tempDiv.style.fontWeight = "Bolder";
        tempDiv.innerHTML = "Zoom in to see more<br/> vacation rentals";
        
        this._mapInfoDiv.appendChild(tempDiv);
        var theDiv = document.getElementById(this._mapArgs.DivID);
        if(theDiv)
        {
            theDiv.appendChild(this._mapInfoDiv);
        }
    },
    
    _resetupMap: function()
    {
        this._isFirstLoad = true;
        this._showWaiting();
        this._layer.DeleteAllShapes();
        this._GetPinData();
    },
    
    _SaveMapParams: function()
    {
        mapType = this._map.GetMapStyle();
    },
    
    _GetDefaultPinData: function()
    {
            var location = document.getElementById("ctl00_phContent_LocationLabel").innerHTML;
      
        //call webservice
            this._showWaiting();
            var criteria = this._getFilteringCriteria();            
            this._service.GetFirstLoad(location,criteria.Prox,unitTypeId, Function.createDelegate(this, this._firstLoad), Utility.OnFailed);
    },
    _firstLoad: function(results)
    {
         ///   Receive data for map.
        /// </summary>  
        /// <param name="result">The webservice result object - Optomised CSV string</param>  
            
        //decode pins
        this._isFirstLoad = true;
        var result=results.split(",")
        var locs = Utility.decodeLine(result[0]);
        var newShapes = new Array();
        
        //clear existing pins
        this._layer.DeleteAllShapes();
        var mapLocation = [];
        //add new pins
        for(x = 0; x < locs.length; x++) {
            var loc = locs[x];
            var bounds = result[x+1];

            mapLocation.push(new VELatLong(loc.Latitude,loc.Longitude));        
   
        }
         this._map.SetMapView(mapLocation);
    },
    
      _getFilteringCriteria: function()
    {
            var price = document.getElementById("ctl00_phContent_PriceSlider").value;
            var location = document.getElementById("ctl00_phContent_LocationLabel").innerHTML;
            var prox = document.getElementById("ctl00_phContent_ProximitySlider").value;
            var sleeps = document.getElementById("ctl00_phContent_SleepsSlider").value;
            
            return {Price:price,Location:location,Prox:prox,Sleeps:sleeps}
    },
    
    _CheckIfMapScrolledOutOfBounds: function()
    {
        if(!this._mapArgs.PropertyProfile)
        {
         var view = this._map.GetMapView();
         var topLeftLatLong = view.TopLeftLatLong;
         if(topLeftLatLong.Latitude > this._topLeftBox.Latitude)
         {
            return true;
         }
         if(topLeftLatLong.Longitude < this._topLeftBox.Longitude)
         {
            return true;
         }
              
         var bottomRightLatLong = view.BottomRightLatLong;
         
         if(bottomRightLatLong.Latitude < this._bottomRightBox.Latitude)
         {
            return true;
         }
         if(bottomRightLatLong.Longitude > this._bottomRightBox.Longitude)
         {
            return true;
         }
         
         return false;
        }
        else
        {
        return true;
        }     
    
    },
    
    _GetPinData: function() {  
        /// <summary>
        ///   Get the latest map data from the webservice.
        /// </summary>
            
        //encode the current map bounds
        if(this._isFirstLoad || this._CheckIfMapScrolledOutOfBounds())
        {
            this._isFirstLoad = false;
            if(!this._mapArgs.PropertyProfile)
            {
                this._showWaiting();
            }
                var zoom;
                bounds = this._CreateMapBounds();
             
                //get zoomlevel
                zoom = this._map.GetZoomLevel();

            if (this._zoomlevel != zoom) {
                //clear existing pins
                this._layer.DeleteAllShapes();
                this._zoomlevel = zoom;
            }
            if(!this._mapArgs.PropertyProfile)
            {
                var criteria = this._getFilteringCriteria();
            //call webservice
                this._service.GetClusteredMapData(bounds, zoom,criteria.Location,criteria.Price,criteria.Prox,criteria.Sleeps,amenities,checkin,checkout,unitTypeId, Function.createDelegate(this, this._OnMapDataSucceeded), Utility.OnFailed);
            }
            else
            {
                this._service.GetPropertyProfilePoint(propId,Function.createDelegate(this, this._OnPPMapDataSucceeded), Utility.OnFailed);
            }
        }
    },
    
    _CreateMapBounds: function()
    {
            var points = new Array();
           
            
            if (this._map.GetMapStyle() == VEMapStyle.Birdseye) {    
                //set zoomlevel      
                zoom = 19;
                var be = this._map.GetBirdseyeScene();
                var rect = be.GetBoundingRectangle();
                points.push(rect.TopLeftLatLong);
                points.push(rect.BottomRightLatLong);

            }else {
                var view = this._map.GetMapView();
                var topLeftLatLong = view.TopLeftLatLong;
                topLeftLatLong.Latitude += this._boundsBuffer;
                topLeftLatLong.Longitude -= this._boundsBuffer;
                this._topLeftBox = topLeftLatLong;
                
                var bottomRightLatLong = view.BottomRightLatLong;
                bottomRightLatLong.Latitude -= this._boundsBuffer;
                bottomRightLatLong.Longitude += this._boundsBuffer;
                this._bottomRightBox = bottomRightLatLong;
                
                points.push(topLeftLatLong);
                points.push(bottomRightLatLong);
              
            }
            var bounds = Utility.createEncodings(points);
            
            return bounds;
    },
    
    _OnPPMapDataSucceeded: function(result) {
        /// <summary>
        ///   Receive data for map.
        /// </summary>  
        /// <param name="result">The webservice result object - Optomised CSV string</param>  
            
        //decode pins
       
        var loc = Utility.decodeLine(result);
        var newShapes = new Array();
        
        //clear existing pins
        this._layer.DeleteAllShapes();
               
        //add new pins
        var newShape = new VEShape(VEShapeType.Pushpin, loc); 
        newShape.SetCustomIcon("<div class=\"ve_pin ve_pin_blue\"></div>");        
                
        this._layer.AddShape(newShape);
       
        if(this._mapArgs.FirstLoad)
        {
            this._map.SetMapView([new VELatLong(newShape.Latitude,newShape.Longitude)]);
            this._map.SetZoomLevel(14);
            this._mapArgs.FirstLoad = false;        
        }
    },

    _OnMapDataSucceeded: function(results) {
        /// <summary>
        ///   Receive data for map.
        /// </summary>  
        /// <param name="result">The webservice result object - Optomised CSV string</param>  
            
        //decode pins
        var result=results.split(",")
        var locs = Utility.decodeLine(result[0]);
        var newShapes = new Array();
        
        //clear existing pins
        this._layer.DeleteAllShapes();
        var mapLocation = [];
        //add new pins
        var counter = 0;
        for(x = 0; x < locs.length; x++) {
            var loc = locs[x];
            var bounds = result[x+1];

            var newShape = new VEShape(VEShapeType.Pushpin, loc);
            newShape.SetCustomIcon("<div class=\"ve_pin ve_pin_blue\"></div>"); 
            newShape.Bounds = bounds;  
            counter++;       
            //set custom png pin, IE6 will require a PNG fix.
            //if(Sys.Browser.agent==Sys.Browser.InternetExplorer&&Sys.Browser.version==6){
            //    newShape.SetCustomIcon("<div class='myPushpinIE6'></div>");
           // }else {  
            //    newShape.SetCustomIcon("<div class='myPushpin'></div>");
           // }
            mapLocation.push(new VELatLong(newShape.Latitude,newShape.Longitude))
            newShapes.push(newShape);
   
        }
        this._layer.AddShape(newShapes);         
        this._createMapInfo(counter);
        this._endWaiting(); 
        
        
         
    },
    
   _HideEro: function(shape)
   {
        this._EnableEroHide();
        this._map.HideInfoBox();
   },
    
    _PinActivate: function(e) {
        /// <summary>
        ///   Receives any mouse of event from VE
        /// </summary>  
        /// <param name="e">The MapEvent object</param>         
        if (e.elementID)
        {
        
            var popupShape = this._map.GetShapeByID(e.elementID)
            if (popupShape)
            {
                if(window.ero.isVisible())
                {                    
                   //this._HideEro(popupShape);
                    closeMapPopup();
                }
                
                //set current pin
                this._currentpin = popupShape;
                this._currentindex = 0;
                
                //get the content for the pin.
                //this._getAJAXContent();
                this._currentpin.SetDescription("<div id='" + this._PopupPrefix + this._currentpin.GetID() + "'><img src=\""+siteurl+"/Images/Zonder-Spinner_small-25.gif\" style=\"float:left;\"/><div style=\"padding-top:1.5%\">Loading...</div></div>");
                this._currentpin.SetTitle("");
                this._map.ShowInfoBox(popupShape);
                    window.ero.dockToElement(document.getElementById(this._currentpin.Primitives[0].iid));
                //this._DisableEroHide();
                this._getAJAXContent();
            }
        }
    },
    
    _setKML: function()
    {
     var points = new Array();
        var zoom;
        
        if (this._map.GetMapStyle() == VEMapStyle.Birdseye) {    
            //set zoomlevel      
            zoom = 19;
            var be = this._map.GetBirdseyeScene();
            var rect = be.GetBoundingRectangle();
            points.push(rect.TopLeftLatLong);
            points.push(rect.BottomRightLatLong);

        }else {
            var view = this._map.GetMapView();
            points.push(view.TopLeftLatLong);
            points.push(view.BottomRightLatLong);
            
            //get zoomlevel
            zoom = this._map.GetZoomLevel();

        }
        var bounds = Utility.createEncodings(points);
    
        var criteria = this._getFilteringCriteria();
        this._service.GetKMLForGE(bounds, zoom,criteria.Location,criteria.Price,criteria.Prox,criteria.Sleeps,amenities,checkin,checkout,unitTypeId, Function.createDelegate(this, KMLDone), Utility.OnFailed);
        
 
    },   
    
    _getAJAXContent: function() {
        /// <summary>
        ///   Request content for popup.
        /// </summary>  
        
        //call the web service
        var criteria = this._getFilteringCriteria();
        this._service.GetPushPin(this._currentpin.Bounds, this._currentindex,criteria.Location,criteria.Price,criteria.Prox,criteria.Sleeps,amenities,checkin,checkout,clipProperties,unitTypeId, Function.createDelegate(this, this._OnContentSucceeded), Utility.OnFailed, this._currentpin.GetID());
    }, 
    
    _GetPopupContent: function(pinData)
    {
        var html;
        if(!pinData.IsResort)
        {
            html = '<span><img class="mapClose" src="'+siteurl+'/images/blank.gif" onclick="closeMapPopup();"/><a onclick="SendMapToPP();" href="'+siteurl+'/PropertyProfile.aspx?PropertyID='+pinData.PropertyID+'"><b style="font-size: 1.5em;">'+pinData.Title+'</b></span>';
            html += '<img style="width: 110px; height: 66px; float: left;margin-top:10px;margin-right:10px;" src="'+siteurl+'/PropertyImages/'+pinData.Image+'"/></a>';
            html += '<p style="margin-top: 10px;">'+pinData.Bedrooms+' Bedrooms<br/>';
            html += pinData.Bathrooms+' Bathrooms<br/>';
            html += 'Sleeps '+pinData.Sleeps+'<br/>';
            html += '<strong style="font-size: 120%;">$'+pinData.MinRate+' - $'+pinData.MaxRate+'/night</strong></p>';
            if(pinData.TotalRecords > 1)
            {
                html += '<ul style="margin-top:5px;font-size:1.3em;">';
            }
            else
            {
                   html += '<ul style="margin-top:10px;font-size:1.3em;">';
            }
            html += '<li class="small_icon share2" style="float:left;margin-right:10px;cursor: pointer;color:#0099CC;"><a onclick="closeMapPopup();doEmail(this,'+pinData.PropertyID+');">Email to Friend</a></li>';
            if(!this._IsAlreadySaved(pinData.PropertyID))
            {            
                html += '<li class="small_icon favorites" style="margin-left:10px;cursor: pointer;color:#0099CC;" onclick="javascript:AddToFavorites('+pinData.PropertyID+',this);">Save To Favorites</li>';
            }
            else
            {
                html += '<li style="margin-left:10px;" class="small_icon favorites">Saved</li>';
            }
            html += '</ul>';
        }
        else
        {
            html = '<span><img class="mapClose" src="'+siteurl+'/images/blank.gif" onclick="closeMapPopup();"/><a href="'+siteurl+'/Listings.aspx?utid='+pinData.UnitTypeId+'&loc='+loc+'"><b style="font-size: 1.5em;">'+pinData.Title+'</b></span>';
            html += '<img style="width: 110px; height: 66px; float: left;margin-top:10px;margin-right:10px;" src="'+siteurl+'/PropertyImages/'+pinData.Image+'"/></a>';
            html += '<p>'+pinData.Details+'</p>';
            html += '<p><a href="'+siteurl+'/Listings.aspx?utid='+pinData.UnitTypeId+'&loc='+loc+'">View Properties</a> (';
            html +=  pinData.ResortPropCount+') </p>';
        }
        
     
        
        return html;
    },
    
    _IsAlreadySaved: function(propId)
    {
        var props = getCookie('Zonder');
        if(props)
        {
            if(props.indexOf(propId) > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        return false;
    },
    
    
    
    _OnContentSucceeded: function(result, ID) { 
        /// <summary>
        ///   Receive content for popup.
        /// </summary>  
        /// <param name="result">The webservice result object - JSON PinData</param>  
        /// <param name="ID">The popup ID associated with this call</param>  
            
        //verify this is the data for the current popup.
        if (ID==this._currentpin.GetID()) {
        
        
            if (this._map.GetMapMode() == VEMapMode.Mode3D) {
                //3D mode fails to be able to retrieve the div we placed earlier so resort to setting the title and description only
                this._currentpin.SetTitle(result.Title);
                this._currentpin.SetDescription(result.Details);
            }else {
                //create the content element
                var el = document.createElement("div");
                el.innerHTML = this._GetPopupContent(result);
                //clear loading and attach the content
                
                
                if (result.TotalRecords > 1) {
                    var tempDiv = document.createElement('div');
                    
                    tempDiv.style.fontSize = "1.25em";
                    tempDiv.style.marginTop = "11px";
                     tempDiv.style.fontWeight = "bold";
                    tempDiv.style.textAlign = "center";
                    //prev / next functionlaity\\
                    showingProps = document.createElement('span');
                    showingProps.style.color = "#000000";
                    showingProps.innerHTML = "(Showing "+(this._currentindex+1)+"/"+result.TotalRecords+")&nbsp;";
                    tempDiv.appendChild(showingProps);
                    
                    if (this._currentindex > 0) { 
                    var prevButton = document.createElement("span");
                    prevButton.innerHTML = "&nbsp;< Previous &nbsp;&nbsp;|";
                    prevButton.style.color = "#0099CC";
                    tempDiv.appendChild(prevButton);
                     
                        prevButton.style.cursor = "pointer";
                        $addHandler(prevButton,"click",Function.createDelegate(this, this._PreviousRecord));      
                    }else {
                     
                    }
                    if (this._currentindex < (result.TotalRecords-1)) { 
                    var nextButton = document.createElement("span");
                    nextButton.innerHTML = "&nbsp;&nbsp;&nbsp;Next >";
                    nextButton.style.color = "#0099CC";
                    tempDiv.appendChild(nextButton);  
                     
                        $addHandler(nextButton,"click",Function.createDelegate(this, this._NextRecord));
                        nextButton.style.cursor = "pointer";                         
                    }else {
                     
                    }
                    el.appendChild(tempDiv);
                }
                
                $get(this._PopupPrefix + ID).innerHTML = "";
                $get(this._PopupPrefix + ID).appendChild(el);
                
                         
            }
            
        }
        if(this._currentpin.GetID() == null)
                {
                    closeMapPopup();
                }    
    },    
    
    _PreviousRecord: function() {
        /// <summary>
        ///   Request the previous record.
        /// </summary>  
        this._currentindex--;
        $get(this._PopupPrefix + this._currentpin.GetID()).innerHTML = "<img src=\""+siteurl+"/Images/Zonder-Spinner_small-25.gif\"/>Loading...";
        this._getAJAXContent();
    },
    
    _NextRecord: function() {
        /// <summary>
        ///   Request the next record.
        /// </summary>      
        this._currentindex++;
        $get(this._PopupPrefix + this._currentpin.GetID()).innerHTML = "<img src=\""+siteurl+"/Images/Zonder-Spinner_small-25.gif\"/>Loading...";
        this._getAJAXContent();
    },             

    Dispose: function() {
        /// <summary>
        ///   cleans up all objects. Detaches all events.
        /// </summary>
   
    }    
}

Zonder.VEMap.Map.registerClass('Zonder.VEMap.Map', null, Sys.IDisposable);

if (typeof(Sys) !== "undefined") Sys.Application.notifyScriptLoaded();


Type.registerNamespace("Zonder.VEMap")
Zonder.VEMap.MapArgs=function(divID,center,zoomlevel,style,fixed,mode,scale,propertyprofile){
this.DivID=divID
this.Center=center
this.Zoomlevel=zoomlevel
this.Style=style
this.Fixed=fixed
this.Scale=scale
this.PropertyProfile=propertyprofile
this.FirstLoad=true}
Zonder.VEMap.MapArgs.registerClass('Zonder.VEMap.MapArgs')
if(typeof(Sys)!=="undefined")Sys.Application.notifyScriptLoaded()

//Override Webservice execution and insert processing queue and throttling
//Very good for VE map where user can pan and zoom very quickly.
//Increase the _maxConcurrentCall if you require more servcies to be called asycn, IE default is only 2
var GlobalCallQueue = {
    _callQueue : [],    // Maintains the list of webmethods to call
    _callInProgressNames : [],    // Maintains the list of webmethods names in progress by browser
    _callInProgress : 0,    // Number of calls currently in progress by browser
    _maxConcurrentCall : 2, // Max number of calls to execute at a time
    call : function(servicePath, methodName, useGet, 
        params, onSuccess, onFailure, userContext, timeout)
    {
        
        var queuedCall = new QueuedCall(servicePath, methodName, useGet, 
            params, onSuccess, onFailure, userContext, timeout);


        //if method name is already waiting then remove from queue then add the new call
        for (var x=0;x<GlobalCallQueue._callQueue.length;x++)
        {
            if (GlobalCallQueue._callQueue[x]._methodName==queuedCall._methodName)
            {
                Array.removeAt( GlobalCallQueue._callQueue, x);
                break;
            }
        }   

        Array.add(GlobalCallQueue._callQueue,queuedCall);
        GlobalCallQueue.run();
    },
    run : function()
    {
        /// Execute a call from the call queue
        if (GlobalCallQueue._callInProgress < GlobalCallQueue._maxConcurrentCall)
        {
            if( 0 == GlobalCallQueue._callQueue.length ) 
            {
                return;
            } 
                       
            GlobalCallQueue._callInProgress ++;
        
            //get first index that is not already in progess
            var runIndex = -1;
            for (var x=0;x<GlobalCallQueue._callQueue.length;x++)
            {
                var found=false;
                for (var y=0;y<GlobalCallQueue._callInProgressNames.length;y++)
                {
                    if (GlobalCallQueue._callQueue[x]._methodName==GlobalCallQueue._callInProgressNames[y])
                    {
                        found=true;
                        break;
                    }
                }  
                if (!found)
                {
                    runIndex = x;
                    break;
                }
            }
            if (runIndex!=-1)
            {
            

                var queuedCall = GlobalCallQueue._callQueue[runIndex];
                Array.removeAt( GlobalCallQueue._callQueue, runIndex );             
                
                //set name in progress
                Array.add(GlobalCallQueue._callInProgressNames,queuedCall._methodName);
                
                // Call the web method
                queuedCall.execute();
            }else
            {
                GlobalCallQueue._callInProgress --;
            }
        }          
    },
    callComplete : function(methodName)
    {
        GlobalCallQueue._callInProgress --;
        //remove name in progress
        for (var x=0;x<GlobalCallQueue._callInProgressNames.length;x++)
        {
            if (GlobalCallQueue._callInProgressNames[x]==methodName)
            {
                Array.removeAt( GlobalCallQueue._callInProgressNames, x );
                break;
            }
        }
        GlobalCallQueue.run();
    }
};

QueuedCall = function( servicePath, methodName, useGet, params, 
    onSuccess, onFailure, userContext, timeout )
{
    this._servicePath = servicePath;
    this._methodName = methodName;
    this._useGet = useGet;
    this._params = params;
    
    this._onSuccess = onSuccess;
    this._onFailure = onFailure;
    this._userContext = userContext;
    this._timeout = timeout;
}

QueuedCall.prototype = 
{
    execute : function()
    {
        Sys.Net.WebServiceProxy.original_invoke( 
            this._servicePath, this._methodName, this._useGet, this._params,  
            Function.createDelegate(this, this.onSuccess), // Handle call complete
            Function.createDelegate(this, this.onFailure), // Handle call complete
            this._userContext, this._timeout );
    },
    onSuccess : function(result, userContext, methodName)
    {
        this._onSuccess(result, userContext, methodName);
        GlobalCallQueue.callComplete(methodName);            
    },        
    onFailure : function(result, userContext, methodName)
    {
        if(this)
        {
            if(this._onFailure)
            {
                this._onFailure(result, userContext, methodName);
            }
        }
        GlobalCallQueue.callComplete(methodName);            
    }        
};

//override invoke
Sys.Net.WebServiceProxy.original_invoke = Sys.Net.WebServiceProxy.invoke;
Sys.Net.WebServiceProxy.invoke = 
    function Sys$Net$WebServiceProxy$invoke(servicePath, methodName, 
        useGet, params, onSuccess, onFailure, userContext, timeout)
{   
    GlobalCallQueue.call(servicePath, methodName, useGet, params, 
        onSuccess, onFailure, userContext, timeout);
}

if (typeof(Sys) !== "undefined") Sys.Application.notifyScriptLoaded();
/* You may give each page an identifying name, server, and channel on
the next lines. */

s.channel="Listings";



var addthis_url;
var addthis_title;
var addthis_pub;

function setAddThis(){
  addthis_url = location.href; 
  if(document.title.match("::"))
  {  
    addthis_title = document.title.replace(/::/g," ");
  }
  else
  {
    addthis_title = document.title;
  }
  addthis_pub    = 'VacationRentalsZonder';     
}

