﻿function searchLocationsNear(zoomClick) {
    var select = document.getElementById("selDay");
    var searchUrl = '/services/theater/theaterdetail.aspx?format=xml&date=' + select.options[select.selectedIndex].value + '&movieIdLIst=' + getSelectedMovieList() + '&lat=' + lat + '&lng=' + lng + '&nelat=' + map.getBounds().getNorthEast().lat() + '&nelng=' + map.getBounds().getNorthEast().lng() + '&swlat=' + map.getBounds().getSouthWest().lat() + '&swlng=' + map.getBounds().getSouthWest().lng();
    GDownloadUrl(searchUrl, function(data) {
        var intheatersListings = document.getElementById('ctl00_cphContent_intheaters_listings');
        if (intheatersListings != null)
            intheatersListings.style.display = "none";
        var xml = GXml.parse(data);
        var theaters = xml.documentElement.getElementsByTagName("theater");
        map.clearOverlays();
        var sidebar = document.getElementById('theaters_sidebar');
        sidebar.innerHTML = '';
        var movielist = document.getElementById("movielist");
        if (theaters.length < 5) {
            if (zoomClick == false) {
                var zoomLevel = map.getZoom();
                if (zoomLevel > 8) {
                    map.setZoom(zoomLevel - 1);
                    searchLocationsNear(false);
                    return;
                }
            }
            if (theaters.length == 0) {
                movielist.innerHTML = "";
                sidebar.innerHTML = '<div class="theater" style="padding: 10px; font-size: 12px; color: #cc0000;">No theaters are available within the current map area. Please zoom out or enter a new city, state or zip in the search area.</div>';
                return;
            }            
        }
        else if (theaters.length > 26) {
            if (zoomClick == false) {
                var zoomLevel = map.getZoom();
                if (zoomLevel < 15) {
                    map.setZoom(zoomLevel + 1);
                    searchLocationsNear(false);
                    return;
                }
            }
            movielist.innerHTML = "";
            sidebar.innerHTML = '<div class="theater" style="padding: 10px; font-size: 12px; color: #cc0000;">More than 26 theaters found. Please zoom in or refine your search.</div>';
            return;
        }
        var bounds = new GLatLngBounds();
        for (var i = 0; i < theaters.length; i++) {
            var theaterid = theaters[i].getAttribute('theaterid');
            var name = theaters[i].getAttribute('name');
            var street = theaters[i].getAttribute('street');
            var city = theaters[i].getAttribute('city');
            var state = theaters[i].getAttribute('state');
            var postalcode = theaters[i].getAttribute('postalcode');
            var address = street + ' ' + city + ', ' + state + ' ' + postalcode;
            var telephone = theaters[i].getAttribute('telephone');
            var friendlyTheaterName = theaters[i].getAttribute('friendlyTheaterName');
            var distance = parseFloat(theaters[i].getAttribute('distance'));
            var point = new GLatLng(parseFloat(theaters[i].getAttribute('lat')), parseFloat(theaters[i].getAttribute('lng')));

            var marker = createMarker(point, name, street, city, state, postalcode, i);
            map.addOverlay(marker);
            var sidebarEntry = createSidebarEntry(marker, name, address, distance, theaterid, friendlyTheaterName, telephone, theaters[i].getAttribute('ticketsAvail'), i);
            sidebar.appendChild(sidebarEntry);
            bounds.extend(point);
        }
        if ($('a.theater-expando') != null) $('a.theater-expando').click(clickTheater);

        var selectedMovieList = getSelectedMovieList();
        if (selectedMovieList.length == 0) {
            movielist.innerHTML = "";
            var movies = xml.documentElement.getElementsByTagName("movie");
            movies = uniqueMovies(movies);
            for (var i = 0; i < movies.length; i++) {
                var movieId = movies[i].getAttribute('id');
                var movieName = movies[i].getAttribute('name');
                movielist.appendChild(createMovieEntry(movieId, movieName));
            }
        }
    });
}
function uniqueMovies(a) {
    var r = new Array();
    o: for (var i = 0, n = a.length; i < n; i++) {
        for (var x = 0, y = r.length; x < y; x++) {
            if (r[x].getAttribute('id') == a[i].getAttribute('id')) continue o;
        }
        r[r.length] = a[i];
    }
    return r;
}
function createMarker(point, name, street, city, state, postalcode, index) {
    var baseIcon = new GIcon();
    baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
    baseIcon.iconSize = new GSize(20, 34);
    baseIcon.shadowSize = new GSize(37, 30);
    baseIcon.iconAnchor = new GPoint(9, 34);
    baseIcon.infoWindowAnchor = new GPoint(9, 2);
    var letteredIcon = new GIcon(baseIcon);
    var letter = String.fromCharCode("A".charCodeAt(0) + index);
    letteredIcon.image = "http://www.google.com/mapfiles/marker" + letter + ".png";
    markerOptions = { icon: letteredIcon };
    var marker = new GMarker(point, markerOptions);
    var html = '<b>' + name + '</b> <br/>' + street + '<br/>' + city + ', ' + state + ' ' + postalcode;
    GEvent.addListener(marker, 'click', function() { marker.openInfoWindowHtml(html); });
    GEvent.addListener(marker, "infowindowopen", function() { no_update = true; });
    GEvent.addListener(marker, "infowindowclose", function() { no_update = false; });
    return marker;
}
function createSidebarEntry(marker, name, address, distance, theaterid, friendlyTheaterName, telephone, ticketsAvail, index) {
    var div = document.createElement('div');
    div.className = "theater";
    var letter = String.fromCharCode("A".charCodeAt(0) + index);
    var image = "transparent url(http://www.google.com/mapfiles/marker" + letter + ".png) no-repeat; cursor: pointer;";
    var html = '<div class="result-number" style="background:' + image + '" ></div>' +
                '<a class="theater-expando" href="/theater/' + theaterid + '/' + friendlyTheaterName + '"></a>' +
            '<h2> <a href="/theater/' + theaterid + '/' + friendlyTheaterName + '">' + name + ' (' + distance.toFixed(1) + ') ' + '</a><span>' + telephone + '</span>' +
            '<a style="position: absolute; right: 10px;  font-weight: normal;" target="_blank" href="http://maps.google.com/maps?q=to ' + address + '">Get Directions</a><p>' + address + '</p>';
    if (ticketsAvail == '1')
        html += '<span style=" position: absolute; right: 10px; top: 17px;" class="fandango-tickets listings">Click a linked showtimes to buy tickets.</span></h2>';
    else
        html += '</h2>';
    div.innerHTML = html;
    GEvent.addDomListener(div.firstChild, 'click', function() {
        GEvent.trigger(marker, 'click');
    });
    return div;
}
function createMovieEntry(movieId, movieName) {
    var div = document.createElement('li');
    var html = '<input id="cbMovieName" type="checkbox" class="cb-moviename" movieid=' + movieId + '>' +
                '<label id="lblMovieName">' + movieName + '</label>';
    div.innerHTML = html;
    return div;
}
function getLocation(address) {
    geocoder.getLatLng(address, function(latlng) {
        if (!latlng) {
            return false
        } else {
            lat = latlng.lat()
            lng = latlng.lng()
        }
    });
}
function getSelectedMovieList() {
    var movieNameCB = $('.cb-moviename');
    var movieList = '';
    if (movieNameCB != null) {
        for (var i = 0; i < movieNameCB.length; i++) {
            if (movieNameCB[i].checked) {
                movieList += $(movieNameCB[i]).attr('movieid'); movieList += ",";
            }
        }
    }
    return movieList;
}
function doClear(textinput) { if (textinput.value == textinput.defaultValue) { textinput.value = "" } }
function setDefault(textinput) { if (textinput.value == '') { textinput.value = textinput.defaultValue } }
function onkeySearch(event, textinput) { if (event.keyCode && event.keyCode == 13) { event.preventDefault();if (textinput.value != textinput.defaultValue) { window.location = "/theaters/" + textinput.value; } } }