/*
    Behaviours for the Auction Calendar Page 
*/

Site.Pages.Calendar = Class.create
(
    Site.Page,
    {
        initialize: function($super, data, options)
        {
            $super();
            
            this.data = data;
            
            this.setOptions
            (
                options,
                {
                    imageBaseUrl: "images/photos_lots_small/"
                }
            );
            
            
            //this.addBlocks("sendRequestOnComplete", "calendarOnDayChange", "_sortData");
            //this.addObservers("clearAllCategoriesOnClick", "clearAllLocationsOnClick");
            
            this.templateListItem = new Template
                                    (
                                        Site.Pages.Calendar.TEMPLATES.LIST_ITEM.interpolatep
                                        (
                                            {
                                                baseUrl: this.options.imageBaseUrl
                                            }
                                        )
                                    );
        },
        
        calendarOnDayChange: function(day)
        {
            //this.setDay(day);
        },
          
        domOnLoad: function($super, event)
        {
            $super(event);

            this.saleTooltips = $('sale-tooltips');
            
            // setup collapse panels
            this.collapsePanelController = new Site.Controllers.CollapsePanel($('criteria'));
         
            //this.listCategories = new Site.Widgets.RichCheckboxList($('list-categories'), { richCheckboxOnClick: this.blocks.richCheckboxOnClick } );
            //this.listLocations = new Site.Widgets.RichCheckboxList($('list-locations'), { richCheckboxOnClick: this.blocks.richCheckboxOnClick } );

            //addEvent($('clear-all-categories'), "click", this.observers.clearAllCategoriesOnClick);
            //addEvent($('clear-all-locations'), "click", this.observers.clearAllLocationsOnClick);
            
            this.list = $('list-items');
            
            this.setupTooltips();
            
            //this.calendar = new Site.Widgets.Calendar($('calendar'), {onDayChange: this.blocks.calendarOnDayChange});

        },
        
        richCheckboxOnClick: function()
        {
            this.sendRequest();
        },
        
        clearAllCategoriesOnClick: function(event)
        {
            this.listCategories.uncheckAll();
            this.sendRequest();

            Event.stop(event);
        },
        
        clearAllLocationsOnClick: function(event)
        {
            this.listLocations.uncheckAll();
            this.sendRequest();

            Event.stop(event);
        },
        
        updateSaleTooltips: function()
        {
            this.saleTooltips.update
            (
                this.data.sales.inject
                (
                    "",
                    function(html, sale)
                    {
                        return Site.Pages.Calendar.TEMPLATES.SALE_TOOLTIP.interpolatep
                        (
                            {
                                saleNumber: sale.saleNumber,
                                
                                auctionTimes: sale.auctionTimes.inject
                                (
                                    "", 
                                    function(html, auctionTime)
                                    {
                                        return html + Site.Pages.Calendar.TEMPLATES.SALE_TOOLTIP_AUCTION_TIME.interpolatep(auctionTime);
                                    },
                                    this
                                ),
                                  
                                viewingTimes: sale.viewingTimes.inject
                                (
                                    "", 
                                    function(html, viewingTime)
                                    {
                                        return html + Site.Pages.Calendar.TEMPLATES.SALE_TOOLTIP_VIEWING_TIME.interpolatep(viewingTime);
                                    },
                                    this
                                )   
                            }
                        );
                    },
                    this
                )
            );
        },
        
        sendRequest: function()
        {
            // here, would gather the values of form elements together and prepate an appropriate request to
            // a web service
            
            var categories = this.listCategories.getValue();
            var locations = this.listLocations.getValue();
            
            this.request = new Ajax.Request
            (
                "js/sample_data/calendar.js?t=" + (new Date()).getTime(),
                {
                    method: "get",
                    onComplete: this.blocks.sendRequestOnComplete
                }
            );

            this.request = null;
        },
        
        sendRequestOnComplete: function(transport)
        {
            this.data = transport.responseText.evalJSON();
            this.updateElements();
        },
        
        updateElements: function()
        {
            this.updateList();

            this.destroyTooltips();
            this.setupTooltips();
        },

        
        /*
            Note:
                This method simulates the expected behaviour - the problem is that data on any subsequent pages is not regarded
                What is really needed is for this to send an AJAX request with a current day value set and to place the auctions up the top
                
        */
        
        setDay: function(day)
        {
            this.day = day;
            
            // sort the data so that any auction in the currently selected range is shown at the top
            //this.data.auctions = this.data.auctions.sort(this.blocks._sortData);
            //this.updateList();
            this.destroyTooltips();
            this.setupTooltips();
        },
        
        _sortData: function(a, b)
        {
            
            if (!this.day)
            {
                 return a.dateLow > b.dateLow ? 1 : -1;
            }
            else
            {
                if (a.dateLow <= this.day && a.dateHigh >= this.day && b.dateLow <= this.day && b.dateHigh >= this.day)
                {
                    return a.dateLow > b.dateLow ? 1 : -1;
                }
                else if (a.dateLow <= this.day && a.dateHigh >= this.day)
                {
                    return -1;
                }
                else if (b.dateLow <= this.day && b.dateHigh >= this.day)
                {
                    return 1;
                }
            }
            
            return a.dateLow > b.dateLow ? 1 : -1;            
        },
        
        updateList: function()
        {
            this.list.update
            (
                this.data.auctions.inject
                (
                    "",
                    function(html, auction, index)
                    {
                        return html + this.templateListItem.evaluatep( { "className": index % 2 == 0 ? "" : "alternate", featuredSaleButton: auction.feature ? Site.Pages.Calendar.TEMPLATES.LIST_ITEM_FEATURED_SALE_BUTTON : '' } ).interpolatep(auction)
                    },
                    this
                )
            );
        },
        
        
        destroyTooltips: function()
        {
            this.saleTooltipsController.destroy();
            
            /*
            $H(this.tooltips).each
            (
                function(pair)
                {
                    pair.value.destroy();
                }
            );
            */        
        },
        
        setupTooltips: function()
        {
            this.saleTooltipsController = new Site.Controllers.SaleTooltips(this.list.select("a.viewing-times"));
        },
       
        
        destroy: function($super)
        {
            this.saleTooltipsController.destroy();
            
            //removeEvent($('clear-all-categories'), "click", this.observers.clearAllCategoriesOnClick);
            //removeEvent($('clear-all-locations'), "click", this.observers.clearAllLocationsOnClick);

            $super();
        }
                  
    }
);

Object.extend
(
    Site.Pages.Calendar,
    {
        TEMPLATES:
        {
            LIST_ITEM: 
                       '<li class="#{className}">'
					 + '<div class="auction-date">'
					 + '<span class="day">#{day}</span> <span class="month">#{month}</span> <span class="date">#{date}</span>'
					 + '</div>'
					 + '<div class="auction-info">'
					 + '<span class="location">KENSINGTON, LONDON</span> '
					 + '<a href="browse_sale.php" rel="#{saleNumber}" class="viewing-times">Sale &amp; Viewing Times</a> '
					 + '<span class="sale">Sale <a href="browse_sale.php" class="sale-number">#{saleNumber}</a></span>'
					 + '<div class="clearer"></div>'
					 + '<p class="description">'
					 + '<a href="browse_sale.html" class="description">#{description}</a>'
					 + '</p>'
					 + '<ul class="auction-links">'
					 + '<li><a href="#" class="bt-track-sale bt"><span>Track Sale</span></a></li>'
					 + '<li><a href="#" class="bt-place-bid bt"><span><strong>Bid Live</strong><em> Register By #{registerBy}</em></span></a></li>'
					 + '#{featuredSaleButton}'
					 + '</ul>'
					 + '</div>'
					 + '<div class="cell"><div class="mid"><div><a href="browse_sale.php"><img src="#{baseUrl}#{image}" alt="" /></a></div></div></div>'
					 + '<div class="clearer"></div>'
					 + '</li>',
					 
			LIST_ITEM_FEATURED_SALE_BUTTON: 
			        '<li><a href="#" class="bt-view-featured-sale">View Featured Sale Page</a></li>',
	
			SALE_TOOLTIP:
			          '<div id="sale-tooltip-#{saleNumber}" class="tooltip" style="display: none;">'
                    + '<div class="cap-tp cap-tp-left"></div><div class="clearer"></div><div class="body">'
                    + '<h6>Auction Times</h6>' 
			        + '<table class="times">'
				    + '#{auctionTimes}'
				    + '</table>'
				    + '<h6>Viewing Times</h6>'
				    + '<table class="times">'
				    + '#{viewingTimes}'
				    + '</table>'
				    + '</div><div class="clearer"></div><div class="cap-bt"></div>'
                    + '</div>' + "\n",
            
            SALE_TOOLTIP_AUCTION_TIME:
	              '<tr><td>#{time}</td></tr>',

	        SALE_TOOLTIP_VIEWING_TIME:
	                '<tr>'
				  + '<th scope="row">#{date}</th>'
				  + '<td>#{timeLow} - #{timeHigh}</td>'
				  + '</tr>'

		}
    }
);