﻿        
var currentFilter = "";
var prevState = "";
var loadingImage = "<div class='session-loading-image'><img src='/content/images/ajax-loader-bar-gold.gif'/></div>";
var noSessions = "<div class='no-sessions'>There are no sessions available.</div>";
var noAdvanceTickets = "<div class='no-tickets'>There are no advance tickets available.</div>";
var optuslogo = "<div id='optuslogo'><img src='/content/images/optus-elephant-session.jpg' width='337px' height='125px' /></a></div>";

$(document).ready(function() {
    //initialise menus
    initCinemaMenu();
    initMovieMenu();
    toggleMenus($("#filter").val());
    saveCookie();
    setModalOffsets();
    $(window).resize(setModalOffsets);
    if ($("#message").val() != "")
        alert($("#message").val());
    var custParam = $("#custParam").val();
    if (custParam.toLowerCase().indexOf("isoptus=true") > -1) {
        var html = $("#headlogos").html();
        html = html.substring(0, html.length - 6) + optuslogo + "</div>";
        $("#headlogos").html(html);
    }
});

function setModalOffsets() {
    var width = $("#session-content").width();
    var height = $("#session-content").height();
    
    var movieModalWidth = $("#movieInfo-modal").width();
    var movieModalHeight = $("#movieInfo-modal").height();
    var attributeModalWidth = $("#attribute-modal").width();
    var attributeModalHeight = $("#attribute-modal").height();

    var leftOffset = Math.floor((width - movieModalWidth) / 2);
    $("#movieInfo-modal").css("left", leftOffset + "px");
    var topOffset = Math.floor((height - movieModalHeight) / 2);
    if (parseInt(topOffset) <= 5)
        topOffset = 5;
    $("#movieInfo-modal").css("top", topOffset + "px");
    
    leftOffset = Math.floor((width - attributeModalWidth) / 2);
    $("#attribute-modal").css("left", leftOffset + "px");
    topOffset = Math.floor((height - attributeModalHeight) / 2);
    if (parseInt(topOffset) <= 5)
        topOffset = 5;
    $("#attribute-modal").css("top", topOffset + "px");
}

function initCinemaMenu() {
    /* This is for the left side cinema menu */
    var filter = $("#filter").val();
    var initState = $("#state").val();
    var initCinema = $("#cinemaToken").val();
    
    $('#cinema-menu .state-container').hide();

    $('#cinema-menu div.cinema').click(
        function() {

            var prevCinemaToken = $('#cinema-menu div.selected').attr("id");
            if (prevCinemaToken != "") {
                // Hide previously selected cinema
                $("#cinema-menu #" + prevCinemaToken).removeClass("selected");
                $("#cinema-menu #" + prevCinemaToken + "-screen-type-div").hide();
            }

            // Set class and load movies 
            $(this).addClass("selected");
            var cinemaToken = $(this).attr("id");
            loadMoviesByCinema(cinemaToken);
            return false;
        }
    );

    $('#cinema-menu .state-header').click(
        function() {
            var selectedState = $(this).attr("id");
            if (prevState == selectedState) {
                // Search for selected cinema and hide
                var cinemaToken = $("#" + selectedState + "-state-container div.selected").attr("id");
                $("#cinema-menu #" + cinemaToken).removeClass("selected");
                $("#cinema-menu #" + cinemaToken + "-screen-type-div").hide();
                
                // Hide state container
                $("#cinema-menu #" + selectedState + "-state-container").hide();
                
                // Save cookie values
                $("#cinemaToken").val("");
                $("#state").val("");
                saveCookie();
                prevState = "";
            }
            else {
                // Show selected state, save cookie values
                $("#" + selectedState + "-state-container").show();
                $("#state").val(selectedState);
                saveCookie();
                prevState = selectedState;
            }
        }
    );
    
    if (filter == "cinema" && (initState != "" || initCinema != "")) {
        if (initState != "") {
            if ($("#cinema-menu #" + initState).html() == null) {
                // Current state is not in the cinema menu so clear state and cinema in the cookie
                $("#cinemaToken").val("");
                $("#state").val("");
                saveCookie();
            }
            else {
                $('#cinema-menu #' + initState).trigger("click");

                if (initCinema != "") {
                    if ($("#cinema-menu #" + initCinema).html() == null) {
                        // Current cinema token is not in the cinema menu so clear cinema in the cookie
                        $("#cinemaToken").val("");
                        saveCookie();
                    }
                    else {
                        var cinemaMenu = $("#cinema-menu");
                        try {
                            $('#cinema-menu #' + initCinema).trigger("click");
                        }
                        catch (e) {
                        }
                    }
                }
            }
        }
    }
}

function initMovieMenu() {
    var filter = $("#filter").val();
    var initMovie = $("#movieId").val();
    
    $('#movie-menu div.movieHeader').click(function() {
        var prevMovieId = $('#movie-menu div.selected').attr("id");
        if (prevMovieId != "") {
            $("#movie-menu #" + prevMovieId).removeClass("selected");
            $("#movie-menu #" + prevMovieId + "-screen-type-div").hide();
        }

        // Set class and show screen type selector
        $(this).addClass("selected");
        var movieId = $(this).attr("id");
        loadCinemasByMovie(movieId);
        return false;
    });
    
    if (filter == "movie" && initMovie != "") {
        if ($("#movie-menu #" + initMovie).html() != null) {
            var movieMenu = $("#movie-menu");
            if (movieMenu[0].scrollTo) {
                movieMenu[0].scrollTo("#" + initMovie);
            }
            $('#movie-menu #' + initMovie).trigger("click");
        }
        else {
            // Current movie Id is not in the movie menu so remove it from the cookie
            $("#movieId").val("");
            saveCookie();
        }
    }
}

function toggleMenus(value) {
    if (value != currentFilter) {
        if (value == "cinema") {
            $("#cinema-tab").attr("src", "/content/images/Tickets_byCinema_on.png");
            $("#movie-tab").attr("src", "/content/images/Tickets_byMovie.png");
            $("#movielist-div").css("display", "none");
            $("#cinemalist-div").css("display", "block");
        }
        else if (value == "movie") {
            $("#cinema-tab").attr("src", "/content/images/Tickets_byCinema.png");
            $("#movie-tab").attr("src", "/content/images/Tickets_byMovie_on.png");
            $("#cinemalist-div").css("display", "none");
            $("#movielist-div").css("display", "block");
        }
        $("#filter").val(value);
        saveCookie();
        currentFilter = value;
    }
}

function loadMoviesByCinema(cinemaToken) {
    $("#session-instruction").hide();
    $("#session-header-div").show();
    $("#session-details-div").show();
    
    $('#session-details-div #nowshowing-list').html(loadingImage);
    $("#cinemaToken").val(cinemaToken);
    $("#movieId").val("");
    $('#session-header-right').html('');
    saveCookie();

    var sessionAttribute = $("#sessionAttribute").val();
    var screenType = $("#screenType").val();
    var useNewTicketing = $("#useNewTicketing").val();

    $.getJSON("/Cinema/DetailJson", { cinemaToken: cinemaToken }, function (data) {
        if (data != "") {
            var cinemaToken = $("#cinemaToken").val();
            var sessionAttribute = $("#sessionAttribute").val();
            var screenType = $("#screenType").val();

            var htmlstring = '<span class="cinema-header">' + data.Fullname + '</span><br />' +
                             '<span class="cinema-address">' + data.Address + '</span><br/>' +
                             '<a href="/Session/Print?cinemaToken=' + cinemaToken + '" class="print-all">print weekly sessions</a>';
            var left = $('#session-header-left');
            left.html(htmlstring);

            if (data.Banner != undefined && data.Banner.length > 0 && data.BannerLink != undefined) {
                // Limit the width of the left hand column on when there's a right hand image
                left.width(346);
                $('#session-header-right').html('<a href="' + data.BannerLink + '"><img src="' + data.Banner + '" alt="" /></a>').show().width(315);
            }
        }
    });

    $.get("/Session/List3", { cinemaToken: cinemaToken, movieId: "0", screenType: screenType, movieAttribute: "", sessionAttribute: sessionAttribute, ticketType: "all", order: "movie", useNewTicketing: useNewTicketing }, function (data) {
        if (data != "") {
            $('#session-details-div #nowshowing-list').html(data);
        }
        else {
            $('#session-details-div #nowshowing-list').html(noSessions);
        }
        
        setHelpTips();
    });
}

function loadCinemasByMovie(movieId) {
    $("#session-instruction").hide();
    $("#session-header-div").show();
    $("#session-header-right").html("");
    $("#session-details-div").show();
    $('#session-details-div #nowshowing-list').html(loadingImage);

    $("#movieId").val(movieId);
    $("#state").val("");
    $("#cinemaToken").val("");
    saveCookie();
    var screenType = $("#screenType").val();
    var sessionAttribute = $("#sessionAttribute").val();
    var useNewTicketing = $("#useNewTicketing").val();
    
    $.getJSON("/Movie/DetailJson", { movieId: movieId }, function(data) {
        if (data != "") {
            var jscriptFunction = "javascript:showMovieInfo('" + data.Url + "');";
            var htmlstring = '<span class="movie-header">' + data.Name + '</span>' +
                             '<span class="movie-info-header" onclick="' + jscriptFunction + '">Movie Info</span><br/>';
            if (data.Rating != "")
                htmlstring += " " + '<span class="movie-rating">' + data.Rating;
            if (data.Policy != "")
                htmlstring += " (" + data.Policy + ")";
            if (data.Rating != "" || data.Policy != "")
                htmlstring += '</span>';
            if (data.Rating.length + data.Policy.length < 45)
                htmlstring += "<br/>" + data.RunningTime;
            else
                htmlstring += " " + data.RunningTime;
            $('#session-header-left').html(htmlstring);
        }
    });

    $.get("/Session/List3", { cinemaToken: "", movieId: movieId, screenType: screenType, movieAttribute: "", sessionAttribute: sessionAttribute, ticketType: "all", order: "cinema", useNewTicketing: useNewTicketing }, function (data) {
        if (data != "") {
            $('#session-details-div #nowshowing-list').html(data);
        }
        else {
            $('#session-details-div #nowshowing-list').html(noSessions);
        }
        
        setHelpTips();
    });
}

function setScreenType(screenType) {
    $("#screenType").val(screenType);
    saveCookie();
    $("#form1").submit();
}

function setHelpTips() {
    
    if ($("#col2 .sessionSoldout").length) {
        $("#col2 .sessionSoldout").jHelperTip({
            trigger: "hover",
            dC: ".session-balloon-soldout",
            autoClose: false,
            opacity: 1,
            topOff: -50,
            leftOff: -44
        });
    }

    if ($("#col2 .sessionHurry").length) {
        $("#col2 .sessionHurry").jHelperTip({
            trigger: "hover",
            dC: ".session-balloon-hurry",
            autoClose: false,
            opacity: 1,
            topOff: -82,
            leftOff: -44
        });
    }

    if ($("#col2 .sessionHurry20").length) {
        $("#col2 .sessionHurry20").jHelperTip({
            trigger: "hover",
            dC: ".session-balloon-hurry20",
            autoClose: false,
            opacity: 1,
            topOff: -82,
            leftOff: -44
        });
    }
    
    $('#attribute-modal').jqm({
        overlay: 50
    })
    
    $('#movieInfo-modal').jqm({
        overlay: 50
    })
}

function showAttributes() {
    $('#attribute-modal').jqmShow();
    $('#attribute-modal').jqmAddClose('.close');
}

function showMovieInfo(movieUrl) {
    $('#movieInfo-modal').jqmShow();
    
    var movieLoading = '<div style="width: 100%; padding: 150px 0 300px 250px"><img src="/content/images/ajax-loader-bar-gold.gif" /></div>';
    $("#movieInfo-modal #content").html(movieLoading);
    
    $.get("/Movie/LimitedDetailHtml", { movieUrl: movieUrl }, function (data) {
        if (data != "") {
            $('#movieInfo-modal #content').html(data);
        }
        $('#movieInfo-modal').jqmAddClose('.close');
    });
    return false;
}

function saveCookie() {
    var filter = $("#filter").val();
    var cinemaToken = $("#cinemaToken").val();
    var movieId = $("#movieId").val();
    var state = $("#state").val();
    var nowShowingState = $("#nowShowingState").val();
    var sessionAttribute = $("#sessionAttribute").val();
    var movieAttribute = $("#movieAttribute").val();
    var screenType = $("#screenType").val();
    var nowShowingMovieId = $("#nowShowingMovieId").val();
    var nowShowingCinemaToken = $("#nowShowingCinemaToken").val();
    
    var value = "filter=" + filter + "&movieId=" + movieId + "&nowShowingMovieId=" + nowShowingMovieId + "&state=" + state + "&nowShowingState=" + nowShowingState +
                "&cinemaToken=" + cinemaToken + "&nowShowingCinemaToken=" + nowShowingCinemaToken + "&sessionAttribute=" + sessionAttribute + "&movieAttribute=" + movieAttribute + 
                "&screenType=" + screenType;
    
    $.cookie("SessionSelector", value, { expires: 180, path: "/sessions" });
}

function persistValue(key, value, action) {
    var list = "";
    if (key == "nowShowingMovieId")
        list = $("#nowShowingMovieId").val();
    else if (key == "nowShowingState")
        list = $("#nowShowingState").val();
    else if (key == "nowShowingCinemaToken")
        list = $("#nowShowingCinemaToken").val();
    var array = list.split(';');
    var exists = false;
    for (var i = 0; i < array.length; i++) {
        if (array[i] == value)
            exists = true;
    }
    
    if (action == "add") 
    {
        if (exists)
        {
            return list;
        }
        else 
        {
            var returnList = list;
            if (returnList == "")
                returnList = value;
            else 
            {
                returnList += ";" + value;
            }
            return returnList;
        }
    }
    else if (action == "remove") 
    {
        if (!exists || list == "") {
            return list;
        }
        else {
            var returnList = "";
            for (var i = 0; i < array.length; i++) {
                if (array[i] != value) {
                    if (returnList == "")
                        returnList = array[i];
                    else
                        returnList += ";" + array[i];
                }
            }
            return returnList;
        }   
    }
}

