﻿function round(value, decimals, roundUp)
{
    if (roundUp)
        return Math.ceil(value*Math.pow(10,decimals))/Math.pow(10,decimals);
    else
        return Math.round(value*Math.pow(10,decimals))/Math.pow(10,decimals);
}

$(function() {
    function DealerLocator(divElement) {
        this.divElement = divElement;
        this.key = $('#bingKey').text();
        this.map = null;
        this.mapDiv = $('#mapDiv');
        this.defaultZoomLevel = 17;
        this.userPin = null;
        this.userInfobox = null;
        this.lastVisibleInfobox = null;
        this.lastDealerPin = null;
        this.lastClickedDealerElement = null;
        this.lastShownDealerID = null;
        this.dealerDirectionIndex = null;
        this.userLocation = null;
        this.data = $('div.data');
        this.dealerDataElement = $('#dealerData');
        this.dealerData = this.dealerDataElement.find('div.dealer');
        this.dealerPins = new Array();
        this.dealerLocations = new Array();
        this.dealerHTML = new Array();
        this.dealerPinPool = new Array();
        this.itineraryPin = null;
        this.pinOffOption = null;
        this.pinOnOption = null;
        this.largeOffset = new Microsoft.Maps.Point(30, 40);
        this.smallOffset = new Microsoft.Maps.Point(27, 40);
        this.dealerInfoboxOffset = this.largeOffset;
        this.dealerInfobox = null;
        this.directionManager = null;
        this.directionStartLocation = null;
        this.directionEndLocation = null;
        this.userPinURL = $('#userPushPin').text();
        this.smallPinURL = $('#logoSmall').text();
        this.smallPinHoverURL = $('#logoSmallHover').text();
        this.largePinURL = $('#logoLarge').text();
        this.largePinHoverURL = $('#logoLargeHover').text();
        this.itineraryPinURL = $('#itineraryPin').text();
        this.findDealerButton = $('#findDealerButton');
        this.locationElement = $('#locationInput');
        this.lastAddress = $('#userLocation').text();
        this.maxResults = $('#maxResults').text();
        this.maxPanResults = $('#maxPanResults').text();
        this.maxRadius = $('#maxRadius').text();
        this.langSpecificColon = $('#langSpecificColon').text();
        this.directionsToHereText = $('#directionsToHereText').text();
        this.locationHelp = $('#locationHelp').text();
        this.visitWebsiteText = $('#visitWebsiteText').text();
        this.goText = $('#goText').text();
        this.minText = $('#minText').text();
        this.viaText = $('#viaText').text();
        this.removeText = $('#removeText').text();
        this.infoArea = divElement.find('div.InfoArea');
        this.dealerSideElement = $('#dealerDiv');
        this.directionsSideElement = $('#directionDiv');
        this.directionsContentElement = $('#directionsContent');
        this.tabButton = $('#tabButton');
        this.showDealerButton = $('#showDealerButton');
        this.dealerShadowTop       = $('#dealerShadowTop');
        this.dealerShadowBottom    = $('#dealerShadowBottom');
        this.directionShadowTop    = $('#directionShadowTop');
        this.directionShadowBottom = $('#directionShadowBottom');
        this.animationDuration = 500;
        this.customInfobox = null;
        this.areDealersLoaded = false;
        this.isFirstGeocode   = false;
        this.IsUserLocated    = false;
        this.isDoingBoundPan  = false;
        this.isDoingZoom      = false;
        this.isResizing       = false;
        this.isViewChanging   = false;
        this.isShowingFullMap = false;
        this.directionsModuleLoaded = false;
        this.isRouting = false;
        this.isShowingDirections = false;
        this.isDoingPanSearch = false;
        this.ignoreDealerPan = false;
        this.isInfoboxHovering = false;
        this.infoboxEnterHandler = null;
        this.infoboxLeaveHandler = null;
        this.ajaxRequest = null;
        this.distanceAjaxRequest = null;
        
        this.smallPinOptions = {
            anchor:new Microsoft.Maps.Point(17, 30),
            height:35,
            icon:this.smallPinURL,
            width:34,
            zIndex:0
        };
        this.smallPinHoverOptions = {
            anchor:new Microsoft.Maps.Point(18, 31),
            height:37,
            icon:this.smallPinHoverURL,
            width:36,
            zIndex:0
        }
        this.largePinOptions = {
            anchor:new Microsoft.Maps.Point(20.5, 37),
            height:42,
            icon:this.largePinURL,
            width:41,
            zIndex:0
        }
        this.largePinHoverOptions = {
            anchor:new Microsoft.Maps.Point(21.5, 38),
            height:44,
            icon:this.largePinHoverURL,
            width:43,
            zIndex:0
        }
        this.itineraryOptions = {
            anchor:new Microsoft.Maps.Point(11, 11),
            icon:this.itineraryPinURL,
            textOffset:new Microsoft.Maps.Point(-1, 3),
            visible:false,
            zIndex:2
        }
        
        var that = this;
        this.ShowInfobox = function(e) {
            that.ShowInfoboxHandler(e);
        };
        this.HideInfobox = function(e) {
            that.HideInfoboxHandler(e);
        };
        this.findDealerButton.click(function() {
            that.FindNearestDealers();
        });
        this.locationElement.focus(function() {
            if (that.locationElement.val() == that.locationHelp) {
                that.locationElement.val('');
            }
            
            $(this).parent().parent().addClass('active');
            $(this).data('focused', true);
        });
        this.locationElement.blur(function() {
            $(this).parent().parent().removeClass('active');
            $(this).data('focused', false);
        });
        this.locationElement.keypress(function(e) {
            if ($(this).data('focused') != true)
                return false;
            
            if (e.which == 13) {
                that.FindNearestDealers();
                return false;
            }
        });
        this.tabButton.click(function() {
            if (that.isResizing)
                return;
            
            that.Resize();
        });
        this.showDealerButton.click(function() {
            that.ShowDealers();
        });
        this.infoArea.data('initialWidth', parseInt(this.infoArea.width()));
        this.tabButton.data('initialLeft', parseInt(this.tabButton.css('left')));
        this.dealerSideElement.data('initialWidth', parseInt(this.dealerSideElement.width()));
        this.directionsSideElement.data('initialWidth', parseInt(this.directionsSideElement.width()));
        this.mapDiv.data('initialWidth', parseInt(this.mapDiv.css('width')));
        //this.directionsSideElement.width(0);
        //this.directionsSideElement.hide();
        this.directionsSideElement.show();
        this.directionsSideElement.fadeOut(0);

        
        this.pinOffOptions = this.largePinOptions;
        this.pinOnOptions  = this.largePinHoverOptions;
        
        var initLat = parseFloat($('#userLat').text());
        var initLng = parseFloat($('#userLng').text());
        var initLocation = new Microsoft.Maps.Location(initLat, initLng);
        this.userLocation = initLocation;

        var mapOptions = {
            credentials:this.key,
            mapTypeId:Microsoft.Maps.MapTypeId.auto,
            center:initLocation,
            zoom:this.defaultZoomLevel,
            enableClickableLogo:false,
            enableSearchLogo:false
        };
        this.map = new Microsoft.Maps.Map(this.mapDiv[0], mapOptions);
        Microsoft.Maps.Events.addThrottledHandler(this.map, 'viewchange', function() { that.FindPannedDealers(); }, 1000);
        Microsoft.Maps.Events.addHandler(this.map, 'viewchangestart', function() { that.ViewChangeStartHandler(); });
        Microsoft.Maps.Events.addHandler(this.map, 'viewchangeend', function() { that.ViewChangeEndHandler(); });
        Microsoft.Maps.Events.addHandler(this.map, 'mousedown', function(e) { that.MouseDownHandler(e); });
  
        Microsoft.Maps.loadModule('Microsoft.Maps.Directions', {
                callback:function() {
                    that.directionsModuleLoaded = true;
                    that.directionManager = new Microsoft.Maps.Directions.DirectionsManager(that.map);
                    
                    Microsoft.Maps.Events.addHandler(that.directionManager, 'directionsError', function(e) {
                        that.GetDirectionsErrorHandler(e);
                    });
                    Microsoft.Maps.Events.addHandler(that.directionManager, 'directionsUpdated', function() {
                        that.GetDirectionsCompleteHandler();
                    });
                }
        });
        
        if (Math.abs(initLat) > 0 && Math.abs(initLng) > 0) {
            if (this.lastAddress != this.locationHelp)
                this.IsUserLocated = true;
            
            this.userLocation = new Microsoft.Maps.Location(initLat, initLng);
            this.userPin = new Microsoft.Maps.Pushpin(initLocation, {
                height:31,
                width:23,
                icon:this.userPinURL,
                anchor:new Microsoft.Maps.Point(3, 32),
                zIndex:1
            });
            
            var userInfoboxOptions = {
                height:40,
                htmlContent:'<div class="customInfoBox">' + $('#userLocation').text() + '</div>',
                location:initLocation,
                offset:new Microsoft.Maps.Point(12, -22),
                visible:false,
                zIndex:2
            };
            // offset:new Microsoft.Maps.Point(15, 10),
            this.userInfobox = new Microsoft.Maps.Infobox(initLocation, userInfoboxOptions);
            this.map.entities.push(this.userInfobox);
            this.userPin.setInfobox(this.userInfobox);

            Microsoft.Maps.Events.addHandler(this.userPin, 'mouseover', this.ShowInfobox);
            Microsoft.Maps.Events.addHandler(this.userPin, 'mouseout', this.HideInfobox);
            this.map.entities.push(this.userPin);
        }
        
        var dealerOptions = {
            offset:this.dealerInfoboxOffset,
            visible:false
        };
        this.dealerInfobox = new Microsoft.Maps.Infobox(initLocation, dealerOptions);
        this.map.entities.push(this.dealerInfobox);
        
        if (this.dealerData.length > 0) {
            this.areDealersLoaded = true;
            
            var index = 0;
            this.dealerData.each(function() {
                index++;
                var id = parseInt($(this).find('div.id').text());
                var dealerName = $(this).find('div.name').text();
                var address1 = $(this).find('div.address1').text();
                var address2 = $(this).find('div.address2').text();
                if (address2 == undefined)
                    address2 = '';
                var city = $(this).find('div.city').text();
                var province = $(this).find('div.province').text();
                var provinceCode = $(this).find('div.provinceCode').text();
                var postalCode = $(this).find('div.postalCode').text();
                var url = $(this).find('div.URL').text();
                var phone = $(this).find('div.phone').text();
                var fax = $(this).find('div.fax').text();
                var distance = $(this).find('div.distance').text();

                var lat = parseFloat($(this).find('div.latitude').text());
                var lng = parseFloat($(this).find('div.longitude').text());
                var location = new Microsoft.Maps.Location(lat, lng);
                var options = $.extend({}, that.pinOffOptions);
                var dealerPin = new Microsoft.Maps.Pushpin(location, options);

                dealerPin.data('id', id);
                dealerPin.data('index', index);
                dealerPin.addShowInfoboxHandler(that.ShowInfobox);
//                dealerPin.addHideInfoboxHandler(that.HideInfobox);
                that.map.entities.push(dealerPin);

                var dealerContent = {
                    id:id,
                    index:index,
                    dealerName:dealerName,
                    url:url,
                    address1:address1,
                    address2:address2,
                    city:city,
                    provinceCode:provinceCode,
                    postalCode:postalCode,
                    phone:phone,
                    fax:fax,
                    distance:distance
                };
                var htmlContent = that.GenerateDealerContent(dealerContent);
                that.dealerHTML.push({
                    id:id,
                    html:htmlContent});
                /*
                var dealerOptions = {
                    htmlContent:htmlContent,
                    location:location,
                    offset:that.dealerInfoboxOffset,
                    visible:false
                };

                var infobox = new Microsoft.Maps.Infobox(location, dealerOptions);
                that.map.entities.push(infobox);
                dealerPin.setInfobox(infobox);
                */
                
                that.dealerPins.push(dealerPin);
                that.dealerLocations.push(location);
            });
            
            this.InitializeDealers();
        }
        else {
            this.map.setView({zoom:3});
            this.Resize();
        }
        
        this.locationElement.val(this.lastAddress);
        this.BoundMapViewToDealers();
        this.dealerSideElement.animate({scrollTop:top}, 0);
        this.ShowDealerShadows();
    };
    
    DealerLocator.prototype = {
        InitializeDealers:function() {
            var foundLastShownDealerID = false;
            var that = this;
            
            var index = 0;
            this.dealerSideElement.find('div.dealerSideInfo').each(function() {
                index++;
                var anchorName = $(this).find('a').text();
                var id = null;
                var lat = 0;
                var lng = 0;
                
                that.dealerDataElement.find('div.dealer').each(function() {
                    var dealerName = $(this).find('div.name').text();
                    if (dealerName == anchorName) {
                        id = parseInt($(this).find('div.id').text());
                        lat = parseFloat($(this).find('div.latitude').text());
                        lng = parseFloat($(this).find('div.longitude').text());
                        
                        return false;
                    }
                });
                
                var pin = null;
                $.each(that.dealerPins, function() {
                    var dealerPin = $(this)[0];
                    var location = dealerPin.getLocation();
                    if (location.latitude == lat && location.longitude == lng) {
                        pin = dealerPin;
                        return false;
                    }
                });

                if (pin != null) {
                    $(this).data('pushpin', pin);
                    
                    pin.data('id', id);
                    pin.data('dealerSideInfo', $(this));
                }
                
                $(this).data('id', id);
                $(this).find('div.directions').data('index', index);
                
                that.AddDealerHandlers($(this));
                if (that.lastShownDealerID != null && id != null && that.lastShownDealerID == id) {
                    $(this).click();
                    foundLastShownDealerID = true;
                }
            });
            
            $('div.directions').click(function() {
                var index = $(this).data('index');
                var lastDealerDirectionIndex = that.dealerDirectionIndex;
                if (lastDealerDirectionIndex == index - 1) {
                    that.dealerSideElement.fadeOut(this.animationDuration);
                    that.directionsSideElement.fadeIn(this.animationDuration);
                    return false;
                }
                
                var location = that.dealerLocations[index-1];
                var dealerPin = that.dealerPins[index-1];
                
                that.dealerDirectionIndex = index - 1;
                that.GetDirections(location, dealerPin);
                return false;
            });

            if (!foundLastShownDealerID)
                this.lastShownDealerID = null;
        },
        ShowDealerInfobox:function(dealerPushpin) {
            if (dealerPushpin == null || dealerPushpin == undefined || this.map == null || this.map == undefined)
                return;
            
            /*
            var infobox = dealerPushpin.getInfobox();
            if (infobox == null || infobox == undefined)
                return;
            */
            var infobox = this.dealerInfobox;
            infobox.setLocation(dealerPushpin.getLocation());
            
            var that = this;
            this.infoboxEnterHandler = Microsoft.Maps.Events.addHandler(infobox, 'mouseenter', function() {
                that.isInfoboxHovering = true;
            });
            this.infoboxLeaveHandler = Microsoft.Maps.Events.addHandler(infobox, 'mouseleave', function() {
                that.isInfoboxHovering = false;
            });
            
            var pinPixelPos = this.map.tryLocationToPixel(infobox.getLocation(), Microsoft.Maps.PixelReference.viewport);
            
            var showingOnBottom = false;
            var showingOnRight = false;
            var arrowClass = '';
            var dealerClass = '';
            if (pinPixelPos.y <= 0) {
                arrowClass += 'top';
                dealerClass += '';
            }
            else {
                arrowClass += 'bottom';
                dealerClass += 'bottom';
                showingOnBottom = true;
            }
            if (pinPixelPos.x <= 0) {
                arrowClass += ' left';
                dealerClass += '';
            }
            else {
                arrowClass += ' right';
                dealerClass += ' right';
                showingOnRight = true;
            }
            
            var index = dealerPushpin.data('index');
            var id = dealerPushpin.data('id');
            //var htmlContent = this.dealerHTML[index-1];
            var htmlContent = '';
            $.each(this.dealerHTML, function() {
                var dealer = $(this)[0];
                if (dealer.id == id) {
                    htmlContent = dealer.html;
                    return false;
                }
            });
            htmlContent = htmlContent.replace(/dealerInfoBox[^"]*"/i, 'dealerInfoBox ' + dealerClass + '"');
            htmlContent = htmlContent.replace(/class="arrow[^"]*"/i, 'class="arrow ' + arrowClass + '"');
            htmlContent = htmlContent.replace(/value=""/, 'value="' + this.locationElement.val() + '"');
            var options = infobox.getOptions();
            options.htmlContent = htmlContent;
            /*
//            var pinAnchor = this.pinOnOptions.anchor;
            var newOffset = new Microsoft.Maps.Point(this.dealerInfoboxOffset.x, 0);
            newOffset.x = this.dealerInfoboxOffset.x;
            if (showingOnBottom)
                newOffset.y = -15;
            else
                newOffset.y = 0;//-this.dealerInfoboxOffset.y - pinAnchor.y;
            options.offset = newOffset;
            */
            
            infobox.setOptions(options);
            infobox.show();
            
            var infoboxDiv = $('div.customInfoBox.dealerInfoBox');
            var parentDiv = infoboxDiv.parent().parent();
            if (showingOnBottom || showingOnRight) {
                var offset = infobox.getOptions().offset;
                if (showingOnBottom) {
                    //infoboxDiv.css('margin-top', -1 * infoboxDiv.height() + offset.y + 15); 
                }
                if (showingOnRight) {
//                    infoboxDiv.css('left', -1 * infoboxDiv.width() - offset.x * 2);
                    var deltaLeft = -1 * infoboxDiv.width() - offset.x * 2;
                    parentDiv.css('left', parseFloat(parentDiv.css('left')) + deltaLeft); 
                }
            }
            
            var pushpinElement = dealerPushpin.getElement();
            var newTop = parseInt($(pushpinElement).css('top'));
            if (showingOnBottom)
                newTop -= infoboxDiv.height() - 19*2 - 15;
            else
                newTop -= 5;
            parentDiv.css('top',newTop);
            
            var goDirectionsButton = $('div.goDirections');
            var inputLocation = $('#startLocation');
            inputLocation.click(function() {
                $(this).focus();
                return false;
            });
            inputLocation.focus(function() {
                if ($(this).data('focused') != true) {
                    $(this).parent().parent().addClass('active');
                    $(this).data('focused', true);
                }
            });
            inputLocation.blur(function() {
                $(this).parent().parent().removeClass('active');
                $(this).data('focused', false);
            });
            inputLocation.keypress(function(e) {
                if ($(this).data('focused') != true)
                    return false;
                
                if (e.which == 13) {
                    goDirectionsButton.click();
                    return false;
                }
            });
            
            var customInfobox = $('div.customInfoBox');
            customInfobox.find('div.close').click(function() {
                if (that.lastClickedDealerElement != null)
                    that.lastClickedDealerElement.click();
            });
            
            var location = dealerPushpin.getLocation();
            goDirectionsButton.click(function() {
                var lastDealerDirectionIndex = that.dealerDirectionIndex;
                for (var i = 0; i < that.dealerPins.length; i++) {
                    if (that.dealerPins[i] == dealerPushpin) {
                        that.dealerDirectionIndex = i;
        
                        break;
                    }
                }
                if (lastDealerDirectionIndex == that.dealerDirectionIndex) {
                    that.dealerSideElement.fadeOut(this.animationDuration);
                    that.directionsSideElement.fadeIn(this.animationDuration);
                    return false;
                }
                
                
                that.GetDirections(location, dealerPushpin, $('#startLocation').val());
            });
            
        },
        HideDealerPin:function(dealerPin) {
            if (dealerPin == null || dealerPin == undefined)
                return;
            
            $('div.customInfoBox div.close').unbind();
            $('div.goDirections').unbind();
            
            var options = $.extend({}, this.pinOffOptions);
            dealerPin.setOptions(options);   

            /*
            dealerPin.hideInfobox();
            */
            
            var infobox = this.dealerInfobox;//dealerPin.getInfobox();
            
            if (infobox != null) {
                infobox.hide();
                Microsoft.Maps.Events.removeHandler(this.infoboxEnterHandler);
                Microsoft.Maps.Events.removeHandler(this.infoboxLeaveHandler);
                this.infoboxEnterHandler = null;
                this.infoboxLeaveHandler = null;
            }
        },
        ShowInfoboxHandler:function(e) {
            if (this.lastVisibleInfobox != null)
                return;
            
            if (e.targetType == 'pushpin') {
                var dealerIndex = $.inArray(e.target, this.dealerPins);
                
                if (e.target == this.userPin) {
                    this.lastVisibleInfobox = e.target.getInfobox();
                    e.target.showInfobox();                    
                }
                else if (this.dealerPins.length > 0 && dealerIndex >= 0) {
                    if (this.lastDealerPin != null) {
                        this.HideDealerPin(this.lastDealerPin);
                        
                        if (this.lastClickedDealerElement != null)
                            this.lastClickedDealerElement.click();
                    }
                    
                    this.ShowDealerInfobox(e.target);
                    this.lastDealerPin = e.target;
                    var options = $.extend({}, this.pinOnOptions);
                    options.visible = true;
                    this.lastDealerPin.setOptions(options);
                    
                    var dealerSideInfo = this.lastDealerPin.data('dealerSideInfo');
                    if (dealerSideInfo != null) {
                        this.ignoreDealerPan = true;
                        
                        var top = dealerSideInfo[0].offsetTop;
                        this.dealerSideElement.animate({scrollTop:top}, 'slow');
                        
                        dealerSideInfo.click();
                    }
                }
            }
        },
        HideInfoboxHandler:function(e) {
            if (this.lastVisibleInfobox != null)
                this.lastVisibleInfobox.hide();
            
            this.lastVisibleInfobox = null;
        },
        FindNearestDealers:function() {
            var address = this.locationElement.val();
            if (address == this.lastAddress)
                return;
            
            if (!(/Canada/i).test(address))
                address += ', Canada';

            if (this.ajaxRequest != null)
                this.ajaxRequest.abort();
            
            var request = "http://dev.virtualearth.net/REST/v1/Locations/" + address + "?output=json&key=" + this.key + '&jsonp=?';
            
            this.ajaxRequest = $.ajax({
                type:'GET',
                url:request,
                dataType:'json',
                success:this.GeocodeHandler,
                context:this
            });
        },
        GeocodeHandler:function(data) {
            this.ajaxRequest = null;

            if (data == null || data == undefined)
                return;
            if (data.resourceSets == null || data.resourceSets == undefined)
                return;
            
            var gcAddress = null;
            var geocodedResults = data.resourceSets[0].resources;
            $.each(geocodedResults, function() {
                var result = $(this)[0];
                if (result.address != null && result.address.countryRegion == "Canada") {
                    gcAddress = $(this)[0];
                    return false;
                }
            });
            
            if (gcAddress != null) {
                this.IsUserLocated = true;
                
                this.locationElement.val(gcAddress.address.formattedAddress);
                this.lastAddress = gcAddress.address.formattedAddress;

                if (this.lastAddress != this.locationHelp)
                    this.isFirstGeocode = true;

                
                this.userLocation = new Microsoft.Maps.Location(gcAddress.point.coordinates[0], gcAddress.point.coordinates[1]);
                this.userPin.setLocation(this.userLocation);
                this.userInfobox.setLocation(this.userLocation);
                this.userInfobox.setOptions({
                    htmlContent:'<div class="customInfoBox">' + gcAddress.address.formattedAddress + '</div>',
                    location:this.userLocation
                });
                var options = this.userInfobox.getOptions();
                
                this.FindDealers(this.maxResults);
            }
        },
        FindDealers:function(maxResults, useCenter) {
            if (this.ajaxRequest != null)
                this.ajaxRequest.abort();
            
            var url = '/Map/DealerFeed.aspx?latitude=';
            if (useCenter) {
                var center = this.map.getCenter()
                url += round(center.latitude, 3, true) + '&longitude=' + round(center.longitude, 3, true);
                url += '&startLatitude=' + this.userLocation.latitude + '&startLongitude=' + this.userLocation.longitude;
            }
            else
                url += this.userLocation.latitude + '&longitude=' + this.userLocation.longitude; 
            url += '&maxRadius=' + this.maxRadius + '&numResults=' + maxResults;
            var that = this;
            this.ajaxRequest = $.ajax({
                type:'GET',
                url:url,
                dataType:'xml',
                success:that.FindDealerHandler,
                context:that
            });
        },
        FindDealerHandler:function(data) {
            this.ajaxRequest = null;
            
            this.dealerInfobox.hide();
            var that = this;
            this.dealerPinPool = new Array();
            $.each(this.dealerPins, function() {
                var pin = $(this)[0];
//                pin.hideInfobox();
                pin.removeShowInfoboxHandler();
                pin.removeHideInfoboxHandler();
//                that.map.entities.remove(pin.getInfobox());
                that.map.entities.remove(pin);
                that.dealerPinPool.push(pin);
            });
            
            if (!this.isDoingPanSearch && this.lastClickedDealerElement != null)
                this.lastClickedDealerElement.click();
            
            this.HideInfoboxHandler();
            this.lastVisibleInfoBox = null;
//            this.lastDealerPin = null;
            this.lastClickedDealerElement = null;
            this.dealerDataElement.empty();
            this.dealerSideElement.empty();
            this.dealerPins = new Array();
            this.dealerLocations = new Array();
            this.dealerHTML = new Array();
            var that = this;
            var dealerData = '';
            var dealerSide = '';
            var index = 0;

            var dealerDataObj = this.ParseDealerData(data);
            $.each(dealerDataObj, function() {
                var dealer = $(this)[0];
                var location = new Microsoft.Maps.Location(dealer.lat, dealer.lng);
                var options = $.extend({}, that.pinOffOptions);
                
                var dealerPin = null;
                if (dealer.index-1 < that.dealerPinPool.length) {
                    dealerPin = that.dealerPinPool[dealer.index-1];
                    dealerPin.setLocation(location);
                }
                else
                    dealerPin = new Microsoft.Maps.Pushpin(location, options);
                dealerPin.data('id', dealer.id);
                dealerPin.data('index', dealer.index);
                dealerPin.addShowInfoboxHandler(that.ShowInfobox);
//                dealerPin.addHideInfoboxHandler(that.HideInfobox);
                that.map.entities.push(dealerPin);
                that.dealerPins.push(dealerPin);
                that.dealerLocations.push(location);
                
                var htmlContent = that.GenerateDealerContent(dealer);
                that.dealerHTML.push({
                    id:dealer.id,
                    html:htmlContent});
            
                dealerData += '<div class="dealer"><div class="id">' + dealer.id + '</div>';
                dealerData += '<div class="name">' + dealer.dealerName + '</div>';
                dealerData += '<div class="address1">' + dealer.address1 + '</div>';
                dealerData += '<div class="address2">' + dealer.address2 + '</div>';
                dealerData += '<div class="city">' + dealer.city + '</div>';
                dealerData += '<div class="province">' + dealer.province + '</div>';
                dealerData += '<div class="provinceCode">' + dealer.provinceCode + '</div>';
                dealerData += '<div class="postalCode">' + dealer.postalCode + '</div>';
                dealerData += '<div class="URL">' + dealer.url + '</div>';
                dealerData += '<div class="phone">' + dealer.phone + '</div>';
                dealerData += '<div class="fax">' + dealer.fax + '</div>';
                dealerData += '<div class="latitude">' + dealer.lat + '</div>';
                dealerData += '<div class="longitude">' + dealer.lng + '</div>';
                dealerData += '<div class="distance">' + dealer.distance + '</div>';
                dealerData += '</div>';
                
                dealerSide += '<div class="dealerSideInfo"><div class="topDealerBorder"></div>';
                dealerSide += '<div class="midDealerBorder">';
                dealerSide += '<div class="dealerLeft inlineBlock"><div class="logo"></div>';
                dealerSide += '<div class="distance">' + dealer.distance + ' km</div></div>';
                dealerSide += '<div class="inlineBlock"><div class="title"><div class="number inlineBlock">' + dealer.index + '.</div><div class="inlineBlock"><a href="' + dealer.url + '" target="_blank">' + dealer.dealerName + '</a></div></div>';
                dealerSide += '<div class="info">';
                dealerSide += '<div>' + dealer.address1 + '</div>';
                if (dealer.address2 != '')
                    dealerSide += '<div>' + dealer.address2 + '</div>';
                dealerSide += '<div>' + dealer.city + ', ' + dealer.provinceCode + ' ' + dealer.postalCode + '</div>';
                dealerSide += '<div>T' + that.langSpecificColon + ' ' + dealer.phone + '</div>';
                dealerSide += '<div>F' + that.langSpecificColon + ' ' + dealer.fax + '</div>';
                dealerSide += '<div><div class="directions"><div class="directionsLeft inlineBlock"></div><div class="directionsMid inlineBlock">' + that.directionsToHereText + 
                    '<div class="directionsArrow inlineBlock"></div></div><div class="directionsRight inlineBlock"></div></div></div>';
                dealerSide += '</div>';
                dealerSide += '</div></div>';
                dealerSide += '<div class="bottomDealerBorder"></div></div>';
            });
            this.dealerDataElement.append($(dealerData));
            this.dealerSideElement.append($(dealerSide));
            
            this.InitializeDealers();
//            this.map.entities.push(this.userInfobox);
//            this.map.entities.push(this.userPin);
            
            if (dealerDataObj.length <= this.maxResults)
                this.BoundMapViewToDealers();
            
            this.areDealersLoaded = true;
            if (this.isShowingFullMap && this.isFirstGeocode)
                this.Resize();
            this.isFirstGeocode = false;
            
            if (this.distanceAjaxRequest != null)
                this.distanceAjaxRequest.abort();

            var url = '/Map/DealerFeed.aspx?latitude=';
            var center = this.map.getCenter()
            url += round(center.latitude, 3, true) + '&longitude=' + round(center.longitude, 3, true);
            url += '&startLatitude=' + round(this.userLocation.latitude, 3, true) + '&startLongitude=' + round(this.userLocation.longitude, 3, true);
            url += '&maxRadius=' + this.maxRadius + '&numResults=' + this.maxPanResults + '&drivingDistance=Y';
            this.distanceAjaxRequest = $.ajax({
                type:'GET',
                url:url,
                dataType:'xml',
                success:this.FindDealerDistanceHandler,
                context:this
            });
        },
        ParseDealerData:function(data) {
            // For IE7/8
            var dealerDataObj = new Array();
            var index = 0;

            var dealers = $(data).find('marker');
            if (dealers.length <= 0)
                return dealerDataObj;
            
            var that = this;
            $(dealers).each(function() {
                index++;
                var id = $(this).attr('id');
                var dealerName = $(this).attr('name');
                var address1 = $(this).attr('address1');
                var address2 = $(this).attr('address2');
                if (address2 == undefined)
                    address2 = '';
                var city = $(this).attr('city');
                var province = $(this).attr('province');
                var provinceCode = $(this).attr('provinceCode');
                var postalCode = $(this).attr('postalCode');
                var url = $(this).attr('href');
                var phone = $(this).attr('phone');
                var fax = $(this).attr('fax');
                var distance = $(this).attr('distance');

                var lat = parseFloat($(this).attr('latitude'));
                var lng = parseFloat($(this).attr('longitude'));
                
                dealerDataObj.push({
                    index:index,
                    id:parseInt(id),
                    dealerName:dealerName,
                    address1:address1,
                    address2:address2,
                    city:city,
                    province:province,
                    provinceCode:provinceCode,
                    postalCode:postalCode,
                    url:url,
                    phone:phone,
                    fax:fax,
                    distance:distance,
                    lat:lat,
                    lng:lng
                });
            });
            
            return dealerDataObj;
        },
        FindDealerDistanceHandler:function(data) {
            this.distanceAjaxRequest = null;
            this.isDoingPanSearch = false;

            var dealerDataObj = this.ParseDealerData(data);
            var that = this;
            var sideInfo = $('div.dealerSideInfo');
            for (var i = 0; i < dealerDataObj.length; i++) {
                var dealer = dealerDataObj[i];
                sideInfo.each(function() {
                    if ($(this).data('id') == dealer.id) {
                        $(this).find('div.distance').text(dealer.distance + ' km');
                        return false;
                    }
                });
                
                //var dealerIDRegex = new RegExp(dealer.id);
                var id = dealer.id;
                for (var j = 0; i < that.dealerHTML.length; j++) {
                    var data = that.dealerHTML[j];
                    if (data.id == id) {
                        var htmlContent = data.html;
                        htmlContent = htmlContent.replace(/"distance">.+km/i, '"distance">' + dealer.distance + ' km');
                        data.html = htmlContent;
                        break;
                    }
                    /*    
                    var htmlContent = that.dealerHTML[j];
                    if (dealerIDRegex.test(htmlContent)) {
                        htmlContent = htmlContent.replace(/"distance">.+km/i, '"distance">' + dealer.distance + ' km');
                        that.dealerHTML[j] = htmlContent;
                        break;
                    }*/
                }
            }
        },
        GenerateDealerContent:function(dealerData) {
            var htmlContent = '<div class="arrow"></div>';
            htmlContent += '<div class="displayHidden">' + dealerData.id + '</div>';
            htmlContent += '<div class="close"></div>';
            htmlContent += '<div class="top"></div>';
            htmlContent += '<div class="middle"><div class="title"><div class="number inlineBlock">' + dealerData.index + '.</div><div class="inlineBlock"><span class="name">' + dealerData.dealerName + '</span></div></div></div>';
            htmlContent += '<div class="website middle"><a target="_blank" href="' + dealerData.url + '">' + this.visitWebsiteText + '</a></div>';
            htmlContent += '<div class="info middle">';
            htmlContent += '<div>' + dealerData.address1 + '</div>';
            if (dealerData.address2 != '' && dealerData.address2 != undefined)
                htmlContent += '<div>' + dealerData.address2 + '</div>';
            htmlContent += '<div>' + dealerData.city + ', ' + dealerData.provinceCode + ' ' + dealerData.postalCode + '</div>';
            htmlContent += '<div>T' + this.langSpecificColon + ' ' + dealerData.phone + '</div>';
            htmlContent += '<div>F' + this.langSpecificColon + ' ' + dealerData.fax + '</div>';
            htmlContent += '<div class="distance">' + dealerData.distance + ' km</div>';
            htmlContent += '<div class="directions"><div class="inlineBlock inputDiv"><div class="inputLeft inlineBlock"></div><div class="inputMiddle inlineBlock"><input id="startLocation" value="" type="text" /></div><div class="inputRight inlineBlock"></div></div>';
            htmlContent += '<div class="goDirections inlineBlock"><div class="blueLeft inlineBlock"></div><div class="blueMid inlineBlock">' + this.goText + '</div><div class="blueRight inlineBlock"></div></div></div>';
            htmlContent += '</div>';
            htmlContent += '<div class="bottom"></div>';
            
            
            return '<div class="customInfoBox dealerInfoBox">' + htmlContent  + '</div>';
        },
        FindPannedDealers:function() {
            if (this.isResizing)
                return;
            
            if (this.IsUserLocated && !this.isDoingBoundPan && !this.isDoingZoom && !this.isRouting && this.isViewChanging) {
            console.log('view change');
                this.isDoingPanSearch = true;

                if (this.distanceAjaxRequest != null)
                    this.distanceAjaxRequest.abort();

                this.FindDealers(this.maxPanResults, true);
            }
        },
        AddDealerHandlers:function(divElement) {
            if (divElement == null || divElement.length <= 0)
                return;
            
            var that = this;
            divElement.click(function(e) {
                var selectedClass = 'selected';

                if (that.lastClickedDealerElement != null) {
                    if (that.lastClickedDealerElement.data('id') != $(this).data('id'))
                        that.lastClickedDealerElement.click();
                }
                
                var dealerClass = $(this).attr('class');
                var pin = $(this).data('pushpin');
                                
                if ((/selected/i).test(dealerClass)) {
                    $(this).removeClass(selectedClass);
                    if (pin != null) {
                        that.HideDealerPin(pin);
                    }

                    that.isInfoboxHovering = false;
                    that.lastClickedDealerElement = null;
                    that.lastShownDealerID = null;
                    that.lastDealerPin = null;
                }
                else {
                    $(this).addClass(selectedClass);
                    if (pin != null) {
                        if (that.lastDealerPin != null)
                            that.lastDealerPin.hideInfobox();
                        
                        var options = $.extend({}, that.pinOnOptions);
                        pin.setOptions(options);
                        
                        that.ShowDealerInfobox(pin);
                        
                        that.lastDealerPin = pin;
                        that.lastShownDealerID = pin.data('id');

                        if (!that.ignoreDealerPan) {
                            var mapBounds = that.map.getBounds();
                            var pinLocation = pin.getLocation();
                            if (!mapBounds.contains(pinLocation))
                            {
                                that.isDoingBoundPan = true;
                                that.map.setView({
                                    center:pinLocation
                                });
                            }
                        }
                    }
                    
                    that.ignoreDealerPan = false;
                    that.lastClickedDealerElement = $(this);
                }
            });
            
        },
        GetDirections:function(location, dealerPin, address) {
            if (this.lastClickedDealerElement != null)
                this.lastClickedDealerElement.click();

            if (this.directionManager == null)
                return;
            
            this.directionManager.resetDirections();
            this.directionManager.setRenderOptions({
//                itineraryContainer: $('#directionsContent')[0],
                displayManeuverIcons:false,
                lastWaypointIcon:"/Content/7907/Media/General/WebImage/2011/DealerLocator/pushpinLogo-med.png",
                waypointPushpinOptions:{zIndex:20}
            });
            
            this.isRouting = true;
            
            if (address == undefined)
                address = this.locationElement.val();
            
            var start;
            if (address == this.lastAddress)
                start = new Microsoft.Maps.Directions.Waypoint({
                    location:this.userLocation,
                    pushpin:this.userPin
                });
            else
                start = new Microsoft.Maps.Directions.Waypoint({
                    address:address,
                    pushpin:this.userPin
                });
            var end = new Microsoft.Maps.Directions.Waypoint({
                location:location,
                pushpin:dealerPin
            });
            this.directionStartLocation = null;
            this.directionEndLocation = location;
            
            this.directionManager.addWaypoint(start);
            this.directionManager.addWaypoint(end);
            
            this.directionManager.calculateDirections();
        },
        GetDirectionsCompleteHandler:function() {
            this.isDoingBoundPan = true;
            
            var that = this;
            /*
            this.dealerSideElement.animate({width:'0px'}, {
                duration:that.animationDuration,
                easing:"easeInOutCubic",
                complete:function() {
//                    that.dealerSideElement.hide();
                }
            });
            this.directionsSideElement.show();
            if (!this.isShowingDirections)
                this.directionsSideElement.width(0);
            this.directionsSideElement.animate({width:this.directionsSideElement.data('initialWidth')}, {
                duration:that.animationDuration
            });
            */
            this.dealerSideElement.fadeOut(this.animationDuration);
            this.directionsSideElement.fadeIn(this.animationDuration);
            
            this.isShowingDirections = true;
            
            var route = this.directionManager.getRouteResult();
            if (route == null)
                return;

            var leg = route[0].routeLegs;
            if (leg.length <= 0)
                return;
            leg = leg[0];
            
            /*
            var distance = round(leg.summary.distance, 1) + ' km';
            var time = round(parseInt(leg.summary.time) / 60, 0);
            
            var info = '<div>' + this.lastAddress + '</div><div>' + distance + ' - ' + time + ' ' + this.minText + '</div>';
            var userInfo = $('div.waypointDisplayText:first');
//            userInfo.empty();
            userInfo.append($(info));
            userInfo.find('#directionDivWaypointText1').hide();
            
            var data = this.dealerData[this.dealerDirectionIndex];
            if (data != null && data != undefined) {
                var dealerName = '<div>' + $(data).find('div.name').text() + '</div>';
                
                var userInfo = $('div.waypointDisplayText:last');
                userInfo.append($(dealerName));
                userInfo.find('#directionDivWaypointText2').hide();
            }
            */                  
            /*
            var waypoints = this.directionManager.getAllWaypoints();
            return;


            console.log(leg);
            console.log(leg.summary);*/
            
            if (this.itineraryPin == null) {
                var startLocation = this.userLocation;
                if (leg.itineraryItems[0] != null && leg.itineraryItems[0].coordinate != null)
                    startLocation = leg.itineraryItems[0].coordinate;
                
                this.itineraryPin = new Microsoft.Maps.Pushpin(startLocation, {
                    visible:false
                });
                this.map.entities.push(this.itineraryPin);
            }
            
            var viaDiv = '';
            var waypoints = this.directionManager.getAllWaypoints();
            if (waypoints.length > 2) {
                for (var i = 1; i < waypoints.length-1; i++) {
                    viaDiv += '<div>';
                    viaDiv += '<span class="via">' + this.viaText + ' ' + waypoints[i].getAddress() + '</span>';
                    viaDiv += '<a href="#" class="via" waypointIndex="' + i + '">' + this.removeText + '</a>';
                    viaDiv += '</div>';
                }
            }
            
            var isIE7 = $.browser.msie && $.browser.version < 8;
            
            this.directionsContentElement.empty();
            var directionHTML = '';
            
            var distance = round(leg.summary.distance, 1) + ' km';
            var time = round(parseInt(leg.summary.time) / 60, 0) + ' ' + this.minText;
            directionHTML += '<div class="waypoint alignTop"><img src="/Content/7907/Media/General/WebImage/2011/DealerLocator/userPushpin.png" />';
            directionHTML += '<div class="inlineBlock waypointDesc alignTop"><div>' + this.lastAddress + '</div>';
            directionHTML += '<div>' + distance + ' - ' + time + '</div>' + viaDiv + '</div></div>';

            directionHTML += '<div class="directionItinerary">';
            for (var i = 0; i < leg.itineraryItems.length; i++) {
                var item = leg.itineraryItems[i];
                directionHTML += '<div class="directionItineraryItem" index="' + i + '">';
                directionHTML += '<div class="itineraryTop"></div>';
                directionHTML += '<div class="itineraryMiddle">';
                directionHTML += '<div class="bullet">' + (i+1) + '.</div>';
                var instruction = item.formattedText;
                instruction = instruction.replace(/<action>(.*)<\/action>(.*)$/gi, '<span class="instruction">$1</span>$2');
                instruction = instruction.replace(/<[^>]*RoadName>|<[^>]*TurnDir>|<[^>]*Toward>|<[^>]*WayPointName>/gi, '');
                instruction = instruction.replace(/<\/span>(.*)$/i, '</span><span class="address">$1</span>');
                instruction = '<div>' + instruction + '</div>';
                
                var distanceHTML = '';
                var distance = item.distance;
                if (distance > 0) {
                    if (distance < 0.1)
                        distance = distance * 1000 + ' m';
                    else
                        distance = distance + ' km';
                    distanceHTML += '<div class="distance">' + distance + '</div>';
                }
                if (isIE7)
                    directionHTML += distanceHTML;
                
                directionHTML += '<div class="instruction">' + instruction + '</div>';
                var hints = '';
                for (var j = 0; j < item.preIntersectionHints.length; j++)
                    hints += item.preIntersectionHints[j] + '. ';
                for (var j = 0; j < item.postIntersectionHints.length; j++)
                    hints += item.postIntersectionHints[j] + '. ';
                if (hints != '')
                    directionHTML += '<div class="hint">' + hints + '</div>';
                
                if (!isIE7)
                    directionHTML += distanceHTML;
                
                directionHTML += '</div>';
                directionHTML += '<div class="itineraryBottom"></div>';
                directionHTML += '</div>';
            }
            directionHTML += '</div>';

            var data = this.dealerData[this.dealerDirectionIndex];
            if (data != null && data != undefined) {
                var dealerName = $(data).find('div.name').text();
                directionHTML += '<div class="waypoint"><img src="/Content/7907/Media/General/WebImage/2011/DealerLocator/pushpinLogo-med.png" />';
                directionHTML += '<div class="inlineBlock waypointDesc alignTop">' + dealerName + '</div>';
            }
            
            this.directionsContentElement.append($(directionHTML));
            var itineraryElements = this.directionsContentElement.find('div.directionItineraryItem');
            itineraryElements.hover(function() {
                    that.ItineraryOverHandler($(this));
                },
                function() {
                    that.ItineraryOutHandler();
                }
            );
            itineraryElements.click(function() {
                that.ItineraryClickHandler($(this));
            });
            this.directionsContentElement.find('a.via').click(function() {
                that.RemoveViaWaypoint($(this).attr('waypointindex'));
                return false;
            });
            
            this.HideDealerShadows();
            this.ShowDirectionShadows();
//            alert('done directions');
        },
        GetDirectionsErrorHandler:function(e) {
            this.isRouting = false;
        },
        RemoveViaWaypoint:function(index) {
            this.directionManager.removeWaypoint(parseInt(index));
            this.directionManager.calculateDirections();
        },
        ItineraryOverHandler:function(element) {
            var route = this.directionManager.getRouteResult();
            if (route == null)
                return;
            
            var leg = route[0].routeLegs;
            if (leg.length <= 0)
                return;
            leg = leg[0];
            
            var index = parseInt(element.attr('index'));
            if (index < 0 || index > leg.itineraryItems.length - 1)
                return;
            var directionStep = leg.itineraryItems[index];
            var location = directionStep.coordinate;

            if (this.itineraryPin == null) {
                this.itineraryPin = new Microsoft.Maps.Pushpin(location);
                this.map.entities.push(this.itineraryPin);
            }
            this.itineraryPin.setLocation(location);
            var options = $.extend({}, this.itineraryOptions);
            options.visible = true;
            options.text = "" + (index+1);
            this.itineraryPin.setOptions(options);
        },
        ItineraryOutHandler:function() {
            this.itineraryPin.setOptions({visible:false});
        },
        ItineraryClickHandler:function(element) {
            this.isRouting = true;
            
            if (this.map == null)
                return;
            
            var route = this.directionManager.getRouteResult();
            if (route == null)
                return;
            
            var leg = route[0].routeLegs;
            if (leg.length <= 0)
                return;
            leg = leg[0];
            
            var index = parseInt(element.attr('index'));
            if (index < 0 || index > leg.itineraryItems.length - 1)
                return;
            
            var targetCenter = leg.itineraryItems[index].coordinate;

            var locations = new Array();
            if (index < 2) {
                for (var i = 0; i < leg.itineraryItems.length && i < 3; i++) {
                    locations.push(leg.itineraryItems[i].coordinate);
                }
            }
            else if (index > leg.itineraryItems.length - 3) {
                for (var i = leg.itineraryItems.length - 1; Math.abs(leg.itineraryItems.length - 1 - i) < 3; i--) {
                    locations.push(leg.itineraryItems[i].coordinate);
                }
            }
            else {
                locations.push(leg.itineraryItems[index-1].coordinate);
                locations.push(leg.itineraryItems[index].coordinate);
                locations.push(leg.itineraryItems[index+1].coordinate);
            }
            
            var bound = Microsoft.Maps.LocationRect.fromLocations(locations);
            this.map.setView({
                bounds:bound,
                center:targetCenter
            });
            
            var options = this.map.getOptions();
            options.zoom = this.map.getTargetZoom();
            this.map.setView(options);
        },
        BoundMapViewToDealers:function() {
            this.isDoingBoundPan = true;
            
            var locations = new Array();
            if (this.userLocation != null)
                locations.push(this.userLocation);
            $.each(this.dealerLocations, function() {
                locations.push($(this)[0]);
            });
            var bound = Microsoft.Maps.LocationRect.fromLocations(locations);
            this.map.setView({bounds:bound});
            
            var options = this.map.getOptions();
            options.zoom = this.map.getTargetZoom();
            options.center = this.userLocation;
            this.map.setView(options);
        },
        ViewChangeStartHandler:function() {
            console.log('view change start');
            this.isViewChanging = true;
            
            if (this.map.getZoom() != this.map.getTargetZoom())
                this.isDoingZoom = true;
        },
        ViewChangeEndHandler:function() {
            console.log('view change end');
            this.isViewChanging = false;
            
            if (this.isDoingZoom && !this.isRouting) {
                var currentZoom = this.map.getTargetZoom();
                if (currentZoom > 8)
                {
                    this.pinOnOptions  = this.largePinHoverOptions;
                    this.pinOffOptions = this.largePinOptions;
                    
                    this.dealerInfoboxOffset = this.largeOffset;
                }
                else {
                    this.pinOnOptions  = this.smallPinHoverOptions;
                    this.pinOffOptions = this.smallPinOptions;
                    
                    this.dealerInfoboxOffset = this.smallOffset;
                }

//                this.FindDealers(this.maxPanResults, true);
            }
            if (this.lastDealerPin != null)
            {
                this.ShowDealerInfobox(this.lastDealerPin);
            }
            
            this.isDoingBoundPan = false;
            this.isDoingZoom = false;
            this.isRouting = false;
        },
        MouseDownHandler:function(e) {
            if (this.isInfoboxHovering)
                e.handled = true;
        },
        ShowDealers:function() {
            if (this.isResizing || !this.isShowingDirections)
                return;
            
            this.ShowDealerShadows();
            this.HideDirectionShadows();
            /*
            var that = this;
//            this.dealerSideElement.show();
            this.dealerSideElement.animate({width:this.dealerSideElement.data('initialWidth')}, {
                duration:that.animationDuration,
                easing:"easeInOutCubic"
            });
            this.directionsSideElement.animate({width:'0px'}, {
                duration:that.animationDuration,
                easing:"easeInOutCubic"
            });
            */
            /*
            this.directionsSideElement.css('position','absolute');
            this.directionsSideElement.fadeOut(this.animationDuration);
            */
            
            this.dealerSideElement.fadeIn(this.animationDuration);
            this.directionsSideElement.fadeOut(this.animationDuration);
        },
        Resize:function() {
            if (this.isShowingFullMap && !this.areDealersLoaded)
                return;
            
            this.isResizing = true;
            var that = this;
            
            if (!this.isShowingFullMap) {
                /*
                this.dealerSideElement.animate({width:'0px'}, {
                    duration:that.animationDuration,
                    easing:"easeInOutCubic",
                    step:function() {
                        if (!that.isShowingDirections) {
                            var width = 900 - that.dealerSideElement.width();

                            that.mapDiv.width(width);
                            that.map.setOptions({width:width});
                        }
                    }
                });
                this.directionsSideElement.animate({width:'0px'}, {
                    duration:that.animationDuration,
                    easing:"easeInOutCubic",
                    step:function() {
                        if (that.isShowingDirections) {
                            var width = 900 - that.directionsSideElement.width();

                            that.mapDiv.width(width);
                            that.map.setOptions({width:width});
                        }
                    }
                });
                */
                this.infoArea.animate({width:'0px'}, {
                    duration:that.animationDuration,
                    easing:"easeInOutCubic",
                    step:function() {
                        var width = 900 - that.infoArea.width();

                        that.mapDiv.width(width);
                        that.map.setOptions({width:width});
                    }
                });
                this.tabButton.animate({left:'0px'}, {
                    duration:that.animationDuration,
                    easing:"easeInOutCubic",
                    complete:function() {
                        that.tabButton.addClass('right');

                        that.mapDiv.removeAttr('style');
                        that.mapDiv.addClass('fullsize');
                        var width = that.mapDiv.width();
                        that.map.setOptions({width:width});
    
                        that.isResizing = false;
                        that.isShowingFullMap = true;
                    }
                });
            }
            else {
                this.mapDiv.css('overflow', 'hidden');
                this.mapDiv.animate({width:this.mapDiv.data('initialWidth')}, {
                    duration:that.animationDuration - 25,
                    easing:"easeInOutCubic",
                    step:function() {
                        var width = that.mapDiv.width();
                        that.map.setOptions({width:width});
                    }                        
                });
                /*
                this.dealerSideElement.animate({width:this.dealerSideElement.data('initialWidth')}, {
                    duration:that.animationDuration,
                    easing:"easeInOutCubic"
                });
                this.directionsSideElement.animate({width:this.directionsSideElement.data('initialWidth')}, {
                    duration:that.animationDuration,
                    easing:"easeInOutCubic"
                });
                */
                this.infoArea.animate({width:this.infoArea.data('initialWidth')}, {
                    duration:that.animationDuration,
                    easing:"easeInOutCubic"
                });
                this.tabButton.animate({left:this.tabButton.data('initialLeft')}, {
                    duration:that.animationDuration,
                    easing:"easeInOutCubic",
                    complete:function() {
                        that.tabButton.removeClass('right');

                        that.mapDiv.removeAttr('style');
                        that.mapDiv.removeClass('fullsize');
                        var width = that.mapDiv.width();
                        that.map.setOptions({width:width});
    
                        that.isResizing = false;
                        that.isShowingFullMap = false;
                    }
                });
            }
        },
        ShowDealerShadows:function() {
            this.dealerShadowTop.fadeIn(this.animationDuration);
            this.dealerShadowBottom.fadeIn(this.animationDuration);
        },
        HideDealerShadows:function() {
            this.dealerShadowTop.fadeOut(this.animationDuration);
            this.dealerShadowBottom.fadeOut(this.animationDuration);
        },
        ShowDirectionShadows:function() {
            this.directionShadowTop.fadeIn(this.animationDuration);
            this.directionShadowBottom.fadeIn(this.animationDuration);
        },
        HideDirectionShadows:function() {
            this.directionShadowTop.fadeOut(this.animationDuration);
            this.directionShadowBottom.fadeOut(this.animationDuration);
        }
    };
    
    $.fn.DealerLocator = function() {
        return this.each(function() {
            var dealerLocator = new DealerLocator($(this));
            $(this).data('DealerLocator', dealerLocator);
        });
    };    
});

$(function() {
    $('div.dealerLocator2011').DealerLocator();
});
