﻿/// <reference path="./Cineplex.js" />

Agility.RegisterNamespace("Cineplex.TheatreDetails");

(function(TheatreDetails) {

    $(function() {
        $("#tabsTheatreDetails").tabs();

        //bind the save as favourite action
        var locationID = parseInt($("#lnkSaveTheatreFavourite").attr("locationID"));
        if (Cineplex.UserContext.IsFavoriteTheatre(locationID)) {
            $("#lnkSaveTheatreFavourite").css("visibility", "hidden");
        } else {
            $("#lnkSaveTheatreFavourite").click(function() {
                var locationID = parseInt($(this).attr("locationID"));
                if (!isNaN(locationID)) {
                    Cineplex.UserContext.AddFavoriteTheatre(locationID);
                    return false;
                }
            });
        }

        //bind the skinned dropdowns
        $("#lstShowtimeDates").CineplexCombo({
            onchange: function() {
                _populateTheatrePrice();
                _populateMovieListings();
                return false;
            }
        });
        
		//bind the time format-switching links
		function lnkSwitchTimeFormat_click(newFormat) {
		    var $hidden = $("#txtTimeFormat");
		    $hidden.val(newFormat);
		    _populateMovieListings();
		    return false;
		}
		$("#lnkSwitchTimeFormat12hr").click(function() { return lnkSwitchTimeFormat_click("12hr"); });
		$("#lnkSwitchTimeFormat24hr").click(function() { return lnkSwitchTimeFormat_click("24hr"); });

        //link  up the map links
        $("#tabsTheatreDetails a.MapLink").live("click", _mapLinkClick);
    });


    var _currentDate = null;

    function _populateTheatrePrice() {

        var currentDate = new Date();
        var dateStr = $("#lstShowtimeDates li a.selected").attr("dateStr");
        if (dateStr != null && dateStr != "") {
            currentDate = Date.parse(dateStr);
        } else {
            dateStr = currentDate.toString("yyyy-M-d");
        }

        _currentDate = currentDate;

        var url = Agility.ResolveUrl("~/Services/AjaxServices.asmx/SearchPricesByTheatreAndDate");

        var arg = {
            theatreID: Cineplex_CurrentTheatreID,
            dateStr: dateStr
        };

        $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            url: url,
            data: JSON.encode(arg),
            dataType: "json",
            success: function(result) {

                if (result == undefined || result.d == undefined) {
                    $("#pnlTheatrePrice").html(Cineplex_errSearchNotCompleted);

                } else {

                    var ary = result.d;


                    $("#pnlTheatrePrice").setTemplateElement("txtPriceListingOnTheatreTemplate");

                    $("#pnlTheatrePrice").processTemplate(ary);

                }

            },
            error: function(error) {
                $("#pnlTheatrePrice").html(Cineplex_errSearchNotCompleted);
            }

        });

    }



    function _populateMovieListings() {

        var currentDate = new Date();
        var dateStr = $("#lstShowtimeDates li a.selected").attr("dateStr");
        if (dateStr != null && dateStr != "") {
            currentDate = Date.parse(dateStr);
        } else {
            dateStr = currentDate.toString("yyyy-M-d");
        }
        var timeFormat = $("#txtTimeFormat").val();

        _currentDate = currentDate;

        //set the height so we don't "jump"
        $("#pnlMovieListing").css("minHeight", $("#pnlMovieListing").height()).css("overflow", "hidden");


        //show progess....
        $("#pnlMovieListing").html(Cineplex.AjaxSpinner());

        //build the query...
        var url = Agility.ResolveUrl("~/Services/AjaxServices.asmx/SearchMoviesByTheatreAndDate");

        var arg = {
            theatreID: Cineplex_CurrentTheatreID,
            dateStr: dateStr,
            timeFormat: timeFormat
        };

        $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            url: url,
            data: JSON.encode(arg),
            dataType: "json",
            success: function(result) {

                if (result == undefined || result.d == undefined) {
                    $("#pnlMovieListing").html(Cineplex_errSearchNotCompleted);

                } else {

                    var ary = result.d;


                    $("#pnlMovieListing").setTemplateElement("txtMovieListingOnTheatreTemplate");
                    $("#pnlMovieListing").setParam("getTicketingLink", Cineplex.GetTicketingLink);
                    $("#pnlMovieListing").setParam("renderExclusiveContent", _renderExclusiveContent);
                    $("#pnlMovieListing").setParam("renderCurrentDate", _getCurrentDate);

                    $("#pnlMovieListing").processTemplate(ary);

                    _scrollToShowTimes();
                    
				    //show the correct clock format link
				    var otherFormat = (timeFormat == "12hr") ? "24hr" : "12hr";
				    $("#lnkSwitchTimeFormat" + timeFormat).hide();
				    $("#lnkSwitchTimeFormat" + otherFormat).show();

                    //link of onclick of trailers
                    //$("#pnlMovieListing a[href^=http://video.cineplex.com/?fr_story=]").click(Cineplex.ShowTrailerDialog);				
                }

            },
            error: function(error) {
                $("#pnlMovieListing").html(Cineplex_errSearchNotCompleted);
                _scrollToShowTimes();
            }

        });


    }

    function _renderExclusiveContent(str) {
        if (str == null || str == "") return "";

        var div = $('<div></div>');
        div.html(str);

        return '<div class="ExclusiveListingContent">' + div.text() + "</div>";
    }

    function _getCurrentDate() {
        return _currentDate.toString(Cineplex_DateFormat);
    }


    function _scrollToShowTimes() {
        //set the height so we don't "jump"
        $(document).scrollTo($("#Showtimes"), {
            duration: 500,
            easing: "swing",
            onAfter: function() {
                $("#pnlMovieListing").css("minHeight", null).css("overflow", "auto");
            }
        });
    }



    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;
            }
        }

    function _trim(str) {
        return str.replace(/^\s+/, "").replace(/\s+$/, "");
    }
    
    TheatreDetails.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_TheatreDetails_moviesUrl + "?state=ALL&genre=" + encodeURIComponent(genre) + "\">" + genre + "</a>";
            resultArr.push(linkHtml);
        }
        return resultArr.join(", ");
    }



    })(Cineplex.TheatreDetails);
