if(typeof(google) != 'undefined') {
    mapsEnabled = true;
}
else {
    mapsEnabled = false;
}

RentScore = function() {
    this.initialize();
    this.propertyAddressMap = null;
    this.propertyStreetViewPanorama = null;
    this.propertyStreetViewMarker = null;
    this.propertyAddressMapMarker = null;
    this.propertyListMap = null;
    this.propertyListMapMarkers = {};
    this.propertyListMapBounds = null;
    this.propertyProfileMap = null;
    this.propertyProfileMapMarker = null;
    this.propertyProfileStreetView = null;
    if(typeof(google) != 'undefined') {
        this.propertyListMapBounds = new google.maps.LatLngBounds;
        this.mapsEnabled = true;
    }
    else {
        this.mapsEnabled = false;
    }
    this.panaromaScanSpeed = 4;
    this.panaromaPaused = false;
    this.panaromaBeingDragged = false;

    this.loginDialog = null;
    this.registerDialog = null;
    this.contactDialog = null;
    this.reviewPropertyDialog = null;
    this.sellPropertyDialog = null;
}

$.extend(RentScore.prototype, {
    initialize: function() {
        this.apiUser = "web";
        this.apiUserKey = "web";
        this.apiUrl = "/api/?username="+this.apiUser+"&key="+this.apiUserKey;

        this.initializeTopNavigationUserDropDownListener();
    },

    initializeTopNavigationUserDropDownListener: function() {
        $(document).ready(function() {
            // Use utility function
            if($('#userDropDownLink').length !== 0) {
                disableSelection($('#userDropDownLink').get(0));
            }
            
            $('#userDropDownLink').click(function(event) {
                event.preventDefault();
                //console.log('Click!');
                
                if($('#userDropDown').is(':visible')) {
                    //console.log('hiding!');
                    $('#userDropDown').hide();
                }
                else {
                    //console.log('showing');
                    $('#userDropDown').show();
                }
            });
            
            $(document).mouseup(function(event) {
                //console.log($(event.target).attr('id'));
                if($(event.target).attr('id') != 'userDropDown' && $(event.target).attr('id') != 'userDropDownLink') {
                    //console.log('hiding')
                    $('#userDropDown').hide();
                }
            });
        });
    },

    toggleTopNavigationSettingsDropDown: function() {
        $('#settingsDropDown').toggle();
    },

    showMessageDialog: function(title, message) {
        this.messageDialog = new Dialog(
            {
                'class': 'formDialog',
                'modalOverlayClass': 'formModalOverlay',
                'header': '',
                ajax: {
                    'url': '/api/web/getMessageDialog/outputType:raw/',
                    'data': {
                        'title': title,
                        'message': message
                    }
                }
            }
        );
    },

    reviewUserPropertyReview: function(userPropertyReviewId, type) {
        // Make sure they are logged in
        if(!user.loggedIn || user.authenticationMethod != 'database') {
            this.showMessageDialog('Must Be Logged In', 'Please <a onclick="rentScore.messageDialog.destroy(); rentScore.showRegisterDialog();">create an account</a> or <a onclick="rentScore.messageDialog.destroy(); rentScore.showLoginDialog();">login</a> to review a user property review.</p>');
        }
        else {
            $('#propertyProfileReviewsTableReviewRowReview'+userPropertyReviewId).html('<img src="/images/animations/loading-circle-bars-grey.gif" alt="Processing..." />');

            var reviewUserPropertyReviewRequest = $.ajax({
                'dataType': 'json',
                'url': '/api/web/reviewUserPropertyReview/userPropertyReviewId:'+userPropertyReviewId+'/type:'+type+'/',
                'success': function(response) {
                    $('#propertyProfileReviewsTableReviewRowReview'+userPropertyReviewId).html($(response).html());
                }
            });
        }
    },

    toggleUserPropertySaved: function(propertyId) {
        // Make sure they are logged in
        if(!user.loggedIn || user.authenticationMethod != 'database') {
            this.showSavePropertyDialog();
        }
        else {
            $('.saveControl').text('...');

            var savePropertyRequest = $.ajax({
                'dataType': 'json',
                'url': '/api/property/toggleUserPropertySaved/propertyId:'+propertyId+'/',
                'success': function(response) {
                    if(response.code == 'removed') {
                        $('.saveControl').text('Save');
                        $('.saveControl').removeClass('saved');
                        $('#userPropertySavedCount').text(parseInt($('#userPropertySavedCount').text(), 10) - 1);
                    }
                    else if(response.code == 'saved') {
                        $('.saveControl').text('Saved');
                        $('.saveControl').addClass('saved');
                        $('#userPropertySavedCount').text(parseInt($('#userPropertySavedCount').text(), 10) + 1);
                    }
                }
            });
        }
    },

    showPropertyProfile: function() {
        switch(window.location.hash) {
            case '#overview':
                this.showPropertyProfileInformationOverviewTab();
                break;
            case '#reviews':
                this.showPropertyProfileInformationReviewsTab();
                break;
            default:
                break;
        }

    },

    showPropertyProfileInformationOverviewTab: function() {
        window.location.hash = 'overview';

        $('#propertyProfileInformationOverviewTab').siblings().removeClass('active');
        $('#propertyProfileInformationOverviewTab').addClass('active');

        $('#propertyProfileInformationTabContents').children().hide();
        $('#propertyProfileInformationTabContents').find('#propertyProfileInformationOverviewTabContent').show();
    },

    showPropertyProfileInformationDetailsTab: function() {
        window.location.hash = 'details';

        $('#propertyProfileInformationDetailsTab').siblings().removeClass('active');
        $('#propertyProfileInformationDetailsTab').addClass('active');

        $('#propertyProfileInformationTabContents').children().hide();
        $('#propertyProfileInformationTabContents').find('#propertyProfileInformationDetailsTabContent').show();
    },

    showPropertyProfileInformationReviewsTab: function() {
        window.location.hash = 'reviews';

        $('#propertyProfileInformationReviewsTab').siblings().removeClass('active');
        $('#propertyProfileInformationReviewsTab').addClass('active');

        $('#propertyProfileInformationTabContents').children().hide();
        $('#propertyProfileInformationTabContents').find('#propertyProfileInformationReviewsTabContent').show();
    },

    showPropertyProfileInformationFacebookTab: function() {
        window.location.hash = 'facebook';

        $('#propertyProfileInformationFacebookTab').siblings().removeClass('active');
        $('#propertyProfileInformationFacebookTab').addClass('active');

        $('#propertyProfileInformationTabContents').children().hide();
        $('#propertyProfileInformationTabContents').find('#propertyProfileInformationFacebookTabContent').show();
    },
    
    showPropertyProfileInformationPayRentTab: function() {
        window.location.hash = 'pay-rent';

        $('#propertyProfileInformationPayRentTab').siblings().removeClass('active');
        $('#propertyProfileInformationPayRentTab').addClass('active');

        $('#propertyProfileInformationTabContents').children().hide();
        $('#propertyProfileInformationTabContents').find('#propertyProfileInformationPayRentTabContent').show();
    },
    
     showSavePropertyDialog: function() {
        this.savePropertyDialog = new Dialog(
            {
                'class': 'formDialog',
                'modalOverlayClass': 'formModalOverlay',
                'header': '',
                ajax: {
                    'url': '/api/web/getSavePropertyDialog/outputType:raw/'
                }
            }
        );
    },

    scrollToPropertyProfileInformation: function() {
        $('html,body').animate({scrollTop: $('.propertyProfileUnitTypeTableHeader').offset().top - 18}, {duration: 'slow', easing: 'swing'});
        $('.propertyProfileUnitTypeTableHeader').animate({
                backgroundColor: '#FFBB7F'
            }, 750, function() {
                $('.propertyProfileUnitTypeTableHeader').animate({
                    backgroundColor: '#F58220'
                });
            }
        );
    },

    showLoginDialog: function() {
        this.loginDialog = new Dialog(
            {
                'class': 'formDialog',
                'modalOverlayClass': 'formModalOverlay',
                'header': '',
                ajax: {
                    'url': '/api/web/getLoginDialog/outputType:raw/',
                    'onSuccess': function() {
                        $('#loginIdentifier').focus();
                    }
                }
            }
        );
    },

    showRegisterDialog: function() {
        this.registerDialog = new Dialog(
            {
                'class': 'formDialog',
                'modalOverlayClass': 'formModalOverlay',
                'header': '',
                ajax: {
                    'url': '/api/web/getRegisterDialog/outputType:raw/',
                    'onSuccess': function() {
                        $('#registerEmail').focus();
                    }
                }
            }
        );
    },
        
    showPropertyProfileDialog: function(dialog, data, onSuccess) {
        this.propertyProfileDialog = new Dialog(
            {
                'class': 'formDialog',
                'modalOverlayClass': 'formModalOverlay',
                'header': '',
                ajax: {
                    'data': data,
                    'url': '/api/web/getPropertyProfile'+dialog+'Dialog/outputType:raw/',
                    'onSuccess': onSuccess
                }
            }
        );
    },
    
    showContactDialog: function() {
        this.contactDialog = new Dialog(
            {
                'class': 'formDialog',
                'modalOverlayClass': 'formModalOverlay',
                'header': '',
                ajax: {
                    'url': '/api/web/getContactDialog/outputType:raw/'
                }
            }
        );
    },

    showReviewPropertyDialog: function(propertyId) {
        this.reviewPropertyDialog = new Dialog(
            {
                'class': 'formDialog',
                'modalOverlayClass': 'formModalOverlay',
                'header': '',
                ajax: {
                    'url': '/api/web/getReviewPropertyDialog/outputType:raw/propertyId:'+propertyId+'/',
                    'onSuccess': function() {
                        $('#reviewPropertyTitle').focus();
                    }
                }
            }
        );
    },

    showSellPropertyDialog: function(propertyId) {
        this.sellPropertyDialog = new Dialog(
            {
                'class': 'formDialog',
                'modalOverlayClass': 'formModalOverlay',
                'header': '',
                ajax: {
                    'url': '/api/web/getSellPropertyDialog/outputType:raw/propertyId:'+propertyId+'/',
                    'onSuccess': function() {
                        $('#sellPropertyTitle').focus();
                    }
                }
            }
        );
    },

    showSubmitLeadDialog: function(propertyId, propertyUnitTypeId) {
        // Set the request URL
        var url = '/api/web/getSubmitLeadDialog/outputType:raw/propertyId:'+propertyId+'/';
        if(propertyUnitTypeId) {
            url += 'propertyUnitTypeId:'+propertyUnitTypeId+'/';
        }

        this.submitLeadDialog = new Dialog(
            {
                'class': 'formDialog',
                'modalOverlayClass': 'formModalOverlay',
                'header': '',
                ajax: {
                    'url': url,
                    'onSuccess': function() {
                        $('#submitLeadName-firstName').focus();
                    }
                }
            }
        );
    },

    togglePropertyProfileExtraDescriptionText: function(a) {
        console.log($(a));
        $('.propertyProfileExtraDescriptionText').toggle();
        if($(a).text() == 'more...') {
            $(a).text('less')
        }
        else {
            $(a).text('more...')
        }
    },

    setupPropertyProfileImageryKeyListeners: function() {
        $(window).keypress(function(event) {
            if(event.keyCode == 39) {
                rentScore.propertyProfileImageryPhotoNext();
            }
            else if(event.keyCode == 37) {
                rentScore.propertyProfileImageryPhotoPrevious();
            }
        });
    },

    propertyProfileImageryPhotoScrollTo: function(li) {
        var rightSide = $(li).position().left + $(li).outerWidth() + $(li).parent().position().left;
        var containerWidth = $(li).parent().parent().outerWidth();

        // Move right
        if(rightSide > containerWidth) {
            $(li).parent().clearQueue().animate({'left': '-='+(rightSide - containerWidth)+'px'}, 250);
        }
        // Move left
        else if($(li).position().left + $(li).parent().position().left < 0) {
            $(li).parent().clearQueue().animate({'left': '-='+($(li).position().left + $(li).parent().position().left)+'px'}, 250);
        }

        if($('.propertyProfileImageryPhotoCaption').text() == '') {
            $('.propertyProfileImageryPhotoCaption').hide();
        }
        else {
            $('.propertyProfileImageryPhotoCaption').show();
        }
    },

    propertyProfileImageryPhotoPrevious: function() {
        if($('.propertyProfileImageryPhotoThumbnails li:first').is('.active')) {
            $('.propertyProfileImageryPhotoThumbnails li:last').click();
        }
        else {
            $('.propertyProfileImageryPhotoThumbnails li.active').prev().click();
        }
    },

    propertyProfileImageryPhotoNext: function() {
        if($('.propertyProfileImageryPhotoThumbnails li:last').is('.active')) {
            $('.propertyProfileImageryPhotoThumbnails li:first').click();
        }
        else {
            $('.propertyProfileImageryPhotoThumbnails li.active').next().click();
        }
    },

    showPropertyProfilePhotos: function() {
        $('#propertyProfileImagery .propertyProfileLeftContainerContent').children().hide();
        $('#propertyProfileImageryPhotos').show();
        $('#propertyProfileImagery .propertyProfileLeftContainerControls li').removeClass('active');
        $('#propertyProfileImagery .propertyProfileLeftContainerControls li').eq(0).addClass('active');
    },

    showPropertyProfileVideos: function() {
        $('#propertyProfileImagery .propertyProfileLeftContainerContent').children().hide();
        $('#propertyProfileImageryVideos').show();
        $('#propertyProfileImagery .propertyProfileLeftContainerControls li').removeClass('active');
        $('#propertyProfileImagery .propertyProfileLeftContainerControls li').eq(1).addClass('active');
    },

    showPropertyProfileVirtualTours: function() {
        $('#propertyProfileImagery .propertyProfileLeftContainerContent').children().hide();
        $('#propertyProfileImageryVirtualTours').show();
        $('#propertyProfileImagery .propertyProfileLeftContainerControls li').removeClass('active');
        $('#propertyProfileImagery .propertyProfileLeftContainerControls li').eq(2).addClass('active');
        
        if($('.propertyProfileImageryVirtualTourCurrent').length > 0) {
            var viewer = $('.propertyProfileImageryVirtualTourCurrent');
            var initialMouseX = 0;
            var initialBackgroundX = 0;
            var backgroundImage = new Image();backgroundImage.src = viewer.css('background-image').replace(/"/g,"").replace(/url\(|\)$/ig, "");
            viewer.css('height', backgroundImage.height);

            viewer.bind('mousedown', function(event){
                rentScore.panoramaBeingDragged = true;
                initialMouseX = event.pageX;
                initialBackgroundX = parseInt(viewer.css('backgroundPosition').split(' ')[0]);
            });
            $(document).bind('mouseup', function(event){
                if(rentScore.panoramaBeingDragged) {
                    rentScore.panoramaBeingDragged = false;
                    // Change the panaroma scan direction
                    if(!rentScore.panaromaPaused) {
                        if(event.pageX <= initialMouseX) {
                            rentScore.panaromaScanSpeed = Math.abs(rentScore.panaromaScanSpeed);
                        }
                        else {
                            rentScore.panaromaScanSpeed = rentScore.panaromaScanSpeed * -1;
                        }
                        rentScore.scanPanorama();
                    }
                }
            });
            $(document).bind('mousemove', function(event){
                if(rentScore.panoramaBeingDragged) {
                    viewer.css('backgroundPosition', ((event.pageX - initialMouseX) / (viewer.width() / backgroundImage.width)) + initialBackgroundX + 'px 0');
                }
            });
            rentScore.scanPanorama();
        }
        
    },

    scanPanorama: function() {
        if(!rentScore.panoramaBeingDragged) {
            $('.propertyProfileImageryVirtualTour').animate({backgroundPosition: '-='+this.panaromaScanSpeed+'px'}, 50, 'linear', function() {
                rentScore.scanPanorama();
            });
        }
    },
    
    showPropertyProfileMap: function(latitude, longitude) {
        $('#propertyProfileImagery .propertyProfileLeftContainerContent').children().hide();
        $('#propertyProfileImageryMap').show();
        $('#propertyProfileImagery .propertyProfileLeftContainerControls li').removeClass('active');
        $('#propertyProfileImagery .propertyProfileLeftContainerControls li.map').addClass('active');

        if(this.propertyProfileMap == null) {
            this.propertyProfileMap = new google.maps.Map(document.getElementById("propertyProfileImageryMap"), {
                zoom: 17,
                center: new google.maps.LatLng(latitude, longitude), // Center of the US
                mapTypeId: google.maps.MapTypeId.ROADMAP,
                navigationControlOptions: {
                    style: google.maps.NavigationControlStyle.SMALL
                },
                noClear: true
            });
            this.propertyProfileMapMarker = new RentScoreMarker(new google.maps.LatLng(latitude, longitude), this.propertyProfileMap);
            //this.propertyProfileMapMarker.tipContent = 'Property Name';
        }
        else {
            this.propertyProfileMap.setCenter(new google.maps.LatLng(parseFloat(latitude, 10), parseFloat(longitude, 10)));
            this.propertyProfileMap.setZoom(17);
        }
    },

    showPropertyProfileStreetView: function(latitude, longitude, streetViewPov) {
        $('#propertyProfileImagery .propertyProfileLeftContainerContent').children().hide();
        $('#propertyProfileImageryStreetView').show();
        $('#propertyProfileImagery .propertyProfileLeftContainerControls li').removeClass('active');
        $('#propertyProfileImagery .propertyProfileLeftContainerControls li').eq(4).addClass('active');

        if(this.propertyProfileStreetView == null) {
            this.propertyProfileStreetView = new google.maps.StreetViewPanorama(document.getElementById("propertyProfileImageryStreetView"), {
                position: new google.maps.LatLng(parseFloat(latitude, 10), parseFloat(longitude, 10)),
                pov: {
                    heading: parseFloat(streetViewPov.heading, 10),
                    pitch: parseFloat(streetViewPov.pitch, 10),
                    zoom: parseFloat(streetViewPov.zoom, 10)
                }
            });
        }
        else {
            this.propertyProfileStreetView.setPosition(new google.maps.LatLng(parseFloat(latitude, 10), parseFloat(longitude, 10)));
            this.propertyProfileStreetView.setPov({
                heading: parseFloat(streetViewPov.heading, 10),
                pitch: parseFloat(streetViewPov.pitch, 10),
                zoom: parseFloat(streetViewPov.zoom, 10)
            });
        }
    },

    setupPropertyList: function() {
        $('.propertyListing').each(function(index, listing) {
            var options = $(listing).find('ul.options');

            $(listing).bind('mouseover', function(event) {
                if(!options.is('hidden')) {
                    options.show();
                }
            });

            $(listing).bind('mouseout', function(event) {
                options.hide();
            });

            $(listing).bind('click', function(event) {
                document.location = $(listing).find('a.propertyListingLink').attr('href');
            });
        });
    },

    setupPropertyListMap: function() {
        var self = this;

        if(!this.mapsEnabled) {
            return;
        }

        this.propertyListMap = new google.maps.Map(document.getElementById("propertyListMap"), {
            zoom: 3,
            center: new google.maps.LatLng(39.5, -98.35), // Center of the US
            mapTypeId: google.maps.MapTypeId.ROADMAP,
            navigationControlOptions: {
                style: google.maps.NavigationControlStyle.SMALL
            },
            mapTypeControl: false,
            noClear: true
        });

        google.maps.event.addListener(this.propertyListMap, 'bounds_changed', function() {
            self.updatePropertyListMapActiveTipPosition();
        });
    //google.maps.event.addListener(this.propertyListMap, 'click', function() { self.hideAllPropertyListMapTips(); });
    },

    addPropertyListMapMarker: function(lat, lng, tipHtml) {
        if(!this.mapsEnabled) {
            return;
        }

        this.propertyListMapMarkers[lat+lng] = new RentScoreMarker(new google.maps.LatLng(lat, lng), this.propertyListMap);
        this.propertyListMapMarkers[lat+lng].tipContent = $(tipHtml.html);

        // Make the listings clickable
        $(this.propertyListMapMarkers[lat+lng].tipContent).bind('click', function(event) {
            document.location = $(this).find('a.propertyListingLink').attr('href');
        });

        this.propertyListMapBounds.extend(new google.maps.LatLng(lat, lng));
    },

    centerPropertyListMap: function() {
        if(!this.mapsEnabled) {
            return;
        }

        this.propertyListMap.fitBounds(this.propertyListMapBounds);
    },

    getHeading: function(latitude1, longitude1, latitude2, longitude2) {
        // Convert the latitudes to degrees
        latitude1 = latitude1 * Math.PI / 180;
        latitude2 = latitude2 * Math.PI / 180;

        // Get the difference between the longitudes in degrees
        var longitudeDelta = (longitude2-longitude1) * Math.PI / 180;

        // Calculate the bearing
        var y = Math.sin(longitudeDelta) * Math.cos(latitude2);
        var x = Math.cos(latitude1) * Math.sin(latitude2) - Math.sin(latitude1) * Math.cos(latitude2) * Math.cos(longitudeDelta);
        var brng = Math.atan2(y, x);
        return (((brng * 180 / Math.PI) + 360) % 360);
    },

    updatePropertyListMapActiveTipPosition: function() {
        $.each(this.propertyListMapMarkers, function(index, marker) {
            if(marker.active) {
                if(marker.visible()) {
                    marker.tip.qtip('api').updatePosition();
                }
                else {
                    marker.tip.qtip('hide');
                }
            }
        });
    },

    hideAllPropertyListMapTips: function() {
        $.each(this.propertyListMapMarkers, function(index, marker) {
            if(marker.active) {
                marker.tip.qtip('hide');
            }
        });
    },

    setupPropertyAddressMap: function() {
        this.propertyAddressMap = new google.maps.Map(document.getElementById("propertyAddressMap"), {
            zoom: 3,
            center: new google.maps.LatLng(39.5, -98.35), // Center of the US
            mapTypeId: google.maps.MapTypeId.ROADMAP,
            mapTypeControl: true,
            mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU},
            navigationControlOptions: {
                style: google.maps.NavigationControlStyle.DEFAULT
            },
            noClear: true
        });
    },

    setupPropertyStreetViewPanorama: function() {
        this.propertyStreetViewPanorama = new google.maps.StreetViewPanorama(document.getElementById("propertyStreetViewPanorama"));
    },

    updatePropertyStreetViewPanorama: function() {
        var self = this;
        //console.log("Updating street view position:", self.propertyStreetViewPanorama.getPosition());
        
        var heading = rentScore.getHeading(self.propertyStreetViewPanorama.getPosition().lat(), self.propertyStreetViewPanorama.getPosition().lng(), self.propertyAddressMapMarker.getPosition().lat(), self.propertyAddressMapMarker.getPosition().lng());
        //console.log('Updating heading:', heading);
        self.propertyStreetViewPanorama.setPov({
            heading: heading,
            pitch: 0,
            zoom: 1
        });

        // Show the marker for the Google truck
        if(self.propertyStreetViewMarker == null) {
            self.propertyStreetViewMarker = new google.maps.Marker({
                position: self.propertyStreetViewPanorama.getPosition(),
                map: self.propertyAddressMap
            });
        }
        else {
            self.propertyStreetViewMarker.setPosition(self.propertyStreetViewPanorama.getPosition());
        }

        //console.log("Street view panorama position: ", self.propertyStreetViewPanorama.getPosition());
    },

    placePropertyAddressMapMarker: function(addressObject, response, context) {
        if(context === undefined) {
            context = this;
        }
        var self = context;

        // Make the request if necessary
        if(response === undefined) {
            this.geocodeAddress(addressObject, "placePropertyAddressMapMarker", self);
        }
        else {
            // Create the marker if necessary
            if(self.propertyAddressMapMarker === null) {
                self.propertyAddressMapMarker = new google.maps.Marker({
                    map: self.propertyAddressMap,
                    position: response[0].geometry.location,
                    draggable: true,
                    bouncy: true
                });

                // Create the panorama if necessary
                if(this.propertyStreetViewPanorama == null) {
                    self.setupPropertyStreetViewPanorama();
                    //console.log("Positioning panorama: ", self.propertyAddressMapMarker.getPosition());
                    self.propertyStreetViewPanorama.setPosition(self.propertyAddressMapMarker.getPosition());
                }

                // Monitor when the user drags the marker
                google.maps.event.addListener(self.propertyAddressMapMarker, 'drag', function() {
                    $('#propertyLatitude').val(self.propertyAddressMapMarker.getPosition().lat());
                    $('#propertyLongitude').val(self.propertyAddressMapMarker.getPosition().lng());
                });

                // When the user stops dragging he marker, update the panoramas position
                google.maps.event.addListener(self.propertyAddressMapMarker, 'dragend', function() {
                    //console.log("Positioning panorama: ", self.propertyAddressMapMarker.getPosition());
                    self.propertyStreetViewPanorama.setPosition(self.propertyAddressMapMarker.getPosition());
                });

                // What the panorama's position has changed, update its orientation
                google.maps.event.addListener(self.propertyStreetViewPanorama, 'position_changed', function() {
                    self.updatePropertyStreetViewPanorama();
                });

                // Monitor changes to the point of view
                google.maps.event.addListener(self.propertyStreetViewPanorama, 'pov_changed', function() {
                    $('#propertyStreetViewHeading').val(self.propertyStreetViewPanorama.getPov().heading);
                    $('#propertyStreetViewPitch').val(self.propertyStreetViewPanorama.getPov().pitch);
                    $('#propertyStreetViewZoom').val(self.propertyStreetViewPanorama.getPov().zoom);
                });
            }
            // Position the marker
            else {
                self.propertyAddressMapMarker.setPosition(response[0].geometry.location);
                //console.log("Positioning panorama: ", self.propertyAddressMapMarker.getPosition());
                self.propertyStreetViewPanorama.setPosition(self.propertyAddressMapMarker.getPosition());
            }

            // Focus the map on the marker
            rentScore.propertyAddressMap.setCenter(response[0].geometry.location);
            rentScore.propertyAddressMap.setZoom(16);

            $("#propertyAddressFormatted-wrapper .choiceWrapper").remove();
            $.each(response, function(index, value) {
                //console.log("Adding formated value", value);
                $("#propertyAddressFormatted-wrapper").append(
                    '<div class="choiceWrapper" id="propertyAddressFormatted-choice'+(index+1)+'-wrapper">\n\
                        <input type="radio" style="display: inline;" class="choice" value="" name="propertyAddressFormatted" id="propertyAddressFormatted-choice'+(index+1)+'">\n\
                        <label style="display: inline;" class="choiceLabel" for="propertyAddressFormatted-choice'+(index+1)+'">'+$.trim(value.formatted_address)+'</label>\n\
                    </div>'
                );
            });

            // Update the lat lng
            $('#propertyLatitude').val(self.propertyAddressMapMarker.getPosition().lat());
            $('#propertyLongitude').val(self.propertyAddressMapMarker.getPosition().lng());
        }
    },

    geocodeAddress: function(addressObject, callbackFunction, context) {
        var addressString = addressObject.addressLine1 + ' ' + addressObject.addressLine2 + ', ' + addressObject.city + ', ' + addressObject.state + ', ' + addressObject.zip + ', ' + addressObject.country;
        var geocoder = new google.maps.Geocoder();
        geocoder.geocode({address:addressString}, function(response) {
            return context[callbackFunction](addressObject, response, context);
        });
    }
});

rentScore = new RentScore();

if(mapsEnabled) {
    function RentScoreMarker(latlng, map) {
        var self = this;

        this.latlng_ = latlng;
        this.active = false;
        this.activeImage = '/images/map-marker-orange.png';
        this.inactiveImage = '/images/map-marker-blue.png';
        this.img = null;
        this.tip = null;
        this.tipContent = '';
        this.tipOptions = {
            style: {
                width: '432px',
                height: '158px',
                padding: 'none',
                border: 'none'
            },
            position: {
                corner: {
                    target: 'topMiddle',
                    tooltip: 'bottomRight'
                }
            },
            show: {
                when: {
                    event: 'click'
                },
                delay: 0,
                effect: {
                    length: 0
                }
            },
            hide: {
                when: {
                    event: 'click'
                },
                delay: 0,
                effect: {
                    length: 0
                }
            },
            api: {
                beforeShow: function() {
                    rentScore.hideAllPropertyListMapTips();
                    self.active = true;
                    self.img.src = self.activeImage;
                },
                onHide: function() {
                    self.active = false;
                    self.img.src = self.inactiveImage;
                }
            }
        };
        // Once the LatLng and text are set, add the overlay to the map.  This will
        // trigger a call to panes_changed which should in turn call draw.
        this.setMap(map);
    }
    RentScoreMarker.prototype = new google.maps.OverlayView();
    RentScoreMarker.prototype.visible = function() {
        var self = this;
        return this.map.getBounds().contains(self.latlng_);
    }
    RentScoreMarker.prototype.draw = function() {
        var self = this;

        // Check if the div has been created.
        var div = this.div_;
        if(!div) {
            // Create a overlay text DIV
            div = this.div_ = document.createElement('DIV');
            // Create the DIV representing our CustomMarker
            div.style.border = "0 solid none";
            div.style.position = "absolute";
            div.style.paddingLeft = "0px";
            div.style.cursor = 'pointer';
            div.style.width = '32px';
            div.style.height = '32px';

            this.img = document.createElement("img");
            this.img.src = this.inactiveImage;
            div.appendChild(this.img);
            google.maps.event.addDomListener(div, "click", function(event) {
                google.maps.event.trigger(self, "click");
            });

            // Then add the overlay to the DOM
            var panes = this.getPanes();
            panes.overlayImage.appendChild(div);

            // If there is supposed to be a tooltip
            if(this.tipContent != '') {
                this.tipOptions.content = this.tipContent;
                this.tip = $(div).qtip(self.tipOptions);
            }
        }

        // Position the overlay
        var point = this.getProjection().fromLatLngToDivPixel(this.latlng_);
        if(point) {
            div.style.left = point.x - 16 + 'px';
            div.style.top = point.y - 16 + 'px';
        }
    };
    RentScoreMarker.prototype.remove = function() {
        // Check if the overlay was on the map and needs to be removed.
        if (this.div_) {
            this.div_.parentNode.removeChild(this.div_);
            this.div_ = null;
        }
    };
    RentScoreMarker.prototype.getPosition = function() {
        return this.latlng_;
    };
}
