﻿if (typeof (Number.prototype.toRad) === "undefined") {
    Number.prototype.toRad = function() {
        return this * Math.PI / 180;
    }
}

// Used a global variable to contain this IE8 puked on the bind.
var gv_this = null;
var gv_credentials = null;
var secondtime = false;

GetCredentials = function(callback) {
    $.ajaxSetup({ cache: false });
    $.getJSON('/DRHorton/MapService.svc/GetCredentials',
    function(json, textStatus) {
        gv_credentials = json;
    }).success(function() {
        callback();
    });
};

function BingMapv7() {
    this.gv_map = null;
    this.gv_zoom = 9;
    this.gv_show_scale_bar = false;
    this.gv_show_dashboard = true;
    this.gv_disable_mouseinput = false;
    this.gv_print = true;
    this.gv_default_latitude = 32.8726670543618;
    this.gv_default_longitude = -96.9406127929688;

    var mapdiv = document.getElementById('myMap');

    if (this.gv_map == null) {
        this.gv_map = new Microsoft.Maps.Map(mapdiv,
                           {
                               credentials: gv_credentials,
                               zoom: this.gv_zoom,
                               showScalebar: this.gv_show_scale_bar,
                               enableSearchLogo: false,
                               enableClickableLogo: false,
                               showCopyright: false,
                               showDashboard: this.gv_show_dashboard,
                               disableMouseInput: this.gv_disable_mouseinput,
                               showLogo: this.gv_print, // Hidden Feature turns off logo
                               showBreadcrumb: false,
                               showNavcontrol: false,
                               showMapTypeSelector: false
                           });
    }                     

    Microsoft.Maps.Globals.maxConcurrentTileDownloads = 16;    
                           
    this.gv_init = false;
    this.gv_layer = null;
    this.gv_map_Width = null;
    this.gv_map_Height = null;
    this.gv_x_cells = null;
    this.gv_y_cells = null;
    this.gv_grid_cells = [];
    this.gv_grid_size = 60;    
    this.gv_cluster_placement = 0;
    this.gv_latitude = this.gv_default_latitude;
    this.gv_longitude = this.gv_default_longitude;
    this.gv_infobox = null;
    this.gv_pins = new Microsoft.Maps.EntityCollection();
    this.gv_data = [];
    this.gv_data_original = [];
    this.gv_community = [];
    this.gv_counter = 0;
    this.gv_lastpin = null;
    this.gv_lastpinindex = null;
    this.gv_listeners = {};
    this.gv_infobox = null;
    this.gv_waypointa = null;
    this.gv_waypointb = null;
    this.gv_directions = null;
    this.gv_options = null;
    this.gv_dashboard_heading = true;    
    this.gv_location_result = null;
    this.gv_country = null;
    this.gv_address = null;
    this.gv_nodealiaspath = null;
    this.gv_city = null;
    this.gv_state = null;
    this.gv_zip = null;
    this.gv_locate = true;
    this.gv_stop_pan = false;    
    this.gv_lock = false;
    this.gv_mousedown = false;
    this.gv_fillinbox = false;
    this.gv_lostmouseposition = false;
    this.gv_microsoftmap = $(".MicrosoftMap");
    this.gv_myinfobox = $("div[id^=myInfobox]");
    this.gv_mapdiv = $("#myMap");
    this.gv_maxthreshhold = "20";
    this.gv_kentico = true; //Assume Kentico
    this.gv_usecluster = false;

    Microsoft.Maps.Pushpin.prototype.animation;
    Microsoft.Maps.Pushpin.prototype._pushpin;
    Microsoft.Maps.Pushpin.prototype._title;
    Microsoft.Maps.Pushpin.prototype._pushpins;

    if (Microsoft.Maps.Pushpin.prototype.setTitle == null) {
        Microsoft.Maps.Pushpin.prototype.setTitle = function(title) { this._title = title; }
    }
    if (Microsoft.Maps.Pushpin.prototype.getTitle == null) {
        Microsoft.Maps.Pushpin.prototype.getTitle = function() { return this._title; }
    }
    if (Microsoft.Maps.Pushpin.prototype.setIcon == null) {
        Microsoft.Maps.Pushpin.prototype.setIcon = function(icon) { this._icon = icon; }
    }
    if (Microsoft.Maps.Pushpin.prototype.setWidth == null) {
        Microsoft.Maps.Pushpin.prototype.setWidth = function(width) { this._width = width; }
    }
    if (Microsoft.Maps.Pushpin.prototype.setHeight == null) {
        Microsoft.Maps.Pushpin.prototype.setHeight = function(height) { this._height = height; }
    }
    if (Microsoft.Maps.Pushpin.prototype.setDraggable == null) {
        Microsoft.Maps.Pushpin.prototype.setDraggable = function(draggable) { this._draggable = draggable; }
    }
    if (Microsoft.Maps.Pushpin.prototype.setAnchor == null) {
        Microsoft.Maps.Pushpin.prototype.setAnchor = function(anchor) { this._calculatedAnchor = anchor; }
    }
    if (Microsoft.Maps.Pushpin.prototype.setText == null) {
        Microsoft.Maps.Pushpin.prototype.setText = function(text) { this._text = text; }
    }
    if (Microsoft.Maps.Pushpin.prototype.setTextOffset == null) {
        Microsoft.Maps.Pushpin.prototype.setTextOffset = function(textOffset) { this._textOffset = textOffset; }
    }
    if (Microsoft.Maps.Pushpin.prototype.setId == null) {
        Microsoft.Maps.Pushpin.prototype.setId = function(id) { this._id = id; }
    }
    if (Microsoft.Maps.Pushpin.prototype.setTypeName == null) {
        Microsoft.Maps.Pushpin.prototype.setTypeName = function(typeName) { this._typeName = typeName; }
    }
    if (Microsoft.Maps.Pushpin.prototype.setVisible == null) {
        Microsoft.Maps.Pushpin.prototype.setVisible = function(visible) { this._visible = visible; }
    }
    if (Microsoft.Maps.Pushpin.prototype.setZIndex == null) {
        Microsoft.Maps.Pushpin.prototype.setZIndex = function(zIndex) { this._zIndex = zIndex; }
    }
    if (Microsoft.Maps.Pushpin.prototype.setPushPin == null) {
        Microsoft.Maps.Pushpin.prototype.setPushPin = function(pushpin) { this._pushpin = pushpin; }
    }
    if (Microsoft.Maps.Pushpin.prototype.getPushPin == null) {
        Microsoft.Maps.Pushpin.prototype.getPushPin = function() { return this._pushpin; }
    }
    if (Microsoft.Maps.Pushpin.prototype.setPushPins == null) {
        Microsoft.Maps.Pushpin.prototype.setPushPins = function(pushpins) { this._pushpins = pushpins; }
    }
    if (Microsoft.Maps.Pushpin.prototype.getPushPins == null) {
        Microsoft.Maps.Pushpin.prototype.getPushPins = function() { return this._pushpins; }
    }

    gv_this = this;
};

BingMapv7.prototype.GetMap = function() {

    var mapdiv = document.getElementById('myMap');

    var options = this.gv_map.getOptions();

    options.zoom = this.gv_zoom;
    options.mapTypeId = Microsoft.Maps.MapTypeId.road;
    options.zIndex = 0;
    options.height = mapdiv.clientHeight,
    options.width = mapdiv.clientWidth
    options.center = new Microsoft.Maps.Location(this.gv_default_latitude, this.gv_default_longitude);

    this.gv_map.setView(options);

    gv_this.gv_map_Width = gv_this.gv_map.getWidth();
    gv_this.gv_map_Height = gv_this.gv_map.getHeight();

    gv_this.gv_x_cells = parseInt(Math.ceil(gv_this.gv_map_Width / gv_this.gv_grid_size));
    gv_this.gv_y_cells = parseInt(Math.ceil(gv_this.gv_map_Height / gv_this.gv_grid_size));

    var ArraySize = (gv_this.gv_x_cells * gv_this.gv_y_cells);

    gv_this.gv_grid_cells = new Array(ArraySize);

    gv_this.gv_map.entities.setOptions({ zIndex: 0 });

    gv_this.AddListener("tilecomplete", function() {
        if (gv_this.gv_lock == true) {
            if (gv_this.gv_microsoftmap.find("#navbar_icon").length == 0) {
                gv_this.gv_microsoftmap.find(".NavBar_zoomControlContainer").after("<br /><span id='navbar_icon' style='position:relative;float:left;display:inline-block;vertical-align:middle;line-height:29px;width:30px;margin:20px 3px;cursor:pointer;'><img src='/App_Themes/Default/images/map_locked.png' onclick=\"gv_this.Lock();\"></span>");
                gv_this.gv_microsoftmap.find("#navbar_icon").click(function() {
                    gv_this.Lock();
                });
            }
        }
    });

    if (gv_this.gv_dashboard_heading) {
        if (!Microsoft.Maps.Events.hasHandler(gv_this.gv_map, 'tiledownloadcomplete')) {
            Microsoft.Maps.Events.addHandler(gv_this.gv_map, 'tiledownloadcomplete', function() {
                gv_this.Fire("tilecomplete");
                gv_this.TileComplete();
            });
        }
    }
    else {
        if (!Microsoft.Maps.Events.hasHandler(gv_this.gv_map, 'tiledownloadcomplete')) {
            Microsoft.Maps.Events.addHandler(gv_this.gv_map, 'tiledownloadcomplete', gv_this.Fire("tilecomplete"));
        }
    }
};

// Cluster Pushpins
BingMapv7.prototype.SetupCluster = function() {
    var data = [];

    gv_this.SetScaleBar(true);

    gv_this.gv_usecluster = true;

    gv_this.gv_layer = new Microsoft.Maps.EntityCollection();

    gv_this.GetMap();

    $.ajaxSetup({ cache: false });
    $.getJSON('/DRHorton/MapService.svc/pushpins', function(json, textStatus) {
        $.each(json.ps, function(i, pushpin) {
            data.push(pushpin);
        });

        gv_this.gv_data = data;

        gv_this.ClusterData();

        gv_this.Cluster();

        gv_this.gv_map.entities.push(gv_this.gv_layer);

        gv_this.gv_microsoftmap.find(".PushPin").children("div").css("font-size", "9pt");
        gv_this.gv_microsoftmap.find(".PushPin").children("div").addClass("PushPinText");
    });
};

BingMapv7.prototype.SetupDraggableView = function(options) {
    gv_this.gv_dashboard_heading = true;

    gv_this.gv_lock = true;

    gv_this.SetScaleBar(true);

    gv_this.gv_layer = new Microsoft.Maps.EntityCollection();

    gv_this.GetMap();

    gv_this.Lock();

    var locate = gv_this.gv_locate;

    if (options != null) {
        if (options.zoomvalue != null) {
            gv_this.gv_zoom = parseInt(options.zoomvalue);
        }
    }

    if (options != null) {
        if (options.locate != null) {
            locate = options.locate;
        }
    }

    gv_this.gv_latitude = gv_this.gv_default_latitude;
    gv_this.gv_longitude = gv_this.gv_default_longitude;

    if (options != null) {
        if (options.latitude != null) {
            $("input[id$=" + options.latitude + "]").val(gv_this.gv_latitude);
        }
        if (options.longitude != null) {
            $("input[id$=" + options.longitude + "]").val(gv_this.gv_longitude);
        }
        if (options.zoom != null) {
            $("input[id$=" + options.zoom + "]").val(gv_this.gv_map.getTargetZoom());
        }
    }

    if (!Microsoft.Maps.Events.hasHandler(gv_this.gv_map, 'viewchange')) {
        Microsoft.Maps.Events.addHandler(gv_this.gv_map, 'viewchange', function() {
            var loc = gv_this.gv_map.getTargetCenter();
            gv_this.gv_latitude = loc.latitude;
            gv_this.gv_longitude = loc.longitude;

            if (options != null) {
                if (options.latitude != null) {
                    $("input[id$=" + options.latitude + "]").val(loc.latitude);
                }
                if (options.longitude != null) {
                    $("input[id$=" + options.longitude + "]").val(loc.longitude);
                }
                if (options.zoom != null) {
                    $("input[id$=" + options.zoom + "]").val(gv_this.gv_map.getTargetZoom());
                }
            }
        });
    }
}

BingMapv7.prototype.SetupDraggablePushPinByPoint = function(options) {
    gv_this.gv_dashboard_heading = true;

    gv_this.gv_lock = true;

    gv_this.SetScaleBar(true);

    gv_this.gv_layer = new Microsoft.Maps.EntityCollection();

    gv_this.GetMap();

    gv_this.Lock();

    var locate = gv_this.gv_locate;

    if (options != null) {
        if (options.zoomvalue != null) {
            gv_this.gv_zoom = parseInt(options.zoomvalue);
        }
    }

    if (options != null) {
        if (options.locate != null) {
            locate = options.locate;
        }
    }

    gv_this.gv_latitude = gv_this.gv_default_latitude;
    gv_this.gv_longitude = gv_this.gv_default_longitude;

    pin = gv_this.AddDraggablePushPin(gv_this.gv_default_latitude, gv_this.gv_default_longitude, null, true, { la: gv_this.gv_default_latitude, lo: gv_this.gv_default_longitude }, "C");

    if (options != null) {
        if (options.latitude != null) {
            $("input[id$=" + options.latitude + "]").val(gv_this.gv_latitude);
        }
        if (options.longitude != null) {
            $("input[id$=" + options.longitude + "]").val(gv_this.gv_longitude);
        }
        if (options.zoom != null) {
            $("input[id$=" + options.zoom + "]").val(gv_this.gv_map.getTargetZoom());
        }
    }

    if (!Microsoft.Maps.Events.hasHandler(pin, 'dragstart')) {
        Microsoft.Maps.Events.addHandler(pin, 'dragstart', function(e) {
            var loc = e.entity.getLocation();
            gv_this.gv_latitude = loc.latitude;
            gv_this.gv_longitude = loc.longitude;

            if (options != null) {
                if (options.latitude != null) {
                    $("input[id$=" + options.latitude + "]").val(loc.latitude);
                }
                if (options.longitude != null) {
                    $("input[id$=" + options.longitude + "]").val(loc.longitude);
                }
                if (options.zoom != null) {
                    $("input[id$=" + options.zoom + "]").val(gv_this.gv_map.getTargetZoom());
                }
            }
        });
    }

    if (!Microsoft.Maps.Events.hasHandler(pin, 'drag')) {
        Microsoft.Maps.Events.addHandler(pin, 'drag', function(e) {
            var loc = e.entity.getLocation();
            gv_this.gv_latitude = loc.latitude;
            gv_this.gv_longitude = loc.longitude;

            if (options != null) {
                if (options.latitude != null) {
                    $("input[id$=" + options.latitude + "]").val(loc.latitude);
                }
                if (options.longitude != null) {
                    $("input[id$=" + options.longitude + "]").val(loc.longitude);
                }
                if (options.zoom != null) {
                    $("input[id$=" + options.zoom + "]").val(gv_this.gv_map.getTargetZoom());
                }
            }

        });
    }

    if (!Microsoft.Maps.Events.hasHandler(pin, 'dragend')) {
        Microsoft.Maps.Events.addHandler(pin, 'dragend', function(e) {
            var loc = e.entity.getLocation();
            gv_this.gv_latitude = loc.latitude;
            gv_this.gv_longitude = loc.longitude;

            if (options != null) {
                if (options.latitude != null) {
                    $("input[id$=" + options.latitude + "]").val(loc.latitude);
                }
                if (options.longitude != null) {
                    $("input[id$=" + options.longitude + "]").val(loc.longitude);
                }
                if (options.zoom != null) {
                    $("input[id$=" + options.zoom + "]").val(gv_this.gv_map.getTargetZoom());
                }
            }

            //gv_this.ZoomToPin(gv_this.gv_layer.indexOf(gv_this.gv_lastpin), gv_this.gv_map.getTargetZoom());
        });
    }

    if (!Microsoft.Maps.Events.hasHandler(gv_this.gv_map, 'viewchange')) {
        Microsoft.Maps.Events.addHandler(gv_this.gv_map, 'viewchange', function() {
            if (options != null) {
                if (options.zoom != null) {
                    $("input[id$=" + options.zoom + "]").val(gv_this.gv_map.getTargetZoom());
                }
            }
        });
    }

    gv_this.gv_layer.push(pin);

    gv_this.gv_map.entities.push(gv_this.gv_layer);

    var zoom = gv_this.gv_map.getTargetZoom();

    gv_this.ZoomToPin(gv_this.gv_layer.indexOf(pin), zoom);
};

BingMapv7.prototype.ZoomToPinNoParam = function() {
    //alert(gv_this.gv_layer.indexOf(gv_this.gv_lastpin));
    gv_this.ZoomToPin(gv_this.gv_layer.indexOf(gv_this.gv_lastpin), gv_this.gv_map.getTargetZoom());
}

BingMapv7.prototype.SetupDraggablePushPinByPointWiz = function(options) {
    gv_this.gv_dashboard_heading = true;

    gv_this.gv_lock = true;

    gv_this.SetScaleBar(true);

    gv_this.gv_layer = new Microsoft.Maps.EntityCollection();

    gv_this.GetMap();

    gv_this.Lock();

    var locate = gv_this.gv_locate;

    var wizid = null;

    if (options != null) {
        if (options.zoomvalue != null) {
            gv_this.gv_zoom = parseInt(options.zoomvalue);
        }
    }

    if (options != null) {
        if (options.locate != null) {
            locate = options.locate;
        }
    }

    if (options != null) {
        if (options.id != null) {
            wizid = options.id;
        }
    }

    gv_this.gv_latitude = gv_this.gv_default_latitude;
    gv_this.gv_longitude = gv_this.gv_default_longitude;

    pin = gv_this.AddDraggablePushPin(gv_this.gv_default_latitude, gv_this.gv_default_longitude, null, true, { la: gv_this.gv_default_latitude, lo: gv_this.gv_default_longitude }, "C");

    if (options != null) {
        if (options.latitude != null) {
            $("input[id$=" + options.latitude + "]").val(gv_this.gv_latitude);
        }
        if (options.longitude != null) {
            $("input[id$=" + options.longitude + "]").val(gv_this.gv_longitude);
        }
        if (options.zoom != null) {
            $("input[id$=" + options.zoom + "]").val(gv_this.gv_map.getTargetZoom());
        }
    }

    if (!Microsoft.Maps.Events.hasHandler(pin, 'dragstart')) {
        Microsoft.Maps.Events.addHandler(pin, 'dragstart', function(e) {
            var loc = e.entity.getLocation();
            gv_this.gv_latitude = loc.latitude;
            gv_this.gv_longitude = loc.longitude;

            if (options != null) {
                if (options.latitude != null) {
                    $("input[id$=" + options.latitude + "]").val(loc.latitude);
                }
                if (options.longitude != null) {
                    $("input[id$=" + options.longitude + "]").val(loc.longitude);
                }
                if (options.zoom != null) {
                    $("input[id$=" + options.zoom + "]").val(gv_this.gv_map.getTargetZoom());
                }
            }
        });
    }

    if (!Microsoft.Maps.Events.hasHandler(pin, 'drag')) {
        Microsoft.Maps.Events.addHandler(pin, 'drag', function(e) {
            var loc = e.entity.getLocation();
            gv_this.gv_latitude = loc.latitude;
            gv_this.gv_longitude = loc.longitude;

            if (options != null) {
                if (options.latitude != null) {
                    $("input[id$=" + options.latitude + "]").val(loc.latitude);
                }
                if (options.longitude != null) {
                    $("input[id$=" + options.longitude + "]").val(loc.longitude);
                }
                if (options.zoom != null) {
                    $("input[id$=" + options.zoom + "]").val(gv_this.gv_map.getTargetZoom());
                }
            }
        });
    }

    if (!Microsoft.Maps.Events.hasHandler(pin, 'dragend')) {
        Microsoft.Maps.Events.addHandler(pin, 'dragend', function(e) {
            var loc = e.entity.getLocation();
            gv_this.gv_latitude = loc.latitude;
            gv_this.gv_longitude = loc.longitude;

            if (options != null) {
                if (options.latitude != null) {
                    $("input[id$=" + options.latitude + "]").val(loc.latitude);
                }
                if (options.longitude != null) {
                    $("input[id$=" + options.longitude + "]").val(loc.longitude);
                }
                if (options.zoom != null) {
                    $("input[id$=" + options.zoom + "]").val(gv_this.gv_map.getTargetZoom());
                }
            }

            var zoom = gv_this.gv_map.getTargetZoom();

            //gv_this.ZoomToPin(gv_this.gv_layer.indexOf(pin), zoom);
        });
    }

    if (!Microsoft.Maps.Events.hasHandler(gv_this.gv_map, 'viewchange')) {
        Microsoft.Maps.Events.addHandler(gv_this.gv_map, 'viewchange', function() {
            if (options != null) {
                if (options.zoom != null) {
                    $("input[id$=" + options.zoom + "]").val(gv_this.gv_map.getTargetZoom());
                }
            }
        });
    }

    gv_this.gv_layer.push(pin);

    gv_this.gv_map.entities.push(gv_this.gv_layer);

    var zoom = gv_this.gv_map.getTargetZoom();

    gv_this.ZoomToPin(gv_this.gv_layer.indexOf(pin), zoom);
};

// Draggable Pushpin
BingMapv7.prototype.SetupDraggablePushPin = function(options) {
    gv_this.gv_dashboard_heading = true;

    gv_this.gv_lock = true;

    gv_this.SetScaleBar(true);

    gv_this.gv_layer = new Microsoft.Maps.EntityCollection();

    gv_this.GetMap();

    gv_this.Lock();

    var country = gv_this.gv_country;
    var address = gv_this.gv_address;
    var city = gv_this.gv_city;
    var state = gv_this.gv_state;
    var zip = gv_this.gv_zip;
    var locate = gv_this.gv_locate;

    if (options != null) {
        if (options.country != null) {
            country = options.country;
        }
        if (options.address != null) {
            address = options.address;
        }
        if (options.city != null) {
            city = options.city;
        }
        if (options.state != null) {
            state = options.state;
        }
        if (options.zip != null) {
            zip = options.zip;
        }
        if (options.locate != null) {
            locate = options.locate;
        }
    }

    gv_this.Location(country, address, city, state, zip, locate, function(result) {

        if (result != null) {
            gv_this.gv_location_result = result.resourceSets[0].resources[0];
        }

        var pin = null;

        if (gv_this.gv_location_result != null) {
            pin = gv_this.AddDraggablePushPin(gv_this.gv_location_result.point.coordinates[0], gv_this.gv_location_result.point.coordinates[1], null, true, { la: gv_this.gv_location_result.point.coordinates[0], lo: gv_this.gv_location_result.point.coordinates[1] }, "C");

            if (options != null) {
                if (options.latitude != null) {
                    $("input[id$=" + options.latitude + "]").val(gv_this.gv_location_result.point.coordinates[0]);
                }
                if (options.longitude != null) {
                    $("input[id$=" + options.longitude + "]").val(gv_this.gv_location_result.point.coordinates[1]);
                }
            }
        } else {
            pin = gv_this.AddDraggablePushPin(gv_this.gv_default_latitude, gv_this.gv_default_longitude, null, true, { la: gv_this.gv_default_latitude, lo: gv_this.gv_default_longitude }, "C");

            if (options != null) {
                if (options.latitude != null) {
                    $("input[id$=" + options.latitude + "]").val(gv_this.gv_default_latitude);
                }
                if (options.longitude != null) {
                    $("input[id$=" + options.longitude + "]").val(gv_this.gv_default_longitude);
                }
            }
        }

        if (!Microsoft.Maps.Events.hasHandler(pin, 'drag')) {
            Microsoft.Maps.Events.addHandler(pin, 'drag', function(e) {
                var loc = e.entity.getLocation();
                gv_this.gv_latitude = loc.latitude;
                gv_this.gv_longitude = loc.longitude;

                if (options != null) {
                    if (options.latitude != null) {
                        $("input[id$=" + options.latitude + "]").val(loc.latitude);
                    }
                    if (options.longitude != null) {
                        $("input[id$=" + options.longitude + "]").val(loc.longitude);
                    }
                }

            });
        }

        if (!Microsoft.Maps.Events.hasHandler(pin, 'dragend')) {
            Microsoft.Maps.Events.addHandler(pin, 'dragend', function(e) {
                var loc = e.entity.getLocation();
                gv_this.gv_latitude = loc.latitude;
                gv_this.gv_longitude = loc.longitude;

                if (options != null) {
                    if (options.latitude != null) {
                        $("input[id$=" + options.latitude + "]").val(loc.latitude);
                    }
                    if (options.longitude != null) {
                        $("input[id$=" + options.longitude + "]").val(loc.longitude);
                    }
                }

                var zoom = gv_this.gv_map.getTargetZoom();

                //gv_this.ZoomToPin(gv_this.gv_layer.indexOf(pin), zoom);
            });
        }

        gv_this.gv_layer.push(pin);

        gv_this.gv_map.entities.push(gv_this.gv_layer);

        var zoom = gv_this.gv_zoom;

        if (result) {
            zoom = 15;
        }

        gv_this.ZoomToPin(gv_this.gv_layer.indexOf(pin), zoom);
    });
};

// Calculate a route.
BingMapv7.prototype.SetupRoute = function(options, callback) {
    gv_this.gv_options = options;

    gv_this.SetScaleBar(true);

    gv_this.gv_layer = new Microsoft.Maps.EntityCollection();

    gv_this.gv_dashboard_heading = false;
    gv_this.gv_show_dashboard = false;
    gv_this.gv_disable_mouseinput = false;

    gv_this.GetMap();

    if (!Microsoft.Maps.Events.hasHandler(gv_this.gv_map, 'dblclick')) {
        Microsoft.Maps.Events.addHandler(gv_this.gv_map, 'dblclick', function(e) { e.handled = true; return; });
    }

    if (!Microsoft.Maps.Events.hasHandler(gv_this.gv_map, 'mousedown')) {
        Microsoft.Maps.Events.addHandler(gv_this.gv_map, 'mousedown', function(e) { e.handled = true; return; });
    }

    if (!Microsoft.Maps.Events.hasHandler(gv_this.gv_map, 'mousemove')) {
        Microsoft.Maps.Events.addHandler(gv_this.gv_map, 'mousemove', function(e) { e.handled = true; return; });
    }

    if (!Microsoft.Maps.Events.hasHandler(gv_this.gv_map, 'mousewheel')) {
        Microsoft.Maps.Events.addHandler(gv_this.gv_map, 'mousewheel', function(e) { e.handled = true; return; });
    }

    if (options != null) {
        if (options.waypointa != null) {
            gv_this.gv_waypointa = options.waypointa;
        }
        if (options.waypointb != null) {
            gv_this.gv_waypointb = options.waypointb;
        }
        else {
            gv_this.LocationByPoint(gv_this.gv_default_latitude, gv_this.gv_default_longitude, function(result) {
                if (result != null) {
                    if (result.resourceSets[0] != null) {
                        if (result.resourceSets[0].resources[0] != null) {
                            gv_this.gv_waypointb = result.resourceSets[0].resources[0].name.toString();

                            var pinb = gv_this.AddRoutePushPin(result.resourceSets[0].resources[0].point.coordinates[0], result.resourceSets[0].resources[0].point.coordinates[1], null, false, [], "B");

                            gv_this.gv_layer.clear();
                            gv_this.gv_layer.push(pinb);
                            gv_this.gv_map.entities.push(gv_this.gv_layer);
                        }
                    }
                }
            }, function() {
                if (callback && typeof (callback) === "function") {
                    callback();
                }
            });
        }
    }
};

BingMapv7.prototype.BeforeZoomChange = function(e) {
    gv_this.gv_zoom = gv_this.gv_map.getZoom();
};

BingMapv7.prototype.SplitZoomPanEvent = function(e) {
    try {
        secondtime = true;
        if (gv_this.gv_map.getTargetZoom() != gv_this.gv_zoom) {
            gv_this.gv_break = false;
            gv_this.MapZoom(e);
        }
        else {
            gv_this.gv_break = false;
            gv_this.MapPan(e);
        }
    } catch (err) {
    }
};

BingMapv7.prototype.MapZoom = function(e) {
    if (gv_this.gv_usecluster) {
        gv_this.ClusterData();

        gv_this.Cluster();
    }

    if (secondtime == true && typeof (secondtime) !== 'undefined') {
        try {
            gv_this.ReloadGrid();
        } catch (err) { }
    }
};

BingMapv7.prototype.MapPan = function(e) {
    if (gv_this.gv_mousedown == false) {
        if (gv_this.gv_usecluster) {
            gv_this.ClusterData();

            gv_this.Cluster();
        }

        if (secondtime == true && typeof(secondtime) !== 'undefined') {
            try {
                gv_this.ReloadGrid();
            } catch (err) { }
        }
    }
};

BingMapv7.prototype.RefreshMap = function() {
    gv_this.ClusterData();

    loaddata();

    gv_this.ClusterData();

    gv_this.Cluster();
};

BingMapv7.prototype.Bounce = function(index) {
    var pin = gv_this.gv_layer.get(index);
    var pinname = pin.getId();

    if (pin.animation == false) {
        pin.animation = true;
        gv_this.gv_microsoftmap.find("#" + pinname).css("zIndex", 999);
        gv_this.gv_microsoftmap.find("#" + pinname).effect("bounce", { distance: 75, times: 3 }, 500, function() {
        gv_this.gv_microsoftmap.find("#" + pinname).css("zIndex", 1);
            pin.animation = false;
        });
    }
};

BingMapv7.prototype.Explode = function(index) {
    var pin = gv_this.gv_layer.get(index);
    var pinname = pin.getId();

    if (pin.animation == false) {
        pin.animation = true;
        gv_this.gv_microsoftmap.find("#" + pinname).css("zIndex", 999);
        gv_this.gv_microsoftmap.find("#" + pinname).effect("explode", 1000, function() {
            gv_this.gv_microsoftmap.find("#" + pinname).css("zIndex", 1);
            gv_this.gv_microsoftmap.find("#" + pinname).show("drop", { direction: "up" }, 1000);
            pin.animation = false;
        });
    }
};

BingMapv7.prototype.Drop = function(index) {
    var pin = gv_this.gv_layer.get(index);
    var pinname = pin.getId();

    if (pin.animation == false) {
        pin.animation = true;
        gv_this.gv_microsoftmap.find("#" + pinname).css("zIndex", 999);
        gv_this.gv_microsoftmap.find("#" + pinname).effect("drop", { direction: "down" }, 1000, function() {
            gv_this.gv_microsoftmap.find("#" + pinname).css("zIndex", 1);
            gv_this.gv_microsoftmap.find("#" + pinname).show("drop", { direction: "up" }, 1000);
            pin.animation = false;
        });
    }
};

BingMapv7.prototype.Pulsate = function(index) {
    var pin = gv_this.gv_layer.get(index);
    var pinname = pin.getId();

    if (pin.animation == false) {
        pin.animation = true;
        gv_this.gv_microsoftmap.find("#" + pinname).css("zIndex", 999);
        gv_this.gv_microsoftmap.find("#" + pinname).effect("pulsate", { times: 3 }, 1000, function() {
            gv_this.gv_microsoftmap.find("#" + pinname).css("zIndex", 1);
            pin.animation = false;
        });
    }
};

BingMapv7.prototype.Shake = function(index) {
    var pin = gv_this.gv_layer.get(index);
    var pinname = pin.getId();

    if (pin.animation == false) {
        pin.animation = true;
        gv_this.gv_microsoftmap.find("#" + pinname).css("zIndex", 999);
        gv_this.gv_microsoftmap.find("#" + pinname).effect("shake", { times: 3 }, 300, function() {
            gv_this.gv_microsoftmap.find("#" + pinname).css("zIndex", 1);
            pin.animation = false;
        });
    }
}

// Method to determine clustering algorithm.
BingMapv7.prototype.CalculateClusteredLatlong = function(cluster, key) {
    switch (gv_this.gv_cluster_placement) {
        case 0:
            var lat = 0, lon = 0;

            var i = cluster.length - 1;
            if (i >= 0) {
                do {
                    lat += cluster[i].la;
                    lon += cluster[i].lo;
                }
                while (i--);
            }

            return new Microsoft.Maps.Location(lat / cluster.length, lon / cluster.length);
        case 1:
            var x = ((key % gv_this.gv_x_cells) + 0.5) * gv_this.gv_grid_size + new Microsoft.Maps.Point(0, 0).x;
            var y = (Math.floor(key / gv_this.gv_x_cells) + 0.5) * gv_this.gv_grid_size + new Microsoft.Maps.Point(0, 0).y;

            return gv_this.gv_map.tryPixelToLocation(new Microsoft.Maps.Point(x, y), Microsoft.Maps.PixelReference.control);
        case 2:
            return new Microsoft.Maps.Location(cluster[0].la, cluster[0].lo);
        default:
        case 3:
            var location = null;

            if (cluster) {
                if (cluster.length > 1) {
                    var maxLat = -85;
                    var minLat = 85;
                    var maxLon = -180;
                    var minLon = 180;

                    for (var i = 0; i < cluster.length; i++) {
                        var c = cluster[i];
                        maxLat = Math.max(c.la, maxLat);
                        minLat = Math.min(c.la, minLat);
                        maxLon = Math.max(c.lo, maxLon);
                        minLon = Math.min(c.lo, minLon);
                    }

                    location = new Microsoft.Maps.Location((maxLat + minLat) / 2, (maxLon + minLon) / 2);
                }
                else {
                    location = new Microsoft.Maps.Location(cluster[0].la, cluster[0].lo);
                }
            }

            return location;
        case 4:
            var location = null;
            if (gv_this.gv_grid_cells[key]) {
                if (gv_this.gv_grid_cells[key].length > 1) {
                    var maxLat = -85;
                    var minLat = 85;
                    var maxLon = -180;
                    var minLon = 180;

                    for (var i = 0; i < gv_this.gv_grid_cells[key].length; i++) {
                        var c = gv_this.gv_grid_cells[key][i];

                        pixel = gv_this.gv_map.tryLocationToPixel(new Microsoft.Maps.Location(c.la, c.lo), Microsoft.Maps.PixelReference.control);

                        if (pixel != null && pixel.x <= gv_this.gv_map_Width && pixel.y <= gv_this.gv_map_Height && pixel.x >= 0 && pixel.y >= 0) {

                            k = Math.floor(pixel.x / gv_this.gv_grid_size);
                            j = Math.floor(pixel.y / gv_this.gv_grid_size);

                            ckey = k + j * gv_this.gv_x_cells;

                            if (ckey == key) {
                                maxLat = Math.max(c.la, maxLat);
                                minLat = Math.min(c.la, minLat);
                                maxLon = Math.max(c.lo, maxLon);
                                minLon = Math.min(c.lo, minLon);
                            }
                        }
                    }
                    location = new Microsoft.Maps.Location((maxLat + minLat) / 2, (maxLon + minLon) / 2);
                }
                else {
                    location = new Microsoft.Maps.Location(cluster[0].la, cluster[0].lo);
                }
            }
            return location;
    }
};

BingMapv7.prototype.GetLayer = function() {
    return gv_this.gv_layer;
};

BingMapv7.prototype.AddElement = function(array, element) {
    return jQuery.merge([element], array);
};

BingMapv7.prototype.ContainsElement = function(array, element) {
    if (jQuery.inArray(element, array) === -1) {
        return false;
    }
    else {
        return true;
    }
};

BingMapv7.prototype.RemoveElement = function(array, element) {
    return jQuery.grep(array, function(value) { return value !== element; });
};

BingMapv7.prototype.ComputeScreenDistance = function(p1, p2){
    return Math.sqrt((p1.x - p2.x) * (p1.x - p2.x) + (p1.y - p2.y) * (p1.y - p2.y));
}

BingMapv7.prototype.IsPointVisible = function(pixel) {
    if (pixel != undefined) {
        if (pixel != null) {
            if (pixel.x <= gv_this.gv_map_Width && pixel.y <= gv_this.gv_map_Height && pixel.x >= 0 && pixel.y >= 0) {
                return true;
            }
        }
    }
    return false;
}

BingMapv7.prototype.PinDistance = function(lat1, lon1, lat2, lon2) {
    var R = 6371; // kmvar
    dLat = (lat2 - lat1);
    var dLon = (lon2 - lon1).toRad();
    var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
        Math.cos(lat1.toRad()) * Math.cos(lat2.toRad()) *
        Math.sin(dLon / 2) * Math.sin(dLon / 2);
    var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
    var d = R * c;

    return gv_this.KiToMi(d);
};

BingMapv7.prototype.ClusterData = function() {
    if (gv_this.gv_data != null) {
        //var i = 0;
        var flag = false;
        var maxthreshhold = gv_this.gv_maxthreshhold;

        if (gv_this.gv_data != null) {
            if (gv_this.gv_data.length != null) {
                //i = (gv_this.gv_data.length)
                var pixel, k, j, key, pin;

                //if (i >= 0) {

                gv_this.gv_grid_cells = new Array;

                for (i = 0; i <= gv_this.gv_data.length; i++) {
                    if (gv_this.gv_data[i] != undefined) {
                        var Pixel = gv_this.gv_map.tryLocationToPixel(new Microsoft.Maps.Location(gv_this.gv_data[i].la, gv_this.gv_data[i].lo), Microsoft.Maps.PixelReference.control);
                        if ((Pixel != undefined) && (Pixel != null)) {
                            gv_this.gv_data[i].Pixel = Pixel;
                        }
                        if (gv_this.gv_data[i].Pixel != undefined && gv_this.gv_data[i].Pixel != null)
                            if (gv_this.IsPointVisible(gv_this.gv_data[i].Pixel)) {

                            gv_this.gv_data[i].Added = false;

                            for (index = 0; index < gv_this.gv_grid_cells.length; index++) {
                                var breakout = false;
                                if (gv_this.gv_grid_cells[index] != undefined) {
                                    for (pin = 0; pin < gv_this.gv_grid_cells[index].length; pin++) {
                                        var distance = gv_this.ComputeScreenDistance(gv_this.gv_data[i].Pixel, gv_this.gv_grid_cells[index][pin].Pixel);
                                        if (distance < maxthreshhold && gv_this.gv_data[index].Added == false) {
                                            gv_this.gv_grid_cells[index].push(gv_this.gv_data[i]);
                                            gv_this.gv_data[i].Added = true;
                                            breakout = true;
                                            break;
                                        }
                                    }
                                    if (breakout) {
                                        break;
                                    }
                                }
                            }

                            if (gv_this.gv_data[i].Added == false) {
                                if (gv_this.gv_grid_cells[i] == undefined) {
                                    gv_this.gv_grid_cells[i] = new Array();
                                    gv_this.gv_grid_cells[i].push(gv_this.gv_data[i]);
                                }
                            }
                        }
                    }
                }
            }
        }
    }
};

BingMapv7.prototype.Cluster = function() {
    var zoom = parseInt(gv_this.gv_map.getZoom());
    var flag = false;

    gv_this.gv_layer.clear();

    gv_this.gv_zoom = gv_this.gv_map.getZoom();

    if (gv_this.gv_data != null) {
        for (i = 0; i < gv_this.gv_grid_cells.length; i++) {
            if (gv_this.gv_grid_cells[null, null, null, i] != null) {
                switch (gv_this.gv_grid_cells[null, null, null, i].length) {
                    case 1:
                        pin = gv_this.AddPushPin(gv_this.gv_grid_cells[i][0].la, gv_this.gv_grid_cells[i][0].lo, "", false, gv_this.gv_grid_cells[i][0], i);
                        pin.isClustered = false;
                        break;
                    default:
                        pin = gv_this.AddClusterPushPin(gv_this.CalculateClusteredLatlong(gv_this.gv_grid_cells[i], i), "", false, gv_this.gv_grid_cells[i], i);
                        pin.isClustered = true;
                        break;
                }

                //pin.GridKey = i;

                gv_this.gv_layer.push(pin);

                gv_this.gv_microsoftmap.find("#" + pin.getId()).css("cursor", "pointer");
                gv_this.gv_microsoftmap.find("#" + pin.getId()).children("div").addClass("PushPinText");
            }
        }
    }
};

BingMapv7.prototype.SetZoom = function(value) {
    gv_this.gv_zoom = value;
};

//This disables control refreshes under Kentico forms
BingMapv7.prototype.SetKentico = function(value) {
    gv_this.gv_kentico = value;
};

BingMapv7.prototype.SetMaxThreshHold = function(value) {
    gv_this.gv_maxthreshhold = value;
};

BingMapv7.prototype.SetScaleBar = function(value) {
    gv_this.gv_show_scale_bar = value;
};

BingMapv7.prototype.GetLatitude = function() {
    return gv_this.gv_latitude;
};

BingMapv7.prototype.GetLongitude = function() {
    return gv_this.gv_latitude;
};

BingMapv7.prototype.SetLatitude = function(value) {
    gv_this.gv_latitude = value;
};

BingMapv7.prototype.SetDefaultLatitude = function(value) {
    gv_this.gv_default_latitude = value;
};

BingMapv7.prototype.SetLongitude = function(value) {
    gv_this.gv_longitude = value;
};

BingMapv7.prototype.SetDefaultLongitude = function(value) {
    gv_this.gv_default_longitude = value;
};

BingMapv7.prototype.SetCountry = function(value) {
    gv_this.gv_country = value;
};

BingMapv7.prototype.SetNodeAliasPath = function(value) {
    gv_this.gv_nodealiaspath = value;
};

BingMapv7.prototype.SetAddress = function(value) {
    gv_this.gv_address = value;
};

BingMapv7.prototype.SetCity = function(value) {
    gv_this.gv_city = value;
};

BingMapv7.prototype.SetState = function(value) {
    gv_this.gv_state = value;
};

BingMapv7.prototype.SetZip = function(value) {
    gv_this.gv_zip = value;
};

BingMapv7.prototype.SetLocate = function(value) {
    gv_this.gv_locate = value;
};

BingMapv7.prototype.SetWayPointA = function(value) {
    gv_this.gv_waypointa = value;
};

BingMapv7.prototype.SetPrint = function(value) {
    gv_this.gv_print = value;
};

BingMapv7.prototype.SetWayPointB = function(value) {
    gv_this.gv_waypointb = value;
};

BingMapv7.prototype.GetWayPointA = function(value) {
    return gv_this.gv_waypointa;
};

BingMapv7.prototype.GetWayPointB = function(value) {
    return gv_this.gv_waypointb;
};

BingMapv7.prototype.AddRoutePushPin = function(Latitude, Longitude, Icon, Draggable, PushPin, i) {
var pin = new Microsoft.Maps.Pushpin(new Microsoft.Maps.Location(Latitude, Longitude), { icon: "/App_Themes/DRHortonSite/images/pushpin_map2.png", textOffset: new Microsoft.Maps.Point(-1, 3), height: 28, width: 22, zIndex: 1, text: i.toString(), typeName: "PushPin PushPin_" + i.toString(), draggable: Draggable });

    pin.animation = false;
    pin.setId("PushPin_" + i.toString());
    pin.setPushPin(PushPin);
    pin.setPushPins(null);

    //Microsoft.Maps.Events.addHandler(pin, 'mouseover', gv_this.PinRouteMouseOver);

    return pin;
};

BingMapv7.prototype.AddDraggablePushPin = function(Latitude, Longitude, Icon, Draggable, PushPin, i) {
var pin = new Microsoft.Maps.Pushpin(new Microsoft.Maps.Location(Latitude, Longitude), { icon: "/App_Themes/DRHortonSite/images/pushpin_map2.png", textOffset: new Microsoft.Maps.Point(-1, 3), height: 28, width: 22, zIndex: 1, text: i.toString(), typeName: "PushPin PushPin_" + i.toString(), draggable: Draggable });

    pin.animation = false;
    pin.setId("PushPin_" + i.toString());
    pin.setPushPin(PushPin);
    pin.setPushPins(null);

    return pin;
};

BingMapv7.prototype.AddPushPin = function(Latitude, Longitude, Icon, Draggable, PushPin, i) {
var pin = new Microsoft.Maps.Pushpin(new Microsoft.Maps.Location(Latitude, Longitude), { icon: "/App_Themes/DRHortonSite/images/pushpin_map2.png", textOffset: new Microsoft.Maps.Point(-1, 3), height: 28, width: 22, zIndex: 1, text: "1", typeName: "PushPin PushPin_" + i.toString(), draggable: Draggable });

    pin.animation = false;
    pin.setId("PushPin_" + i.toString());
    pin.setPushPin(PushPin);
    pin.setPushPins(null);

    if (!Microsoft.Maps.Events.hasHandler(pin, 'mouseover')) {
        Microsoft.Maps.Events.addHandler(pin, 'mouseover', gv_this.PinMouseOver);
    }

    return pin;
};

BingMapv7.prototype.AddClusterPushPin = function(location, Icon, Draggable, PushPins, i) {
var pin = new Microsoft.Maps.Pushpin(location, { icon: "/App_Themes/DRHortonSite/images/pushpin_map2.png", textOffset: new Microsoft.Maps.Point(-1, 3), height: 28, width: 22, zIndex: 1, text: PushPins.length.toString(), typeName: "PushPin PushPin_" + i.toString(), draggable: Draggable });

    pin.animation = false;
    pin.setId("PushPin_" + i.toString());
    pin.setPushPin(null);
    pin.setPushPins(PushPins);

    if (!Microsoft.Maps.Events.hasHandler(pin, 'mouseover')) {
        Microsoft.Maps.Events.addHandler(pin, 'mouseover', gv_this.PinClusterMouseOver);
    }

    return pin;
};


BingMapv7.prototype.InfoBox = function(name) {
    // do not remove background-image:url(\".\") from box below IE BUG fix: transparent divs in ie do not capture mouse events..
    var script = "<div id='myInfobox" + name + "' style='padding-top:10px; visibility:hidden;border: none 1px black;position:absolute; top:0px; left:0px; width:260px; z-index:1000000; font-family:Arial; font-size:10px; height: 28px;cursor:pointer;padding:0px;background-image:url(\".\")'>";
    script = script + "<div id='infoboxText" + name + "' style='border: solid 1px black;background-color:White;display:block; min-height:100px; position:absolute; top:10px; left:25px; width:240px;overflow:hidden;'>";
    script = script + "<div style='line-height:20px;'><b id='infoboxTitle" + name + "' style='display:block;background-color:#002B56;color:white;position:absolute;top:2px;left:2px;width:236px;text-align:center;height:20px;overflow:hidden;'></b>";
    script = script + "</div>";
    script = script + "<a id='infoboxDescription" + name + "' style='position:absolute; top:30px; left:10px; width:220px;'></a>";
    script = script + "</div>";
    script = script + "</div>";
    return script;    
};

BingMapv7.prototype.CreateRouteInfoBox = function(shape, title, description) {
    var pushpin = shape.getPushPin();

    var pinname = shape.getId();

    $("body").append(gv_this.InfoBox(pinname));

    gv_this.gv_infobox = $("#myInfobox" + pinname);

    gv_this.gv_myinfobox = gv_this.gv_infobox;

    $(document).ready(function() {
        try {
            gv_this.gv_infobox.css({ width: '295px' });
            gv_this.gv_infobox.find("#infoboxText" + pinname).css({ height: '190px', width: '190px' });
            gv_this.gv_infobox.find("#infoboxTitle" + pinname).css({ width: '185px' });
            gv_this.gv_infobox.find("#infoboxDescription" + pinname).css({ width: '185px' });

            var pin = gv_this.gv_microsoftmap.find("." + pinname);
            var offset = pin.offset();

            gv_this.gv_infobox.find("#infoboxTitle" + pinname).html(title);
            gv_this.gv_infobox.find("#infoboxDescription" + pinname).html(description);
            gv_this.gv_infobox.css({ 'visibility': 'visible', 'top': offset.top + 'px', 'left': (parseFloat(offset.left) - 217).toString() + 'px' });
        } catch (e) { }
    });
};

BingMapv7.prototype.ShowRouteInfoBox = function(e) {
    var pin = e.target;

    var pinname = pin.getId();

    var pushpin = pin.getPushPin();

    gv_this.gv_myinfobox.css("visibility", "hidden");

    gv_this.gv_myinfobox.remove();

    gv_this.CreateRouteInfoBox(pin, "start", "address");

    gv_this.gv_microsoftmap.find("div[class^=PushPin_]").css("zIndex", 1);
    gv_this.gv_microsoftmap.find("div[class^=PushPin_] div").css("zIndex", 1);

    gv_this.gv_microsoftmap.find("." + pinname).css("zIndex", 2);
    gv_this.gv_microsoftmap.find("." + pinname + " div").css("zIndex", 2);

    if (gv_this.gv_infobox.length != 0) {
        gv_this.gv_infobox.mouseleave(function(e) {
            gv_this.gv_infobox.css("visibility", "hidden");
        });
    }
};

BingMapv7.prototype.CreateInfoBox = function(shape) {
    var pushpin = shape.getPushPin();

    var pinname = shape.getId();

    $("body").append(gv_this.InfoBox(pinname));

    gv_this.gv_infobox = $("#myInfobox" + pinname);

    gv_this.gv_myinfobox = gv_this.gv_infobox;

    $(document).ready(function() {
        try {
            gv_this.gv_infobox.css({ width: '350px' });
            gv_this.gv_infobox.find("#infoboxText" + pinname).css({ height: '150px', width: '300px' });
            gv_this.gv_infobox.find("#infoboxTitle" + pinname).css({ width: '296px' });
            gv_this.gv_infobox.find("#infoboxDescription" + pinname).css({ width: '296px' });

            var pin = gv_this.gv_microsoftmap.find("." + pinname);
            var offset = pin.offset();

            gv_this.gv_infobox.find("#infoboxTitle" + pinname).html(pushpin.nm);
            gv_this.gv_infobox.find("#infoboxDescription" + pinname).html("<div style=\"text-align:center;width:300px;\"><img src=\"/App_Themes/DRHortonSite/images/wait/wait30.gif\"></div><div style=\"text-align:center;width:300px;\">Loading Please Wait...</div>");
            gv_this.gv_infobox.css({ 'visibility': 'visible', 'top': offset.top + 'px', 'left': (parseFloat(offset.left) - 330).toString() + 'px' });
        } catch (e) { }
    });

    $.ajaxSetup({ cache: false });
    $.getJSON('/DRHorton/MapService.svc/communities/' + pushpin.id,
    function(json, textStatus) {
        gv_this.gv_community = json;
    }).success(
        function() {

            if (gv_this.gv_fillinbox == true) {
                return;
            }

            gv_this.gv_fillinbox = true;

            if (gv_this.gv_community == null) {
                return;
            }

            var details = "";
            var isQuickMoveIns = "";
            var title = "";

            if (gv_this.gv_community.a1 && gv_this.gv_community.a1 != null && gv_this.gv_community.a1.length > 0) {
                details += gv_this.gv_community.a1 + "<br />";
            }

            if (gv_this.gv_community.a2 && gv_this.gv_community.a2 != null && gv_this.gv_community.a2.length > 0) {
                details += gv_this.gv_community.a2 + "<br />";
            }

            details += gv_this.gv_community.c + ", " + gv_this.gv_community.s + "<br />";

            if (gv_this.gv_community.ph && gv_this.gv_community.ph != null && gv_this.gv_community.ph.length > 0) {
                details += "<br />" + gv_this.gv_community.ph + "<br />";
            }

            details += gv_this.gv_community.ht + "<br />";
            if (gv_this.gv_community.pw == "pleaseCall") {
                details += "Please Call<br />";
            }
            else {
                details += "Starting from the " + gv_this.gv_community.p + "<br />";
            }

            if (gv_this.gv_community.nm != null && gv_this.gv_community.nm.length > 0) {
                var pushpinImageUrl = "/App_Themes/DRHortonSite/images/image_not_available.png";
                if (gv_this.gv_community.tu != null && gv_this.gv_community.tu.length > 0) {
                    pushpinImageUrl = gv_this.gv_community.tu + "?width=125&height=100";
                }
                title = "<div class='pushpinImageWrapper'><a href='" + gv_this.gv_community.cu + "'><img class='pushpinImage' src='" + pushpinImageUrl + "' height='100' width='125'/></a></div>";
                title = title + "<a href='" + gv_this.gv_community.cu + "'>" + gv_this.gv_community.nm + "</a>";
                title = title + "<div class='pushpinDetailQMIWrapper'><div class='pushpinDetails'>" + details + "</div><div class='pushpinQMIs'>" + isQuickMoveIns + "</div></div>";
            }
            gv_this.gv_infobox.find("#infoboxDescription" + pinname).html(title);

            gv_this.gv_fillinbox = false;

        });
};

BingMapv7.prototype.ShowInfoBox = function(e) {
    var pin = e.target;

    var pinname = pin.getId();

    var pushpin = pin.getPushPin();

    gv_this.gv_myinfobox.css("visibility", "hidden");

    gv_this.gv_myinfobox.remove();

    gv_this.CreateInfoBox(pin);

    gv_this.gv_microsoftmap.find("div[id^=PushPin_]").css("zIndex", 1);
    gv_this.gv_microsoftmap.find("div[id^=PushPin_] div").css("zIndex", 1);

    gv_this.gv_microsoftmap.find("#" + pinname).css("zIndex", 2);
    gv_this.gv_microsoftmap.find("#" + pinname + " div").css("zIndex", 2);

    if (gv_this.gv_infobox.length != 0) {
        gv_this.gv_infobox.mouseleave(function(e) {
            gv_this.gv_infobox.css("visibility", "hidden");
        });
    }
};

BingMapv7.prototype.CreateClusterInfoBox = function(shape) {

    var pushpin = shape.getPushPin();

    var pinname = shape.getId();

    $("body").append(this.InfoBox(pinname));

    gv_this.gv_infobox = $("#myInfobox" + pinname);

    gv_this.gv_myinfobox = gv_this.gv_infobox;

    $(document).ready(function() {
        try {
            gv_this.gv_infobox.css({ width: '295px' });
            gv_this.gv_infobox.find("#infoboxText" + pinname).css({ height: '190px', width: '240px' });
            gv_this.gv_infobox.find("#infoboxTitle" + pinname).css({ width: '236px' });
            gv_this.gv_infobox.find("#infoboxDescription" + pinname).css({ width: '236px' });

            var pin = gv_this.gv_microsoftmap.find("." + pinname);
            var offset = pin.offset();

            gv_this.gv_infobox.find("#infoboxTitle" + pinname).html("Communities");
            gv_this.gv_infobox.find("#infoboxDescription" + pinname).html("<div style=\"text-align:center;width:240px;\"><img src=\"/App_Themes/DRHortonSite/images/wait/wait30.gif\"></div><div style=\"text-align:center;width:240px;\">Loading Please Wait...</div>");
            gv_this.gv_infobox.css({ 'visibility': 'visible', 'top': offset.top + 'px', 'left': (parseFloat(offset.left) - 270).toString() + 'px' });
        } catch (e) { }
    });

    var pushpins = shape.getPushPins();
    var divH = 190;

    var index = this.gv_layer.indexOf(shape);

    for (var j = 0; j < pushpins.length; ++j) {
        var kid = pushpins[j];
        var divLH = 13;

        var divH = (pushpins.length < 10) ? (divLH * pushpins.length) : 130;

        var anchors = "<ul class=\"paging\" style='position: relative; height: " + (divH) + "px;'><ol style='list-style-type: none'>";
        var communitiesCnt = "";

        for (i = 0; i < pushpins.length; i++) {
            var pushpin = pushpins[i];
            var communityname = pushpin.cn;
            if (pushpin.cn.length >= 40) {
                communityname = communityname.substring(0, 37) + "...";
            }

            anchors += "<li>" + (i + 1).toString() + ".&nbsp;<a href = '" + pushpin.url + "'>" + communityname + "</a></li>";
        }
    }

    anchors += "</ol></ul>";

    if (pushpins.length <= 10) {
        anchors += "<div style=\"height:30px\"></div>";
    }

    communitiesCnt = "<br /><div style='display:block;vertical-align:middle;text-align:center;width:230px;height:40px;'><img src='/App_Themes/DRHortonSite/images/magnifier.png' style='float:left;padding-left:5px;'><a href='#' onClick=\"gv_this.ZoomToPin('" + index + "', gv_this.gv_zoom);\" style='float:right;line-height:40px;padding-right:5px;'>" + "&nbsp;Zoom in on these {0} communities.".replace("{0}", pushpins.length) + "</a></div>";
    anchors += communitiesCnt;

    divH = (pushpins.length < 10) ? 120 + (divLH * pushpins.length) : 250

    $(document).ready(function() {
        gv_this.gv_infobox.find("#infoboxText" + pinname).css("height", divH + "px");
        gv_this.gv_infobox.find("#infoboxDescription" + pinname).html(anchors);
    });
};

BingMapv7.prototype.ShowClusterInfoBox = function(e) {
    var pin = e.target;

    var pinname = pin.getId();

    gv_this.gv_myinfobox.css("visibility", "hidden");

    gv_this.gv_myinfobox.remove()

    gv_this.CreateClusterInfoBox(pin);

    gv_this.Pager();

    gv_this.gv_microsoftmap.find("div[id^=PushPin_]").css("zIndex", 1);
    gv_this.gv_microsoftmap.find("div[id^=PushPin_] div").css("zIndex", 1);

    gv_this.gv_microsoftmap.find("#" + pinname).css("zIndex", 2);
    gv_this.gv_microsoftmap.find("#" + pinname + " div").css("zIndex", 2);

    if (gv_this.gv_infobox.length != 0) {
        gv_this.gv_infobox.mouseleave(function(e) {
            gv_this.gv_infobox.css("visibility", "hidden");
        });
    }
};

BingMapv7.prototype.HideInfobox = function(e) {
    var mapElem = gv_this.gv_map.getRootElement();

    if (e.targetType == "map") {
        mapElem.style.cursor = "pointer";
        gv_this.gv_myinfobox.css("visibility", "hidden");
        gv_this.gv_lostmouseposition = true;
    }
};

BingMapv7.prototype.MapViewChange = function(e) {
    var mapElem = gv_this.gv_map.getRootElement();
    if (e.targetType == "map") {
        mapElem.style.cursor = "pointer";
        gv_this.gv_myinfobox.css("visibility", "hidden");
    }
};

BingMapv7.prototype.CloseInfoBox = function() {
    if (gv_this.gv_infobox.length != 0) {
        gv_this.gv_infobox.css("visibility", "hidden");
    }
};

BingMapv7.prototype.PinMouseOver = function(e) {
    var pin = e.target;

    var pinname = pin.getId();

    gv_this.gv_lostmouseposition = false;

    $.doTimeout(pinname, 250, function() {
        if (gv_this.gv_lostmouseposition == false) {
            gv_this.ShowInfoBox(e);
        }
    }, false);
};

BingMapv7.prototype.PinClusterMouseOver = function(e) {
    var pin = e.target;

    var pinname = pin.getId();

    gv_this.gv_lostmouseposition = false;

    $.doTimeout(pinname, 250, function() {
        if (gv_this.gv_lostmouseposition == false) {
            gv_this.ShowClusterInfoBox(e);
        }
    }, false);
    //gv_this.ShowClusterInfoBox(e);
};

BingMapv7.prototype.PinRouteMouseOver = function(e) {
    gv_this.ShowRouteInfoBox(e);
};

BingMapv7.prototype.ReloadGrid = function() {
    if (secondtime == true && typeof (secondtime) !== 'undefined') {
        var north = gv_this.gv_map.getTargetBounds().getNorthwest();
        var south = gv_this.gv_map.getTargetBounds().getSoutheast();

        var top = north.latitude;
        var bottom = south.latitude;
        var left = north.longitude;
        var right = south.longitude;

        try {
            if ((gv_this.gv_kentico == false) && secondtime == true && typeof (secondtime) !== 'undefined') {
                RefreshControl(top, right, bottom, left);
            }
        } catch (e) { alert(e); };
    }
};

BingMapv7.prototype.TileComplete = function() {

    if (!Microsoft.Maps.Events.hasHandler(gv_this.gv_map.entities, 'entityadded')) {
        Microsoft.Maps.Events.addHandler(gv_this.gv_map.entities, 'entityadded', function(e) {
        });
    }

    if (!Microsoft.Maps.Events.hasHandler(gv_this.gv_map.entities, 'entitychanged')) {
        Microsoft.Maps.Events.addHandler(gv_this.gv_map.entities, 'entitychanged', function(e) {
        });
    }

    if (!Microsoft.Maps.Events.hasHandler(gv_this.gv_map.entities, 'entityremoved')) {
        Microsoft.Maps.Events.addHandler(gv_this.gv_map.entities, 'entityremoved', function(e) {
        });
    }

    if (!Microsoft.Maps.Events.hasHandler(gv_this.gv_map, 'viewchange')) {
        Microsoft.Maps.Events.addHandler(gv_this.gv_map, 'viewchange', gv_this.MapViewChange);
    }

    if (!Microsoft.Maps.Events.hasHandler(gv_this.gv_map, 'viewchangeend')) {
        Microsoft.Maps.Events.addThrottledHandler(gv_this.gv_map, 'viewchangeend', gv_this.SplitZoomPanEvent, 250);
    }

    if (!Microsoft.Maps.Events.hasHandler(gv_this.gv_map, 'mousemove')) {
        Microsoft.Maps.Events.addHandler(gv_this.gv_map, 'mousemove', gv_this.HideInfobox);
    }

    if (!Microsoft.Maps.Events.hasHandler(gv_this.gv_map, 'mouseup')) {
        Microsoft.Maps.Events.addHandler(gv_this.gv_map, 'mouseup', function() { gv_this.gv_mousedown = false; gv_this.SplitZoomPanEvent(); });
    }

    if (!Microsoft.Maps.Events.hasHandler(gv_this.gv_map, 'mousedown')) {
        Microsoft.Maps.Events.addHandler(gv_this.gv_map, 'mousedown', function() { gv_this.gv_mousedown = true; });
    }

    if (gv_this.gv_lock == true) {
        if (gv_this.gv_microsoftmap.find("#navbar_icon").length == 0) {
            gv_this.gv_microsoftmap.find(".NavBar_zoomContainer").after("<br /><span id='navbar_icon' style='position:relative;float:left;display:inline-block;vertical-align:middle;line-height:29px;width:30px;margin:0 3px;cursor:pointer;'><img src='/App_Themes/Default/images/map_locked.png' onclick=\"gv_this.Lock();\"></span>");
            gv_this.gv_microsoftmap.find("#navbar_icon").click(function() {
                gv_this.Lock();
            });
        }
    }
    if (gv_this.gv_lock == false) {
        //gv_this.MapServiceLocationByPoint(gv_this.gv_default_latitude, gv_this.gv_default_longitude);
    }
};

BingMapv7.prototype.MapServiceLocationByPoint = function(latitude, longitude) {
    var return_value = null;
    $.ajaxSetup({ cache: false });
    $.getJSON('/DRHorton/MapService.svc/location/' + latitude.toString() + "/" + longitude.toString(),
    function(json, textStatus) {
        return_value = json;
    }).success(
    function() {
        if (gv_this.gv_microsoftmap.find("#navbar_custom").length == 0) {
            gv_this.gv_microsoftmap.find(".NavBar_compassContainer").before("<div id='navbar_custom' style='position:relative;float:left;display:inline-block;vertical-align:middle;line-height:29px;width:300px;margin:0 3px'>" + return_value + "</div>");
            gv_this.gv_microsoftmap.find(".NavBar_top").css('width', '800px');
            gv_this.gv_microsoftmap.find(".NavBar_compassContainer").css({ 'position': 'relative', 'float': 'left' });
            gv_this.gv_microsoftmap.find(".NavBar_zoomContainer").css({ 'position': 'relative', 'float': 'left' });
            gv_this.gv_microsoftmap.find(".NavBar_typeButtonContainer").css({ 'position': 'relative', 'float': 'left' });
        }
    });
};

BingMapv7.prototype.EntityAdded = function(e) {
    // not implemented
};

// Zoom to pin using the pin index.
BingMapv7.prototype.ZoomToPin = function(index, zoom) {
    try {
        var pin = gv_this.gv_layer.get(index);
        
        if (gv_credentials == 'undefined') {
            alert("undefined");
        }

        var pushpins = pin.getPushPins();
        var pushpin = pin.getPushPin();

        var options = gv_this.gv_map.getOptions();

        if (pushpins) {
            if (pushpins.length > 1) {
                var maxLat = -85;
                var minLat = 85;
                var maxLon = -180;
                var minLon = 180;

                for (var i = 0; i < pushpins.length; i++) {
                    var pushpin = pushpins[i];
                    maxLat = Math.max(pushpin.la, maxLat);
                    minLat = Math.min(pushpin.la, minLat);
                    maxLon = Math.max(pushpin.lo, maxLon);
                    minLon = Math.min(pushpin.lo, minLon);
                }

                options.center = new Microsoft.Maps.Location(
				(maxLat + minLat) / 2,
				(maxLon + minLon) / 2
			);

                var zoom1 = 0;
                var zoom2 = 0;
                if ((maxLon != minLon) && (maxLat != minLat)) {
                    zoom1 = Math.log(360 / 256 * gv_this.gv_map.getWidth() / (maxLon - minLon)) / Math.log(2);
                    zoom2 = Math.log(180 / 256 * gv_this.gv_map.getHeight() / (maxLat - minLat)) / Math.log(2);
                }

                var zoom3 = Math.round(Math.min(zoom1, zoom2));
                if (zoom3 != 0) {
                    options.zoom = zoom3;
                } else {
                    try {
                        options.zoom = gv_this.gv_map.getTargetZoom() + 1;
                    } catch (err) {
                        options.zoom = gv_this.gv_map.getTargetZoom();
                    }
                }

            } else if (l == 1) {
                options.center = new Microsoft.Maps.Location(pushpins[0].la, pushpins[0].lo);
            }

            gv_this.CloseInfoBox();
        }
        else {
            var newlocation = new Microsoft.Maps.Location(pushpin.la, pushpin.lo);
            
            options.center = newlocation;
            
            options.zoom = zoom;            
        }
        gv_this.gv_map.setView(options);        
    }
    catch (err) {
    }
};

BingMapv7.prototype.AddListener = function(type, listener) {
    if (typeof gv_this.gv_listeners[type] == "undefined") {
        gv_this.gv_listeners[type] = [];
    }

    gv_this.gv_listeners[type].push(listener);
};

BingMapv7.prototype.Fire = function(event) {
    if (typeof event == "string") {
        event = { type: event };
    }
    if (!event.target) {
        event.target = this;
    }

    if (!event.type) {
        throw new Error("Event object missing 'type' property.");
    }

    if (gv_this.gv_listeners[event.type] instanceof Array) {
        var listeners = gv_this.gv_listeners[event.type];
        for (var i = 0, len = listeners.length; i < len; i++) {
            listeners[i].call(this, event);
        }
    }
};

BingMapv7.prototype.RemoveListener = function(type, listener) {
    if (gv_this.gv_listeners[type] instanceof Array) {
        var listeners = gv_this.gv_listeners[type];
        for (var i = 0, len = listeners.length; i < len; i++) {
            if (listeners[i] == listener) {
                listeners.splice(i, 1);
                break;
            }
        }
    }
};

// Reverse lookup using res service.
BingMapv7.prototype.LocationByPoint = function(latitude, longitude, callback1, callback2) {
    var url = "http://dev.virtualearth.net/REST/v1/Locations"

    gv_this.gv_location_result = null;

    url += "/" + latitude.toString() + "," + longitude.toString();
    url += "?key=" + gv_credentials;

    $.ajax
            ({
                url: url,
                dataType: "jsonp",
                data: {},
                jsonp: "jsonp",
                success: function(result) {
                    callback1(result);
                },
                complete: function() {
                    callback2();
                }
            });
};

// Lookup location using rest service.
BingMapv7.prototype.Location = function(country, address, city, state, zip, locate, callback) {
    var url = "http://dev.virtualearth.net/REST/v1/Locations"

    gv_this.gv_location_result = null;

    if (country == null) {
        url += "?countryRegion=US";
    } else {
        url += "?countryRegion=" + country;
    }
    if (state != null) {
        url += "&adminDistrict=" + state;
    }
    if (city != null) {
        url += "&locality=" + city;
    }
    if (zip != null) {
        url += "&postalCode=" + zip;
    }
    if (address != null) {
        url += "&addressLine=" + address;
    }
    url += "&key=" + gv_credentials;

    if (locate == true) {
        $.ajax
            ({
                url: url,
                dataType: "jsonp",
                data: {},
                jsonp: "jsonp",
                success: function(result) {
                    callback(result);
                }
            });
    }
    else {
        callback(null);
    }
};

// Calculate a route between two way points..
BingMapv7.prototype.Route = function(callback) {
    var url = "http://dev.virtualearth.net/REST/v1/Routes?wp.0=" + escape(gv_this.gv_waypointa) + "&wp.1=" + escape(gv_this.gv_waypointb) + "&routePathOutput=Points&output=json&key=" + gv_credentials;
    $.ajax
    ({
        url: url,
        dataType: "jsonp",
        data: {},
        jsonp: "jsonp",
        success: function(result) {
            var routediv = $("#" + gv_this.gv_options.routediv);
            routediv.html("");

            gv_this.gv_layer.clear();
            gv_this.gv_map.entities.push(gv_this.gv_layer);

            if (result &&
                   result.resourceSets &&
                   result.resourceSets.length > 0 &&
                   result.resourceSets[0].resources &&
                   result.resourceSets[0].resources.length > 0) {

                var rrr = result.resourceSets[0].resources[0];
                var rl = rrr.routeLegs[0];

                var bbox = rrr.bbox;

                var items = rl.itineraryItems;
                var written = "Total&nbsp;Distance:&nbsp;(" + gv_this.KiToMi(rl.travelDistance).toString() + "mi)<br /><br />";

                written += "<ol id=\"routeul\">"
                for (var i = 0, len = items.length; i < len; i++) {
                    written += "<li>" + items[i].instruction.text + " (" + gv_this.KiToMi(items[i].travelDistance).toString() + " mi)</li>"
                }
                written += "</ol>";

                var start = rl.startLocation;

                if (start.confidence.toLowerCase() != "high") {
                    return;
                }

                gv_this.gv_waypointa = start.name.toString();

                var pina = gv_this.AddRoutePushPin(start.point.coordinates[0], start.point.coordinates[1], null, false, [], "A");

                var end = rl.endLocation;

                gv_this.gv_waypointb = end.name.toString();

                var pinb = gv_this.AddRoutePushPin(end.point.coordinates[0], end.point.coordinates[1], null, false, [], "B");

                if (gv_this.gv_options != null) {
                    if (gv_this.gv_options.routediv) {
                        routediv.html(written);
                        routediv.show();
                    }
                }

                var viewBoundaries = Microsoft.Maps.LocationRect.fromLocations(new Microsoft.Maps.Location(bbox[0], bbox[1]), new Microsoft.Maps.Location(bbox[2], bbox[3]));
                gv_this.gv_map.setView({ bounds: viewBoundaries });

                var routeline = rrr.routePath.line;
                var routepoints = new Array();

                for (var i = 0; i < routeline.coordinates.length; i++) {
                    routepoints[i] = new Microsoft.Maps.Location(routeline.coordinates[i][0], routeline.coordinates[i][1]);
                }

                var routeshape = new Microsoft.Maps.Polyline(routepoints, { strokeColor: new Microsoft.Maps.Color(200, 0, 0, 200) });

                gv_this.gv_layer.clear();
                gv_this.gv_layer.push(routeshape);
                gv_this.gv_layer.push(pina);
                gv_this.gv_layer.push(pinb);
                gv_this.gv_map.entities.push(gv_this.gv_layer);
            }
        },
        complete: function() {
            if (callback && typeof (callback) === "function") {
                callback();
            }
        },
        error: function() {
            //
        }
    });
};

// Convert Kilometers to Miles.
BingMapv7.prototype.KiToMi = function(value) {
    var value = (value / 16.1) * 10;
    return (Math.round(value * 100) / 100);
};

// Lock Map.
BingMapv7.prototype.Lock = function() {
    var messagediv = "<div id=\"MapLockedMsg\" style=\"z-index:100;font-family: Verdana;font-weight:bold;font-size: 12px;font-variant:small-caps;cursor: pointer;\">The map is currently locked.<br /><br />Click here to un-lock.<br /><br /><span style=\"font-size: 10px\">To lock the map use the lock icon located at the top left corner of the map under the map controls.</span></div>";
    gv_this.gv_mapdiv.block({ baseZ: 100, message: messagediv, css: { padding: '10px', width: '300px', height: '125px', backgroundColor: '#953030', color: '#fbfbfb', textAlign: 'center' }, overlayCSS: { backgroundColor: '#FAF7F5', opacity: 0.6} });

    $('.blockUI').corner();

    gv_this.gv_microsoftmap.find("#navbar_icon img").attr("src", "/App_Themes/Default/images/map_locked.png");

    $('#MapLockedMsg').bind('click', function() {
        gv_this.Unlock();
    });
};

// Unlock Map.
BingMapv7.prototype.Unlock = function() {
    gv_this.gv_microsoftmap.find("#navbar_icon img").attr("src", "/App_Themes/Default/images/map_unlocked.png");
    gv_this.gv_mapdiv.unblock();
};

BingMapv7.prototype.Pager = function(options) {

    var defaults = {
        pageSize: 10,
        currentPage: 1,
        holder: ""
    };
    var options = $.extend(defaults, options);
    var myinfobox = gv_this.gv_myinfobox;
    var selector = myinfobox.find("ul.paging ol");
    var totalRecords = myinfobox.find("ul.paging ol").children().length;
    var pageCounter = 1;

    selector.children().each(function(i) {
        if (i < pageCounter * options.pageSize && i >= (pageCounter - 1) * options.pageSize) {
            $(this).addClass("page" + pageCounter);
        }
        else {
            $(this).addClass("page" + (pageCounter + 1));
            pageCounter++;
        }
    });

    selector.children().hide();

    myinfobox.find(".page" + options.currentPage).show();

    myinfobox.find("ul.paging .pageNav").remove();

    if (pageCounter > 1) {

        var pageNav = "<br /><div class=\"pageNav\" style='text-align:center;'>";
        pageNav += "<span class=\"PreviousPage2\" style=\"display:inline;\"><font color=\"grey\">&larr; Previous</font></span><span class=\"PreviousPage\" style=\"display:none;\"><a rel=\"1\" href=\"#\" style=\"text-decoration:none\">&larr; Previous</a></span>&nbsp;|&nbsp;";
        pageNav += "<span class=\"NextPage2\" style=\"display:none;\"><font color=\"grey\">Next &rarr;</font></span><span class=\"NextPage\"><a rel=\"2\" href=\"#\" style=\"text-decoration:none\">Next &rarr;</a></span>";
        pageNav += "</div>";

        if (options.holder == "") {
            myinfobox.find("ul.paging").after(pageNav);
        }
        else {
            myinfobox.find("ul.paging").append(pageNav);
        }

        myinfobox.find(".pageNav .NextPage a").bind("click", { myinfobox: myinfobox }, function(e) {

            var clickedLink = e.data.myinfobox.find(".pageNav .NextPage a").attr("rel");

            options.currentPage = clickedLink;

            e.data.myinfobox.find(".pageNav .PreviousPage a").attr("rel", parseInt(options.currentPage) - 1);

            if (options.currentPage == 1) {
                e.data.myinfobox.find(".pageNav .PreviousPage2").show();
                e.data.myinfobox.find(".pageNav .PreviousPage").hide();
            } else {
                e.data.myinfobox.find(".pageNav .PreviousPage2").hide();
                e.data.myinfobox.find(".pageNav .PreviousPage").show();
            }

            e.data.myinfobox.find(".pageNav .NextPage a").attr("rel", parseInt(options.currentPage) + 1);

            if (options.currentPage == pageCounter) {
                e.data.myinfobox.find(".pageNav .NextPage2").show();
                e.data.myinfobox.find(".pageNav .NextPage").hide();
            } else {
                e.data.myinfobox.find(".pageNav .NextPage2").hide();
                e.data.myinfobox.find(".pageNav .NextPage").show();
            }

            selector.children().hide();
            selector.find(".page" + clickedLink).show();
            return false;
        });

        myinfobox.find(".pageNav .PreviousPage a").bind("click", { myinfobox: myinfobox }, function(e) {

            var clickedLink = e.data.myinfobox.find(".pageNav .PreviousPage a").attr("rel");

            options.currentPage = clickedLink;

            e.data.myinfobox.find(".pageNav .PreviousPage a").attr("rel", parseInt(options.currentPage) - 1);

            if (options.currentPage == 1) {
                e.data.myinfobox.find(".pageNav .PreviousPage2").show();
                e.data.myinfobox.find(".pageNav .PreviousPage").hide();
            } else {
                e.data.myinfobox.find(".pageNav .PreviousPage2").hide();
                e.data.myinfobox.find(".pageNav .PreviousPage").show();
            }

            e.data.myinfobox.find(".pageNav .NextPage a").attr("rel", parseInt(options.currentPage) + 1);

            if (options.currentPage == pageCounter) {
                e.data.myinfobox.find(".pageNav .NextPage2").show();
                e.data.myinfobox.find(".pageNav .NextPage").hide();
            } else {
                e.data.myinfobox.find(".pageNav .NextPage2").hide();
                e.data.myinfobox.find(".pageNav .NextPage").show();
            }

            selector.children().hide();
            selector.find(".page" + clickedLink).show();
            return false;
        });
    }
};





