﻿/// <reference path="./JavascriptConstants.aspx/Cineplex.Constants.js" />
/// <reference path="./API/Agility.UGC.API.js" />
/// <reference path="./External/jquery.cookies.2.2.0.js" />
/// <reference path="./External/jquery.autocomplete-vsdoc.js" />

if (window["isIE6"] == null) {
    window["isIE6"] = /msie|MSIE 6/.test(navigator.userAgent);
}

Agility.RegisterNamespace("Cineplex");
Agility.RegisterNamespace("Cineplex.UserContext");

(function(Cineplex) {


    _cineplexUserProfileDS = null;

    $(function() {
        var loc_cookie = Agility.QueryString("loc_cookie");
        if (loc_cookie) {
            Cineplex.UserContext.SetCurrentLocation(loc_cookie);
        }

        //add the logout link if neccessary
        if (Cineplex.UserContext.IsAuthenticated()) {
            var linkElem = $("#cineplex-h .TopLinks");
            var linkHtml = linkElem.html();
            var logoutLink = Cineplex.Constants.Values.lnkLogout;
            if (logoutLink == undefined) logoutLink = "Logout";
            linkHtml = "<a id='lnkLogoutGlobal' href='/Logout.aspx'>" + logoutLink + "</a>" + linkHtml;
            linkElem.html(linkHtml);
            $("#lnkLogoutGlobal").click(Cineplex.UserContext.Logout);
        }

	if (Cineplex.GetCurrentLanguage() == "fr-ca") {
            $("#shareThis").css("background", "url(http://www.cineplex.com/ecms.ashx/fr/shareThisUpdateBG.jpg) bottom left no-repeat").css("padding", "4px 0 0 6px").css("width", "304px").css("height", "36px").css("margin-bottom","10px");
        }
        else {
            $("#shareThis").css("background", "url(http://www.cineplex.com/ecms.ashx/en/shareThisUpdateBG.jpg) bottom left no-repeat").css("padding", "4px 0 0 6px").css("width", "304px").css("height", "36px").css("margin-bottom", "10px");
        }

        //Show the label text in the input box
        $('#cineplex-search-label').labelOver('over-apply');

        //Add binding to trap enter key in the search input box
        $('#cineplex-search-q').keydown(function(event) {
            var keyCodeEntered = (event.which) ? event.which : event.keyCode;

            if (keyCodeEntered == '10' || keyCodeEntered == '13') {
                event.preventDefault();
                event.stopPropagation();
                $('#cineplex-h-search-form').submit();
                return false;
            }

            return true;
        });

        //Find a theatre, find a movie and find in store
        $('#cineplex-h-nav .Widget').hover(function() {
            $(this).data("org", $(this).attr("src"));
            $(this).attr("src", $(this).attr("hover"));
        }, function() {
            $(this).attr("src", $(this).data("org"));
        });


        //init the scrollers...

        $("div.cineplexscroller").each(function() {
            var elem = $(this);
            var size = parseInt(elem.attr("pageSize"));
            if (isNaN(size)) size = 5;

            //adjust the min height if neccessary (60 is the height of the scroller header on movie items and store items)
            var minHeightTest = $(".items", elem).height() + 60;

            if (minHeightTest > elem.height()) {
                elem.css("minHeight", minHeightTest);
            }

            elem.scrollable({ size: size, clickable: false }).navigator();

        });

        //init the box office tabs
        $("#boxOfficeTabs").tabs();


        //location selection
        $("#cineplex-choose-location").CineplexDialog({
            width: 380,
            height: 210,
            fixedHeight: true,
            top: 180,
            modal: true,
            autoOpen: false,
            closeText: '',
            close: function(event, ui) {
            }
        });

        // Slide Toggle of Terms and Conditions Corporate Sales - Corporate Products
        $(document).ready(function() {
            //hide the all of the element with class msg_body
            $(".msg_body").hide();
            //toggle the componenet with class msg_body
            $(".msg_head").click(function() {
                $(this).next(".msg_body").slideToggle(600);
            });

            $("#divFamousArchive div.MP a").html("&nbsp;");

        });


        //theatre picker
        $('#cineplex-find-a-theatre').CineplexDialog({
            width: 582,
            height: 336,
            top: 180,
            modal: true,
            autoOpen: false,
            closeText: '',
            close: function(event, ui) {
                var div = $('#cineplex-find-a-theatre');

                if (div.data('initHTML') != null) {
                    div.html(div.data('initHTML'));
                }
            }
        });

        //movie picker
        $('#cineplex-find-a-movie').CineplexDialog({
            width: 582,
            height: 336,
            top: 180,
            modal: true,
            autoOpen: false,
            closeText: '',
            close: function(event, ui) {
                var div = $('#cineplex-find-a-movie');

                if (div.data('initHTML') != null) {
                    div.html(div.data('initHTML'));
                }
            }
        });

        //store
        $('#cineplex-find-in-store').CineplexDialog({
            width: 582,
            height: 336,
            top: 180,
            modal: true,
            autoOpen: false,
            closeText: '',
            close: function(event, ui) {
                var div = $('#cineplex-find-in-store');

                if (div.data('initHTML') != null) {
                    div.html(div.data('initHTML'));
                }
            }
        });

        //video dialog
        $("#cineplex-video-dialog").CineplexDialog({
            width: 658,
            height: 385,
            modal: true,
            autoOpen: false,
            close: function(event, ui) {
                $("#cineplex-video-dialog").html("");
            }
        });

        //maps dialog
        $("#cineplex-map-dialog").CineplexDialog({
            width: 685,
            height: 550,
            modal: true,
            autoOpen: false,
            close: function(event, ui) {
                $("#cineplex-map-dialog").html("");
            }
        });

        //Hookup nav buttons
        $('#cineplex-lnkNav-Theatre').click(_theatreSelectionDialog);
        $('#cineplex-lnkNav-Movie').click(_movieSelectionDialog);
        $('#cineplex-lnkNav-Store').click(_findInStoreDialog);

        //hook up the trailer links and the "location based url" links...
        $(document).click(_handleDocumentClickForAnchorTags);

        //footer dropdowns
        var comboArgs = {
            onchange: function() {
                return true;
            }
        };
        $("#cineplex-ft-theatre-dropdown").CineplexCombo(comboArgs);
        $("#cineplex-ft-showtime-dropdown").CineplexCombo(comboArgs);

    });

    function _findInStoreDialog(event) {
        var div = $('#cineplex-find-in-store');

        if (div.data('initHTML') == null) {
            div.data('initHTML', div.html());
        }

        div.CineplexDialog('open');

        div.load(Agility.ResolveUrl('~/Dialogs/Find-In-Store.aspx'), "cb=" + new Date().getTime(), null);

        return false;
    }

    function _movieSelectionDialog(event) {
        ///do the movie select dialog

        //check for location
        var location = Cineplex.UserContext.GetCurrentLocation();

        if (location == null) {
            //show the location and come back here when done...
            Cineplex.ShowLocationDialog(function() {
                _movieSelectionDialog(event);
            });
            return false;
        }

        var div = $('#cineplex-find-a-movie');

        if (div.data('initHTML') == null) {
            div.data('initHTML', div.html());
        }

        //Show dialog
        div.CineplexDialog('open');

        div.load(Agility.ResolveUrl('~/Dialogs/Find-A-Movie.aspx'), "cb=" + new Date().getTime(), function(response, textStatus, request) {
            var input = $('#movie-search-city');
            input.val(location);
            input.autocomplete(Agility.ResolveUrl("~/Services/LocationAutoComplete.ashx"));
            input.focus();

            //bind search
            input.keypress(function(event) {
                var keyCodeEntered = (event.which) ? event.which : event.keyCode;
                if (keyCodeEntered == '10' || keyCodeEntered == '13') {
                    Cineplex.ShowMovies();

                    return false;
                }

                return true;
            });

            $('#movie-search-button').click(function() {
                Cineplex.ShowMovies();
                return false;
            });

            //run the initial search
            if (location != "") {
                Cineplex.ShowMovies();
            }
        });
        return false;
    }

    function _theatreSelectionDialog(event) {
        ///do the theatre select dialog

        //check for location
        var location = Cineplex.UserContext.GetCurrentLocation();

        if (location == null) {
            //show the location and come back here when done...
            Cineplex.ShowLocationDialog(function() {
                _theatreSelectionDialog(event);
            });
            return false;
        }

        var div = $('#cineplex-find-a-theatre');

        if (div.data('initHTML') == null) {
            div.data('initHTML', div.html());
        }

        //Show dialog
        div.CineplexDialog('open');

        div.load(Agility.ResolveUrl('~/Dialogs/Find-A-Theatre.aspx'), "cb=" + new Date().getTime(), function(response, textStatus, request) {
            var input = $('#theatre-search-city');
            input.autocomplete(Agility.ResolveUrl("~/Services/LocationAutoComplete.ashx"));
            input.val(location);
            input.focus();

            //bind search
            input.keypress(function(event) {
                var keyCodeEntered = (event.which) ? event.which : event.keyCode;
                if (keyCodeEntered == '10' || keyCodeEntered == '13') {
                    Cineplex.ShowTheatres();

                    return false;
                }

                return true;
            });


            $('#theatre-search-button').click(function() {
                Cineplex.ShowTheatres();
                return false;
            });

            //run the initial search
            if (location != "") {
                Cineplex.ShowTheatres();
            }
        });

        return false;
    }

    Cineplex.ShowLocationDialog = function(callback) {
        /// <summary>
        /// Shows the location selection dialog
        /// </summary>        
        /// <param name="callback" type="Function">The callback function that will be called on "submit".</param> 

        $("#cineplex-choose-location .LocSearching").hide();
        var searchArea = $("#cineplex-choose-location .LocationSelectionArea").html("");
        $("#cineplex-choose-location").CineplexDialog("open");

        //pop the search box in there...
        var html = '<div class="Search"><div class="SearchBox"><div class="SearchBoxTop"></div><div class="SearchBoxMiddle">';
        html += '<input class="SearchInput" value="" type="text" />';
        html += '</div><div class="SearchBoxBottom"></div></div>';
        var imgUrl = Agility.ResolveUrl("~/Images/Buttons/" + Cineplex.GetCurrentLanguage() + "/btnSubmit.png");
        html += '<input class="SearchButton" type="image" src="' + imgUrl + '" alt="Submit" name="" />';
        html += '<div class="Clear"></div></div>';

        var searchArea = $("#cineplex-choose-location .LocationSelectionArea").html(html);
        $("#cineplex-choose-location .LocNotFound").hide();

        //add the location autocomplete...
        $(".SearchInput", searchArea).autocomplete(Agility.ResolveUrl("~/Services/LocationAutoComplete.ashx"));
        $(".SearchInput", searchArea).focus();

        //bind the click event
        $(".SearchButton", searchArea).click(function() {
            var location = $.trim($(".SearchInput", searchArea).val());
            if (location != "") {
                $("#cineplex-choose-location .LocNotFound").hide();
                $("#cineplex-choose-location .LocSearching").show();

                Cineplex.UserContext.SetCurrentLocation(location, function(newLocation) {
                    $("#cineplex-choose-location .LocSearching").hide();

                    if (newLocation == "") {
                        $("#cineplex-choose-location .LocNotFound").show();
                    } else {
                        $("#cineplex-choose-location").CineplexDialog("close");
                        callback(newLocation);
                    }
                });
            }
            return false;
        });

        //bind the enter key click        
        $(".SearchInput", searchArea).keydown(function(event) {
            if (event.keyCode == 13) {
                var location = $.trim($(".SearchInput", searchArea).val());
                if (location != "") {

                    $("#cineplex-choose-location .LocNotFound").hide();
                    $("#cineplex-choose-location .LocSearching").show();

                    Cineplex.UserContext.SetCurrentLocation(location, function(newLocation) {
                        $("#cineplex-choose-location .LocSearching").hide();

                        if (newLocation == "") {
                            $("#cineplex-choose-location .LocNotFound").show();
                        } else {
                            $("#cineplex-choose-location").CineplexDialog("close");
                            callback(newLocation);
                        }
                    });
                }
                return false;
            }
        });

    }

    Cineplex.EndRequestHandler = function(src, args) {

        ///the end request handler for Update Panels...
        if (args.get_error != undefined && args.get_error() != null) {
            args.set_errorHandled(true);
            alert("An error has occurred.  Please try the action again.");
        }
    }

    Cineplex.GetCurrentLanguage = function() {
        return window.Cineplex_Language;
    }

    Cineplex.GetCookieDomain = function() {
        return window.Cineplex_CookieDomain;
    }



    Cineplex.ShowMapDialog = function(theatreMappings) {
        /// <summary>
        /// Shows the map dialog.
        /// </summary>
        /// <parameter name="theatreMappings" type="Array">Array of theatre mapping objects with name,latitude and longitude fields.</parameter>

        if (theatreMappings == undefined || !$.isArray(theatreMappings)) return false;
        
        // wire up objects
        var mapLegend = new Cineplex.MapLegend(),
            mapDataService = new Cineplex.MapDataService(),
            mapPointCache = new Cineplex.MapPointCache(),
            iconLookup = new Cineplex.IconLookup(),
            theatreMap = new Cineplex.TheatreMap(mapDataService, mapLegend, mapPointCache, iconLookup),
            mapDialog = new Cineplex.MapDialog(theatreMap);
        
        mapDialog.open(theatreMappings);
        
        return true;

    }


    Cineplex.MapTheatres = function() {

        var location = Cineplex.UserContext.GetCurrentLocation();

        if (location == null) {
            //show the location and come back here when done...
            Cineplex.ShowLocationDialog(function() {
                Cineplex.MapTheatres();
            });
            return false;
        }

        var url = Agility.ResolveUrl('~/Services/CineplexTopNav.ashx?func=getTheatres&callback=?')
        $.getJSON(url, "pgsize=999&city=" + encodeURI(location),

			function(data) {
			    //data class = { Message = "", d = [[{Name = "", Address = "", Telephone = "", ID = "" }, ... {Name = "", Address = "", Telephone = "", ID = "" }]]

			    if (data == undefined || data.d == undefined || !$.isArray(data.d)) {
			        //show nothing...
			        if (data && data.Message != null) {
			            alert(data.Message);
			        }
			        return;
			    }


			    var lst = new Array();

			    for (var i = 0; i < data.d.length; i++) {
			        var ary = data.d[0];
			        for (var p = 0; p < ary.length; p++) {
			            var t = {
			                theatre: ary[p].Name,
			                latitude: ary[p].Latitude,
			                longitude: ary[p].Longitude,
			                theatreid: ary[p].ID
			            }
			            lst[lst.length] = t;
			        }
			    }


			    Cineplex.ShowMapDialog(lst);


			});
        return false;
    }

    var Cineplex_Random = Math.floor(Math.random() * 1100000);

    Cineplex.GetTicketingLink = function(showtime) {
        /// <summary>
        /// Gets the ticketing link.  Used in Client Templated listings.
        /// </summary>
        /// <parameter name="showtime" type="object">The showtime json object.</parameter>

        var text = showtime.PlayDateStr;
        var url = "";

        //special case for the Alliance theatres...
        //7293	AAC Beaches - "B54AB2A7-A171-4F64-B6A8-03F661440A19"
        //7295	AAC Cumberland - "080944C9-0842-4264-A901-3DD9457F8D8E"
        if (showtime.LocationID == 7293 || showtime.LocationID == 7295) {

            var houseID = "";
            if (showtime.LocationID == 7293) houseID = "6591";
            if (showtime.LocationID == 7295) houseID = "6600";

            url = "http://www.movietickets.com/house_detail.asp?house_id=" + houseID + "&rdate=" + showtime.DateStr;
        } else {

            //all other theatres

            //check if ticketing is on/off
            if (showtime.TicketsAvailable == false) {
                return text;
            }

            //check for sold out...
            if (showtime.IsSoldOut) {
                if (Cineplex.GetCurrentLanguage().toLowerCase() == "fr-ca") {
                    return text + "&nbsp;-&nbsp;<b>COMPLET</b>";
                }
                else {
                    return text + "&nbsp;-&nbsp;<b>SOLD OUT</b>";
                }
            }

            var returnUrl = location.href;

            if (returnUrl.indexOf("?") != -1) {
                returnUrl = returnUrl.substring(0, returnUrl.indexOf("?"));
            }
            returnUrl += "?date=" + escape(showtime.DateStr);


            //build the URL
            url = Agility.ResolveUrl("~/Ticketing.ashx?");
            url += "LocationId=" + showtime.LocationID;
            url += "&VistaSessionId=" + showtime.VistaSessionId;
            url += "&IsMobile=false";
            url += "&ReturnURL=" + escape(returnUrl);
            url += "&PromotionCode=";
            url += "&rnd=" + Cineplex_Random;
        }
        var html = '<a href="' + url + '">' + text + '</a>';

        return html;
    }

    Cineplex.ShowTrailerDialog = function(url) {

        if (url == undefined || url == null || url == "") return true;

        var imgUrl = Agility.ResolveUrl("~/ecms.ashx/Flash/trailer-noflash-" + Cineplex.GetCurrentLanguage() + ".jpg");
        $("#cineplex-video-dialog").html("");
        $("#cineplex-video-dialog").CineplexDialog("open");

        //get the story id from the url - if we can't then just kick out..

        var storyID = Agility.QueryString("fr_story", url);
        if (storyID == null || storyID == "") return true;

        var swf = "http://cineplex.pb.feedroom.com/pb-comp/cineplex/custom1/player.swf";
        var divID = "cineplex-video-dialog";

        var so = new SWFObject(swf, divID + "-swf", "626", "380", "8", "#FFFFFF");
        so.addVariable("SkinName", "custom1");
        so.addVariable("SiteID", "cineplex");
        so.addVariable("SiteName", "Cineplex");
        so.addVariable("ChannelID", "");
        so.addVariable("StoryID", storyID);
        so.addVariable("Volume", ".5");
        so.addParam("quality", "high");
        so.addParam("allowFullScreen", "true");
        so.addParam("allowScriptAccess", "always");
        so.addParam("menu", "false");
        if (!so.write(divID)) {
            $("#cineplex-video-dialog").html("<a href='" + url + "'><img src='" + imgUrl + "' alt='Flash plugin not installed.' style='width:626px; height: 380px; border-width:0px' /></a>");
            $("#cineplex-video-dialog a").focus();
        }
        return false;
    }



    function _handleDocumentClickForAnchorTags(event) {
        try {

            if (event == undefined) return true;
            if (event.target == undefined) return true;
            if (event.button != 0) return true;

            var target = event.target;
            if (target.tagName != "A") {
                target = $(target).parents("a");
            }

            if ($(target).hasClass("direct")) return true;
            if ($(target).hasClass("Direct")) return true;

            var href = $(target).attr("href");
            if (href != null && href != "") {
                if (href.toLowerCase().indexOf("cineplex.com/?fr_story=") > -1) {
                    //clicked on a trailer link
                    return Cineplex.ShowTrailerDialog(href);
                }

                if (href.toLowerCase().indexOf("/ticketing.ashx") > -1 && href.indexOf("&rnd=") == -1) {
                    //ticketing link, add the random calc if neccessary
                    href += "&rnd=" + Cineplex_Random;
                    location.href = href;
                    return false;
                }

                //check trailer based urls...
                return _checkTrailerBasedUrl(target);
            }
        } catch (error) {

        }
        return true;
    }

    //init the onclick of urls that require the location cookie to be set
    function _checkTrailerBasedUrl(target) {

        if (Cineplex.Constants == undefined || Cineplex.Constants.LocationBasedUrls == undefined) return true;

        //check for the user's location
        //check for location
        var location = Cineplex.UserContext.GetCurrentLocation();

        if (location != null) return true;
        var attr = $(target).attr("href");
        var id = $(target).attr("id");
        if (id == "cineplex-lnkNav-Theatre" || id == "cineplex-lnkNav-Movie") {
            return true;
        }

        if (attr == undefined || attr == null || attr == "" || attr == "#" || attr.indexOf("mailto") == 0) return true;


        for (var i = 0; i < Cineplex.Constants.LocationBasedUrls.length; i++) {
            var locUrl = Cineplex.Constants.LocationBasedUrls[i].toLowerCase();


            if (attr.toLowerCase().indexOf(locUrl) != -1) {
                Cineplex.ShowLocationDialog(function() {
                    window.location.href = attr;
                });
                return false;
            }

        }

        return true;

    }

    jQuery.fn.labelOver = function(overClass) {
        return this.each(function() {
            var label = jQuery(this);
            var f = label.attr('for');
            if (f) {
                var input = jQuery('#' + f);

                this.hide = function() {
                    label.css({ textIndent: -10000 })
                }

                this.show = function() {
                    if (input.val() == '') label.css({ textIndent: 0 })
                }

                // handlers
                input.focus(this.hide);
                input.blur(this.show);
                label.addClass(overClass).click(function() { input.focus() });

                if (input.val() != '') this.hide();

                //Show text
                label.show();

                //store label object
                input.data('labelObj', label);
            }
        })
    }

    //add a plugin for similar cities
    jQuery.fn.extend({
        SimilarCities: function(onselect) {

            var location = Cineplex.UserContext.GetCurrentLocation();
            if (location == null || location == "") return;

            var jElem = $(this);

            //clear out the current element
            jElem.html("");

            //get the similar cities
            var url = Agility.ResolveUrl("~/Services/LocationSimilarCities.ashx?location=" + escape(location));
            $.getJSON(url, null, function(data) {

                if (data != null && $.isArray(data) && data.length > 0) {
                    var html = Cineplex.Constants.lblDidYouMean + " ";
                    for (var i = 0; i < data.length; i++) {
                        if (data[i] == location) {
                            html += data[i];
                        } else {
                            html += "<a href='javascript:;' class='SimilarLocLink'>" + data[i] + "</a>";
                        }
                        if (i < data.length - 1) {
                            html += " " + Cineplex.Constants.lblOr + " ";
                        }
                    }

                    jElem.html(html);

                    $("a.SimilarLocLink", jElem).click(function() {
                        var newLoc = $(this).html();
                        onselect(newLoc);
                    });

                }
            });




        }
    });

    //add a plugin to build our dialog...
    jQuery.fn.extend({
        CineplexDialog: function(arg) {


            if (arg == undefined || arg == null) arg = {};

            //try to grab the jQuery object we applied the dialog to
            var dlg = $(this).data("cineplex_dialog");
            if (dlg != null) {
                if (window.isIE6) {
                    dlg.dialog('option', 'position', ['auto', 180]);
                }
                dlg.dialog(arg);
                return dlg;
            }


            //initialize if need be...									
            var height = 150;
            if (arg.height > 0) height = arg.height;

            arg.minHeight = 0;
            arg.height = undefined;

            //add the wrappers...
            var html = '<div class="CineplexDialog">';
            html += '<div class="ui-dialog-left"><div class="ui-dialog-right"><div class="ui-dialog-middle"></div></div></div>';
            html += '<div class="ui-dialog-footer-right"><div class="ui-dialog-footer-left"><div class="ui-dialog-footer-mid"></div></div></div>';
            html += '</div>';

            var dlg = $(html);

            if (arg.fixedHeight) {
                $(".ui-dialog-middle", dlg).css("height", height).append($(this));
            }
            else {
                $(".ui-dialog-middle", dlg).css("min-height", height).css("_height", height).append($(this));
            }

            //initialize the dialog
            if (arg.top > 0) {


            }
            var retVal = dlg.dialog(arg);
            $(this).show();

            //adjust the top location (normal dialog doesn't support this)
            if (arg.top > 0) {
                dlg.parent(".ui-dialog").css("top", arg.top);
            }

            //add the jQuery obect to element we began with
            $(this).data("cineplex_dialog", dlg);
            return retVal;

        }
    });


    //COMBOBOX PLUGIN
    jQuery.fn.extend({
        CineplexCombo: function(arg) {
            if ($(this).size() == 1) {
                _makeCineplexCombo($(this), arg);
            }
        }
    });

    function _makeCineplexCombo(ul, arg) {


        //build the html		
        var html = "<div class='dd'>";
        html += "<div class='ddTitle'>"
        html += "<span class='arrow'></span>";
        html += "<a class='textTitle' href='javascript:;'>";
        html += "</a>";
        html += "</div>";
        html += "</div>";
        var container = $(html);

        container.insertBefore(ul);

        var div = $(".dd", container);

        ul.remove();
        ul.addClass("ddChild");
        container.append(ul);
        if (ul.width() > 0) {
            container.width(ul.width());
        } else {
            container.css("width", ul.css("width"));
        }

        var documentClick = function(e) {
            var el = e.target;
            if (container.find('*').index(el) >= 0) { //Click inside
                return true;
            }
            expandCombo();
            return false;
        }


        var expandCombo = function() {
            if (ul.css("display") == "block") {
                ul.slideUp("fast", function() {
                    $("ul li a", container).removeClass("hover");
                    $(".textTitle", container).focus();
                    $(document).unbind("click", documentClick);
                });
            } else {

                $(ul).slideDown("fast", function() {

                    $(document).click(documentClick);
                    var item = _getSelectedComboItem(container);
                    if (item != null) {
                        item.focus();
                    }
                });


            }
        };

        $(".ddTitle", container).click(expandCombo);

        container.keydown(function(e) {
            if (e.keyCode == 13) {

                //enter key
                if (ul.css("display") == "block") {
                    var hoverIndex = _getComboHoverItemIndex(container);
                    var selectedIndex = _getSelectedComboItemIndex(container);
                    if (hoverIndex != selectedIndex) {

                        _setSelectedComboItemIndex(container, hoverIndex);

                        if (arg && arg.onchange != undefined && $.isFunction(arg.onchange)) {
                            arg.onchange($(this));
                        }
                    }
                }

                expandCombo();



                return false;
            }
            if (ul.css("display") == "block") {
                if (e.keyCode == 38) {
                    //up
                    _setHoverComboItemIndex(container, _getComboHoverItemIndex(container) - 1);
                    return false;
                }

                if (e.keyCode == 40) {
                    //down
                    _setHoverComboItemIndex(container, _getComboHoverItemIndex(container) + 1);
                    return false;
                }
                if (e.keyCode == 27) {
                    //escape
                    expandCombo();
                }
            }
        });



        $("li a", ul).click(function() {
            $("li a", ul).removeClass("selected");
            $(this).addClass("selected");
            _selectComboItem(container);
            var retVal = true;
            if (arg.onchange != undefined && $.isFunction(arg.onchange)) {
                retVal = arg.onchange($(this));
            }
            ul.hide();
            $(document).unbind("click", documentClick);

            $(".textTitle", container).focus();

            return retVal;
        });

        _selectComboItem(container);
    }



    function _getComboHoverItemIndex(container) {
        var hoverItem = _getComboHoverItem(container);

        var li = hoverItem.parent("li");
        return $("ul li", container).index(li);
    }

    function _getComboHoverItem(container) {
        var hoverItem = $("ul.ddChild li a.hover", container);
        if (hoverItem.size() == 0) {
            hoverItem = _getSelectedComboItem(container);
        }

        if (hoverItem.size() == 0) {
            hoverItem = $("ul.ddChild li a", container);
            if (hoverItem.size() == 0) return;
            hoverItem = $(hoverItem.get(0));
        }

        return hoverItem;
    }

    function _getSelectedComboItem(container) {
        var selectedItem = $("ul.ddChild li a.selected", container);
        if (selectedItem.size() == 0) {
            selectedItem = $("ul.ddChild li a", container);
            if (selectedItem.size() == 0) return;
            selectedItem = selectedItem.get(0);
        }

        return selectedItem;
    }

    function _getSelectedComboItemIndex(container) {
        var selectedItem = _getSelectedComboItem(container);
        var li = selectedItem.parent("li")
        return $("ul li", container).index(li);
    }

    function _setHoverComboItemIndex(container, index) {
        if (index < 0) {
            index = $("ul li", container).size() - 1;
        } else if (index >= $("ul li", container).size()) {
            index = 0;
        }

        $("ul li a", container).removeClass("hover");

        $("a", $("ul li", container).get(index)).addClass("hover").focus();

    }

    function _setSelectedComboItemIndex(container, index) {
        if (index < 0) {
            index = $("ul li", container).size() - 1;
        } else if (index >= $("ul li", container).size()) {
            index = 0;
        }

        $("ul li a", container).removeClass("hover");
        $("ul li a", container).removeClass("selected");

        $("a", $("ul li", container).get(index)).addClass("selected").focus();
        _selectComboItem(container)

    }


    function _selectComboItem(container) {
        $("ul li a", container).removeClass("hover");
        var selectedItem = _getSelectedComboItem(container);
        if (selectedItem != null) {
            $(".textTitle", container).html($(selectedItem).html());
        }
    }


    Cineplex.AjaxSpinner = function() {
        return '<div class="AjaxContentLoader"></div>';
    }

    Cineplex.ShowMovies = function() {
        //Clear html
        $('.RotatorPager', $('#cineplex-find-a-movie')).html('');
        $('#cineplex-search-results-loading').show();

        var location = $('#movie-search-city').val();

        //set the location cookie and validate that it is a real location...
        Cineplex.UserContext.SetCurrentLocation(location, function(newLocation) {
            if (newLocation != "") {
                location = newLocation;
                $('#movie-search-city').val(location);
            } else {
                $('#cineplex-search-results-loading').hide();
                $("#cineplex-find-movie-results").html("<li>" + Cineplex.Constants.Values.reqEnterSearchLocation + "</li>");
                return;
            }

            //Get data
            var ret = Cineplex.GetMovies(location, function(data) {

                //init pager
                var r = $('.Rotator', $('#cineplex-find-a-movie'));
                r.css("visibility", "hidden");
                if (r.length > 0) {
                    r.data("pageIndex", 0);
                    r.data("pageCssSelector", "li.page");

                    if (data != undefined && data != null && data.d != undefined && data.d != null && data.d.length > 0) {
                        var results = $('#cineplex-find-movie-results');
                        results.setTemplateElement('cineplex-find-movie-results-template');
                        results.setParam("last", data.d.length);

                        results.processTemplate(data.d);

                        //Auto ellipsis
                        $('.auto', $('#cineplex-find-movie-results')).each(function(i) {
                            var element = $(this);

                            if (element.text().length > 41) {
                                element.attr('title', element.text());
                                element.html(element.text().substr(0, 38) + "&hellip;");
                            }
                        });



                    } else {
                        var msg = "The results could not be displayed.";
                        if (data != undefined && data.Message != undefined && data.Message != null) {
                            msg = data.Message;
                        }
                        $("#cineplex-find-movie-results").html("<li>" + msg + "</li>");
                    }

                    $('#cineplex-search-results-loading').hide();
                    _initializeRotator(r);
                }


            });

            if (ret == false) {
                $('#cineplex-search-results-loading').hide();
                $('#cineplex-find-movie-results').html('');
            }
        });
    }

    Cineplex.ShowTheatres = function() {

        var location = $('#theatre-search-city').val();

        //Clear html
        $('.RotatorPager', $('#cineplex-find-a-theatre')).html('');
        $('#cineplex-search-results-loading').show();

        //set the location cookie and validate that it is a real location...
        Cineplex.UserContext.SetCurrentLocation(location, function(newLocation) {
            if (newLocation != "") {
                location = newLocation;
                $('#theatre-search-city').val(location);
            } else {
                $('#cineplex-search-results-loading').hide();
                $("#cineplex-find-theatre-results").html("<li>" + Cineplex.Constants.Values.reqEnterSearchLocation + "</li>");
                return;
            }

            //Get data
            var ret = Cineplex.GetTheatres(location, function(data) {
                //init pager
                var r = $('.Rotator', $('#cineplex-find-a-theatre'));
                r.css("visibility", "hidden");
                if (r.length > 0) {
                    r.data("pageIndex", 0);


                    if (data != undefined && data != null && data.d.length > 0) {
                        var results = $('#cineplex-find-theatre-results');
                        results.setTemplateElement('cineplex-find-theatre-results-template');
                        results.setParam("last", data.d.length);
                        results.processTemplate(data.d);

                    } else {
                        var msg = "The results could not be displayed.";
                        if (data != undefined && data.Message != undefined && data.Message != null) {
                            msg = data.Message;
                        }
                        $("#cineplex-find-theatre-results").html("<li>" + msg + "</li>");
                    }

                    _initializeRotator(r);
                    $('#cineplex-search-results-loading').hide();
                }
            });

            if (ret == false) {
                $('#cineplex-search-results-loading').hide();
                $('#cineplex-find-theatre-results').html('');
            }
        });
    }

    Cineplex.GetMovies = function(city, callback) {
        if (callback != undefined && callback != null && !jQuery.isFunction(callback)) {
            alert("GetMovies: Callback arg is not a function");
            return;
        }

        if (city == null || city.length == 0) {
            return false;
        }

        var url = Agility.ResolveUrl('~/Services/CineplexTopNav.ashx?func=getMovies&callback=?');

        $.getJSON(url, "pgsize=20&city=" + encodeURI(city),
			function(data) {
			    //data class = { Message = "", d = [[{Name = "", Address = "", Telephone = "", ID = "" }, ... {Name = "", Address = "", Telephone = "", ID = "" }]]
			    callback(data);
			});
    }

    Cineplex.GetTheatres = function(city, callback) {
        if (callback != null && typeof callback != "function") {
            alert("GetTheatres: Callback arg is not a function");
            return;
        }

        if (city == null || city.length == 0) {
            return false;
        }

        var url = Agility.ResolveUrl('~/Services/CineplexTopNav.ashx?func=getTheatres&callback=?')
        $.getJSON(url, "pgsize=6&city=" + encodeURI(city),

			function(data) {
			    //data class = { Message = "", d = [[{Name = "", Address = "", Telephone = "", ID = "" }, ... {Name = "", Address = "", Telephone = "", ID = "" }]]
			    callback(data);
			});
    }

    function _initializeRotator(rotator) {

        var pageSize = parseInt(rotator.attr("pageSize"));
        if (isNaN(pageSize)) pageSize = 5;


        var pageIndex = rotator.data("pageIndex");
        if (pageIndex == null) {
            rotator.data("pageIndex", 0)
            pageIndex = 0;
        }

        var lastPageIndex = rotator.data("lastPageIndex");
        if (lastPageIndex == null) {
            lastPageIndex = 0;
        }

        rotator.data("lastPageIndex", pageIndex);


        //hide the old list itemss
        var lst = null;
        var pageCssSelector = rotator.data("pageCssSelector");
        if (pageCssSelector != null && pageCssSelector.length >= 0) {
            lst = $(pageCssSelector, rotator);
        }
        else {
            lst = $("li", rotator);
        }

        lst.hide();


        //show only the lst items on this page
        var offsetIndex = pageIndex * pageSize;



        $(lst.get(offsetIndex)).css("marginLeft", "0px");
        for (var i = offsetIndex; i < lst.size() && i < offsetIndex + pageSize; i++) {
            $(lst.get(i)).show();
        }

        //show the new list...

        if ($(".RotatorPager", rotator).html() == "") {
            //setup the pager
            var pagecount = Math.floor(lst.size() / pageSize);
            if (lst.size() % pageSize > 0) pagecount++;

            rotator.data("pagecount", pagecount);

            var html = "";

            if (pagecount > 1) {
                html += "<a href='javascript:;' class='PageCtrl BackPage' pageIndex=\"" + (pageIndex - 1) + "\"><img class='btnRotatorBack' alt=\"" + window.Cineplex.Constants.Values.PreviousPage + "\" src=\"/Images/blank.gif\" /></a>";
                for (var i = 0; i < pagecount; i++) {
                    var c = "btnRotatorPage PagerImage";
                    if (i == pageIndex) c = "btnRotatorPage-On PagerImage";
                    html += "<a href='javascript:;' class='PageCtrl' pageIndex=\"" + i + "\"><img class=\"" + c + "\" alt=\"" + window.Cineplex.Constants.Values.Page + " " + (i + 1) + "\" src=\"/Images/blank.gif\" /></a>";
                }
                html += "<a href='javascript:;' class='PageCtrl NextPage' pageIndex=\"" + (pageIndex + 1) + "\"><img class='btnRotatorNext' alt=\"" + window.Cineplex.Constants.Values.NextPage + "\" src=\"/Images/blank.gif\" /></a>";

            }

            pager = $(".RotatorPager", rotator).html(html);
            rotator.data("pager", pager);

            //bind the pager events	
            $("a.PageCtrl", pager).click(function() {
                if (rotator.data("isAnimating") == true) return false;

                var newPageIndex = parseInt($(this).attr("pageIndex"));
                pageIndex = rotator.data("pageIndex");
                if (newPageIndex == pageIndex) return false;

                if (newPageIndex > pagecount - 1) newPageIndex = 0;
                if (newPageIndex < 0) newPageIndex = pagecount - 1;

                rotator.data("pageIndex", newPageIndex);
                _initializeRotator(rotator);
            });

        } else {
            //pager already rendered...
            var pager = rotator.data("pager");

            //select the proper item
            $("img.PagerImage", pager).attr("className", "btnRotatorPage PagerImage");

            $("img.PagerImage", pager).each(function(elemIndex, elem) {
                $(this).attr("alt", window.Cineplex.Constants.Values.Page + " " + (elemIndex + 1));
            });
            $("a[pageIndex=" + pageIndex + "] img.PagerImage", pager).attr("className", "btnRotatorPage-On PagerImage").attr("alt", "*" + window.Cineplex.Constants.Values.Page + " " + (pageIndex + 1) + "*");

            //set the page indexes for the back/next buttons...
            $(".NextPage", pager).attr("pageIndex", pageIndex + 1);
            $(".BackPage", pager).attr("pageIndex", pageIndex - 1);
        }

        rotator.css("visibility", "visible");
        $(".RotatorItems ul", rotator).show();

    }
    
    Cineplex.InitializeRotator = _initializeRotator; //making publicaclly accessible for use in Cineplex.MapDialog




    Cineplex.InitializeAjaxPager = function(rotator, pageSize, pageIndex, totalCount, onpageChanged) {


        var lastPageIndex = rotator.data("lastPageIndex");
        if (lastPageIndex == null) {
            lastPageIndex = 0;
        }


        var lastTotalCount = rotator.data("lastTotalCount");
        if (lastTotalCount == null) {
            lastTotalCount = 0;
        }



        rotator.data("lastPageIndex", pageIndex);


        //if the totalCount changes, reset the whole thing...
        if (lastTotalCount != totalCount) {
            $(".RotatorPager", rotator).html("");
        }
        rotator.data("lastTotalCount", totalCount);

        if ($(".RotatorPager", rotator).html() == "") {
            //setup the pager
            var pagecount = Math.floor(totalCount / pageSize);
            if (totalCount % pageSize > 0) pagecount++;

            rotator.data("pagecount", pagecount);

            var html = "";

            if (pagecount > 1) {
                html += "<a href='javascript:;' class='PageCtrl BackPage' pageIndex=\"" + (pageIndex - 1) + "\"><img class='btnRotatorBack' alt=\"" + window.Cineplex.Constants.Values.PreviousPage + "\" src=\"/Images/blank.gif\" /></a>";
                for (var i = 0; i < pagecount; i++) {
                    var c = "btnRotatorPage PagerImage";
                    if (i == pageIndex) c = "btnRotatorPage-On PagerImage";
                    html += "<a href='javascript:;' class='PageCtrl' pageIndex=\"" + i + "\"><img class=\"" + c + "\" alt=\"" + window.Cineplex.Constants.Values.Page + " " + (i + 1) + "\" src=\"/Images/blank.gif\" /></a>";
                }
                html += "<a href='javascript:;' class='PageCtrl NextPage' pageIndex=\"" + (pageIndex + 1) + "\"><img class='btnRotatorNext' alt=\"" + window.Cineplex.Constants.Values.NextPage + "\" src=\"/Images/blank.gif\" /></a>";

            }

            pager = $(".RotatorPager", rotator).html(html);
            rotator.data("pager", pager);

            //bind the pager events	
            $("a.PageCtrl", pager).click(function() {
                if (rotator.data("isAnimating") == true) return false;

                var newPageIndex = parseInt($(this).attr("pageIndex"));
                pageIndex = rotator.data("pageIndex");
                if (newPageIndex == pageIndex) return false;

                if (newPageIndex > pagecount - 1) newPageIndex = 0;
                if (newPageIndex < 0) newPageIndex = pagecount - 1;
                rotator.data("pageIndex", newPageIndex);
                onpageChanged(newPageIndex);

            });

        } else {
            //pager already rendered...
            var pager = rotator.data("pager");

            //select the proper item
            $("img.PagerImage", pager).attr("className", "btnRotatorPage PagerImage");

            $("img.PagerImage", pager).each(function(elemIndex, elem) {
                $(this).attr("alt", window.Cineplex.Constants.Values.Page + " " + (elemIndex + 1));
            });
            $("a[pageIndex=" + pageIndex + "] img.PagerImage", pager).attr("className", "btnRotatorPage-On PagerImage").attr("alt", "*" + window.Cineplex.Constants.Values.Page + " " + (pageIndex + 1) + "*");

            //set the page indexes for the back/next buttons...
            $(".NextPage", pager).attr("pageIndex", pageIndex + 1);
            $(".BackPage", pager).attr("pageIndex", pageIndex - 1);
        }

        rotator.css("visibility", "visible");

    }






})(Cineplex);




/*
 * User Context Object...
 */

(function(UserContext) {
	
	var _theatresCookieName = "Cineplex_FaveTheatres";
	var _moviesCookieName = "Cineplex_FaveMovies";	
	var _anonCookieName = "Cineplex_Anonymous";
	
	
	$(function() {
		
		$("#pnlRemoveAllFavourites").click(function() {
			UserContext.RemoveAllFavourites();
		});
	});
	
	UserContext.IsAuthenticated = function() {
		authVal = $.cookies.get("CineplexAuthASPNET");	
		if (authVal == undefined || authVal == null || authVal == "") return false;
		return true;
	}
	
	UserContext.Logout = function() {
		var domain = Cineplex.GetCookieDomain();					
		$.cookies.del("CineplexAuthASPNET", { path: '/', domain: domain });
		return true;
	}
	
	UserContext.GetCurrentLocation = function() {
		/// <summary>
        /// Gets the current user's location string (CITY - PROV)
        /// </summary>
        
		//U=&L=Delson+-+QC&R=50&RM=&F=
				
		var anonCookieVal = $.cookies.get(_anonCookieName);
		if (anonCookieVal == null) return null;
		
		if (anonCookieVal == "U") {
			//parse the legacy cookie manually...
			var ary = document.cookie.split(";");
			for (var i=0;i<ary.length; i++) {
				// Cineplex_Anonymous=U=&L=Ajax+-+ON&R=50&RM=&F=
				if (ary[i].indexOf(_anonCookieName) != -1) {
					anonCookieVal = ary[i].substring(ary[i].indexOf(_anonCookieName) + _anonCookieName.length + 1);
				}
			}			
		}
		
		loc = Agility.QueryString("L", "/?" + anonCookieVal);					
		if (loc == undefined || loc == null || loc == "" || loc == "Select a City" || loc.indexOf("ctionnez une ville") != -1) return null;
		
		return loc;		
		
	}
	
	UserContext.SetCurrentLocation = function(location, callback) {
		/// <summary>
        /// Sets the current user's location string (CITY - PROV)
        /// </summary>
        /// <param name="location" type="string">The location string to set.</param>      
        /// <param name="callback" type="Function">The callback function that will provide the parsed location value.</param>      

        $.getJSON(Agility.ResolveUrl('~/Services/Location.ashx?location='+ escape(location) +'&callback=?'), function(loc) {				
			if (loc && loc != undefined && loc != null && loc != "") {
				
				var domain = Cineplex.GetCookieDomain();		
				
				//cookie format
				//U=&L=Delson+-+QC&R=50&RM=&F=
				
				var anonCookieVal = $.cookies.get(_anonCookieName);
				var U = Agility.QueryString("U", "/?" + anonCookieVal);
				var R = Agility.QueryString("R", "/?" + anonCookieVal);				
				if (isNaN(parseInt(R))) R = "50";
				if (U == null || U == "null") U = "";
				
				if (loc != "") {
					var str = "U=" + U + "&L=" + loc + "&R=" + R;
					$.cookies.set(_anonCookieName, str, { expiresAt: Date.parse("2030/1/1"), path: '/', domain: domain });
				}
				
				if (typeof(callback) == "function") {
				    callback(loc);
				}
			} else if (typeof(callback) == "function") {
				callback("");
			}
		});
	}
	
	
	UserContext.BindFavourites = function() {
		//bind the favourite theatres/movies list...
		_bindFavourites();
	}
	
	UserContext.RemoveAllFavourites = function() {
		var domain = Cineplex.GetCookieDomain();
		
		
        $.cookies.set(_moviesCookieName, null, { expiresAt: Date.parse("2030/1/1"), path: '/', domain: domain });
        $.cookies.set(_theatresCookieName, null, { expiresAt: Date.parse("2030/1/1"), path: '/', domain: domain });
        _bindFavourites();
	}
	
	UserContext.GetFavoriteMovies = function(callback, errorCallback) {
		/// <summary>
        /// Gets a list of the user's favourite movies.
        /// </summary>
        /// <param name="callback" type="Function">The callback function.  This is passed an array of Theatre objects with an ID, Name and Url.</param>      
        /// <param name="errorCallback" type="Function">The error callback function.</param>      

        var currentValue = $.cookies.get(_moviesCookieName);

        var lst = new Array();
        if (currentValue != undefined && currentValue != "undefined" && currentValue != null && currentValue != "") {
			
			lst = currentValue.split(",");
			
			$.getJSON(Agility.ResolveUrl('~/Services/Favourites.ashx?func=movies&ids='+lst.join(",")+'&callback=?'), function(data) {				
				if (data && data.d != undefined && $.isArray(data.d)) {
					callback(data.d);
				} else {
					errorCallback();
				}
			});			
        }  else {
			callback(lst);
        }              
        
	}
	
	UserContext.GetFavoriteTheatres = function(callback, errorCallback) {
		/// <summary>
        /// Gets a list of the user's favourite theatres.
        /// </summary>
        /// <param name="callback" type="Function">The callback function.  This is passed an array of Theatre objects with an ID, Name and Url.</param>      
        /// <param name="errorCallback" type="Function">The error callback function.</param>      
        
        var currentValue = $.cookies.get(_theatresCookieName);

        var lst = new Array();
        if (currentValue != undefined && currentValue != "undefined" && currentValue != null && currentValue != "") {
			lst = currentValue.split(",");
			
			$.getJSON(Agility.ResolveUrl('~/Services/Favourites.ashx?func=theatres&ids='+lst.join(",")+'&callback=?'), function(data) {				
				if (data && data.d != undefined && $.isArray(data.d)) {
					callback(data.d);
				} else {
					errorCallback();
				}
			});			
        }  else {
			callback(lst);
        }              
        
	}
	
	UserContext.RemoveFavouriteMovie = function(filmID) {
		/// <summary>
        /// Remove a movie from the list of the current user's favourites.
        /// </summary>
        /// <param name="filmID" type="Number">The filmID of the movie (int).</param>  
		 filmID = parseInt(filmID);
        if (isNaN(filmID)) return;
        
        var currentValue = $.cookies.get(_moviesCookieName);
        var lst = new Array();
        if (currentValue != undefined && currentValue != null && currentValue != "") {
			lst = currentValue.split(",");
        }
        
        lst = $.grep(lst, function(elem, index) {
			return parseInt(elem)  != filmID;
        });
        
        var newValue =  lst.join(",");
		var domain = Cineplex.GetCookieDomain();
		
		
        $.cookies.set(_moviesCookieName, newValue, { expiresAt: Date.parse("2030/1/1"), path: '/', domain: domain });
		
		_bindFavourites();
		return;        
        
	}
	
	UserContext.RemoveFavouriteTheatre = function(locationID) {
		/// <summary>
        /// Remove a theatre from the list of the current user's favourites.
        /// </summary>
        /// <param name="locationID" type="Number">The location_id of the theatre (int).</param>  
		 locationID = parseInt(locationID);
        if (isNaN(locationID)) return;
        var currentValue = $.cookies.get(_theatresCookieName);
        var lst = new Array();
        if (currentValue != undefined && currentValue != null && currentValue != "") {
			lst = currentValue.split(",");
        }
        
        lst = $.grep(lst, function(elem, index) {
			return parseInt(elem)  != locationID;
        });
        
        var newValue =  lst.join(",");
		var domain = Cineplex.GetCookieDomain();
		
		
        $.cookies.set(_theatresCookieName, newValue, { expiresAt: Date.parse("2030/1/1"), path: '/', domain: domain });
		
		_bindFavourites();
		return;        
        
	}
	
	UserContext.IsFavouriteMovie = function(filmID) {
		/// <summary>
        /// Checks if a filmID is already in the user's favourite's list.
        /// </summary>
        /// <param name="filmID" type="Number">The filmID of the movie (int).</param>      
        
        filmID = parseInt(filmID);
        if (isNaN(filmID)) return;
     
        var currentValue = $.cookies.get(_moviesCookieName);
        var lst = new Array();
        if (currentValue != undefined && currentValue != null && currentValue != "") {
			lst = currentValue.split(",");
        }
        
		if ($.inArray(filmID, lst) == -1 && $.inArray(filmID + "", lst) == -1) {
			return false;
		}
		
		return true;
								
        
	}
	
	UserContext.AddFavoriteMovie = function(filmID) {
		/// <summary>
        /// Adds a movie to the list of the current user's favourites.
        /// </summary>
        /// <param name="filmID" type="Number">The filmID of the movie (int).</param>      
        
        filmID = parseInt(filmID);
        if (isNaN(filmID)) return;
     
        var currentValue = $.cookies.get(_moviesCookieName);
        var lst = new Array();
        if (currentValue != undefined && currentValue != null && currentValue != "") {
			lst = currentValue.split(",");
        }
        
		if ($.inArray(filmID, lst) == -1 && $.inArray(filmID + "", lst) == -1) {
			lst[lst.length] = filmID;
		}
						
		var newValue =  lst.join(",");
		var domain = Cineplex.GetCookieDomain();

		//set the cookie
		$.cookies.set(_moviesCookieName, newValue, { expiresAt: Date.parse("2030/1/1"), path: '/', domain: domain });
		
		_bindFavourites();
		return;        
        
	}
	
	UserContext.IsFavoriteTheatre = function(locationID) {
		/// <summary>
        /// Checks if a locationID is in the user's favourites.
        /// </summary>
        /// <param name="locationID" type="Number">The location_id of the theatre (int).</param>      
        
        locationID = parseInt(locationID);
        if (isNaN(locationID)) return;
        
        var currentValue = $.cookies.get(_theatresCookieName);
        var lst = new Array();
        if (currentValue != undefined && currentValue != null && currentValue != "") {
			lst = currentValue.split(",");
        }
        
		if ($.inArray(locationID, lst) == -1 && $.inArray(locationID + "", lst) == -1) {
			return false;
		}			
			
		return true;
        
	}
	
	UserContext.AddFavoriteTheatre = function(locationID) {
		/// <summary>
        /// Adds a theatre to the list of the current user's favourites.
        /// </summary>
        /// <param name="locationID" type="Number">The location_id of the theatre (int).</param>      
        
        locationID = parseInt(locationID);
        if (isNaN(locationID)) return;
        
        var currentValue = $.cookies.get(_theatresCookieName);
        var lst = new Array();
        if (currentValue != undefined && currentValue != null && currentValue != "") {
			lst = currentValue.split(",");
        }
        
		if ($.inArray(locationID, lst) == -1 && $.inArray(locationID + "", lst) == -1) {
			lst[lst.length] = locationID;
		}			
			
		var newValue =  lst.join(",");
		var domain = Cineplex.GetCookieDomain();


		//set the cookie
		
		$.cookies.set(_theatresCookieName, newValue, { expiresAt: Date.parse("2030/1/1"), path: '/', domain: domain });
		
		_bindFavourites();
		return;        
        
	}
	
	function _bindFavourites() {
	
		//check if the favourites panel is here...
		if ($("#pnlFavouritesLoading").size() == 0) return;
		
		$("div.MyFavouriteTheatres").hide();
		$("div.MyFavouriteMovies").hide();		
		$("div.NoFavourites").show();
		$("#pnlFavouritesLoading").show();
		$("#pnlFavouritesMessage").hide();
		
		var height = $("#pnlFavouritesContainer").height();
		$("#pnlFavouritesContainer").css("minHeight", height);
		
		
		UserContext.GetFavoriteTheatres(
			function(lstTheatres) {
				//success

				if (lstTheatres.length > 0) {
					
					var html = "<ul>";
					for (var i=0; i<lstTheatres.length; i++) {
						var t = lstTheatres[i];
						html += "<li>";
						
						html += '<a class="FavouriteLineItem ';
						if (i % 2 != 0) {
							html += 'FavouriteLineItemAlt" ';
						} else {
							html += '" ';
						}
						html += 'href="' + Agility.ResolveUrl(t.Url) + '">' + t.Name + '</a>';						
						html += '<a class="FavouriteDelete" href="javascript:;" locationID="'+t.ID+'">Remove</a>';
						html += "</li>";
					}			
					html += "</ul>";
					html += "<div class='Clear'></div>";
					$("#pnlFavouriteTheatres").html(html);
					$("div.MyFavouriteTheatres").show();
					
					//bind the remove actions
					$("#pnlFavouriteTheatres a.FavouriteDelete").click(function() {
						UserContext.RemoveFavouriteTheatre($(this).attr("locationID"));
					});										

				} else {
					$("#pnlFavouriteTheatres").html("");																				
				}
				
				_bindFavourites2(lstTheatres);
				
			},
			function() {
				//error
				$("#pnlFavouriteTheatres").html("An error occurred.  Please try again.");
				$("#pnlFavouritesLoading").hide();
				$("#pnlFavouritesMessage").show();
				
			}
		);		
	}
	
	function _bindFavourites2(lstTheatres) {
		UserContext.GetFavoriteMovies(
			function(lstMovies) {
				//success

				if (lstMovies.length > 0) {
					
					var html = "<ul>";
					for (var i=0; i<lstMovies.length; i++) {
						var t = lstMovies[i];
						html += "<li>";
						html += '<a class="FavouriteLineItem ';
						if (i % 2 != 0) {
							html += 'FavouriteLineItemAlt" ';
						} else {
							html += '" ';
						}
						html += 'href="' + Agility.ResolveUrl(t.Url) + '">' + t.Name + '</a>';						
						html += '<a class="FavouriteDelete" href="javascript:;" filmID="'+t.ID+'">Remove</a>';
						html += "</li>";
					}			
					html += "</ul>";
					html += "<div class='Clear'></div>";
					$("#pnlFavouriteMovies").html(html);
					//bind the remove actions
					$("#pnlFavouriteMovies a.FavouriteDelete").click(function() {
						UserContext.RemoveFavouriteMovie($(this).attr("filmID"));
					});
					
					$("div.MyFavouriteMovies").show();
										
				} else {
					//no films...
					$("#pnlFavouriteMovies").html("");
				}
				
				if (lstMovies.length + lstTheatres.length == 0) {
					//if both lists are empty...
					$("div.MyFavouriteTheatres").hide();
					$("div.MyFavouriteMovies").hide();		
					$("div.NoFavourites").show();
					$("#pnlFavouritesLoading").hide();
					$("#pnlFavouritesMessage").show();
					$("#pnlRemoveAllFavourites").hide();
				} else {
					$("div.NoFavourites").hide();
					$("#pnlRemoveAllFavourites").show();
					
				}
			},
			function() {
				//error
				$("#pnlFavouriteTheatres").html("An error occurred.  Please try again.");
				$("#pnlFavouritesLoading").hide();
				$("#pnlFavouritesMessage").show();
				
			}
		);
	}

}) (Cineplex.UserContext);



//LEGACY METHODS DOWN HERE
function bdayProvinceCalc(elem) {
	var url = elem.value;
	if (location.href.toLowerCase().indexOf("ispreview=true") != -1) {
		url += "&ispreview=true";
	}
	location.href=url;
}

function topLevelRedirect(url) 
{
	var form = document.createElement("form");
	form.setAttribute("method", "GET");
	form.setAttribute("action", url);	
	form.setAttribute("target", "_top");
	document.body.appendChild(form);
	form.submit();
}


