﻿/**
* static object that handles page logic for the accommodation prices page
* @class 
* @constructor
* @param {jQuery} $ Reference to the jQuery object
*/
var AccoPrices = function($) {

    /**
    * @namespace Private methods and variables
    */
    var priv = {

        /**
        * Image with loading animation.
        * @type jQuery
        * @private
        */
        $loader: null,

        /**
        * Container to load price table into. Has attached data('url') with url where to load it from.
        * @type jQuery
        * @private
        */
        $container: null,

        /**
        * Load price table using ajax from specified url.
        * @private
        */
        loadPrices: function(url) {
            location.href = url;
            return false;
        },

        /**
        * Actions to do when price table is loaded through ajax
        * @private
        */
        onTableLoaded: function() {
            priv.bindTableQuestionPopups();
            priv.bindTransportTypeButtons()
            priv.bindAirportButtons();
            priv.bindDurationLinks();
            priv.bindMonthLinks();
            PricesTooltip.InitTooltips();
            Occupancy.OnReady();
            priv.$container.show();
            priv.$loader.hide();
        },

        /**
        * Bind click event to the airport radio buttons, but only when there
        * are multiple airports to choose from.
        * @private
        */
        bindAirportButtons: function() {
            var buttons = $('#departure-airport input[type=radio]');
            if (buttons.length > 1) {
                buttons.click(function() {
                    var url = priv.url;
                    url = url.replace(/&airport=[^&]*/, '');
                    if ($(this).val()) { url = url + "&airport=" + $(this).val(); }
                    return !priv.loadPrices(url);
                });
            }
        },

        /**
        * Bind click event to the transport type radio buttons
        * @private
        */
        bindTransportTypeButtons: function() {
            var buttons = $('#departure-transport input[type=radio]');
            if (buttons.length > 1) {
                buttons.click(function() {
                    var url = priv.url;
                    url = url.replace(/&transporttype=[^&]*/, '');
                    if ($(this).val()) { url = url + "&transporttype=" + $(this).val(); }
                    return !priv.loadPrices(url);
                });
            }
        },

        /**
        * Bind events on the links to questions popups in the main content area each time table is reloaded.
        * @private
        */
        bindTableQuestionPopups: function() {
            // Bind methods to show popups for questions in main area
            $("#questions div.item a").bind('click', function() {
                return priv.loadInLightbox(this, "questionPopup");
            });
        },

        /**
        * @private
        */
        bindDurationLinks: function() {
            priv.bindLinks($("#prices .vacationlengths a"));
            priv.bindLinks($("#prices .to_available a"));
        },

        /**
        * @private
        */
        bindMonthLinks: function() {
            priv.bindLinks($("#months a"));
            priv.bindLinks($("#prices .soonerlater a"));
            priv.bindLinks($("#prices-bottom a"));
        },

        /**
        * @private
        */
        bindLinks: function(links) {
            links.click(function() {
                priv.url = $(this).attr('href');
                return !priv.loadPrices(priv.url);
            });
        },

        /**
        * Bind events on the links to questions popups, both in the left sidebar and in the main content area.
        * @private
        */
        bindQuestionPopups: function() {
            // add container for question popups
            $('body').append("<div id=\"questionPopup\"></div>");

            // Bind methods to show popups for questions in main area
            $("#questions div.item a").bind('click', function() {
                return priv.loadInLightbox(this, "questionPopup");
            });

            // Bind methods to show popups for questions in left sidebar
            $("#questions-left ul.questions li a").not(".more-questions").bind('click', function() {
                return priv.loadInLightbox(this, "questionPopup");
            });

            // Open faq in new window
            $("#questions-left ul.questions li a.more-questions").bind('click', function() {
                Utils.newWindow(this, 800, 640);
                return false;
            });
        },

        adjustLastminutesPopup: function($listItem, $lastminutePopup) {
            var top = $listItem.position().top;
            var topOffset = $listItem.offset().top;
            var winheight = $(window).height();
            var height = $lastminutePopup.height();
            if (topOffset - $(window).scrollTop() + height > winheight) {
                if (winheight > height) {
                    $lastminutePopup.css('top', (top - $lastminutePopup.height() + 10) + 'px');
                }
                else {
                    // default behaviour
                }
            }

        },
        
		bindLastminuteTooltip: function (){
            $("td.lastminute-trip").hover(
                function() {
                    var $listItem = $(this);
                    var $lastminutePopup = $("div.lastminuteTooltip", this);

                    var $informationBlock = $("#lastminute-tooltip-popup");
                    $informationBlock.css({ 'height': 'auto', 'border': 'none', 'padding': '5px'})
                    $informationBlock.height($informationBlock.get(0).offsetHeight + 20);
                    priv.adjustLastminutesPopup($listItem, $lastminutePopup);
                    $lastminutePopup.html($informationBlock.html()); 
                    
                    $lastminutePopup.show();

                    return false;
                },
                function() {
                    var $lastminutePopup = $("div.lastminuteTooltip", this);
                    $lastminutePopup.hide();
                    $lastminutePopup.css('top', ($(this).position().top + $(this).height() + 2) + 'px');
                    return false;
                }
            )
        },

        /**
        * Load the contents of the href of the anchor in a lightbox, wrapped in standard popup markup
        * @param {HTMLElement} anchor The anchor
        * @param {String} id ID to set on the popup container
        * @return {Boolean} false, to use in event handler and stop browser default behavior
        * @private
        */
        loadInLightbox: function(anchor, id) {
            var $anchor = $(anchor);

            var options = {
                container: document.getElementById(id),
                literal: false,
                title: $anchor.text(),
                contentUrl: $anchor.attr('href'),
                width: '643px'
            };
            var lightbox = Lightbox.CreateCached($anchor.attr('href'), options);
            lightbox.Show();
            return false;
        }
    };

    /** @scope AccoPrices */
    return {

        /**
        * Initializes the logic for the current page
        * to be called on $(document).ready
        */
        OnReady: function() {
            priv.$loader = $('#prices-loader');
            priv.$container = $('#prices-container');

            priv.url = location.href.replace(/#.*$/, '');
            priv.onTableLoaded();

            priv.bindQuestionPopups();
            priv.bindLastminuteTooltip();
            PricesTooltip.OnReady();
            Basket.OnReady();
        },

        /**
        * Add a newly selected price to the basket. Several parameters are used.
        */
        AddToBasket: function(packageid, packagecode, duration, roomtype, departuredate, transportcode, airportcode, price, accommodationid, mealplancode, $curobj, evt) {
        Basket.AddToBasket(packageid, packagecode, duration, roomtype, departuredate, transportcode, airportcode, price, accommodationid, mealplancode, $curobj, evt, "fixed-small", 205);
        },

        /*
        * Redraw the basket box. There are 2 possible situations:
        * 1. A price has been selected from the table, it will be added to the box
        * 2. The user closed the box. All parameters and previously selected prices will be cleared and the basket will be removed.
        * @param {Integer} height (Optional) The offset height of the basket. Used to determine whether to close or expand the basket.
        */
        ReDraw: function(height) {
            Basket.ReDraw(height);
        },

        /**
        * Remove the basket; clear all parameters
        */
        RemoveBasket: function() {
			Basket.RemoveBasket();
			$('#basket-container').slideUp();
        },

        /**
        * Get whether it is currently possible to open the tooltip
        * @return {Boolean} True if nothing prevents the tooltip from showing
        */
        CanShowTooltip: function() {
            return !Basket.IsAnimating();
        },

        /**
        * Perform certain actions when starting animation of the basket
        */
        StartingAnimation: function() {
            PricesTooltip.Hide();
        }
    };
} (jQuery);
