﻿/// <reference path="./Cineplex.js" />

Agility.RegisterNamespace("Cineplex.MovieListing");

(function(MovieListing) {
    MovieListing.pageSize = 10; //page size
    MovieListing.formId = "movieListingForm";
    MovieListing.releaseStateLabels = {};

    var _isFirstLoad = true;

    $(function() {
        //fix the left padding for this module
        $('#MovieListing').css('margin-left', '-10px');

        //bind to form submit
        $('#' + MovieListing.formId).submit(function() {
            var location = Cineplex.UserContext.GetCurrentLocation();
            _populateListings(location, 0);

            return false;
        });

        //bind the skinned dropdowns
        $("#lstMovieListingGenre").CineplexCombo({
            onchange: function(selected) {
                $('#txtGenre').val($(selected).attr('genreid'));
                return false;
            }
        });

        //bind the skinned dropdowns
        $("#lstMovieListingType").CineplexCombo({
            onchange: function(selected) {
                $('#txtType').val($(selected).attr('typeid'));
                return false;
            }
        });

        //bind the save as favourite action
        $("#lnkSaveMovieFavourite").click(function() {
            var filmID = parseInt($(this).attr("filmID"));
            if (!isNaN(filmID)) {
                Cineplex.UserContext.AddFavoriteMovie(filmID);
                return false;
            }
        });

        //bind radio buttons
        $('#movie-release-state-nowplaying').click(function() {
            var location = Cineplex.UserContext.GetCurrentLocation();
            _populateListings(location, 0);
        });

        $('#movie-release-state-comingsoon').click(function() {
            var location = Cineplex.UserContext.GetCurrentLocation();
            _populateListings(location, 0);
        });


        $('#movie-release-state-all').click(function() {
            var location = Cineplex.UserContext.GetCurrentLocation();
            _populateListings(location, 0);
        });

        //show adv filter click
        $('#ShowMovieListingAdvancedFilters').click(function() {
            MovieListing.showAdvancedFilterPanel();
            return false;
        });

        //view map click
        $("#viewmap").click(Cineplex.MapTheatres);

        //calendar
        $('#adv-release-start').datepicker({
			duration: "",
            buttonImage: Agility.ResolveUrl('~/Images/Buttons/btnCalendar.png'),
            buttonText: 'mm/dd/yy',
            buttonImageOnly: true,
            showOn: 'both',
            altFormat: 'mm/dd/yy',
            onSelect: function(dateText, input) {
                var label = $(this).data('labelObj');
                //hide
                if (dateText != "") {
                    label.css({ textIndent: -10000 });
                }
            }
        });

        $('#adv-release-end').datepicker({
			duration: "",
            buttonImage: Agility.ResolveUrl('~/Images/Buttons/btnCalendar.png'),
            buttonText: 'mm/dd/yy',
            buttonImageOnly: true,
            showOn: 'both',
            altFormat: 'mm/dd/yy',
            onSelect: function(dateText, input) {
                var label = $(this).data('labelObj');
                //hide
                if (dateText != "") {
                    label.css({ textIndent: -10000 });
                }
            }
        });

        //label overlays
        $('#adv-release-start-label').labelOver('over-apply');
        $('#adv-release-end-label').labelOver('over-apply');

        //location search
        var setLocation = function() {
            Cineplex.UserContext.SetCurrentLocation($("#movie-listing-location").val(), _populateListings);
        };

        //add autocomplete to location field
        $("#movie-listing-location").autocomplete(Agility.ResolveUrl("~/Services/LocationAutoComplete.ashx"));

        $("#movie-listing-location").keydown(function(e) {
            var keyCodeEntered = (e.which) ? e.which : e.keyCode;

            if (keyCodeEntered == 13) {
                setLocation();
                return false;
            }
        });

        $("#movie-listing-refresh-button").click(function() {
            setLocation();
            return false;
        });

        //check for location
        var location = Cineplex.UserContext.GetCurrentLocation();

        //Get page index
        var pageIndex = Agility.QueryString('page');

        if (pageIndex != undefined) {
            pageIndex = pageIndex - 1;
        }

        //location
        if (location == null) {
            //show the location and come back here when done...
            Cineplex.ShowLocationDialog(function(loc) {
                _populateListings(loc, pageIndex);
            });
        } else {
            _populateListings(location, pageIndex);
        }
    });

    function _populateListings(location, pageIndex) {

        //load spinner
        //set the height so we don't "jump"
        $("#movie-listing-results").css("minHeight", $("#mp").height()).css("overflow", "hidden");

        //Show spinner
        $("#movie-listing-results").html(Cineplex.AjaxSpinner());

        //Hide pager
        $('#pnlMovieListingPager').hide();
        
        //determine location
        if (location == undefined) {
            location = $("#movie-listing-location").val();
        } else {
            $("#movie-listing-location").val(location);
        }

        //fix page
        if (pageIndex == undefined) {
            pageIndex = 0;
        }

        //Scroll back to top        
        if (!_isFirstLoad) {
            $(document).scrollTo($("#MovieListing"), {
                duration: 500,
                easing: "swing",
                onAfter: function() {
                    $("#movie-listing-results").css("minHeight", null).css("overflow", 'auto');
                }
            });
        }

        _isFirstLoad = false;

        //Load data
        MovieListing.GetMovies(location, pageIndex, function(data) {

            //Update the title
            $("input:radio[@name=state]", $('#divReleaseStates')).click(function() {
                var checkedvalue = $(this).val();
                var h2 = $('#MovieListingTitle');
                if (checkedvalue == "NP") {
                    h2.text(h2.attr("title") + " " + MovieListing.releaseStateLabels.np);
                }
                else if (checkedvalue == "CS") {
                    h2.text(h2.attr("title") + " " + MovieListing.releaseStateLabels.cs);
                }
                else if (checkedvalue == "ALL") {
                    h2.text(h2.attr("title") + " " + MovieListing.releaseStateLabels.all);
                }
            });

            //Clear min height
            $("#movie-listing-results").css("minHeight", null);

            //build ui
            if (data == undefined || (data.d != undefined && data.d.length == 0)) {
                if (Cineplex_errMovieListingSearchNotCompleted != undefined) {
                    $("#movie-listing-results").html('<div class="NoResultsMessage">' + Cineplex_errMovieListingSearchNotCompleted + '</div>');
                }
            } else {
                var results = $('#movie-listing-results');
                results.setTemplateElement('movie-listing-template');
                results.setParam("renderExclusiveContent", _renderExclusiveContent);
                results.processTemplate(data.d);

                //Init
                Cineplex.InitializeAjaxPager($("#pnlMovieListingPager"), MovieListing.pageSize, pageIndex, data.total, function(newPageIndex) {
                    _populateListings(location, newPageIndex);
                });

                //Show pager
                $('#pnlMovieListingPager').show();

                //load the similar cities
                $("#pnlSimilarCities").SimilarCities(function(newLocation) {
                    Cineplex.UserContext.SetCurrentLocation(newLocation, function(setLoc) {
                        _populateListings(setLoc);
                    });
                });
            }
        });
    }

    function _renderExclusiveContent(str) {
        if (str == null || str == "") return "";

        var div = $('<div></div>');
        div.html(str);

        return '<div class="ExclusiveContent">' + div.text() + "</div>";
    }

    MovieListing.GetMovies = function(location, pageIndex, callback) {
        if (callback != null && typeof callback != "function") {
            alert("MovieListing.GetMovies: Callback arg is not a function");
            return;
        }

        if (location == null || location.length == 0) {
            return false;
        }

        var url = Agility.ResolveUrl('~/Services/MovieLookup.ashx?func=getMovieListings&callback=?');

        var query = $('#' + MovieListing.formId)
                        .find("input,textarea,select,hidden")
                        .not("#__VIEWSTATE,#__EVENTVALIDATION").serialize() + "&page=" + pageIndex + "&pagesize=" + MovieListing.pageSize;

        $.getJSON(url, query,
			function(data) {
			    //data class = { total : 99, d : [{ Title : "", ImageUrl : "", ReleaseDate : "", Runtime : "", Genre : "", Showtimes : "", TrailerUrl: "", FilMRating : { ImageUrl: "", Description: "", Warning: "" }}, ...
			    //                                  { Title : "", ImageUrl : "", ReleaseDate : "", Runtime : "", Genre : "", Showtimes : "", TrailerUrl: "", FilMRating : { ImageUrl: "", Description: "", Warning: "" } }] }
			    callback(data);
			});
    }

    MovieListing.closeAdvancedFilterPanel = function() {
        var filter = $('#divAdvancedFilter');
        filter.slideUp(500, function() {
            $('#' + MovieListing.formId + ' .Search').css('margin-bottom', '30px');
            $('#ShowMovieListingAdvancedFilters').show();
        });
    }

    MovieListing.showAdvancedFilterPanel = function() {
        $('#' + MovieListing.formId + ' .Search').slideDown(250, function() {
            $(this).css('margin-bottom', '14px');
            var filter = $('#divAdvancedFilter');

            filter.slideDown(500, function() {
                $('#ShowMovieListingAdvancedFilters').hide();
            });
        });
    }
    
    function _trim(str) {
        return str.replace(/^\s+/, "").replace(/\s+$/, "");
    }
    
    MovieListing.BuildGenreLinks = function(genres) {
        var split = (genres || "").split(","),
            resultArr = [],
            linkHtml, genre;
        for(var i = 0; i < split.length; i++) {
            genre = _trim(split[i]);
            linkHtml = "<a href=\"" + Cineplex.MovieListing.moviesUrl + "?state=ALL&genre=" + encodeURIComponent(genre) + "\">" + genre + "</a>";
            resultArr.push(linkHtml);
        }
        return resultArr.join(", ");
    }

})(Cineplex.MovieListing);