﻿/// <reference path="./Cineplex.js" />

Agility.RegisterNamespace("Cineplex.TheatreListing");

(function(TheatreListing) {
    TheatreListing.pageSize = 10; //default page size    

    var _isFirstLoad = true;

    $(function() {
        //bind the save as favourite action
        $("#theatre-listing-results .favouriteTheatre").live('click', function() {
            var theatreID = $(this).attr("theatreID");

            if (theatreID != undefined) {
                Cineplex.UserContext.AddFavoriteTheatre(theatreID);
                return false;
            }
        });

        //view map click
        $("#viewmap").click(Cineplex.MapTheatres);

        //get location from cookie
        var location = Cineplex.UserContext.GetCurrentLocation();
        
        //check for querystring value for location
        var qsLoc = Agility.QueryString("loc_cookie") || Agility.QueryString("location");
        if (qsLoc) {
            location = qsLoc;
        }

        //location search
        var setLocation = function(loc) {
            if (loc == undefined) {
                loc = $("#threatre-listing-location").val();
            }

            Cineplex.UserContext.SetCurrentLocation(loc, _populateListings);
        };

        //add autocomplete to location field
        $("#theatre-listing-location").autocomplete(Agility.ResolveUrl("~/Services/LocationAutoComplete.ashx"));

        $("#theatre-listing-location").keydown(function(event) {
            var keyCodeEntered = (event.which) ? event.which : event.keyCode;

            if (keyCodeEntered == 13) {
                setLocation($(this).val());
                return false;
            }
        });

        $("#theatre-listing-refresh-button").click(function() {
            setLocation($("#theatre-listing-location").val());
            return false;
        });

        //Get page index
        var pageIndex = Agility.QueryString('page');

        if (pageIndex == null || pageIndex == "") {
            pageIndex = 0;
        } else {
            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);
        }

        //link  up the map links
        $("#theatre-listing-results .MapLink").live("click", _mapLinkClick);
    });

    function _populateListings(location, pageIndex) {
        var minHeight = $("#mp").height();

        if (minHeight > 750) {
            minHeight = 750;
        }

        //set the height so we don't "jump"
        $("#theatre-listing-results").css("minHeight", minHeight).css("overflow", "hidden");

        //Show spinner        
        $("#theatre-listing-results").html(Cineplex.AjaxSpinner());

        if (location == undefined) {
            location = $("#theatre-listing-location").val();
        } else {

            $("#theatre-listing-location").val(location);
        }

        if (pageIndex == undefined) {
            pageIndex = 0;
        }

        //Scroll back to top        
        if (!_isFirstLoad) {
            $(document).scrollTo($("#TheatreListing"), {
                duration: 500,
                easing: "swing",
                onAfter: function() {
                    $("#theatre-listing-results").css("minHeight", null).css("overflow", "auto");
                }
            });
        }

        _isFirstLoad = false;

        //Load data
        TheatreListing.GetTheatres(location, pageIndex, function(data) {
            if (data == undefined || (data.d != undefined && data.d.length == 0)) {
                if (Cineplex_errMovieListingSearchNotCompleted != undefined) {
                    $("#theatre-listing-results").html('<div class="NoResultsMessage">' + Cineplex_errMovieListingSearchNotCompleted + '</div>');
                }
            } else {

                var results = $('#theatre-listing-results');
                results.setTemplateElement('theatre-listing-template');
                results.setParam("renderExclusiveContent", _renderExclusiveContent);
                results.setParam("urlEncode", _urlEncode);
                results.processTemplate(data.d);

                //Init pager
                Cineplex.InitializeAjaxPager($("#pnlTheatreListingPager"), TheatreListing.pageSize, pageIndex, data.total, function(newPageIndex) {
                    _populateListings(location, newPageIndex);
                });

                //load the similar cities
                $("#pnlSimilarCities").SimilarCities(function(newLocation) {
                    Cineplex.UserContext.SetCurrentLocation(newLocation, function(setLoc) {
                        _populateListings(setLoc);
                    });
                });
            }
        });
    }

    TheatreListing.GetTheatres = function(location, pageIndex, callback) {
        if (callback != null && typeof callback != "function") {
            alert("TheatreListing.GetTheatres: Callback arg is not a function");
            return;
        }

        if (location == null || location.length == 0) {
            return false;
        }

        var url = Agility.ResolveUrl('~/Services/TheatreLookup.ashx?func=getTheatreListings&callback=?');
        var formData = $('#theatreListingForm').serialize();

        if (formData == null || formData == "") {
            formData = 'location=' + escape(location);

            var tech = $('#theatre-listing-technology:checked');
            if (tech != null && tech.length > 0) {
                formData = formData + "&" + tech.val() + "=true";
            }
        }

        var query = formData + "&page=" + pageIndex + "&pagesize=" + TheatreListing.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);
			});
    }

    function _renderExclusiveContent(str) {
        if (str == null || str == "") return "";

        var div = $('<div></div>');
        div.html(str);

        return '<div class="ExclusiveContent">' + div.text() + "</div>";
    }

    function _urlEncode(str) {
        if (str == undefined) {
            return "";
        }

        return escape(str);
    }

    function _getMapLink(t) {
        var url = "http://maps.google.com/?q=";
        url += escape(t.Name) + "@" + t.Latitude + "," + t.Longitude;
        return url;
    }

    function _mapLinkClick() {
        var latitude = $(this).attr("latitude");
        var longitude = $(this).attr("longitude");
        var theatre = $(this).attr("theatre");
        var theatreid = $(this).attr("theatreid");

        if (Cineplex.ShowMapDialog([{
            latitude: latitude,
            longitude: longitude,
            theatre: theatre,
            theatreid: theatreid
}])) {
                return false;
            }
        }
    })(Cineplex.TheatreListing);