﻿
// todo - move out fadeIn effect and setInterval for slide show to allow customization by user
(function($) {

    $.extend($.ui.tabs.prototype, {
        fixPanels: function(options) {
            this.panels.addClass('ui-tabs-hide');           
            switch (parseInt(options.index)) {
                case 0:
                    this.panels.eq(options.index).removeClass('ui-tabs-hide');
                    break;
                case 4:
                    this.panels.eq(2).removeClass('ui-tabs-hide');
                    break;
                default:
                    this.panels.eq(1).removeClass('ui-tabs-hide');
                    break;
            }

            return this;
        }
    });
})(jQuery);

function PD_Media(allowPhotoStretching) {
    
    var PHOTO_TAB = 0;
    var BIRDSEYE_TAB = 1;
    var STREETMAP_TAB = 2;
    var DIRECTIONS_TAB = 3;
    var VIRTUALTOUR_TAB = 4;
    
    var currentTab = parseInt(SE_PD_InitialTab);
    var currentPhoto = -1;
    this.SetTabVisibility = SetTabVisibility;
    this.SetTabVisibility();
    var PhotosSlideShowInterval = 0;
    var PhotosSlideShowDelay = 3000;
    this.allowPhotoStretching = allowPhotoStretching;

    this.Photos_SetUpTab = Photos_SetUpTab;
    this.BirdsEye_SetUpTab = BirdsEye_SetUpTab;
    this.StreetMap_SetUpTab = StreetMap_SetUpTab;
    this.Directions_SetUpTab = Directions_SetUpTab;
    this.Photos_GetSizes = Photos_GetSizes;
    this.Photos_AddBehaviors = Photos_AddBehaviors;
    this.Directions_Get = Directions_Get
    this.Directions_Clear = Directions_Clear;
    this.Directions_Print = Directions_Print;
    this.Photos_StopSlideShow = Photos_StopSlideShow;

    var self = this;

    var origMapHeight = $(".pd_map_block").css("height");
    if (origMapHeight)
        origMapHeight = origMapHeight.replace("px", "");
    if (typeof (origMapHeight) == 'undefined' || parseInt(origMapHeight) < 300)
        origMapHeight = 300;
    if ($(".sr_listing_image_popup").length > 0)
        origMapHeight = $(".sr_listing_image_popup").height() - 50;
    if (!this.hasTabs) {
        $("#pd_mediatabs").hide();
        return;
    }
    $('#pd_mediatabs').tabs(
        {
            selected: currentTab,
            show: function (e, ui) {
                var selectedIndex = ui.index
                
                ShowTabPanels();
                
                switch (parseInt(selectedIndex)) {
                    case PHOTO_TAB:
                        self.Photos_SetUpTab();
                        break;
                    case BIRDSEYE_TAB:
                        self.BirdsEye_SetUpTab();
                        break;
                    case STREETMAP_TAB:
                        self.StreetMap_SetUpTab();
                        break;
                    case DIRECTIONS_TAB:
                        self.Directions_SetUpTab();
                        break;
                    case VIRTUALTOUR_TAB:
                        VirtualTour_SetUpTab();
                        break;
                }
                $('#pd_media_tabs_list').show("fast");
            }
        }
    );
   
     function SetTabVisibility() {
        var requestedTab = currentTab;
        this.hasTabs = false;
        if (photoCount == 0) {
            $("#pd_media_li_photos").hide();            
        }
        else {
            this.hasTabs = true;
        }
        
        $("#pd_media_li_birdseye").hide();
        
        if (!isMappable) {
            $("#pd_media_li_birdseye").hide();
            $("#pd_media_li_street_map").hide();
            $("#pd_media_li_driving_directions").hide();
        }
        else {
            var thisPDMedia = this;
            
            if (!this.hasTabs && currentTab == PHOTO_TAB) {
                if (mediaMapSettings.birdseyeZoom)
                {
                    currentTab = BIRDSEYE_TAB
                    $("#pd_media_li_birdseye").show();
                }
                else
                    currentTab = STREETMAP_TAB;
            }
            
            this.hasTabs = true;
            if (mediaMapSettings.birdseyeZoom == null) {
                SEMap.Services.getBirdseyeZoomRange(mediaMapSettings.centerPoint,
                    function (zoomRange) {
                        thisPDMedia.birdseyeZoomRange = zoomRange;
                        if (zoomRange) {
                            $("#pd_media_li_birdseye").show();

                            if (requestedTab == PHOTO_TAB && photoCount == 0) {
                                currentTab = BIRDSEYE_TAB;
                                // need to wait until the map is loaded before reloading it with the birdseye
                                setTimeout(function () {
                                    $('#pd_mediatabs').tabs("option", "selected", BIRDSEYE_TAB);
                                }, 0);
                            }
                        }
                        else
                            $("#pd_media_li_birdseye").hide();

                    });
            }
            else if (mediaMapSettings.birdseyeZoom >= 0) {
                $("#pd_media_li_birdseye").show();
                if (mediaMapSettings.birdseyeZoom == 0)
                    $("#pd_media_li_birdseye a").text("Aerial View");
            }
        }        
        
        if (virtualTourUrl == "")
            $("#pd_media_li_virtual_tour").hide();
        else {
            if (!this.hasTabs) currentTab = VIRTUALTOUR_TAB;
            this.hasTabs = true;
        }
    }

    function ShowTabPanels() {

        // needed to correct tab visibility
        // because of bug when using the same div for multiple tabs
        $(".pd_virtual_tour_container").hide();
        $('#pd_mediatabs').tabs('fixPanels', { index: $('#pd_mediatabs').tabs('option', 'selected') });

    }

    function Photos_SetUpTab() {

        if ($(".pd_photos_tab_photos img").length == 0)
            return;
        if ($(".pd_photos_tab_photos img").length == 1)
            $(".pd_photos_tab_selector").hide();
        else {
            $(".pd_photos_tab_photos").show();
            $(".pd_photos_control").show();
        }
        $("#pd_photos_count").html(photoCount);

        $(".pd_photos_tab_photos").width($(".pd_photos_tab_photos img").outerWidth(true) * 2 + 6);
        $(".pd_photos_tab_selector").width($(".pd_photos_tab_photos").outerWidth(true) + MLX_GetScrollBarWidth());
        $(".pd_photos_tab_main").resizeToFillContainerWidth(($(".pd_photos_tab_photos img").length > 1) ? $(".pd_photos_tab_selector") : null);

        if (photoCount > 0) {
            this.Photos_GetSizes();
            this.Photos_AddBehaviors();
            $(".pd_photos_tab_photos img").filter(":first").click();
        }
    }

    function Photos_GetSizes() {
        
        var imgHeight = 400;

        var imgWidth = $(".pd_photos_tab_main").width();
        var maxWidth = $(".pd_photos_tab_main img").css("max-width").replace("px", "");
        var maxHeight = null;
       
        if (typeof ($(".pd_photos_tab_main img").css("max-height")) != 'undefined')
            maxHeight = $(".pd_photos_tab_main img").css("max-height").replace("px", "");
        var foundTargetAspects = [];
        var maxImageHeight = 0;
        var maxImageWidth = 0;
        var self = this;
        $(".pd_photos_tab_photos img").each(function () {
            var origHeight = $(this).attr("origHeight");
            var origWidth = $(this).attr("origWidth");
            
            var aspectRatio = origWidth / origHeight;
            maxImageHeight = Math.min(maxHeight, Math.max(maxImageHeight, origHeight));
            if (aspectRatio > 1 && aspectRatio < 2) {
                foundTargetAspects.push(aspectRatio);
            }
            $(this).data('origHeight', origHeight);
            $(this).data('origWidth', origWidth);
        })
        
        var meanAspect = 0;            
        if (foundTargetAspects.length > 0) {
            var meanAspect = 0;
            for (var iRatio = 0; iRatio < foundTargetAspects.length; iRatio++) {
                meanAspect += foundTargetAspects[iRatio];
            }
            meanAspect = meanAspect / foundTargetAspects.length;
            imgWidth = $(".pd_photos_tab_main").width();
            if (!isNaN(maxWidth) && imgWidth > maxWidth) {
                imgWidth = maxWidth;
            }
            if (maxHeight && !isNaN(maxHeight) && imgHeight > maxHeight) {
                imgHeight = maxHeight;
            }
            else {
                imgHeight = imgWidth / meanAspect;
            }
            origMapHeight = imgHeight;
        }                

        var photoIndex = 0
        $(".pd_photos_tab_photos img").each(function () {
            var aspectRatio = $(this).data('origWidth') / $(this).data('origHeight');

            if (!self.allowPhotoStretching && ($(this).data('origHeight') < .8 * imgHeight 
                || $(this).data('origWidth') < .8 * imgWidth )) {
                $(this).data('newHeight', $(this).data('origHeight'));
                $(this).data('newWidth', $(this).data('origWidth'));
            }

            else if (aspectRatio > .8 * meanAspect && aspectRatio < 1.3 * meanAspect) {
                $(this).data('newHeight', imgHeight);
                $(this).data('newWidth', imgWidth);
            } else if (aspectRatio <= .8 * meanAspect) {
                $(this).data('newHeight', imgHeight);
                $(this).data('newWidth', imgHeight * aspectRatio);
            } else if (aspectRatio >= 1.3 * meanAspect) {
                $(this).data('newHeight', imgHeight / aspectRatio);
                $(this).data('newWidth', imgWidth);
            }
            else {
                $(this).data('newHeight', imgHeight);
                $(this).data('newWidth', imgWidth);
            }
            $(this).data('photoIndex', photoIndex);
            photoIndex++;

        })
        
        if (self.allowPhotoStretching)
            $("#pd_tabular_selector").height(imgHeight);
        else
            $("#pd_tabular_selector").height(Math.min(imgHeight, maxImageHeight));
    }

    function Photos_AddBehaviors() {
        $(".pd_photos_tab_photos img").hover(
        function () { $(this).addClass("pd_photos_tab_photos_selected"); },
        function () { $(this).removeClass("pd_photos_tab_photos_selected"); });

        $(".pd_photos_tab_photos img").click(function () {
            $(".pd_photos_tab_photos img").removeClass("ui-state-focus");
            $(".pd_photos_tab_photos img").removeClass("pd_photos_tab_photos_current");
            $(this).addClass("pd_photos_tab_photos_current");
            $(this).addClass("ui-state-focus");
            var imgControl = $("#pd_photo_main img").hide().fadeIn(750);

            var url = $(this).attr("src");
            var wrap = $("#pd_photo_main");
            $(".pd_photos_tab_main").css("margin-top", 0);
            $(".pd_photos_tab_main img").height($(this).data('newHeight'));
            $(".pd_photos_tab_main img").width($(this).data('newWidth'));

            var vertMargin = Math.max(($(".pd_photos_tab_main").parent().availableHeight()
                - $(".pd_photos_control").outerHeight()
                - $(this).data('newHeight')) / 2, 0);

            $(".pd_photos_tab_main").css("margin-top", vertMargin);

            wrap.find("img").attr("src", url);

            currentPhoto = parseInt($(this).data('photoIndex'));
            $("#pd_photos_current").html(currentPhoto + 1);

        });
        $("#pd_photos_control_next").click(Photos_GoNext);
        $("#pd_photos_control_prev").click(Photos_GoPrev);
        $("#pd_photos_control_slideshow").click(Photos_SlideShow);
    }
    function Photos_GoNext() {
        Photos_Go(currentPhoto < photoCount - 1 ? currentPhoto + 1 : 0);
        return false;

    }
    function Photos_GoPrev() {
        Photos_Go(currentPhoto > 0 ? currentPhoto - 1 : photoCount - 1);
        return false;
    }
    function Photos_Go(toIndex) {
        setTimeout(function () {
            $(".pd_photos_tab_photos img").eq(toIndex).click()
        }, 20);
    }

    function Photos_SlideShow() {
        if (PhotosSlideShowInterval == 0) {
            Photos_GoNext();
            PhotosSlideShowInterval = setInterval(function () { $("#pd_photos_control_next").click() }, PhotosSlideShowDelay);
            $("#pd_photos_control_slideshow").html("Stop Slide Show");
        }
        else {
            Photos_StopSlideShow();
        }
    }
    function Photos_StopSlideShow() {
        clearInterval(PhotosSlideShowInterval);
        PhotosSlideShowInterval = 0;
        $("#pd_photos_control_slideshow").html("Slide Show");
    }

    function Bing_NavBarSetup(currentTab) {
        if (currentTab == BIRDSEYE_TAB) {
            $("#MSVE_navAction_topBar").hide();
            $("#MSVE_navAction_topBackground").hide();
        }
        else {
            $("#MSVE_navAction_topBar").show();
            $("#MSVE_navAction_topBackground").show();
            
        }
    }

    function BirdsEye_SetUpTab() {

        this.Directions_Clear();
        $(".pd_map_block").height(origMapHeight);

        var options = {};
        options.mapType = SEMap.MapType.birdseye;
        if(this.birdseyeZoomRange && this.birdseyeZoomRange.zoomMax) 
             options.zoomLevel = this.birdseyeZoomRange.zoomMax;
        
        this.Load_MediaMap(options);   

        Bing_NavBarSetup(BIRDSEYE_TAB);
    }

    function StreetMap_SetUpTab() {
        $(".pd_map_block").height(origMapHeight);
              
        this.Load_MediaMap({mapType: SEMap.MapType.road, showPushpins: true});        
        this.Directions_Clear();        
        Bing_NavBarSetup(STREETMAP_TAB);
    }

    function Directions_SetUpTab() {
        $(".pd_map_block").height(origMapHeight);

        this.Load_MediaMap({ mapType: SEMap.MapType.road, dashboardSize: SEMap.DashboardSize.small });
 
        $(".pd_map_container").addClass("pd_map_container_directions");

        if ($("#txtTo").val().length == 0)
            $("#txtTo").val(toAddress)
        if (SE_GetCookie("pd_last_from_address"))
            $("#txtFrom").val(SE_GetCookie("pd_last_from_address"));
        $(".pd_map_driving_directions_container").show();

        $(".pd_map_driving_directions").html("")
        var self = this;
        $("#btnDirectionsPrint").hide();
        $("#btnDirectionsGo").click(function () { self.Directions_Get(); });
        $("#btnDirectionsPrint").click(function () { self.Directions_Print(); });        
    }

    function Directions_Clear() {
        if (this.map) {
            this.map.clearRoute();
            $(".pd_map_driving_directions_container").hide();
            $(".pd_map_container").removeClass("pd_map_container_directions");
        }
    }

    function Directions_Get() {
        var self = this;
        $(".pd_map_driving_directions").html("");
        if ($("#txtFrom").val().length > 0 && $("#txtTo").val().length > 0) {
            this.map.getDirections($("#txtFrom").val(), $("#txtTo").val(),
                function (route, error) {

                    if ($('#pd_mediatabs').tabs('option', 'selected') == DIRECTIONS_TAB) {

                        if (route && error == null) {
                            $("#btnDirectionsPrint").show();
                            var turns = "<div class=pd_map_driving_directions_steps>Total distance: " + route.travelDistance;
                            turns += "<br/>Total time: " + route.travelDuration;
                            for (var iLeg = 0; iLeg < route.legs.length; iLeg++) {
                                turns += "<li>" + route.legs[iLeg] + "</li>";
                            }
                            turns += "</ol></div>";
                        }
                        else {
                            turns = "<div class='pd_map_driving_directions_steps'>"
                            + error + "</div>";
                        }
                        $(".pd_map_driving_directions").show().html(turns);
                        $(".pd_map_block").height(Math.max(($(".pd_map_driving_directions_container").height() * 1.2), origMapHeight) + "px");
                    }
                    else
                        self.Directions_Clear();
                }
            );
            SE_SetCookie("pd_last_from_address", $("#txtFrom").val());           
        }
        else
            alert("Please enter both \"From\" and \"To\" addresses.");
        return false;
    }    

    function Directions_Print() {

        var url = "/search/directions.aspx?"
            + "toAddress=" + escape($("#txtTo").val())
            + "&fromAddress=" + escape($("#txtFrom").val())
            + "&latitude=" + this.map.centerPoint.latitude
            + "&longitude=" + this.map.centerPoint.longitude
            + "&sourceApp=" + this.map.sourceApp
            + "&zoom=" + this.map.getZoomLevel()
            + "&print=yes";

        SE_OpenWin(url, 700, 900, 'directions');
    }

    function VirtualTour_SetUpTab() {
        $(".pd_virtual_tour_container").height(origMapHeight).show();

        if (virtualTourUrl != 'ShowVirtualTourTabWithoutPopup')
            SE_OpenWin(virtualTourUrl, 800, 600, 'virtualtour');
    }
        
}

PD_Media.prototype.Load_MediaMap = function (options) {

    if (this.map)
        this.map.killMe();
    
    this.map = new SEMap($(mediaMapSettings.div));

    this.map.clientID = 'ctlMediaMap_map';
    this.map.sourceApp = mediaMapSettings.sourceApp;
    this.map.centerPoint = mediaMapSettings.centerPoint;

    this.map.birdseyeOrientation = mediaMapSettings.birdseyeOrientation;
    this.map.birdseyeZoom = mediaMapSettings.birdseyeZoom;
    this.map.enableClickPopup = false;

    this.map.markers.push(mediaMapSettings.marker);
    this.map.markers[0].map = this.map;
    this.map.markers[0].location = mediaMapSettings.centerPoint;
    this.map.markers[0].setDefaultIcons();
   

    this.map.mapType = options.mapType ? options.mapType : SEMap.MapType.road;
    this.map.controlSize = options.dashboardSize ? options.dashboardSize : SEMap.DashboardSize.large;
    this.map.zoomLevel = options.zoomLevel ? options.zoomLevel : 14;
    if (options.mapType == SEMap.MapType.birdseye && mediaMapSettings.birdseyeZoom)
        this.map.zoomLevel = mediaMapSettings.birdseyeZoom;

    this.map.hideMapTypeSelector = true;

    this.map.init();
   
}


