//
// TSP-specific Google map functions
// Copyright (c) 2009 Fandango, Inc. 
//
// Global variables
//
var map;
var geocoder = new GClientGeocoder();
var mapInitialCenterPoint;
var mapInitialCenterPointTheaterIndex;
var mapInitialViewRect;
var numberOfTheaters;
var theaterCount;
var theaterInfoParams = [];
var theaterPopup = false;
var _currentTheaterIndex = -1;
var qsKeyAutoload = "theaterload";
var debug = false;

// Log a debug message to the console if we have a console
function log(msg) {
    if (typeof(console) != "undefined" && debug) {
        console.log(msg);
    }
}

// Called after every theater overlay (icon) created.  Sets up map when all theater pins have been added.
function addedTheater() {
    theaterCount++;

    // After last theater point is calculated, set up the map.       
    if (theaterCount == numberOfTheaters) {
        // Adjust zoom level so that all pushpins are visible and it's zoomed in as much as possible.
        var zoomLevel = Math.min(13, map.getBoundsZoomLevel(mapInitialViewRect));       // subtract - 1 to zoom out one additional level.
        map.setCenter(mapInitialViewRect.getCenter(), zoomLevel);
        
        setUpMapEvents();
        
        // Show map after the zoom and center have been set.
        $("#theaters_map").css("visibility", "visible");
    }
}

function addedTheaterPopupMap() {
	map.setCenter(mapInitialViewRect.getCenter(), 15);
	$("#theaters_map").css("visibility", "visible");
}

// Use Google geocoder if we don't have lat and lon data.
function createMarkerNoCoords(theaterData, geocodeAddress, index) {
    var result;
    try {
        geocoder.getLatLng(
            geocodeAddress,
            function(point) {
                if (!point) {
                    // Nothing to do
                    $("body").append("<!-- Geocode address: " + geocodeAddress + " not found" + " -->");
                } else {
                    $("body").append("<!-- Geocode address: " + geocodeAddress + " found, x=" + point.lat() + ", y=" + point.lng() + " -->");
                    result = createMarker(point, theaterData, index);
                    
                    // This is a callback function - so the calling function is long gone.  Add marker manually here.
                    map.addOverlay(result);
                }
				
				if(theaterPopup) {
					addedTheaterPopupMap();
				}
				else {
					addedTheater();
				}
            }
        );
    }
    catch (err) {
    }
    
    return result;
}

// Creates a marker at the given point with the given number label
function createMarker(point, theaterData, index) {
    //
    // Set up the icon.  "_iconProperties" should be defined in your page.
    //
    var baseIcon = new GIcon();
    baseIcon.iconSize = new GSize(_iconProperties.sizeX, _iconProperties.sizeY);
    baseIcon.iconAnchor = new GPoint(_iconProperties.anchorX, _iconProperties.anchorY);
    baseIcon.infoWindowAnchor = new GPoint(_iconProperties.infoWindowAnchorX, _iconProperties.infoWindowAnchorY);
    baseIcon.infoShadowAnchor = new GPoint(_iconProperties.infoShadowAnchorX, _iconProperties.infoShadowAnchorY);
    baseIcon.shadow = _iconProperties.shadowGraphicUrl;
    baseIcon.shadowSize = new GSize(_iconProperties.shadowGraphicSizeX,_iconProperties.shadowGraphicSizeY);
    var letteredIcon = new GIcon(baseIcon);
    letteredIcon.image = _iconProperties.iconUrlFunction(index);
    
    var marker = new GMarker(point, {icon:letteredIcon, title:theaterData.theaterName});
    theaterData.marker = marker;
    
    //
    // If we use tabs - second tab shows the theater's icon
    //
    // var infoTabs = [
    //     new GInfoWindowTab("Info", theaterData.tab1HTML),
    //     new GInfoWindowTab("Icon", contentSecondary)
    // ];
    
    GEvent.addListener(marker, "click", function() {
        // If tabs: marker.openInfoWindowTabsHtml(infoTabs);
        marker.openInfoWindowHtml(theaterData.tab1HTML);
        if (theaterData.onClickFunction != null) {
            theaterData.onClickFunction(index);
        }
    });
    
    // Record map center point (first theater)
    if (!mapInitialCenterPoint || mapInitialCenterPointTheaterIndex > index) {
        mapInitialCenterPoint = point;
        mapInitialCenterPointTheaterIndex = index;
        map.setCenter(mapInitialCenterPoint);
    }
    
    // Build rectangle containing each theater point
    if (!mapInitialViewRect) {
        mapInitialViewRect = new GLatLngBounds(point,  point);
    } else {
        mapInitialViewRect.extend(point);
    }
    
    return marker;
}

// Scroll a theater in the showtimes list into view.
function ScrollTheaterIntoView(index) {
    $(".theater .info h3:eq(" + index + ")")[0].scrollIntoView();    
}

// Perform various actions when theater dropdown list is changed.
function HandleDropDownChange(dropdown) {
    var selectedValue = dropdown.value;
    var delayForTracking = false;
    
    if (typeof(trackDropdownChange) == "function") {
        trackDropdownChange();
        delayForTracking = true;
    }
    
    if (selectedValue != '') {
        if (isNaN(selectedValue)) {
            if (delayForTracking) {
                triggeredDropDownList = dropdown;
                setTimeout("DropDownNav(triggeredDropDownList);", 500);
            } else {
                DropDownNav(dropdown);
            }
        } else {
            if (map) {
                theaterClicked(selectedValue);
            } else {
                ScrollTheaterIntoView(selectedValue);
            }
        }
    }
}

// Append (or change) an autoload value to the url.
function AppendAutoload(url, value) {
    var result = url;
    if (url != null && value != null) {
        var pos = url.search(qsKeyAutoload);
        if (pos != -1) {
            result = result.substring(0, pos - 1);
        }
        result += "&" + qsKeyAutoload + "=" + value;
    }
    return result;
}

// Runs after map is completely set up.
function setUpMapEvents() {
    // If we have a pagination event that caused a page change, autoload the next theater in the list.
    var uri = window.location.href;
    var theaterload = parseUri(uri).queryKey.theaterload;
    if (theaterload != null) {
        if (theaterload == "first") {
            theaterClicked(0);
        } else if (theaterload == "last") {
            theaterClicked(numberOfTheaters - 1);
        } else {
            theaterClicked(parseInt(theaterload));
        }
    } else {
        theaterClicked(0);
    }
}

// On the map view, make sure we can see at least 50 pixels worth of showtimes, scrolling the div as necessary.
function scrollShowtimesInfoView(index) {
    // Make sure the showtimes are in view - scroll the container to them.  The $(...)[0] index gets the DOM element from the jquery object.
    var pixelsToGuaranteeSeeing = 50;
    var topOfShowtimes = $(".tsp_map_details:eq(" + index + ")")[0].offsetTop;
    var heightOfMain = $("#theaterSummary").height();
    var pixelsWeCanSee = heightOfMain - topOfShowtimes;
    
    log('pixelsToGuaranteeSeeing=' + pixelsToGuaranteeSeeing + '; topOfShowtimes=' + topOfShowtimes + '; heightOfMain=' + heightOfMain + '; pixelsWeCanSee=' + pixelsWeCanSee);
    if (pixelsWeCanSee < pixelsToGuaranteeSeeing) {
        var pixelsToScroll = pixelsToGuaranteeSeeing - pixelsWeCanSee;
        var currentScroll = $("#theaterSummary").scrollTop();
        log('pixelsToScroll=' + pixelsToScroll + '; currentScroll=' + currentScroll);
        
        $("#theaterSummary").scrollTop(pixelsToScroll + currentScroll);
    }
}

// Set up UI for the theater indicated by index.
function theaterClicked(index, caller) {
    log("In theaterClicked(" + index + ")... _currentTheaterIndex = " + _currentTheaterIndex);
     
    // Don't continue if the theater is already selected.
    if (_currentTheaterIndex == index) {
        return;
    }
    
    if (map) {
        // This seems to be the best animation strategy for all browsers.  Sliding up and sliding down at once is not smooth in IE when there 
        // are a lot of movies and showtimes.
        if (_currentTheaterIndex >= 0) {
            log("sliding up: " + _currentTheaterIndex);
            $(".tsp_map_details:eq(" + _currentTheaterIndex + ")").hide();
        } 
        $(".tsp_map_details:eq(" + index + ")").slideDown('slow', function() { scrollShowtimesInfoView(index); });
        
        // Save current theater index for future reference.
        _currentTheaterIndex = index;
        
        // Open the info window on the map
        var theaterInfo = theaterInfoParams[index];
        map.closeInfoWindow();
        if (theaterInfo.marker != null) {
            theaterInfo.marker.openInfoWindowHtml(theaterInfo.tab1HTML);
        }
        
        // Manually hide any buy-button popup menus.
        $("div").filter(".showtimes_quickpick").each(function() {
            hideBuyButtonMenu($(this).attr("id"));
        });
    }

    // Record the current theater so if the user changes the date the correct theater will automatically open when the page refreshes.
    $("#select_showdate option").each(function() {
        var link = $(this).attr("value");
        var pos = link.search(qsKeyAutoload);
        if (pos != -1) {
            link = link.substring(0, pos - 1);
        }
        link += "&" + qsKeyAutoload + "=" + index;
        $(this).attr("value", link);
    });

    setTimeout("doPageChangeNonRefresh();", 500);  // Allow some time for animations/javascript to run.
}

// Record a page refresh when the page doesn't actually refresh, and reload the ads.
function doPageChangeNonRefresh() {
    // These lines must be in this order or Javascript becomes unhappy.
    DoWSSPageView();    // in scripts.js
    RefreshAds();       // in global.js
}

$(document).ready(function() {
    $(".theaterSummaryList h3 a").each(function(i) {
        // Set up click event for the theater list.
        $(this).click(function() {
            theaterClicked(i);
            return false;
        });
    });
});
