﻿// 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);
$(document).ready(function() {

    var PHOTO_TAB = 0;
    var BIRDSEYE_TAB = 1;
    var STREETMAP_TAB = 2;
    var DIRECTIONS_TAB = 3;
    var VIRTUALTOUR_TAB = 4;

    var currentTab = SE_PD_InitialTab;
    var currentPhoto = -1;
    var hasTabs = SetTabVisibility();
    var PhotosSlideShowInterval = 0;
    var PhotosSlideShowDelay = 3000;

    var origMapHeight = $(".pd_map_block").css("height");
    if (origMapHeight)
        origMapHeight = origMapHeight.replace("px", "");
    if (typeof (origMapHeight) == 'undefined' || parseInt(origMapHeight) < 300)
        origMapHeight = 300;
    if (!hasTabs) {
        $("#pd_mediatabs").hide();
        return;
    }
    $('#pd_mediatabs').tabs(
        { selected: currentTab,
            show: function() {
                var selectedIndex = $('#pd_mediatabs').tabs('option', 'selected');

                ShowTabPanels();

                switch (parseInt(selectedIndex)) {
                    case PHOTO_TAB:
                        Photos_SetUpTab();
                        break;
                    case BIRDSEYE_TAB:
                        BirdsEye_SetUpTab();
                        break;
                    case STREETMAP_TAB:
                        StreetMap_SetUpTab();
                        break;
                    case DIRECTIONS_TAB:
                        Directions_SetUpTab();
                        break;
                    case VIRTUALTOUR_TAB:

                        VirtualTour_SetUpTab();
                        break;
                }
                $('#pd_media_tabs_list').show("fast");
            }
        }
    );

    function SetTabVisibility() {

        var hasTabs = false;
        if (photoCount == 0) {
            $("#pd_media_li_photos").hide();
        }
        else {
            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 latLon = new VELatLong(centerPoint.latitude, centerPoint.longitude);
            var beMap = new VEMap("divBETestMap");
            beMap.SetDashboardSize(VEDashboardSize.Tiny);
            beMap.LoadMap(latLon, 17);
            beMap.AttachEvent("onobliqueenter", function() { $("#pd_media_li_birdseye").show(); });

            if (!hasTabs)
                currentTab = BIRDSEYE_TAB;
            hasTabs = true;

        }

        if (virtualTourUrl == "")
            $("#pd_media_li_virtual_tour").hide();
        else {
            if (!hasTabs) currentTab = VIRTUALTOUR_TAB;
            hasTabs = true;
        }
        return hasTabs;
    }
    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) {
            Photos_GetSizes();
            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 foundTargetAspect = false;
        $(".pd_photos_tab_photos img").each(function() {
            var img = new Image();
            img.src = $(this).attr("src");
            var aspectRatio = img.width / img.height;

            if (!foundTargetAspect && aspectRatio > 1 && aspectRatio < 2) {
                imgWidth = $(".pd_photos_tab_main").width();

                if (!isNaN(maxWidth) && imgWidth > maxWidth) {
                    imgWidth = maxWidth;
                }
                if (maxHeight && !isNaN(maxHeight) && imgHeight > maxHeight) {
                    imgHeight = maxHeight;
                }
                else {
                    imgHeight = imgWidth / aspectRatio;
                }
                foundTargetAspect = true; ;
            }
            $(this).data('origHeight', img.height);
            $(this).data('origWidth', img.width);
            origMapHeight = imgHeight;
        })
        var photoIndex = 0
        $(".pd_photos_tab_photos img").each(function() {
            var aspectRatio = $(this).data('origWidth') / $(this).data('origHeight');

            if (aspectRatio > 1 && aspectRatio < 2) {
                $(this).data('newHeight', imgHeight);
                $(this).data('newWidth', imgWidth);
            } else if (aspectRatio < 1) {
                $(this).data('newHeight', imgHeight);
                $(this).data('newWidth', imgHeight * aspectRatio);
            } else if (aspectRatio > 2) {
                $(this).data('newHeight', imgHeight / aspectRatio);
                $(this).data('newWidth', imgWidth);
            }
            else {
                $(this).data('newHeight', imgHeight);
                $(this).data('newWidth', imgWidth);
            }
            $(this).data('photoIndex', photoIndex);
            photoIndex++;

        })
        $("#pd_tabular_selector").height(imgHeight);
    }

    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()
                - $(".pd_photos_tab_main img").outerHeight()) / 2, 0);

            $(".pd_photos_tab_main").css("margin-top", vertMargin);

            var img = new Image();
            img.onload = function() {
                var mainImg = wrap.find("img").attr("src", url);
            };
            img.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 {
            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();
            $("#MSVE_navAction_ObliqueMapView").hide();
        }
    }

    function BirdsEye_SetUpTab() {

        Directions_Clear();
        $(".pd_map_block").height(origMapHeight);
        ctlMap._reSize();

        if (ctlMap.getZoomLevel > 2)
            ctlMap.zoomLevel = 2;
        ctlMap.fitMarkers();
        if (!ctlMap.map) {
            Load_ctlMap(VEMapStyle.Birdseye);
            ctlMap.map.AttachEvent("onobliqueenter", function() {
                ctlMap.map.SetMapStyle(VEMapStyle.Birdseye);
                ctlMap.addMarkers(); 
            });
        }
        else
            ctlMap.map.SetMapStyle(VEMapStyle.Birdseye)



        Bing_NavBarSetup(BIRDSEYE_TAB);
    }

    function StreetMap_SetUpTab() {
        $(".pd_map_block").height(origMapHeight);
        if (ctlMap.map) ctlMap.map.Dispose();
        ctlMap.map = null;

        Load_ctlMap(VEMapStyle.Road);
        ctlMap._reSize();
        Directions_Clear();
        ctlMap.addMarkers();
        Bing_NavBarSetup(STREETMAP_TAB);

    }

    function Directions_SetUpTab() {
        $(".pd_map_block").height(origMapHeight);
        if (ctlMap.map) ctlMap.map.Dispose();
        ctlMap.map = null;

        Load_ctlMap(VEMapStyle.Road, VEDashboardSize.Small);

        ctlMap._reSize();

        $(".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("")

        $("#btnDirectionsPrint").hide();
        $("#btnDirectionsGo").click(Directions_Get);
        $("#btnDirectionsPrint").click(Directions_Print);
    }

    function Directions_Clear() {
        if (ctlMap.map) {
            ctlMap.map.DeleteRoute();
            $(".pd_map_driving_directions_container").hide();
            $(".pd_map_container").removeClass("pd_map_container_directions");
        }
    }

    function Directions_Get() {

        $(".pd_map_driving_directions").html("");
        if ($("#txtFrom").val().length > 0 && $("#txtTo").val().length > 0) {
            ctlMap.getDirections($("#txtFrom").val(), $("#txtTo").val(), Directions_OnGotRoute);
            SE_SetCookie("pd_last_from_address", $("#txtFrom").val());
            ctlMap.clearMarkers();
        }
        else
            alert("Please enter both \"From\" and \"To\" addresses.");
        return false;
    }

    function Directions_OnGotRoute(turns) {

        if ($('#pd_mediatabs').tabs('option', 'selected') == DIRECTIONS_TAB) {

            $("#btnDirectionsPrint").show();

            $(".pd_map_driving_directions").show().html(turns);
            $(".pd_map_block").height(Math.max(($(".pd_map_driving_directions_container").height() * 1.2), origMapHeight) + "px");
            ctlMap._reSize();
        }
        else
            Directions_Clear();
    }

    function Directions_Print() {

        var url = "/search/directions.aspx?"
            + "toAddress=" + escape($("#txtTo").val())
            + "&fromAddress=" + escape($("#txtFrom").val())
            + "&latitude=" + ctlMap.centerPoint.latitude
            + "&longitude=" + ctlMap.centerPoint.longitude
            + "&sourceApp=" + ctlMap.sourceApp
            + "&zoom=" + ctlMap.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');
    }

    //    function ShowDivDialog(html) {

    //        if (html) {
    //            $("#pd_media_dialog").dialog("open");
    //            $("#pd_media_dialog iframe").hide();
    //            $("#pd_media_dialog div").html(html).show();
    //            $(".ui-widget-overlay").click(function() {
    //                $(this).hide();
    //                $("#pd_media_dialog").dialog('close');
    //            })
    //        }
    //        return false;
    //    }
})

//function MLX_SetupIFrameDialog(jqDialog, Width, Height) {
//    jqDialog.dialog({
//        autoOpen: false,
//        modal: true,
//        height: (Height ? Height : Math.min((.9 * $(window).height()), 800)) + 14,
//        width: (Width ? Width : Math.min((.9 * $(window).width()), 1024)) + 14,
//        position: 'center',
//        closeOnEscape: true,
//        close: function() { $(jqDialog.selector + " iframe").attr("src", "/common/blank.htm"); }
//    });
//}

//function MLX_ShowIFrameDialog(src) {
//    if (src) {
//        $("#pd_media_dialog").dialog("open");
//        $("#pd_media_dialog iframe").attr("src", src).show();
//        $("#pd_media_dialog iframe").attr("scrolling", "no").show();
//        $(".ui-widget-overlay").click(function() {
//            $(this).hide();
//            $("#pd_media_dialog").dialog('close');
//        })
//    }
//    return false;
//}

